The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

253 lines
7.6 KiB

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