formatter.rb 7.1 KB

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