formatter.rb 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. if options[:inline_poll_options] && status.preloadable_poll
  17. raw_content = raw_content + "\n\n" + status.preloadable_poll.options.map { |title| "[ ] #{title}" }.join("\n")
  18. end
  19. return '' if raw_content.blank?
  20. unless status.local?
  21. html = reformat(raw_content)
  22. html = encode_custom_emojis(html, status.emojis, options[:autoplay]) if options[:custom_emojify]
  23. return html.html_safe # rubocop:disable Rails/OutputSafety
  24. end
  25. linkable_accounts = status.active_mentions.map(&:account)
  26. linkable_accounts << status.account
  27. html = raw_content
  28. html = "RT @#{prepend_reblog} #{html}" if prepend_reblog
  29. html = encode_and_link_urls(html, linkable_accounts)
  30. html = encode_custom_emojis(html, status.emojis, options[:autoplay]) if options[:custom_emojify]
  31. html = simple_format(html, {}, sanitize: false)
  32. html = html.delete("\n")
  33. html.html_safe # rubocop:disable Rails/OutputSafety
  34. end
  35. def reformat(html)
  36. sanitize(html, Sanitize::Config::MASTODON_STRICT)
  37. rescue ArgumentError
  38. ''
  39. end
  40. def plaintext(status)
  41. return status.text if status.local?
  42. text = status.text.gsub(/(<br \/>|<br>|<\/p>)+/) { |match| "#{match}\n" }
  43. strip_tags(text)
  44. end
  45. def simplified_format(account, **options)
  46. html = account.local? ? linkify(account.note) : reformat(account.note)
  47. html = encode_custom_emojis(html, account.emojis, options[:autoplay]) if options[:custom_emojify]
  48. html.html_safe # rubocop:disable Rails/OutputSafety
  49. end
  50. def sanitize(html, config)
  51. Sanitize.fragment(html, config)
  52. end
  53. def format_spoiler(status, **options)
  54. html = encode(status.spoiler_text)
  55. html = encode_custom_emojis(html, status.emojis, options[:autoplay])
  56. html.html_safe # rubocop:disable Rails/OutputSafety
  57. end
  58. def format_poll_option(status, option, **options)
  59. html = encode(option.title)
  60. html = encode_custom_emojis(html, status.emojis, options[:autoplay])
  61. html.html_safe # rubocop:disable Rails/OutputSafety
  62. end
  63. def format_display_name(account, **options)
  64. html = encode(account.display_name.presence || account.username)
  65. html = encode_custom_emojis(html, account.emojis, options[:autoplay]) if options[:custom_emojify]
  66. html.html_safe # rubocop:disable Rails/OutputSafety
  67. end
  68. def format_field(account, str, **options)
  69. html = account.local? ? encode_and_link_urls(str, me: true) : reformat(str)
  70. html = encode_custom_emojis(html, account.emojis, options[:autoplay]) if options[:custom_emojify]
  71. html.html_safe # rubocop:disable Rails/OutputSafety
  72. end
  73. def linkify(text)
  74. html = encode_and_link_urls(text)
  75. html = simple_format(html, {}, sanitize: false)
  76. html = html.delete("\n")
  77. html.html_safe # rubocop:disable Rails/OutputSafety
  78. end
  79. private
  80. def html_entities
  81. @html_entities ||= HTMLEntities.new
  82. end
  83. def encode(html)
  84. html_entities.encode(html)
  85. end
  86. def encode_and_link_urls(html, accounts = nil, options = {})
  87. entities = utf8_friendly_extractor(html, extract_url_without_protocol: false)
  88. if accounts.is_a?(Hash)
  89. options = accounts
  90. accounts = nil
  91. end
  92. rewrite(html.dup, entities) do |entity|
  93. if entity[:url]
  94. link_to_url(entity, options)
  95. elsif entity[:hashtag]
  96. link_to_hashtag(entity)
  97. elsif entity[:screen_name]
  98. link_to_mention(entity, accounts)
  99. end
  100. end
  101. end
  102. def count_tag_nesting(tag)
  103. if tag[1] == '/' then -1
  104. elsif tag[-2] == '/' then 0
  105. else 1
  106. end
  107. end
  108. # rubocop:disable Metrics/BlockNesting
  109. def encode_custom_emojis(html, emojis, animate = false)
  110. return html if emojis.empty?
  111. emoji_map = emojis.each_with_object({}) { |e, h| h[e.shortcode] = [full_asset_url(e.image.url), full_asset_url(e.image.url(:static))] }
  112. i = -1
  113. tag_open_index = nil
  114. inside_shortname = false
  115. shortname_start_index = -1
  116. invisible_depth = 0
  117. while i + 1 < html.size
  118. i += 1
  119. if invisible_depth.zero? && inside_shortname && html[i] == ':'
  120. shortcode = html[shortname_start_index + 1..i - 1]
  121. emoji = emoji_map[shortcode]
  122. if emoji
  123. original_url, static_url = emoji
  124. replacement = begin
  125. if animate
  126. "<img draggable=\"false\" class=\"emojione\" alt=\":#{encode(shortcode)}:\" title=\":#{encode(shortcode)}:\" src=\"#{encode(original_url)}\" />"
  127. else
  128. "<img draggable=\"false\" class=\"emojione custom-emoji\" alt=\":#{encode(shortcode)}:\" title=\":#{encode(shortcode)}:\" src=\"#{encode(static_url)}\" data-original=\"#{original_url}\" data-static=\"#{static_url}\" />"
  129. end
  130. end
  131. before_html = shortname_start_index.positive? ? html[0..shortname_start_index - 1] : ''
  132. html = before_html + replacement + html[i + 1..-1]
  133. i += replacement.size - (shortcode.size + 2) - 1
  134. else
  135. i -= 1
  136. end
  137. inside_shortname = false
  138. elsif tag_open_index && html[i] == '>'
  139. tag = html[tag_open_index..i]
  140. tag_open_index = nil
  141. if invisible_depth.positive?
  142. invisible_depth += count_tag_nesting(tag)
  143. elsif tag == '<span class="invisible">'
  144. invisible_depth = 1
  145. end
  146. elsif html[i] == '<'
  147. tag_open_index = i
  148. inside_shortname = false
  149. elsif !tag_open_index && html[i] == ':'
  150. inside_shortname = true
  151. shortname_start_index = i
  152. end
  153. end
  154. html
  155. end
  156. # rubocop:enable Metrics/BlockNesting
  157. def rewrite(text, entities)
  158. text = text.to_s
  159. # Sort by start index
  160. entities = entities.sort_by do |entity|
  161. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  162. indices.first
  163. end
  164. result = []
  165. last_index = entities.reduce(0) do |index, entity|
  166. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  167. result << encode(text[index...indices.first])
  168. result << yield(entity)
  169. indices.last
  170. end
  171. result << encode(text[last_index..-1])
  172. result.flatten.join
  173. end
  174. UNICODE_ESCAPE_BLACKLIST_RE = /\p{Z}|\p{P}/
  175. def utf8_friendly_extractor(text, options = {})
  176. old_to_new_index = [0]
  177. escaped = text.chars.map do |c|
  178. output = begin
  179. if c.ord.to_s(16).length > 2 && UNICODE_ESCAPE_BLACKLIST_RE.match(c).nil?
  180. CGI.escape(c)
  181. else
  182. c
  183. end
  184. end
  185. old_to_new_index << old_to_new_index.last + output.length
  186. output
  187. end.join
  188. # Note: I couldn't obtain list_slug with @user/list-name format
  189. # for mention so this requires additional check
  190. special = Extractor.extract_urls_with_indices(escaped, options).map do |extract|
  191. new_indices = [
  192. old_to_new_index.find_index(extract[:indices].first),
  193. old_to_new_index.find_index(extract[:indices].last),
  194. ]
  195. next extract.merge(
  196. indices: new_indices,
  197. url: text[new_indices.first..new_indices.last - 1]
  198. )
  199. end
  200. standard = Extractor.extract_entities_with_indices(text, options)
  201. extra = Extractor.extract_extra_uris_with_indices(text, options)
  202. Extractor.remove_overlapping_entities(special + standard + extra)
  203. end
  204. def link_to_url(entity, options = {})
  205. url = Addressable::URI.parse(entity[:url])
  206. html_attrs = { target: '_blank', rel: 'nofollow noopener noreferrer' }
  207. html_attrs[:rel] = "me #{html_attrs[:rel]}" if options[:me]
  208. Twitter::Autolink.send(:link_to_text, entity, link_html(entity[:url]), url, html_attrs)
  209. rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
  210. encode(entity[:url])
  211. end
  212. def link_to_mention(entity, linkable_accounts)
  213. acct = entity[:screen_name]
  214. return link_to_account(acct) unless linkable_accounts
  215. account = linkable_accounts.find { |item| TagManager.instance.same_acct?(item.acct, acct) }
  216. account ? mention_html(account) : "@#{encode(acct)}"
  217. end
  218. def link_to_account(acct)
  219. username, domain = acct.split('@')
  220. domain = nil if TagManager.instance.local_domain?(domain)
  221. account = EntityCache.instance.mention(username, domain)
  222. account ? mention_html(account) : "@#{encode(acct)}"
  223. end
  224. def link_to_hashtag(entity)
  225. hashtag_html(entity[:hashtag])
  226. end
  227. def link_html(url)
  228. url = Addressable::URI.parse(url).to_s
  229. prefix = url.match(/\A(https?:\/\/(www\.)?|xmpp:)/).to_s
  230. text = url[prefix.length, 30]
  231. suffix = url[prefix.length + 30..-1]
  232. cutoff = url[prefix.length..-1].length > 30
  233. "<span class=\"invisible\">#{encode(prefix)}</span><span class=\"#{cutoff ? 'ellipsis' : ''}\">#{encode(text)}</span><span class=\"invisible\">#{encode(suffix)}</span>"
  234. end
  235. def hashtag_html(tag)
  236. "<a href=\"#{encode(tag_url(tag))}\" class=\"mention hashtag\" rel=\"tag\">#<span>#{encode(tag)}</span></a>"
  237. end
  238. def mention_html(account)
  239. "<span class=\"h-card\"><a href=\"#{encode(ActivityPub::TagManager.instance.url_for(account))}\" class=\"u-url mention\">@<span>#{encode(account.username)}</span></a></span>"
  240. end
  241. end