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.

73 lines
1.8 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 = link_urls(html)
  14. html = link_mentions(html, status.mentions)
  15. html = link_hashtags(html)
  16. html.html_safe # rubocop:disable Rails/OutputSafety
  17. end
  18. def reformat(html)
  19. sanitize(html, tags: %w(a br p), attributes: %w(href rel))
  20. end
  21. def simplified_format(account)
  22. return reformat(account.note) unless account.local?
  23. html = encode(account.note)
  24. html = link_urls(html)
  25. html.html_safe # rubocop:disable Rails/OutputSafety
  26. end
  27. private
  28. def encode(html)
  29. HTMLEntities.new.encode(html)
  30. end
  31. def link_urls(html)
  32. auto_link(html, link: :urls, html: { rel: 'nofollow noopener' }) do |text|
  33. truncate(text.gsub(/\Ahttps?:\/\/(www\.)?/, ''), length: 30)
  34. end
  35. end
  36. def link_mentions(html, mentions)
  37. html.gsub(Account::MENTION_RE) do |match|
  38. acct = Account::MENTION_RE.match(match)[1]
  39. mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
  40. mention.nil? ? match : mention_html(match, mention.account)
  41. end
  42. end
  43. def link_hashtags(html)
  44. html.gsub(Tag::HASHTAG_RE) do |match|
  45. hashtag_html(match)
  46. end
  47. end
  48. def hashtag_html(match)
  49. prefix, affix = match.split('#')
  50. "#{prefix}<a href=\"#{tag_url(affix.downcase)}\" class=\"mention hashtag\">#<span>#{affix}</span></a>"
  51. end
  52. def mention_html(match, account)
  53. "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"h-card u-url p-nickname mention\">@<span>#{account.username}</span></a>"
  54. end
  55. end