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