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.

321 lines
9.9 KiB

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