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

91 lines
2.6 KiB

8 years ago
7 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. AUTOLINK_RE = /https?:\/\/([\S]+\.[!#$&-;=?-[\]_a-z~]|%[\w\d]{2}]+[\w])/i
  9. def format(status)
  10. return reformat(status.content) unless status.local?
  11. html = status.text
  12. html = encode(html)
  13. html = simple_format(html, {}, sanitize: false)
  14. html = html.gsub(/\n/, '')
  15. html = link_urls(html)
  16. html = link_mentions(html, status.mentions)
  17. html = link_hashtags(html)
  18. html.html_safe # rubocop:disable Rails/OutputSafety
  19. end
  20. def reformat(html)
  21. sanitize(html, tags: %w(a br p span), attributes: %w(href rel class))
  22. end
  23. def plaintext(status)
  24. return status.text if status.local?
  25. strip_tags(status.text)
  26. end
  27. def simplified_format(account)
  28. return reformat(account.note) unless account.local?
  29. html = encode(account.note)
  30. html = link_urls(html)
  31. html = link_hashtags(html)
  32. html.html_safe # rubocop:disable Rails/OutputSafety
  33. end
  34. private
  35. def encode(html)
  36. HTMLEntities.new.encode(html)
  37. end
  38. def link_urls(html)
  39. Twitter::Autolink.auto_link_urls(html, url_target: '_blank',
  40. link_attribute_block: lambda { |_, a| a[:rel] << ' noopener' },
  41. link_text_block: lambda { |_, text| link_html(text) })
  42. end
  43. def link_mentions(html, mentions)
  44. html.gsub(Account::MENTION_RE) do |match|
  45. acct = Account::MENTION_RE.match(match)[1]
  46. mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? }
  47. mention.nil? ? match : mention_html(match, mention.account)
  48. end
  49. end
  50. def link_hashtags(html)
  51. html.gsub(Tag::HASHTAG_RE) do |match|
  52. hashtag_html(match)
  53. end
  54. end
  55. def link_html(url)
  56. prefix = url.match(/\Ahttps?:\/\/(www\.)?/).to_s
  57. text = url[prefix.length, 30]
  58. suffix = url[prefix.length + 30..-1]
  59. cutoff = url[prefix.length..-1].length > 30
  60. "<span class=\"invisible\">#{prefix}</span><span class=\"#{cutoff ? 'ellipsis' : ''}\">#{text}</span><span class=\"invisible\">#{suffix}</span>"
  61. end
  62. def hashtag_html(match)
  63. prefix, affix = match.split('#')
  64. "#{prefix}<a href=\"#{tag_url(affix.downcase)}\" class=\"mention hashtag\">#<span>#{affix}</span></a>"
  65. end
  66. def mention_html(match, account)
  67. "#{match.split('@').first}<a href=\"#{TagManager.instance.url_for(account)}\" class=\"h-card u-url p-nickname mention\">@<span>#{account.username}</span></a>"
  68. end
  69. end