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.

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