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