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