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