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.

71 lines
1.7 KiB

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