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.

325 lines
10 KiB

7 years ago
3 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. return encode(account.username) unless account.has_attribute?('display_name')
  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, with_domain: 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 markdown_link_check(html, entity)
  87. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  88. aft_s = html[indices.last ..]
  89. bef_s = html[0 .. indices.first-1]
  90. re = /(!?)\[([^\n\[\]]*?)\]\($/
  91. if aft_s and bef_s and aft_s.start_with?(')') and bef_s =~ re
  92. new_indices = [bef_s =~ re, indices.last+1]
  93. new_entity = {
  94. indices: new_indices,
  95. url: entity[:url],
  96. link_text: $2
  97. }
  98. if $1 == '!'
  99. new_entity[:img] = true
  100. end
  101. new_entity
  102. else
  103. entity
  104. end
  105. end
  106. def encode_and_link_urls(html, accounts = nil, options = {})
  107. entities = utf8_friendly_extractor(html, extract_url_without_protocol: false)
  108. entities = entities.map { |entity| entity[:url] ? markdown_link_check(html, entity) : entity }
  109. if accounts.is_a?(Hash)
  110. options = accounts
  111. accounts = nil
  112. end
  113. rewrite(html.dup, entities) do |entity|
  114. if entity[:url]
  115. link_to_url(entity, options)
  116. elsif entity[:hashtag]
  117. link_to_hashtag(entity)
  118. elsif entity[:screen_name]
  119. link_to_mention(entity, accounts, options)
  120. end
  121. end
  122. end
  123. def count_tag_nesting(tag)
  124. if tag[1] == '/' then -1
  125. elsif tag[-2] == '/' then 0
  126. else 1
  127. end
  128. end
  129. # rubocop:disable Metrics/BlockNesting
  130. def encode_custom_emojis(html, emojis, animate = false)
  131. return html if emojis.empty?
  132. emoji_map = emojis.each_with_object({}) { |e, h| h[e.shortcode] = [full_asset_url(e.image.url), full_asset_url(e.image.url(:static))] }
  133. i = -1
  134. tag_open_index = nil
  135. inside_shortname = false
  136. shortname_start_index = -1
  137. invisible_depth = 0
  138. while i + 1 < html.size
  139. i += 1
  140. if invisible_depth.zero? && inside_shortname && html[i] == ':'
  141. shortcode = html[shortname_start_index + 1..i - 1]
  142. emoji = emoji_map[shortcode]
  143. if emoji
  144. original_url, static_url = emoji
  145. replacement = begin
  146. if animate
  147. image_tag(original_url, draggable: false, class: 'emojione', alt: ":#{shortcode}:", title: ":#{shortcode}:")
  148. else
  149. image_tag(original_url, draggable: false, class: 'emojione custom-emoji', alt: ":#{shortcode}:", title: ":#{shortcode}:", data: { original: original_url, static: static_url })
  150. end
  151. end
  152. before_html = shortname_start_index.positive? ? html[0..shortname_start_index - 1] : ''
  153. html = before_html + replacement + html[i + 1..-1]
  154. i += replacement.size - (shortcode.size + 2) - 1
  155. else
  156. i -= 1
  157. end
  158. inside_shortname = false
  159. elsif tag_open_index && html[i] == '>'
  160. tag = html[tag_open_index..i]
  161. tag_open_index = nil
  162. if invisible_depth.positive?
  163. invisible_depth += count_tag_nesting(tag)
  164. elsif tag == '<span class="invisible">'
  165. invisible_depth = 1
  166. end
  167. elsif html[i] == '<'
  168. tag_open_index = i
  169. inside_shortname = false
  170. elsif !tag_open_index && html[i] == ':'
  171. inside_shortname = true
  172. shortname_start_index = i
  173. end
  174. end
  175. html
  176. end
  177. # rubocop:enable Metrics/BlockNesting
  178. def rewrite(text, entities)
  179. text = text.to_s
  180. # Sort by start index
  181. entities = entities.sort_by do |entity|
  182. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  183. indices.first
  184. end
  185. result = []
  186. last_index = entities.reduce(0) do |index, entity|
  187. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  188. result << encode(text[index...indices.first])
  189. result << yield(entity)
  190. indices.last
  191. end
  192. result << encode(text[last_index..-1])
  193. result.flatten.join
  194. end
  195. def utf8_friendly_extractor(text, options = {})
  196. # Note: I couldn't obtain list_slug with @user/list-name format
  197. # for mention so this requires additional check
  198. special = Extractor.extract_urls_with_indices(text, options)
  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. html_attrs[:class] = "media-gallery__item-thumbnail" if entity[:img]
  208. Twitter::TwitterText::Autolink.send(:link_to_text, entity, link_html(entity[:url], entity[:link_text], entity[:img]), 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, options = {})
  213. acct = entity[:screen_name]
  214. return link_to_account(acct, options) unless linkable_accounts
  215. same_username_hits = 0
  216. account = nil
  217. username, domain = acct.split('@')
  218. domain = nil if TagManager.instance.local_domain?(domain)
  219. linkable_accounts.each do |item|
  220. same_username = item.username.casecmp(username).zero?
  221. same_domain = item.domain.nil? ? domain.nil? : item.domain.casecmp(domain)&.zero?
  222. if same_username && !same_domain
  223. same_username_hits += 1
  224. elsif same_username && same_domain
  225. account = item
  226. end
  227. end
  228. account ? mention_html(account, with_domain: same_username_hits.positive? || options[:with_domain]) : "@#{encode(acct)}"
  229. end
  230. def link_to_account(acct, options = {})
  231. username, domain = acct.split('@')
  232. domain = nil if TagManager.instance.local_domain?(domain)
  233. account = EntityCache.instance.mention(username, domain)
  234. account ? mention_html(account, with_domain: options[:with_domain]) : "@#{encode(acct)}"
  235. end
  236. def link_to_hashtag(entity)
  237. hashtag_html(entity[:hashtag])
  238. end
  239. def link_html(url, link_text, img)
  240. url = Addressable::URI.parse(url).to_s
  241. if img
  242. return "<img src=\"#{url}\" alt=\"#{link_text}\" referrerpolicy=\"no-referrer\">"
  243. elsif link_text
  244. return "<span>#{link_text}</span><span class=\"invisible\">#{encode(url)}</span>"
  245. end
  246. prefix = url.match(/\A(https?:\/\/(www\.)?|xmpp:)/).to_s
  247. text = url[prefix.length, 30]
  248. suffix = url[prefix.length + 30..-1]
  249. cutoff = url[prefix.length..-1].length > 30
  250. "<span class=\"invisible\">#{encode(prefix)}</span><span class=\"#{cutoff ? 'ellipsis' : ''}\">#{encode(text)}</span><span class=\"invisible\">#{encode(suffix)}</span>"
  251. end
  252. def hashtag_html(tag)
  253. "<a href=\"#{encode(tag_url(tag))}\" class=\"mention hashtag\" rel=\"tag\">#<span>#{encode(tag)}</span></a>"
  254. end
  255. def mention_html(account, with_domain: false)
  256. "<span class=\"h-card\"><a href=\"#{encode(ActivityPub::TagManager.instance.url_for(account))}\" class=\"u-url mention\">@<span>#{with_domain ? encode(account.pretty_acct) : format_display_name(account, custom_emojify: true)}</span></a></span>"
  257. end
  258. end