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.

83 lines
2.2 KiB

8 years ago
8 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. def format(status)
  9. return reformat(status.content) unless status.local?
  10. html = status.text
  11. html = encode(html)
  12. html = simple_format(html, {}, sanitize: false)
  13. html = html.gsub(/\n/, '')
  14. html = link_urls(html)
  15. html = link_mentions(html, status.mentions)
  16. html = link_hashtags(html)
  17. html.html_safe # rubocop:disable Rails/OutputSafety
  18. end
  19. def reformat(html)
  20. sanitize(html, tags: %w(a br p), attributes: %w(href rel))
  21. end
  22. def simplified_format(account)
  23. return reformat(account.note) unless account.local?
  24. html = encode(account.note)
  25. html = link_urls(html)
  26. html = link_hashtags(html)
  27. html.html_safe # rubocop:disable Rails/OutputSafety
  28. end
  29. private
  30. def encode(html)
  31. HTMLEntities.new.encode(html)
  32. end
  33. def link_urls(html)
  34. html.gsub(URI.regexp(%w(http https))) do |match|
  35. link_html(match)
  36. end
  37. end
  38. def link_mentions(html, mentions)
  39. html.gsub(Account::MENTION_RE) do |match|
  40. acct = Account::MENTION_RE.match(match)[1]
  41. mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
  42. mention.nil? ? match : mention_html(match, mention.account)
  43. end
  44. end
  45. def link_hashtags(html)
  46. html.gsub(Tag::HASHTAG_RE) do |match|
  47. hashtag_html(match)
  48. end
  49. end
  50. def link_html(url)
  51. prefix = url.match(/\Ahttps?:\/\/(www\.)?/).to_s
  52. text = url[prefix.length, 30]
  53. suffix = url[prefix.length + 30..-1]
  54. "<a rel=\"nofollow noopener\" target=\"_blank\" href=\"#{url}\"><span class=\"invisible\">#{prefix}</span><span class=\"ellipsis\">#{text}</span><span class=\"invisible\">#{suffix}</span></a>"
  55. end
  56. def hashtag_html(match)
  57. prefix, affix = match.split('#')
  58. "#{prefix}<a href=\"#{tag_url(affix.downcase)}\" class=\"mention hashtag\">#<span>#{affix}</span></a>"
  59. end
  60. def mention_html(match, account)
  61. "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"h-card u-url p-nickname mention\">@<span>#{account.username}</span></a>"
  62. end
  63. end