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.

95 lines
2.4 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. if (status.spoiler?)
  13. spoilerhtml = status.spoiler_text
  14. spoilerhtml = encode(spoilerhtml)
  15. html = wrap_spoilers(html, spoilerhtml)
  16. else
  17. html = simple_format(html, sanitize: false)
  18. end
  19. html = html.gsub(/\n/, '')
  20. html = link_urls(html)
  21. html = link_mentions(html, status.mentions)
  22. html = link_hashtags(html)
  23. html.html_safe # rubocop:disable Rails/OutputSafety
  24. end
  25. def reformat(html)
  26. sanitize(html, tags: %w(a br p), attributes: %w(href rel))
  27. end
  28. def simplified_format(account)
  29. return reformat(account.note) unless account.local?
  30. html = encode(account.note)
  31. html = link_urls(html)
  32. html = link_hashtags(html)
  33. html.html_safe # rubocop:disable Rails/OutputSafety
  34. end
  35. private
  36. def encode(html)
  37. HTMLEntities.new.encode(html)
  38. end
  39. def wrap_spoilers(html, spoilerhtml)
  40. spoilerhtml = simple_format(spoilerhtml, {class: "spoiler-helper"}, {sanitize: false})
  41. html = simple_format(html, {class: ["spoiler", "spoiler-on"]}, {sanitize: false})
  42. spoilerhtml + html
  43. end
  44. def link_urls(html)
  45. html.gsub(URI.regexp(%w(http https))) do |match|
  46. link_html(match)
  47. end
  48. end
  49. def link_mentions(html, mentions)
  50. html.gsub(Account::MENTION_RE) do |match|
  51. acct = Account::MENTION_RE.match(match)[1]
  52. mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
  53. mention.nil? ? match : mention_html(match, mention.account)
  54. end
  55. end
  56. def link_hashtags(html)
  57. html.gsub(Tag::HASHTAG_RE) do |match|
  58. hashtag_html(match)
  59. end
  60. end
  61. def link_html(url)
  62. link_text = truncate(url.gsub(/\Ahttps?:\/\/(www\.)?/, ''), length: 30)
  63. "<a rel=\"nofollow noopener\" target=\"_blank\" href=\"#{url}\">#{link_text}</a>"
  64. end
  65. def hashtag_html(match)
  66. prefix, affix = match.split('#')
  67. "#{prefix}<a href=\"#{tag_url(affix.downcase)}\" class=\"mention hashtag\">#<span>#{affix}</span></a>"
  68. end
  69. def mention_html(match, account)
  70. "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"h-card u-url p-nickname mention\">@<span>#{account.username}</span></a>"
  71. end
  72. end