闭社主体 forked from https://github.com/tootsuite/mastodon
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.

49 lines
1.2 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' }) do |text|
  24. truncate(text.gsub(/\Ahttps?:\/\/(www\.)?/, ''), length: 30)
  25. end
  26. end
  27. def link_mentions(html, mentions)
  28. html.gsub(Account::MENTION_RE) do |match|
  29. acct = Account::MENTION_RE.match(match)[1]
  30. mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
  31. mention.nil? ? match : mention_html(match, mention.account)
  32. end
  33. end
  34. def mention_html(match, account)
  35. "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"mention\">@<span>#{account.username}</span></a>"
  36. end
  37. end