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 = simple_format(html, sanitize: false)
  11. html = link_urls(html)
  12. html = link_mentions(html, status.mentions)
  13. html.html_safe
  14. end
  15. def reformat(status)
  16. sanitize(status.content, tags: %w(a br p), attributes: %w(href rel))
  17. end
  18. private
  19. def encode(html)
  20. HTMLEntities.new.encode(html)
  21. end
  22. def link_urls(html)
  23. auto_link(html, link: :urls, html: { rel: 'nofollow noopener' })
  24. end
  25. def link_mentions(html, mentions)
  26. html.gsub(Account::MENTION_RE) do |match|
  27. acct = Account::MENTION_RE.match(match)[1]
  28. mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
  29. mention.nil? ? match : 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.username}</span></a>"
  34. end
  35. end