Various runtime configuration fixes
[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.ActivityPub.ActivityPub
7 alias Pleroma.Web.ActivityPub.Relay
8 alias Pleroma.Web.ActivityPub.Transmogrifier
9 alias Pleroma.Web.ActivityPub.Utils
10 alias Pleroma.Web.OStatus
11 require Logger
12
13 @websub Application.get_env(:pleroma, :websub)
14 @ostatus Application.get_env(:pleroma, :ostatus)
15 @httpoison Application.get_env(:pleroma, :httpoison)
16 @max_jobs 20
17
18 def init(args) do
19 {:ok, args}
20 end
21
22 def start_link do
23 spawn(fn ->
24 # 1 minute
25 Process.sleep(1000 * 60 * 1)
26 enqueue(:refresh_subscriptions, nil)
27 end)
28
29 GenServer.start_link(
30 __MODULE__,
31 %{
32 in: {:sets.new(), []},
33 out: {:sets.new(), []}
34 },
35 name: __MODULE__
36 )
37 end
38
39 def handle(:refresh_subscriptions, _) do
40 Logger.debug("Federator running refresh subscriptions")
41 Websub.refresh_subscriptions()
42
43 spawn(fn ->
44 # 6 hours
45 Process.sleep(1000 * 60 * 60 * 6)
46 enqueue(:refresh_subscriptions, nil)
47 end)
48 end
49
50 def handle(:request_subscription, websub) do
51 Logger.debug("Refreshing #{websub.topic}")
52
53 with {:ok, websub} <- Websub.request_subscription(websub) do
54 Logger.debug("Successfully refreshed #{websub.topic}")
55 else
56 _e -> Logger.debug("Couldn't refresh #{websub.topic}")
57 end
58 end
59
60 def handle(:publish, activity) do
61 Logger.debug(fn -> "Running publish for #{activity.data["id"]}" end)
62
63 with actor when not is_nil(actor) <- User.get_cached_by_ap_id(activity.data["actor"]) do
64 {:ok, actor} = WebFinger.ensure_keys_present(actor)
65
66 if ActivityPub.is_public?(activity) do
67 if OStatus.is_representable?(activity) do
68 Logger.info(fn -> "Sending #{activity.data["id"]} out via WebSub" end)
69 Websub.publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
70
71 Logger.info(fn -> "Sending #{activity.data["id"]} out via Salmon" end)
72 Pleroma.Web.Salmon.publish(actor, activity)
73 end
74
75 if Keyword.get(Application.get_env(:pleroma, :instance), :allow_relay) do
76 Logger.info(fn -> "Relaying #{activity.data["id"]} out" end)
77 Relay.publish(activity)
78 end
79 end
80
81 Logger.info(fn -> "Sending #{activity.data["id"]} out via AP" end)
82 Pleroma.Web.ActivityPub.ActivityPub.publish(actor, activity)
83 end
84 end
85
86 def handle(:verify_websub, websub) do
87 Logger.debug(fn ->
88 "Running WebSub verification for #{websub.id} (#{websub.topic}, #{websub.callback})"
89 end)
90
91 @websub.verify(websub)
92 end
93
94 def handle(:incoming_doc, doc) do
95 Logger.info("Got document, trying to parse")
96 @ostatus.handle_incoming(doc)
97 end
98
99 def handle(:incoming_ap_doc, params) do
100 Logger.info("Handling incoming AP activity")
101
102 params = Utils.normalize_params(params)
103
104 # NOTE: we use the actor ID to do the containment, this is fine because an
105 # actor shouldn't be acting on objects outside their own AP server.
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 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
110 {:ok, activity}
111 else
112 %Activity{} ->
113 Logger.info("Already had #{params["id"]}")
114 :error
115
116 _e ->
117 # Just drop those for now
118 Logger.info("Unhandled activity")
119 Logger.info(Poison.encode!(params, pretty: 2))
120 :error
121 end
122 end
123
124 def handle(:publish_single_ap, params) do
125 ActivityPub.publish_one(params)
126 end
127
128 def handle(:publish_single_websub, %{xml: xml, topic: topic, callback: callback, secret: secret}) do
129 signature = @websub.sign(secret || "", xml)
130 Logger.debug(fn -> "Pushing #{topic} to #{callback}" end)
131
132 with {:ok, %{status_code: code}} <-
133 @httpoison.post(
134 callback,
135 xml,
136 [
137 {"Content-Type", "application/atom+xml"},
138 {"X-Hub-Signature", "sha1=#{signature}"}
139 ],
140 timeout: 10000,
141 recv_timeout: 20000,
142 hackney: [pool: :default]
143 ) do
144 Logger.debug(fn -> "Pushed to #{callback}, code #{code}" end)
145 else
146 e ->
147 Logger.debug(fn -> "Couldn't push to #{callback}, #{inspect(e)}" end)
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