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.

86 lines
2.4 KiB

7 years ago
7 years ago
  1. # frozen_string_literal: true
  2. require 'singleton'
  3. class Formatter
  4. include Singleton
  5. include RoutingHelper
  6. include ActionView::Helpers::TextHelper
  7. include ActionView::Helpers::SanitizeHelper
  8. AUTOLINK_RE = /https?:\/\/([\S]+\.[!#$&-;=?-[\]_a-z~]|%[\w\d]{2}]+[\w])/i
  9. def format(status)
  10. return reformat(status.content) unless status.local?
  11. html = status.text
  12. html = encode(html)
  13. html = simple_format(html, {}, sanitize: false)
  14. html = html.gsub(/\n/, '')
  15. html = link_urls(html)
  16. html = link_mentions(html, status.mentions)
  17. html = link_hashtags(html)
  18. html.html_safe # rubocop:disable Rails/OutputSafety
  19. end
  20. def reformat(html)
  21. sanitize(html, tags: %w(a br p), attributes: %w(href rel))
  22. end
  23. def simplified_format(account)
  24. return reformat(account.note) unless account.local?
  25. html = encode(account.note)
  26. html = link_urls(html)
  27. html = link_hashtags(html)
  28. html.html_safe # rubocop:disable Rails/OutputSafety
  29. end
  30. private
  31. def encode(html)
  32. HTMLEntities.new.encode(html)
  33. end
  34. def link_urls(html)
  35. Twitter::Autolink.auto_link_urls(html, url_target: '_blank',
  36. link_attribute_block: lambda { |_, a| a[:rel] << ' noopener' },
  37. link_text_block: lambda { |_, text| link_html(text) })
  38. end
  39. def link_mentions(html, mentions)
  40. html.gsub(Account::MENTION_RE) do |match|
  41. acct = Account::MENTION_RE.match(match)[1]
  42. mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
  43. mention.nil? ? match : mention_html(match, mention.account)
  44. end
  45. end
  46. def link_hashtags(html)
  47. html.gsub(Tag::HASHTAG_RE) do |match|
  48. hashtag_html(match)
  49. end
  50. end
  51. def link_html(url)
  52. prefix = url.match(/\Ahttps?:\/\/(www\.)?/).to_s
  53. text = url[prefix.length, 30]
  54. suffix = url[prefix.length + 30..-1]
  55. cutoff = url[prefix.length..-1].length > 30
  56. "<span class=\"invisible\">#{prefix}</span><span class=\"#{cutoff ? 'ellipsis' : ''}\">#{text}</span><span class=\"invisible\">#{suffix}</span>"
  57. end
  58. def hashtag_html(match)
  59. prefix, affix = match.split('#')
  60. "#{prefix}<a href=\"#{tag_url(affix.downcase)}\" class=\"mention hashtag\">#<span>#{affix}</span></a>"
  61. end
  62. def mention_html(match, account)
  63. "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"h-card u-url p-nickname mention\">@<span>#{account.username}</span></a>"
  64. end
  65. end