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.

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