federator.ex 6.66 KB
Newer Older
1
defmodule Pleroma.Web.Federator do
lain's avatar
lain committed
2
  use GenServer
3
  alias Pleroma.User
lain's avatar
lain committed
4
  alias Pleroma.Activity
lain's avatar
lain committed
5
  alias Pleroma.Web.{WebFinger, Websub}
eal's avatar
eal committed
6
  alias Pleroma.Web.Federator.RetryQueue
7
  alias Pleroma.Web.ActivityPub.ActivityPub
8
  alias Pleroma.Web.ActivityPub.Relay
lain's avatar
lain committed
9
  alias Pleroma.Web.ActivityPub.Transmogrifier
10
  alias Pleroma.Web.ActivityPub.Utils
11
  alias Pleroma.Web.OStatus
12
13
  require Logger

lain's avatar
lain committed
14
  @websub Application.get_env(:pleroma, :websub)
15
  @ostatus Application.get_env(:pleroma, :ostatus)
lain's avatar
lain committed
16
  @max_jobs 20
lain's avatar
lain committed
17

lain's avatar
lain committed
18
19
20
21
  def init(args) do
    {:ok, args}
  end

lain's avatar
lain committed
22
  def start_link do
lain's avatar
lain committed
23
    spawn(fn ->
lain's avatar
lain committed
24
25
      # 1 minute
      Process.sleep(1000 * 60 * 1)
lain's avatar
lain committed
26
27
      enqueue(:refresh_subscriptions, nil)
    end)
lain's avatar
lain committed
28
29
30
31
32
33
34
35
36

    GenServer.start_link(
      __MODULE__,
      %{
        in: {:sets.new(), []},
        out: {:sets.new(), []}
      },
      name: __MODULE__
    )
lain's avatar
lain committed
37
  end
38

lain's avatar
lain committed
39
40
41
  def handle(:refresh_subscriptions, _) do
    Logger.debug("Federator running refresh subscriptions")
    Websub.refresh_subscriptions()
lain's avatar
lain committed
42

lain's avatar
lain committed
43
    spawn(fn ->
lain's avatar
lain committed
44
45
      # 6 hours
      Process.sleep(1000 * 60 * 60 * 6)
lain's avatar
lain committed
46
47
48
49
      enqueue(:refresh_subscriptions, nil)
    end)
  end

lain's avatar
lain committed
50
51
  def handle(:request_subscription, websub) do
    Logger.debug("Refreshing #{websub.topic}")
lain's avatar
lain committed
52
53

    with {:ok, websub} <- Websub.request_subscription(websub) do
lain's avatar
lain committed
54
55
56
57
58
59
      Logger.debug("Successfully refreshed #{websub.topic}")
    else
      _e -> Logger.debug("Couldn't refresh #{websub.topic}")
    end
  end

60
  def handle(:publish, activity) do
lain's avatar
lain committed
61
    Logger.debug(fn -> "Running publish for #{activity.data["id"]}" end)
lain's avatar
lain committed
62

63
    with actor when not is_nil(actor) <- User.get_cached_by_ap_id(activity.data["actor"]) do
lain's avatar
lain committed
64
      {:ok, actor} = WebFinger.ensure_keys_present(actor)
lain's avatar
lain committed
65

66
      if ActivityPub.is_public?(activity) do
67
68
69
        if OStatus.is_representable?(activity) do
          Logger.info(fn -> "Sending #{activity.data["id"]} out via WebSub" end)
          Websub.publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
70

71
72
73
          Logger.info(fn -> "Sending #{activity.data["id"]} out via Salmon" end)
          Pleroma.Web.Salmon.publish(actor, activity)
        end
74

75
        if Keyword.get(Application.get_env(:pleroma, :instance), :allow_relay) do
kaniini's avatar
kaniini committed
76
          Logger.info(fn -> "Relaying #{activity.data["id"]} out" end)
77
          Relay.publish(activity)
kaniini's avatar
kaniini committed
78
        end
79
      end
lain's avatar
lain committed
80
81

      Logger.info(fn -> "Sending #{activity.data["id"]} out via AP" end)
82
      Pleroma.Web.ActivityPub.ActivityPub.publish(actor, activity)
83
84
85
86
    end
  end

  def handle(:verify_websub, websub) do
lain's avatar
lain committed
87
88
89
90
    Logger.debug(fn ->
      "Running WebSub verification for #{websub.id} (#{websub.topic}, #{websub.callback})"
    end)

lain's avatar
lain committed
91
    @websub.verify(websub)
92
93
  end

94
  def handle(:incoming_doc, doc) do
95
    Logger.info("Got document, trying to parse")
96
97
98
    @ostatus.handle_incoming(doc)
  end

lain's avatar
lain committed
99
  def handle(:incoming_ap_doc, params) do
feld's avatar
feld committed
100
    Logger.info("Handling incoming AP activity")
lain's avatar
lain committed
101

102
103
    params = Utils.normalize_params(params)

104
105
    # NOTE: we use the actor ID to do the containment, this is fine because an
    # actor shouldn't be acting on objects outside their own AP server.
lain's avatar
lain committed
106
    with {:ok, _user} <- ap_enabled_actor(params["actor"]),
