078f3ec119baa2206c83d426e88b0fdb38225db8
[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 @instance Application.get_env(:pleroma, :instance)
16 @federating Keyword.get(@instance, :federating)
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 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
74 if Mix.env() != :test do
75 Logger.info(fn -> "Relaying #{activity.data["id"]} out" end)
76 Pleroma.Web.ActivityPub.Relay.publish(activity)
77 end
78 end
79
80 Logger.info(fn -> "Sending #{activity.data["id"]} out via AP" end)
81 Pleroma.Web.ActivityPub.ActivityPub.publish(actor, activity)
82 end
83 end
84
85 def handle(:verify_websub, websub) do
86 Logger.debug(fn ->
87 "Running WebSub verification for #{websub.id} (#{websub.topic}, #{websub.callback})"
88 end)
89
90 @websub.verify(websub)
91 end
92
93 def handle(:incoming_doc, doc) do
94 Logger.info("Got document, trying to parse")
95 @ostatus.handle_incoming(doc)
96 end
97
98 def handle(:incoming_ap_doc, params) do
99 Logger.info("Handling incoming AP activity")
100
101 params = Utils.normalize_params(params)
102
103 with {:ok, _user} <- ap_enabled_actor(params["actor"]),
104 nil <- Activity.normalize(params["id"]),
105 {:ok, _activity} <- Transmogrifier.handle_incoming(params) do
106 else
107 %Activity{} ->
108 Logger.info("Already had #{params["id"]}")
109
110 _e ->
111 # Just drop those for now
112 Logger.info("Unhandled activity")
113 Logger.info(Poison.encode!(params, pretty: 2))
114 end
115 end
116
117 def handle(:publish_single_ap, params) do
118 ActivityPub.publish_one(params)
119 end
120
121 def handle(:publish_single_websub, %{xml: xml, topic: topic, callback: callback, secret: secret}) do
122 signature = @websub.sign(secret || "", xml)
123 Logger.debug(fn -> "Pushing #{topic} to #{callback}" end)
124
125 with {:ok, %{status_code: code}} <-
126 @httpoison.post(
127 callback,
128 xml,
129 [
130 {"Content-Type", "application/atom+xml"},
131 {"X-Hub-Signature", "sha1=#{signature}"}
132 ],
133 timeout: 10000,
134 recv_timeout: 20000,
135 hackney: [pool: :default]
136 ) do
137 Logger.debug(fn -> "Pushed to #{callback}, code #{code}" end)
138 else
139 e ->
140 Logger.debug(fn -> "Couldn't push to #{callback}, #{inspect(e)}" end)
141 end
142 end
143
144 def handle(type, _) do
145 Logger.debug(fn -> "Unknown task: #{type}" end)
146 {:error, "Don't know what to do with this"}
147 end
148
149 def enqueue(type, payload, priority \\ 1) do
150 if @federating do
151 if Mix.env() == :test do
152 handle(type, payload)
153 else
154 GenServer.cast(__MODULE__, {:enqueue, type, payload, priority})
155 end
156 end
157 end
158
159 def maybe_start_job(running_jobs, queue) do
160 if :sets.size(running_jobs) < @max_jobs && queue != [] do
161 {{type, payload}, queue} = queue_pop(queue)
162 {:ok, pid} = Task.start(fn -> handle(type, payload) end)
163 mref = Process.monitor(pid)
164 {:sets.add_element(mref, running_jobs), queue}
165 else
166 {running_jobs, queue}
167 end
168 end
169
170 def handle_cast({:enqueue, type, payload, _priority}, state)
171 when type in [:incoming_doc, :incoming_ap_doc] do
172 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
173 i_queue = enqueue_sorted(i_queue, {type, payload}, 1)
174 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
175 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
176 end
177
178 def handle_cast({:enqueue, type, payload, _priority}, state) do
179 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
180 o_queue = enqueue_sorted(o_queue, {type, payload}, 1)
181 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
182 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
183 end
184
185 def handle_cast(m, state) do
186 IO.inspect("Unknown: #{inspect(m)}, #{inspect(state)}")
187 {:noreply, state}
188 end
189
190 def handle_info({:DOWN, ref, :process, _pid, _reason}, state) do
191 %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
192 i_running_jobs = :sets.del_element(ref, i_running_jobs)
193 o_running_jobs = :sets.del_element(ref, o_running_jobs)
194 {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
195 {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
196
197 {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
198 end
199
200 def enqueue_sorted(queue, element, priority) do
201 [%{item: element, priority: priority} | queue]
202 |> Enum.sort_by(fn %{priority: priority} -> priority end)
203 end
204
205 def queue_pop([%{item: element} | queue]) do
206 {element, queue}
207 end
208
209 def ap_enabled_actor(id) do
210 user = User.get_by_ap_id(id)
211
212 if User.ap_enabled?(user) do
213 {:ok, user}
214 else
215 ActivityPub.make_user_from_ap_id(id)
216 end
217 end
218 end