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.

236 lines
6.8 KiB

8 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) 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) 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) 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)
  49. html = encode(status.spoiler_text)
  50. html = encode_custom_emojis(html, status.emojis)
  51. html.html_safe # rubocop:disable Rails/OutputSafety
  52. end
  53. def format_field(account, str)
  54. return reformat(str).html_safe unless account.local? # rubocop:disable Rails/OutputSafety
  55. encode_and_link_urls(str, me: true).html_safe # rubocop:disable Rails/OutputSafety
  56. end
  57. def linkify(text)
  58. html = encode_and_link_urls(text)
  59. html = simple_format(html, {}, sanitize: false)
  60. html = html.delete("\n")
  61. html.html_safe # rubocop:disable Rails/OutputSafety
  62. end
  63. private
  64. def encode(html)
  65. HTMLEntities.new.encode(html)
  66. end
  67. def encode_and_link_urls(html, accounts = nil, options = {})
  68. entities = Extractor.extract_entities_with_indices(html, extract_url_without_protocol: false)
  69. if accounts.is_a?(Hash)
  70. options = accounts
  71. accounts = nil
  72. end
  73. rewrite(html.dup, entities) do |entity|
  74. if entity[:url]
  75. link_to_url(entity, options)
  76. elsif entity[:hashtag]
  77. link_to_hashtag(entity)
  78. elsif entity[:screen_name]
  79. link_to_mention(entity, accounts)
  80. end
  81. end
  82. end
  83. def count_tag_nesting(tag)
  84. if tag[1] == '/' then -1
  85. elsif tag[-2] == '/' then 0
  86. else 1
  87. end
  88. end
  89. def encode_custom_emojis(html, emojis)
  90. return html if emojis.empty?
  91. emoji_map = emojis.map { |e| [e.shortcode, full_asset_url(e.image.url(:static))] }.to_h
  92. i = -1
  93. tag_open_index = nil
  94. inside_shortname = false
  95. shortname_start_index = -1
  96. invisible_depth = 0
  97. while i + 1 < html.size
  98. i += 1
  99. if invisible_depth.zero? && inside_shortname && html[i] == ':'
  100. shortcode = html[shortname_start_index + 1..i - 1]
  101. emoji = emoji_map[shortcode]
  102. if emoji
  103. replacement = "<img draggable=\"false\" class=\"emojione\" alt=\":#{shortcode}:\" title=\":#{shortcode}:\" src=\"#{emoji}\" />"
  104. before_html = shortname_start_index.positive? ? html[0..shortname_start_index - 1] : ''
  105. html = before_html + replacement + html[i + 1..-1]
  106. i += replacement.size - (shortcode.size + 2) - 1
  107. else
  108. i -= 1
  109. end
  110. inside_shortname = false
  111. elsif tag_open_index && html[i] == '>'
  112. tag = html[tag_open_index..i]
  113. tag_open_index = nil
  114. if invisible_depth.positive?
  115. invisible_depth += count_tag_nesting(tag)
  116. elsif tag == '<span class="invisible">'
  117. invisible_depth = 1
  118. end
  119. elsif html[i] == '<'
  120. tag_open_index = i
  121. inside_shortname = false
  122. elsif !tag_open_index && html[i] == ':'
  123. inside_shortname = true
  124. shortname_start_index = i
  125. end
  126. end
  127. html
  128. end
  129. def rewrite(text, entities)
  130. chars = text.to_s.to_char_a
  131. # Sort by start index
  132. entities = entities.sort_by do |entity|
  133. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  134. indices.first
  135. end
  136. result = []
  137. last_index = entities.reduce(0) do |index, entity|
  138. indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
  139. result << encode(chars[index...indices.first].join)
  140. result << yield(entity)
  141. indices.last
  142. end
  143. result << encode(chars[last_index..-1].join)
  144. result.flatten.join
  145. end
  146. def link_to_url(entity, options = {})
  147. url = Addressable::URI.parse(entity[:url])
  148. html_attrs = { target: '_blank', rel: 'nofollow noopener' }
  149. html_attrs[:rel] = "me #{html_attrs[:rel]}" if options[:me]
  150. Twitter::Autolink.send(:link_to_text, entity, link_html(entity[:url]), url, html_attrs)
  151. rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
  152. encode(entity[:url])
  153. end
  154. def link_to_mention(entity, linkable_accounts)
  155. acct = entity[:screen_name]
  156. return link_to_account(acct) unless linkable_accounts
  157. account = linkable_accounts.find { |item| TagManager.instance.same_acct?(item.acct, acct) }
  158. account ? mention_html(account) : "@#{acct}"
  159. end
  160. def link_to_account(acct)
  161. username, domain = acct.split('@')
  162. domain = nil if TagManager.instance.local_domain?(domain)
  163. account = EntityCache.instance.mention(username, domain)
  164. account ? mention_html(account) : "@#{acct}"
  165. end
  166. def link_to_hashtag(entity)
  167. hashtag_html(entity[:hashtag])
  168. end
  169. def link_html(url)
  170. url = Addressable::URI.parse(url).to_s
  171. prefix = url.match(/\Ahttps?:\/\/(www\.)?/).to_s
  172. text = url[prefix.length, 30]
  173. suffix = url[prefix.length + 30..-1]
  174. cutoff = url[prefix.length..-1].length > 30
  175. "<span class=\"invisible\">#{encode(prefix)}</span><span class=\"#{cutoff ? 'ellipsis' : ''}\">#{encode(text)}</span><span class=\"invisible\">#{encode(suffix)}</span>"
  176. end
  177. def hashtag_html(tag)
  178. "<a href=\"#{tag_url(tag.downcase)}\" class=\"mention hashtag\" rel=\"tag\">#<span>#{tag}</span></a>"
  179. end
  180. def mention_html(account)
  181. "<span class=\"h-card\"><a href=\"#{TagManager.instance.url_for(account)}\" class=\"u-url mention\">@<span>#{account.username}</span></a></span>"
  182. end
  183. end