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