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

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