<commit_before># frozen_string_literal: true

class ProcessFeedService < BaseService
  def call(body, account)
    xml = Nokogiri::XML(body)
    xml.encoding = 'utf-8'

    update_author(body, account)
    process_entries(xml, account)
  end

  private

  def update_author(body, account)
    RemoteProfileUpdateWorker.perform_async(account.id, body.force_encoding('UTF-8'), true)
  end

  def process_entries(xml, account)
    xml.xpath('//xmlns:entry', xmlns: TagManager::XMLNS).reverse_each.map { |entry| ProcessEntry.new.call(entry, account) }.compact
  end

  class ProcessEntry
    include AuthorExtractor

    def call(xml, account)
      @account = account
      @xml     = xml

      return if skip_unsupported_type?

      case verb
      when :post, :share
        return create_status
      when :delete
        return delete_status
      end
    rescue ActiveRecord::RecordInvalid => e
      Rails.logger.debug "Nothing was saved for #{id} because: #{e}"
      nil
    end

    private

    def create_status
      if redis.exists("delete_upon_arrival:#{id}")
        Rails.logger.debug "Delete for status #{id} was queued, ignoring"
        return
      end

      status, just_created = nil

      Rails.logger.debug "Creating remote status #{id}"

      if verb == :share
        original_status = shared_status_from_xml(@xml.at_xpath('.//activity:object', activity: TagManager::AS_XMLNS))
        return nil if original_status.nil?
      end

      ApplicationRecord.transaction do
        status, just_created = status_from_xml(@xml)

        return if status.nil?
        return status unless just_created

        if verb == :share
          status.reblog = original_status.reblog? ? original_status.reblog : original_status
        end

        status.save!
      end

      if thread?(@xml) && status.thread.nil?
        Rails.logger.debug "Trying to attach #{status.id} (#{id(@xml)}) to #{thread(@xml).first}"
        ThreadResolveWorker.perform_async(status.id, thread(@xml).second)
      end

      notify_about_mentions!(status) unless status.reblog?
      notify_about_reblog!(status) if status.reblog? && status.reblog.account.local?

      Rails.logger.debug "Queuing remote status #{status.id} (#{id}) for distribution"

      LinkCrawlWorker.perform_async(status.id) unless status.spoiler_text?
      DistributionWorker.perform_async(status.id)

      status
    end

    def notify_about_mentions!(status)
      status.mentions.includes(:account).each do |mention|
        mentioned_account = mention.account
        next unless mentioned_account.local?
        NotifyService.new.call(mentioned_account, mention)
      end
    end

    def notify_about_reblog!(status)
      NotifyService.new.call(status.reblog.account, status)
    end

    def delete_status
      Rails.logger.debug "Deleting remote status #{id}"
      status = Status.find_by(uri: id)

      if status.nil?
        redis.setex("delete_upon_arrival:#{id}", 6 * 3_600, id)
      else
        RemoveStatusService.new.call(status)
      end

      nil
    end

    def skip_unsupported_type?
      !([:post, :share, :delete].include?(verb) && [:activity, :note, :comment].include?(type))
    end

    def shared_status_from_xml(entry)
      status = find_status(id(entry))

      return status unless status.nil?

      FetchRemoteStatusService.new.call(url(entry))
    end

    def status_from_xml(entry)
      # Return early if status already exists in db
      status = find_status(id(entry))

      return [status, false] unless status.nil?

      # If status embeds an author, find that author
      # If that author cannot be found, don't record the status (do not misattribute)
      if account?(entry)
        begin
          account = author_from_xml(entry)
          return [nil, false] if account.nil?
        rescue Goldfinger::Error
          return [nil, false]
        end
      else
        account = @account
      end

      return [nil, false] if account.suspended?

      status = Status.create!(
        uri: id(entry),
        url: url(entry),
        account: account,
        text: content(entry),
        spoiler_text: content_warning(entry),
        created_at: published(entry),
        reply: thread?(entry),
        language: content_language(entry),
        visibility: visibility_scope(entry),<commit_msg>Fix feed author not being enforced in ProcessFeedService (#4092)<commit_after># frozen_string_literal: true

class ProcessFeedService < BaseService
  def call(body, account)
    xml = Nokogiri::XML(body)
    xml.encoding = 'utf-8'

    update_author(body, account)
    process_entries(xml, account)
  end

  private

  def update_author(body, account)
    RemoteProfileUpdateWorker.perform_async(account.id, body.force_encoding('UTF-8'), true)
  end

  def process_entries(xml, account)
    xml.xpath('//xmlns:entry', xmlns: TagManager::XMLNS).reverse_each.map { |entry| ProcessEntry.new.call(entry, account) }.compact
  end

  class ProcessEntry
    include AuthorExtractor

    def call(xml, account)
      @account = account
      @xml     = xml

      return if skip_unsupported_type?

      case verb
      when :post, :share
        return create_status
      when :delete
        return delete_status
      end
    rescue ActiveRecord::RecordInvalid => e
      Rails.logger.debug "Nothing was saved for #{id} because: #{e}"
      nil
    end

    private

    def create_status
      if redis.exists("delete_upon_arrival:#{@account.id}:#{id}")
        Rails.logger.debug "Delete for status #{id} was queued, ignoring"
        return
      end

      status, just_created = nil

      Rails.logger.debug "Creating remote status #{id}"

      if verb == :share
        original_status = shared_status_from_xml(@xml.at_xpath('.//activity:object', activity: TagManager::AS_XMLNS))
        return nil if original_status.nil?
      end

      ApplicationRecord.transaction do
        status, just_created = status_from_xml(@xml)

        return if status.nil?
        return status unless just_created

        if verb == :share
          status.reblog = original_status.reblog? ? original_status.reblog : original_status
        end

        status.save!
      end

      if thread?(@xml) && status.thread.nil?
        Rails.logger.debug "Trying to attach #{status.id} (#{id(@xml)}) to #{thread(@xml).first}"
        ThreadResolveWorker.perform_async(status.id, thread(@xml).second)
      end

      notify_about_mentions!(status) unless status.reblog?
      notify_about_reblog!(status) if status.reblog? && status.reblog.account.local?

      Rails.logger.debug "Queuing remote status #{status.id} (#{id}) for distribution"

      LinkCrawlWorker.perform_async(status.id) unless status.spoiler_text?
      DistributionWorker.perform_async(status.id)

      status
    end

    def notify_about_mentions!(status)
      status.mentions.includes(:account).each do |mention|
        mentioned_account = mention.account
        next unless mentioned_account.local?
        NotifyService.new.call(mentioned_account, mention)
      end
    end

    def notify_about_reblog!(status)
      NotifyService.new.call(status.reblog.account, status)
    end

    def delete_status
      Rails.logger.debug "Deleting remote status #{id}"
      status = Status.find_by(uri: id, account: @account)

      if status.nil?
        redis.setex("delete_upon_arrival:#{@account.id}:#{id}", 6 * 3_600, id)
      else
        RemoveStatusService.new.call(status)
      end
    end

    def skip_unsupported_type?
      !([:post, :share, :delete].include?(verb) && [:activity, :note, :comment].include?(type))
    end

    def shared_status_from_xml(entry)
      status = find_status(id(entry))

      return status unless status.nil?

      FetchRemoteStatusService.new.call(url(entry))
    end

    def status_from_xml(entry)
      # Return early if status already exists in db
      status = find_status(id(entry))

      return [status, false] unless status.nil?

      account = @account

      return [nil, false] if account.suspended?

      status = Status.create!(
        uri: id(entry),
        url: url(entry),
        account: account,
        text: content(entry),
        spoiler_text: content_warning(entry),
        created_at: published(entry),
        reply: thread?(entry),
        language: content_language(entry),
        visibility: visibility_scope(entry),
{'fraction_non_alphanumeric': 0.1011677788369876, 'fraction_numerical': 0.0021448999046711154, 'mean_word_length': 2.8359232175502744, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 41}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3851405', 'n_tokens_mistral': 2522, 'n_tokens_neox': 2427, 'n_words': 590}