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.

47 lines
1.1 KiB

  1. require 'singleton'
  2. class Formatter
  3. include Singleton
  4. include ActionView::Helpers::TextHelper
  5. include ActionView::Helpers::SanitizeHelper
  6. def format(status)
  7. return reformat(status) unless status.local?
  8. html = status.text
  9. html = encode(html)
  10. html = link_urls(html)
  11. html = link_mentions(html, status.mentions)
  12. html.html_safe
  13. end
  14. def reformat(status)
  15. sanitize(status.content, tags: %w(a br p), attributes: %w(href rel))
  16. end
  17. private
  18. def encode(html)
  19. HTMLEntities.new.encode(html)
  20. end
  21. def link_urls(html)
  22. auto_link(html, link: :urls, html: { rel: 'nofollow noopener' })
  23. end
  24. def link_mentions(html, mentions)
  25. html.gsub(Account::MENTION_RE) do |match|
  26. acct = Account::MENTION_RE.match(match)[1]
  27. mention = mentions.find { |mention| mention.account.acct.eql?(acct) }
  28. return match if mention.nil?
  29. mention_html(match, mention.account)
  30. end
  31. end
  32. def mention_html(match, account)
  33. "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"mention\">@<span>#{account.acct}</span></a>"
  34. end
  35. end