107
         nil <- Activity.normalize(params["id"]),
108
         :ok <- Transmogrifier.contain_origin_from_id(params["actor"], params),
109
110
         {:ok, activity} <- Transmogrifier.handle_incoming(params) do
      {:ok, activity}
lain's avatar
lain committed
111
112
113
    else
      %Activity{} ->
        Logger.info("Already had #{params["id"]}")
114
        :error
lain's avatar
lain committed
115

feld's avatar
feld committed
116
      _e ->
lain's avatar
lain committed
117
118
        # Just drop those for now
        Logger.info("Unhandled activity")
lain's avatar
lain committed
119
        Logger.info(Poison.encode!(params, pretty: 2))
120
        :error
lain's avatar
lain committed
121
122
123
    end
  end

lain's avatar
lain committed
124
  def handle(:publish_single_ap, params) do
eal's avatar
eal committed
125
126
127
128
129
    case ActivityPub.publish_one(params) do
      {:ok, _} ->
        :ok

      {:error, _} ->
eal's avatar
eal committed
130
        RetryQueue.enqueue(params, ActivityPub)
eal's avatar
eal committed
131
    end
lain's avatar
lain committed
132
133
  end

eal's avatar
eal committed
134
135
  def handle(
        :publish_single_websub,
Maksim's avatar
Maksim committed
136
        %{xml: _xml, topic: _topic, callback: _callback, secret: _secret} = params
eal's avatar
eal committed
137
138
139
140
141
142
      ) do
    case Websub.publish_one(params) do
      {:ok, _} ->
        :ok

      {:error, _} ->
eal's avatar
eal committed
143
        RetryQueue.enqueue(params, Websub)
lain's avatar
lain committed
144
145
146
    end
  end

Thog's avatar
Thog committed
147
  def handle(type, _) do
lain's avatar
lain committed
148
    Logger.debug(fn -> "Unknown task: #{type}" end)
feld's avatar
feld committed
149
    {:error, "Don't know what to do with this"}
150
151
  end

href's avatar
href committed
152
153
154
  if Mix.env() == :test do
    def enqueue(type, payload, priority \\ 1) do
      if Pleroma.Config.get([:instance, :federating]) do
lain's avatar
lain committed
155
        handle(type, payload)
href's avatar
href committed
156
157
158
159
160
      end
    end
  else
    def enqueue(type, payload, priority \\ 1) do
      if Pleroma.Config.get([:instance, :federating]) do
lain's avatar
lain committed
161
162
        GenServer.cast(__MODULE__, {:enqueue, type, payload, priority})
      end
lain's avatar
lain committed
163
164
165
166
    end
  end

  def maybe_start_job(running_jobs, queue) do
lain's avatar
lain committed
167
    if :sets.size(running_jobs) < @max_jobs && queue != [] do
lain's avatar
lain committed
168
      {{type, payload}, queue} = queue_pop(queue)
lain's avatar
lain committed
169
170
171
172
173
      {:ok, pid} = Task.start(fn -> handle(type, payload) end)
      mref = Process.monitor(pid)
      {:sets.add_element(mref, running_jobs), queue}
    else
      {running_jobs, queue}
174
175
    end
  end
lain's avatar
lain committed
176

feld's avatar
feld committed
177
  def handle_cast({:enqueue, type, payload, _priority}, state)
lain's avatar
lain committed
178
      when type in [:incoming_doc, :incoming_ap_doc] do
179
    %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
lain's avatar
lain committed
180
    i_queue = enqueue_sorted(i_queue, {type, payload}, 1)
181
182
183
184
    {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
    {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
  end

feld's avatar
feld committed
185
  def handle_cast({:enqueue, type, payload, _priority}, state) do
186
    %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
lain's avatar
lain committed
187
    o_queue = enqueue_sorted(o_queue, {type, payload}, 1)
188
189
    {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
    {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
lain's avatar
lain committed
190
191
  end

Thog's avatar
Thog committed
192
193
194
195
196
  def handle_cast(m, state) do
    IO.inspect("Unknown: #{inspect(m)}, #{inspect(state)}")
    {:noreply, state}
  end

197
198
199
200
201
202
203
204
  def handle_info({:DOWN, ref, :process, _pid, _reason}, state) do
    %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
    i_running_jobs = :sets.del_element(ref, i_running_jobs)
    o_running_jobs = :sets.del_element(ref, o_running_jobs)
    {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
    {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)

    {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
lain's avatar
lain committed
205
  end
lain's avatar
lain committed
206
207
208

  def enqueue_sorted(queue, element, priority) do
    [%{item: element, priority: priority} | queue]
lain's avatar
lain committed
209
    |> Enum.sort_by(fn %{priority: priority} -> priority end)
lain's avatar
lain committed
210
211
212
213
214
  end

  def queue_pop([%{item: element} | queue]) do
    {element, queue}
  end
lain's avatar
lain committed
215
216
217

  def ap_enabled_actor(id) do
    user = User.get_by_ap_id(id)
lain's avatar
lain committed
218

lain's avatar
lain committed
219
220
221
222
223
224
    if User.ap_enabled?(user) do
      {:ok, user}
    else
      ActivityPub.make_user_from_ap_id(id)
    end
  end
225
end