94e3979beb9ef17721575b5e3d19ee936665f012
[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 Logger.info(fn -> "Relaying #{activity.data["id"]} out" end)
75 Pleroma.Web.ActivityPub.Relay.publish(activity)
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 @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