Merge remote-tracking branch 'origin' into validate-user-info
[akkoma] / lib / pleroma / web / federator / federator.ex
1 defmodule Pleroma.Web.Federator do
2 use GenServer
3 alias Pleroma.User
4 alias Pleroma.Activity
5 alias Pleroma.Web.{WebFinger, Websub}
6 alias Pleroma.Web.Federator.RetryQueue
7 alias Pleroma.Web.ActivityPub.ActivityPub
8 alias Pleroma.Web.ActivityPub.Relay
9 alias Pleroma.Web.ActivityPub.Transmogrifier
10 alias Pleroma.Web.ActivityPub.Utils
11 alias Pleroma.Web.OStatus
12 require Logger
13
14 @websub Application.get_env(:pleroma, :websub)
15 @ostatus Application.get_env(:pleroma, :ostatus)
16 @httpoison Application.get_env(:pleroma, :httpoison)
17 @max_jobs 20
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 * 1)
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_ap, params) do
126 case ActivityPub.publish_one(params) do
127 {:ok, _} ->
128 :ok
129
130 {:error, _} ->
131 RetryQueue.enqueue(params, ActivityPub)
132 end
133 end
134
135 def handle(
136 :publish_single_websub,
137 %{xml: xml, topic: topic, callback: callback, secret: secret} = params
138 ) do
139 case Websub.publish_one(params) do
140 {:ok, _} ->
141 :ok
142
143 {:error, _} ->
144 RetryQueue.enqueue(params, Websub)
145 end
146 end
147
148 def handle(type, _) do
149 Logger.debug(fn -> "Unknown task: #{type}" end)
150 {:error, "Don't know what to do with this"}
151 end
152
153 if Mix.env() == :test do
154 def enqueue(type, payload, priority \\ 1) do
155 if Pleroma.Config.get([:instance, :federating]) do
156 handle(type, payload)
157 end
158 end
159 else
160 def enqueue(type, payload, priority \\ 1) do
161 if Pleroma.Config.get([:instance, :federating]) do
162 GenServer.cast(__MODULE__, {:enqueue, type, payload, priority})
163 end
164 end
165 end
166
167 def maybe_start_job(running_jobs, queue) do
168 if :sets.size(running_jobs) < @max_jobs && queue != [] do
169 {{type, payload}, queue} = queue_pop(queue)
170 {:ok, pid} = Task.start(fn -> handle(type, payload) end)
171 mref = Process.monitor(pid)
172 {:sets.add_element(mref, running_jobs), queue}
173 else
174 {running_jobs, queue}
175 end
176 end
177
178 def handle_cast({:enqueue, type, payload, _priority}, state)
179 when type in [:incoming_doc, :incoming_ap_doc] do
180 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
181 i_queue = enqueue_sorted(i_queue, {type, payload}, 1)
182 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
183 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
184 end
185
186 def handle_cast({:enqueue, type, payload, _priority}, state) do
187 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
188 o_queue = enqueue_sorted(o_queue, {type, payload}, 1)
189 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
190 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
191 end
192
193 def handle_cast(m, state) do
194 IO.inspect("Unknown: #{inspect(m)}, #{inspect(state)}")
195 {:noreply, state}
196 end
197
198 def handle_info({:DOWN, ref, :process, _pid, _reason}, state) do
199 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
200 i_running_jobs = :sets.del_element(ref, i_running_jobs)
201 o_running_jobs = :sets.del_element(ref, o_running_jobs)
202 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
203 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
204
205 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
206 end
207
208 def enqueue_sorted(queue, element, priority) do
209 [%{item: element, priority: priority} | queue]
210 |> Enum.sort_by(fn %{priority: priority} -> priority end)
211 end
212
213 def queue_pop([%{item: element} | queue]) do
214 {element, queue}
215 end
216
217 def ap_enabled_actor(id) do
218 user = User.get_by_ap_id(id)
219
220 if User.ap_enabled?(user) do
221 {:ok, user}
222 else
223 ActivityPub.make_user_from_ap_id(id)
224 end
225 end
226 end