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.

292 lines
9.2 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. def utf8_friendly_extractor(text, options = {})
  174. # Note: I couldn't obtain list_slug with @user/list-name format
  175. # for mention so this requires additional check
  176. special = Extractor.extract_urls_with_indices(text, options)
  177. standard = Extractor.extract_entities_with_indices(text, options)
  178. extra = Extractor.extract_extra_uris_with_indices(text, options)
  179. Extractor.remove_overlapping_entities(special + standard + extra)
  180. end
  181. def link_to_url(entity, options = {})
  182. url = Addressable::URI.parse(entity[:url])
  183. html_attrs = { target: '_blank', rel: 'nofollow noopener noreferrer' }
  184. html_attrs[:rel] = "me #{html_attrs[:rel]}" if options[:me]
  185. Twitter::TwitterText::Autolink.send(:link_to_text, entity, link_html(entity[:url]), url, html_attrs)
  186. rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
  187. encode(entity[:url])
  188. end
  189. def link_to_mention(entity, linkable_accounts, options = {})
  190. acct = entity[:screen_name]
  191. return link_to_account(acct, options) unless linkable_accounts
  192. same_username_hits = 0
  193. account = nil
  194. username, domain = acct.split('@')
  195. domain = nil if TagManager.instance.local_domain?(domain)
  196. linkable_accounts.each do |item|
  197. same_username = item.username.casecmp(username).zero?
  198. same_domain = item.domain.nil? ? domain.nil? : item.domain.casecmp(domain)&.zero?
  199. if same_username && !same_domain
  200. same_username_hits += 1
  201. elsif same_username && same_domain
  202. account = item
  203. end
  204. end
  205. account ? mention_html(account, with_domain: same_username_hits.positive? || options[:with_domain]) : "@#{encode(acct)}"
  206. end
  207. def link_to_account(acct, options = {})
  208. username, domain = acct.split('@')
  209. domain = nil if TagManager.instance.local_domain?(domain)
  210. account = EntityCache.instance.mention(username, domain)
  211. account ? mention_html(account, with_domain: options[:with_domain]) : "@#{encode(acct)}"
  212. end
  213. def link_to_hashtag(entity)
  214. hashtag_html(entity[:hashtag])
  215. end
  216. def link_html(url)
  217. url = Addressable::URI.parse(url).to_s
  218. prefix = url.match(/\A(https?:\/\/(www\.)?|xmpp:)/).to_s
  219. text = url[prefix.length, 30]
  220. suffix = url[prefix.length + 30..-1]
  221. cutoff = url[prefix.length..-1].length > 30
  222. "<span class=\"invisible\">#{encode(prefix)}</span><span class=\"#{cutoff ? 'ellipsis' : ''}\">#{encode(text)}</span><span class=\"invisible\">#{encode(suffix)}</span>"
  223. end
  224. def hashtag_html(tag)
  225. "<a href=\"#{encode(tag_url(tag))}\" class=\"mention hashtag\" rel=\"tag\">#<span>#{encode(tag)}</span></a>"
  226. end
  227. def mention_html(account, with_domain: false)
  228. "<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>"
  229. end
  230. end