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.

248 lines
7.4 KiB

7 years ago
  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, options[:autoplay]) 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, options[:autoplay]) 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, options[:autoplay]) 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, **options)
  49. html = encode(status.spoiler_text)
  50. html = encode_custom_emojis(html, status.emojis, options[:autoplay])
  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, options[:autoplay]) 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, options[:autoplay]) 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, animate = false)
  97. return html if emojis.empty?
  98. emoji_map = if animate
  99. emojis.map { |e| [e.shortcode, full_asset_url(e.image.url)] }.to_h
  100. else
  101. emojis.map { |e| [e.shortcode, full_asset_url(e.image.url(:static))] }.to_h
  102. end
  103. i = -1
  104. tag_open_index = nil
  105. inside_shortname = false
  106. shortname_start_index = -1
  107. invisible_depth = 0
  108. while i + 1 < html.size
  109. i += 1
  110. if invisible_depth.zero? && inside_shortname && html[i] == ':'
  111. shortcode = html[shortname_start_index + 1..i - 1]
  112. emoji = emoji_map[shortcode]
  113. if emoji
  114. replacement = "<img draggable=\"false\" class=\"emojione\" alt=\":#{shortcode}:\" title=\":#{shortcode}:\" src=\"#{emoji}\" />"
  115. before_html = shortname_start_index.positive? ? html[0..shortname_start_index - 1] : ''
  116. html = before_html + replacement + html[i + 1..-1]
  117. i += replacement.size - (shortcode.size + 2) - 1
  118. else
  119. i -= 1
  120. end
  121. inside_shortname = false
  122. elsif tag_open_index && html[i] == '>'
  123. tag = html[tag_open_index..i]
  124. tag_open_index = nil
  125. if invisible_depth.positive?
  126. invisible_depth += count_tag_nesting(tag)
  127. elsif tag == '<span class="invisible">'
  128. invisible_depth = 1
  129. end
  130. elsif html[i] == '<'
  131. tag_open_index = i
  132. inside_shortname = false
  133. elsif !tag_open_index && html[i] == ':'
  134. inside_shortname = true
  135. shortname_start_index = i
  136. end
  137. end
  138. html
  139. end
  140. def rewrite(text, entities)
  141. chars = text.to_s.to_char_a
  142. # Sort by start index
  143. entities = entities.sort_by do |entity|
  144. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  145. indices.first
  146. end
  147. result = []
  148. last_index = entities.reduce(0) do |index, entity|
  149. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  150. result << encode(chars[index...indices.first].join)
  151. result << yield(entity)
  152. indices.last
  153. end
  154. result << encode(chars[last_index..-1].join)
  155. result.flatten.join
  156. end
  157. def link_to_url(entity, options = {})
  158. url = Addressable::URI.parse(entity[:url])
  159. html_attrs = { target: '_blank', rel: 'nofollow noopener' }
  160. html_attrs[:rel] = "me #{html_attrs[:rel]}" if options[:me]
  161. Twitter::Autolink.send(:link_to_text, entity, link_html(entity[:url]), url, html_attrs)
  162. rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
  163. encode(entity[:url])
  164. end
  165. def link_to_mention(entity, linkable_accounts)
  166. acct = entity[:screen_name]
  167. return link_to_account(acct) unless linkable_accounts
  168. account = linkable_accounts.find { |item| TagManager.instance.same_acct?(item.acct, acct) }
  169. account ? mention_html(account) : "@#{acct}"
  170. end
  171. def link_to_account(acct)
  172. username, domain = acct.split('@')
  173. domain = nil if TagManager.instance.local_domain?(domain)
  174. account = EntityCache.instance.mention(username, domain)
  175. account ? mention_html(account) : "@#{acct}"
  176. end
  177. def link_to_hashtag(entity)
  178. hashtag_html(entity[:hashtag])
  179. end
  180. def link_html(url)
  181. url = Addressable::URI.parse(url).to_s
  182. prefix = url.match(/\Ahttps?:\/\/(www\.)?/).to_s
  183. text = url[prefix.length, 30]
  184. suffix = url[prefix.length + 30..-1]
  185. cutoff = url[prefix.length..-1].length > 30
  186. "<span class=\"invisible\">#{encode(prefix)}</span><span class=\"#{cutoff ? 'ellipsis' : ''}\">#{encode(text)}</span><span class=\"invisible\">#{encode(suffix)}</span>"
  187. end
  188. def hashtag_html(tag)
  189. "<a href=\"#{tag_url(tag.downcase)}\" class=\"mention hashtag\" rel=\"tag\">#<span>#{tag}</span></a>"
  190. end
  191. def mention_html(account)
  192. "<span class=\"h-card\"><a href=\"#{TagManager.instance.url_for(account)}\" class=\"u-url mention\">@<span>#{account.username}</span></a></span>"
  193. end
  194. end