You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

218 lines
6.2 KiB

7 years ago
  1. # frozen_string_literal: true
  2. require 'singleton'
  3. require_relative './sanitize_config'
  4. class Formatter
  5. include Singleton
  6. include RoutingHelper
  7. include ActionView::Helpers::TextHelper
  8. def format(status, options = {})
  9. if status.reblog?
  10. prepend_reblog = status.reblog.account.acct
  11. status = status.proper
  12. else
  13. prepend_reblog = false
  14. end
  15. raw_content = status.text
  16. unless status.local?
  17. html = reformat(raw_content)
  18. html = encode_custom_emojis(html, status.emojis) if options[:custom_emojify]
  19. return html.html_safe # rubocop:disable Rails/OutputSafety
  20. end
  21. linkable_accounts = status.mentions.map(&:account)
  22. linkable_accounts << status.account
  23. html = raw_content
  24. html = "RT @#{prepend_reblog} #{html}" if prepend_reblog
  25. html = encode_and_link_urls(html, linkable_accounts)
  26. html = encode_custom_emojis(html, status.emojis) if options[:custom_emojify]
  27. html = simple_format(html, {}, sanitize: false)
  28. html = html.delete("\n")
  29. html.html_safe # rubocop:disable Rails/OutputSafety
  30. end
  31. def reformat(html)
  32. sanitize(html, Sanitize::Config::MASTODON_STRICT)
  33. end
  34. def plaintext(status)
  35. return status.text if status.local?
  36. text = status.text.gsub(/(<br \/>|<br>|<\/p>)+/) { |match| "#{match}\n" }
  37. strip_tags(text)
  38. end
  39. def simplified_format(account)
  40. return reformat(account.note).html_safe unless account.local? # rubocop:disable Rails/OutputSafety
  41. html = encode_and_link_urls(account.note)
  42. html = simple_format(html, {}, sanitize: false)
  43. html = html.delete("\n")
  44. html.html_safe # rubocop:disable Rails/OutputSafety
  45. end
  46. def sanitize(html, config)
  47. Sanitize.fragment(html, config)
  48. end
  49. def format_spoiler(status)
  50. html = encode(status.spoiler_text)
  51. html = encode_custom_emojis(html, status.emojis)
  52. html.html_safe # rubocop:disable Rails/OutputSafety
  53. end
  54. private
  55. def encode(html)
  56. HTMLEntities.new.encode(html)
  57. end
  58. def encode_and_link_urls(html, accounts = nil)
  59. entities = Extractor.extract_entities_with_indices(html, extract_url_without_protocol: false)
  60. rewrite(html.dup, entities) do |entity|
  61. if entity[:url]
  62. link_to_url(entity)
  63. elsif entity[:hashtag]
  64. link_to_hashtag(entity)
  65. elsif entity[:screen_name]
  66. link_to_mention(entity, accounts)
  67. end
  68. end
  69. end
  70. def count_tag_nesting(tag)
  71. if tag[1] == '/' then -1
  72. elsif tag[-2] == '/' then 0
  73. else 1
  74. end
  75. end
  76. def encode_custom_emojis(html, emojis)
  77. return html if emojis.empty?
  78. emoji_map = emojis.map { |e| [e.shortcode, full_asset_url(e.image.url(:static))] }.to_h
  79. i = -1
  80. tag_open_index = nil
  81. inside_shortname = false
  82. shortname_start_index = -1
  83. invisible_depth = 0
  84. while i + 1 < html.size
  85. i += 1
  86. if invisible_depth.zero? && inside_shortname && html[i] == ':'
  87. shortcode = html[shortname_start_index + 1..i - 1]
  88. emoji = emoji_map[shortcode]
  89. if emoji
  90. replacement = "<img draggable=\"false\" class=\"emojione\" alt=\":#{shortcode}:\" title=\":#{shortcode}:\" src=\"#{emoji}\" />"
  91. before_html = shortname_start_index.positive? ? html[0..shortname_start_index - 1] : ''
  92. html = before_html + replacement + html[i + 1..-1]
  93. i += replacement.size - (shortcode.size + 2) - 1
  94. else
  95. i -= 1
  96. end
  97. inside_shortname = false
  98. elsif tag_open_index && html[i] == '>'
  99. tag = html[tag_open_index..i]
  100. tag_open_index = nil
  101. if invisible_depth.positive?
  102. invisible_depth += count_tag_nesting(tag)
  103. elsif tag == '<span class="invisible">'
  104. invisible_depth = 1
  105. end
  106. elsif html[i] == '<'
  107. tag_open_index = i
  108. inside_shortname = false
  109. elsif !tag_open_index && html[i] == ':'
  110. inside_shortname = true
  111. shortname_start_index = i
  112. end
  113. end
  114. html
  115. end
  116. def rewrite(text, entities)
  117. chars = text.to_s.to_char_a
  118. # Sort by start index
  119. entities = entities.sort_by do |entity|
  120. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  121. indices.first
  122. end
  123. result = []
  124. last_index = entities.reduce(0) do |index, entity|
  125. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  126. result << encode(chars[index...indices.first].join)
  127. result << yield(entity)
  128. indices.last
  129. end
  130. result << encode(chars[last_index..-1].join)
  131. result.flatten.join
  132. end
  133. def link_to_url(entity)
  134. normalized_url = Addressable::URI.parse(entity[:url]).normalize
  135. html_attrs = { target: '_blank', rel: 'nofollow noopener' }
  136. Twitter::Autolink.send(:link_to_text, entity, link_html(entity[:url]), normalized_url, html_attrs)
  137. rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
  138. encode(entity[:url])
  139. end
  140. def link_to_mention(entity, linkable_accounts)
  141. acct = entity[:screen_name]
  142. return link_to_account(acct) unless linkable_accounts
  143. account = linkable_accounts.find { |item| TagManager.instance.same_acct?(item.acct, acct) }
  144. account ? mention_html(account) : "@#{acct}"
  145. end
  146. def link_to_account(acct)
  147. username, domain = acct.split('@')
  148. domain = nil if TagManager.instance.local_domain?(domain)
  149. account = Account.find_remote(username, domain)
  150. account ? mention_html(account) : "@#{acct}"
  151. end
  152. def link_to_hashtag(entity)
  153. hashtag_html(entity[:hashtag])
  154. end
  155. def link_html(url)
  156. url = Addressable::URI.parse(url).to_s
  157. prefix = url.match(/\Ahttps?:\/\/(www\.)?/).to_s
  158. text = url[prefix.length, 30]
  159. suffix = url[prefix.length + 30..-1]
  160. cutoff = url[prefix.length..-1].length > 30
  161. "<span class=\"invisible\">#{encode(prefix)}</span><span class=\"#{cutoff ? 'ellipsis' : ''}\">#{encode(text)}</span><span class=\"invisible\">#{encode(suffix)}</span>"
  162. end
  163. def hashtag_html(tag)
  164. "<a href=\"#{tag_url(tag.downcase)}\" class=\"mention hashtag\" rel=\"tag\">#<span>#{tag}</span></a>"
  165. end
  166. def mention_html(account)
  167. "<span class=\"h-card\"><a href=\"#{TagManager.instance.url_for(account)}\" class=\"u-url mention\">@<span>#{account.username}</span></a></span>"
  168. end
  169. end