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