闭社主体 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.

62 lines
1.6 KiB

8 years ago
8 years ago
  1. require 'singleton'
  2. class Formatter
  3. include Singleton
  4. include RoutingHelper
  5. include ActionView::Helpers::TextHelper
  6. include ActionView::Helpers::SanitizeHelper
  7. def format(status)
  8. return reformat(status) unless status.local?
  9. html = status.text
  10. html = encode(html)
  11. html = simple_format(html, sanitize: false)
  12. html = link_urls(html)
  13. html = link_mentions(html, status.mentions)
  14. html = link_hashtags(html)
  15. html.html_safe
  16. end
  17. def reformat(status)
  18. sanitize(status.content, tags: %w(a br p), attributes: %w(href rel))
  19. end
  20. private
  21. def encode(html)
  22. HTMLEntities.new.encode(html)
  23. end
  24. def link_urls(html)
  25. auto_link(html, link: :urls, html: { rel: 'nofollow noopener' }) do |text|
  26. truncate(text.gsub(/\Ahttps?:\/\/(www\.)?/, ''), length: 30)
  27. end
  28. end
  29. def link_mentions(html, mentions)
  30. html.gsub(Account::MENTION_RE) do |match|
  31. acct = Account::MENTION_RE.match(match)[1]
  32. mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
  33. mention.nil? ? match : mention_html(match, mention.account)
  34. end
  35. end
  36. def link_hashtags(html)
  37. html.gsub(Tag::HASHTAG_RE) do |match|
  38. hashtag_html(match)
  39. end
  40. end
  41. def hashtag_html(match)
  42. prefix, affix = match.split('#')
  43. "#{prefix}<a href=\"#{tag_url(affix.downcase)}\" class=\"mention hashtag\">#<span>#{affix}</span></a>"
  44. end
  45. def mention_html(match, account)
  46. "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"mention\">@<span>#{account.username}</span></a>"
  47. end
  48. end