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.

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