about summary refs log tree commit diff
path: root/app/services/process_interaction_service.rb
blob: b91cfcf66c70dd5adedf74732921104a55fc1063 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class ProcessInteractionService
  include ApplicationHelper

  def call(envelope, target_account)
    body = salmon.unpack(envelope)
    xml  = Nokogiri::XML(body)

    return unless involves_target_account?(xml, target_account) && contains_author?(xml)

    username = xml.at_xpath('/xmlns:entry/xmlns:author/xmlns:name').content
    url      = xml.at_xpath('/xmlns:entry/xmlns:author/xmlns:uri').content
    domain   = Addressable::URI.parse(url).host
    account  = Account.find_by(username: username, domain: domain)

    if account.nil?
      account = follow_remote_account_service.("acct:#{username}@#{domain}")
      return if account.nil?
    end

    if salmon.verify(envelope, account.keypair)
      case get_verb(xml)
      when :follow
        account.follow!(target_account)
      when :unfollow
        account.unfollow!(target_account)
      when :favorite
        # todo: a favourite
      when :post
        # todo: a reply
      when :share
        # todo: a reblog
      end
    end
  end

  private

  def contains_author?(xml)
    !(xml.at_xpath('/xmlns:entry/xmlns:author/xmlns:name').nil? || xml.at_xpath('/xmlns:entry/xmlns:author/xmlns:uri').nil?)
  end

  def involves_target_account?(xml, account)
    targeted_at_account?(xml, account) || mentions_account?(xml, account)
  end

  def targeted_at_account?(xml, account)
    target_id = xml.at_xpath('/xmlns:entry/activity:object/xmlns:id')
    !target_id.nil? && target_id.content == profile_url(name: account.username)
  end

  def mentions_account?(xml, account)
    xml.xpath('/xmlns:entry/xmlns:link[@rel="mentioned"]').each do |mention_link|
      return true if mention_link.attribute('ref') == profile_url(name: account.username)
    end

    false
  end

  def get_verb(xml)
    verb = xml.at_xpath('//activity:verb').content.gsub 'http://activitystrea.ms/schema/1.0/', ''
    verb.to_sym
  end

  def salmon
    OStatus2::Salmon.new
  end

  def follow_remote_account_service
    FollowRemoteAccountService.new
  end
end