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.

84 lines
2.6 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. # Unapproved and unconfirmed accounts should not be mentionable
  31. next if mentioned_account&.local? && !(mentioned_account.user_confirmed? && mentioned_account.user_approved?)
  32. # If the account cannot be found or isn't the right protocol,
  33. # first try to resolve it
  34. if mention_undeliverable?(mentioned_account)
  35. begin
  36. mentioned_account = ResolveAccountService.new.call(Regexp.last_match(1))
  37. rescue Webfinger::Error, HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::UnexpectedResponseError
  38. mentioned_account = nil
  39. end
  40. end
  41. # If after resolving it still isn't found or isn't the right
  42. # protocol, then give up
  43. next match if mention_undeliverable?(mentioned_account) || mentioned_account&.suspended?
  44. mention = @previous_mentions.find { |x| x.account_id == mentioned_account.id }
  45. mention ||= mentioned_account.mentions.new(status: @status)
  46. @current_mentions << mention
  47. "@#{mentioned_account.acct}"
  48. end
  49. @status.save!
  50. end
  51. def assign_mentions!
  52. @current_mentions.each do |mention|
  53. mention.save if mention.new_record?
  54. end
  55. # If previous mentions are no longer contained in the text, convert them
  56. # to silent mentions, since withdrawing access from someone who already
  57. # received a notification might be more confusing
  58. removed_mentions = @previous_mentions - @current_mentions
  59. Mention.where(id: removed_mentions.map(&:id)).update_all(silent: true) unless removed_mentions.empty?
  60. end
  61. def mention_undeliverable?(mentioned_account)
  62. mentioned_account.nil? || (!mentioned_account.local? && !mentioned_account.activitypub?)
  63. end
  64. end