Credo fixes: alias grouping/ordering
[akkoma] / lib / pleroma / web / federator / federator.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Federator do
6 use GenServer
7
8 alias Pleroma.{Activity, User}
9 alias Pleroma.Web.{WebFinger, Websub, Salmon}
10 alias Pleroma.Web.ActivityPub.{ActivityPub, Relay, Transmogrifier, Utils}
11 alias Pleroma.Web.Federator.RetryQueue
12 alias Pleroma.Web.OStatus
13
14 require Logger
15
16 @websub Application.get_env(:pleroma, :websub)
17 @ostatus Application.get_env(:pleroma, :ostatus)
18
19 def init(args) do
20 {:ok, args}
21 end
22
23 def start_link do
24 spawn(fn ->
25 # 1 minute
26 Process.sleep(1000 * 60)
27 enqueue(:refresh_subscriptions, nil)
28 end)
29
30 GenServer.start_link(
31 __MODULE__,
32 %{
33 in: {:sets.new(), []},
34 out: {:sets.new(), []}
35 },
36 name: __MODULE__
37 )
38 end
39
40 def handle(:refresh_subscriptions, _) do
41 Logger.debug("Federator running refresh subscriptions")
42 Websub.refresh_subscriptions()
43
44 spawn(fn ->
45 # 6 hours
46 Process.sleep(1000 * 60 * 60 * 6)
47 enqueue(:refresh_subscriptions, nil)
48 end)
49 end
50
51 def handle(:request_subscription, websub) do
52 Logger.debug("Refreshing #{websub.topic}")
53
54 with {:ok, websub} <- Websub.request_subscription(websub) do
55 Logger.debug("Successfully refreshed #{websub.topic}")
56 else
57 _e -> Logger.debug("Couldn't refresh #{websub.topic}")
58 end
59 end
60
61 def handle(:publish, activity) do
62 Logger.debug(fn -> "Running publish for #{activity.data["id"]}" end)
63
64 with actor when not is_nil(actor) <- User.get_cached_by_ap_id(activity.data["actor"]) do
65 {:ok, actor} = WebFinger.ensure_keys_present(actor)
66
67 if ActivityPub.is_public?(activity) do
68 if OStatus.is_representable?(activity) do
69 Logger.info(fn -> "Sending #{activity.data["id"]} out via WebSub" end)
70 Websub.publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
71
72 Logger.info(fn -> "Sending #{activity.data["id"]} out via Salmon" end)
73 Pleroma.Web.Salmon.publish(actor, activity)
74 end
75
76 if Keyword.get(Application.get_env(:pleroma, :instance), :allow_relay) do
77 Logger.info(fn -> "Relaying #{activity.data["id"]} out" end)
78 Relay.publish(activity)
79 end
80 end
81
82 Logger.info(fn -> "Sending #{activity.data["id"]} out via AP" end)
83 Pleroma.Web.ActivityPub.ActivityPub.publish(actor, activity)
84 end
85 end
86
87 def handle(:verify_websub, websub) do
88 Logger.debug(fn ->
89 "Running WebSub verification for #{websub.id} (#{websub.topic}, #{websub.callback})"
90 end)
91
92 @websub.verify(websub)
93 end
94
95 def handle(:incoming_doc, doc) do
96 Logger.info("Got document, trying to parse")
97 @ostatus.handle_incoming(doc)
98 end
99
100 def handle(:incoming_ap_doc, params) do
101 Logger.info("Handling incoming AP activity")
102
103 params = Utils.normalize_params(params)
104
105 # NOTE: we use the actor ID to do the containment, this is fine because an
106 # actor shouldn't be acting on objects outside their own AP server.
107 with {:ok, _user} <- ap_enabled_actor(params["actor"]),
108 nil <- Activity.normalize(params["id"]),
109 :ok <- Transmogrifier.contain_origin_from_id(params["actor"], params),
110 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
111 {:ok, activity}
112 else
113 %Activity{} ->
114 Logger.info("Already had #{params["id"]}")
115 :error
116
117 _e ->
118 # Just drop those for now
119 Logger.info("Unhandled activity")
120 Logger.info(Poison.encode!(params, pretty: 2))
121 :error
122 end
123 end
124
125 def handle(:publish_single_salmon, params) do
126 Salmon.send_to_user(params)
127 end
128
129 def handle(:publish_single_ap, params) do
130 case ActivityPub.publish_one(params) do
131 {:ok, _} ->
132 :ok
133
134 {:error, _} ->
135 RetryQueue.enqueue(params, ActivityPub)
136 end
137 end
138
139 def handle(
140 :publish_single_websub,
141 %{xml: _xml, topic: _topic, callback: _callback, secret: _secret} = params
142 ) do
143 case Websub.publish_one(params) do
144 {:ok, _} ->
145 :ok
146
147 {:error, _} ->
148 RetryQueue.enqueue(params, Websub)
149 end
150 end
151
152 def handle(type, _) do
153 Logger.debug(fn -> "Unknown task: #{type}" end)
154 {:error, "Don't know what to do with this"}
155 end
156
157 if Mix.env() == :test do
158 def enqueue(type, payload, _priority \\ 1) do
159 if Pleroma.Config.get([:instance, :federating]) do
160 handle(type, payload)
161 end
162 end
163 else
164 def enqueue(type, payload, priority \\ 1) do
165 if Pleroma.Config.get([:instance, :federating]) do
166 GenServer.cast(__MODULE__, {:enqueue, type, payload, priority})
167 end
168 end
169 end
170
171 def maybe_start_job(running_jobs, queue) do
172 if :sets.size(running_jobs) < Pleroma.Config.get([__MODULE__, :max_jobs]) && queue != [] do
173 {{type, payload}, queue} = queue_pop(queue)
174 {:ok, pid} = Task.start(fn -> handle(type, payload) end)
175 mref = Process.monitor(pid)
176 {:sets.add_element(mref, running_jobs), queue}
177 else
178 {running_jobs, queue}
179 end
180 end
181
182 def handle_cast({:enqueue, type, payload, _priority}, state)
183 when type in [:incoming_doc, :incoming_ap_doc] do
184 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
185 i_queue = enqueue_sorted(i_queue, {type, payload}, 1)
186 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
187 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
188 end
189
190 def handle_cast({:enqueue, type, payload, _priority}, state) do
191 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
192 o_queue = enqueue_sorted(o_queue, {type, payload}, 1)
193 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
194 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
195 end
196
197 def handle_cast(m, state) do
198 {:noreply, state}
199 end
200
201 def handle_info({:DOWN, ref, :process, _pid, _reason}, state) do
202 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
203 i_running_jobs = :sets.del_element(ref, i_running_jobs)
204 o_running_jobs = :sets.del_element(ref, o_running_jobs)
205 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
206 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
207
208 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
209 end
210
211 def enqueue_sorted(queue, element, priority) do
212 [%{item: element, priority: priority} | queue]
213 |> Enum.sort_by(fn %{priority: priority} -> priority end)
214 end
215
216 def queue_pop([%{item: element} | queue]) do
217 {element, queue}
218 end
219
220 def ap_enabled_actor(id) do
221 user = User.get_by_ap_id(id)
222
223 if User.ap_enabled?(user) do
224 {:ok, user}
225 else
226 ActivityPub.make_user_from_ap_id(id)
227 end
228 end
229 end