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.

81 lines
2.4 KiB

  1. # frozen_string_literal: true
  2. class ProcessMentionsService < BaseService
  3. include Payloadable
  4. # Scan status for mentions and fetch remote mentioned users, create
  5. # local mention pointers, send Salmon notifications to mentioned
  6. # remote users
  7. # @param [Status] status
  8. def call(status)
  9. @status = status
  10. return unless @status.local?
  11. @previous_mentions = @status.active_mentions.includes(:account).to_a
  12. @current_mentions = []
  13. Status.transaction do
  14. scan_text!
  15. assign_mentions!
  16. end
  17. end
  18. private
  19. def scan_text!
  20. @status.text = @status.text.gsub(Account::MENTION_RE) do |match|
  21. username, domain = Regexp.last_match(1).split('@')
  22. domain = begin
  23. if TagManager.instance.local_domain?(domain)
  24. nil
  25. else
  26. TagManager.instance.normalize_domain(domain)
  27. end
  28. end
  29. mentioned_account = Account.find_remote(username, domain)
  30. # If the account cannot be found or isn't the right protocol,
  31. # first try to resolve it
  32. if mention_undeliverable?(mentioned_account)
  33. begin
  34. mentioned_account = ResolveAccountService.new.call(Regexp.last_match(1))
  35. rescue Webfinger::Error, HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::UnexpectedResponseError
  36. mentioned_account = nil
  37. end
  38. end
  39. # If after resolving it still isn't found or isn't the right
  40. # protocol, then give up
  41. next match if mention_undeliverable?(mentioned_account) || mentioned_account&.suspended?
  42. mention = @previous_mentions.find { |x| x.account_id == mentioned_account.id }
  43. mention ||= mentioned_account.mentions.new(status: @status)
  44. @current_mentions << mention
  45. "@#{mentioned_account.acct}"
  46. end
  47. @status.save!
  48. end
  49. def assign_mentions!
  50. @current_mentions.each do |mention|
  51. mention.save if mention.new_record?
  52. end
  53. # If previous mentions are no longer contained in the text, convert them
  54. # to silent mentions, since withdrawing access from someone who already
  55. # received a notification might be more confusing
  56. removed_mentions = @previous_mentions - @current_mentions
  57. Mention.where(id: removed_mentions.map(&:id)).update_all(silent: true) unless removed_mentions.empty?
  58. end
  59. def mention_undeliverable?(mentioned_account)
  60. mentioned_account.nil? || (!mentioned_account.local? && !mentioned_account.activitypub?)
  61. end
  62. end