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