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.

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