Credo fixes: alias grouping/ordering
[akkoma] / lib / pleroma / web / websub / websub.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Websub do
6 alias Ecto.Changeset
7 alias Pleroma.{Instances, Repo}
8 alias Pleroma.Web.Websub.{WebsubServerSubscription, WebsubClientSubscription}
9 alias Pleroma.Web.OStatus.FeedRepresenter
10 alias Pleroma.Web.{XML, Endpoint, OStatus}
11 alias Pleroma.Web.Router.Helpers
12 require Logger
13
14 import Ecto.Query
15
16 @httpoison Application.get_env(:pleroma, :httpoison)
17
18 def verify(subscription, getter \\ &@httpoison.get/3) do
19 challenge = Base.encode16(:crypto.strong_rand_bytes(8))
20 lease_seconds = NaiveDateTime.diff(subscription.valid_until, subscription.updated_at)
21 lease_seconds = lease_seconds |> to_string
22
23 params = %{
24 "hub.challenge": challenge,
25 "hub.lease_seconds": lease_seconds,
26 "hub.topic": subscription.topic,
27 "hub.mode": "subscribe"
28 }
29
30 url = hd(String.split(subscription.callback, "?"))
31 query = URI.parse(subscription.callback).query || ""
32 params = Map.merge(params, URI.decode_query(query))
33
34 with {:ok, response} <- getter.(url, [], params: params),
35 ^challenge <- response.body do
36 changeset = Changeset.change(subscription, %{state: "active"})
37 Repo.update(changeset)
38 else
39 e ->
40 Logger.debug("Couldn't verify subscription")
41 Logger.debug(inspect(e))
42 {:error, subscription}
43 end
44 end
45
46 @supported_activities [
47 "Create",
48 "Follow",
49 "Like",
50 "Announce",
51 "Undo",
52 "Delete"
53 ]
54 def publish(topic, user, %{data: %{"type" => type}} = activity)
55 when type in @supported_activities do
56 response =
57 user
58 |> FeedRepresenter.to_simple_form([activity], [user])
59 |> :xmerl.export_simple(:xmerl_xml)
60 |> to_string
61
62 query =
63 from(
64 sub in WebsubServerSubscription,
65 where: sub.topic == ^topic and sub.state == "active",
66 where: fragment("? > (NOW() at time zone 'UTC')", sub.valid_until)
67 )
68
69 subscriptions = Repo.all(query)
70
71 callbacks = Enum.map(subscriptions, & &1.callback)
72 reachable_callbacks_metadata = Instances.filter_reachable(callbacks)
73 reachable_callbacks = Map.keys(reachable_callbacks_metadata)
74
75 subscriptions
76 |> Enum.filter(&(&1.callback in reachable_callbacks))
77 |> Enum.each(fn sub ->
78 data = %{
79 xml: response,
80 topic: topic,
81 callback: sub.callback,
82 secret: sub.secret,
83 unreachable_since: reachable_callbacks_metadata[sub.callback]
84 }
85
86 Pleroma.Web.Federator.enqueue(:publish_single_websub, data)
87 end)
88 end
89
90 def publish(_, _, _), do: ""
91
92 def sign(secret, doc) do
93 :crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16() |> String.downcase()
94 end
95
96 def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
97 with {:ok, topic} <- valid_topic(params, user),
98 {:ok, lease_time} <- lease_time(params),
99 secret <- params["hub.secret"],
100 callback <- params["hub.callback"] do
101 subscription = get_subscription(topic, callback)
102
103 data = %{
104 state: subscription.state || "requested",
105 topic: topic,
106 secret: secret,
107 callback: callback
108 }
109
110 change = Changeset.change(subscription, data)
111 websub = Repo.insert_or_update!(change)
112
113 change =
114 Changeset.change(websub, %{valid_until: NaiveDateTime.add(websub.updated_at, lease_time)})
115
116 websub = Repo.update!(change)
117
118 Pleroma.Web.Federator.enqueue(:verify_websub, websub)
119
120 {:ok, websub}
121 else
122 {:error, reason} ->
123 Logger.debug("Couldn't create subscription")
124 Logger.debug(inspect(reason))
125
126 {:error, reason}
127 end
128 end
129
130 def incoming_subscription_request(user, params) do
131 Logger.info("Unhandled WebSub request for #{user.nickname}: #{inspect(params)}")
132
133 {:error, "Invalid WebSub request"}
134 end
135
136 defp get_subscription(topic, callback) do
137 Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) ||
138 %WebsubServerSubscription{}
139 end
140
141 # Temp hack for mastodon.
142 defp lease_time(%{"hub.lease_seconds" => ""}) do
143 # three days
144 {:ok, 60 * 60 * 24 * 3}
145 end
146
147 defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
148 {:ok, String.to_integer(lease_seconds)}
149 end
150
151 defp lease_time(_) do
152 # three days
153 {:ok, 60 * 60 * 24 * 3}
154 end
155
156 defp valid_topic(%{"hub.topic" => topic}, user) do
157 if topic == OStatus.feed_path(user) do
158 {:ok, OStatus.feed_path(user)}
159 else
160 {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
161 end
162 end
163
164 def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
165 topic = subscribed.info.topic
166 # FIXME: Race condition, use transactions
167 {:ok, subscription} =
168 with subscription when not is_nil(subscription) <-
169 Repo.get_by(WebsubClientSubscription, topic: topic) do
170 subscribers = [subscriber.ap_id | subscription.subscribers] |> Enum.uniq()
171 change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
172 Repo.update(change)
173 else
174 _e ->
175 subscription = %WebsubClientSubscription{
176 topic: topic,
177 hub: subscribed.info.hub,
178 subscribers: [subscriber.ap_id],
179 state: "requested",
180 secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64(),
181 user: subscribed
182 }
183
184 Repo.insert(subscription)
185 end
186
187 requester.(subscription)
188 end
189
190 def gather_feed_data(topic, getter \\ &@httpoison.get/1) do
191 with {:ok, response} <- getter.(topic),
192 status when status in 200..299 <- response.status,
193 body <- response.body,
194 doc <- XML.parse_document(body),
195 uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
196 hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
197 name = XML.string_from_xpath("/feed/author[1]/name", doc)
198 preferredUsername = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
199 displayName = XML.string_from_xpath("/feed/author[1]/poco:displayName", doc)
200 avatar = OStatus.make_avatar_object(doc)
201 bio = XML.string_from_xpath("/feed/author[1]/summary", doc)
202
203 {:ok,
204 %{
205 "uri" => uri,
206 "hub" => hub,
207 "nickname" => preferredUsername || name,
208 "name" => displayName || name,
209 "host" => URI.parse(uri).host,
210 "avatar" => avatar,
211 "bio" => bio
212 }}
213 else
214 e ->
215 {:error, e}
216 end
217 end
218
219 def request_subscription(websub, poster \\ &@httpoison.post/3, timeout \\ 10_000) do
220 data = [
221 "hub.mode": "subscribe",
222 "hub.topic": websub.topic,
223 "hub.secret": websub.secret,
224 "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
225 ]
226
227 # This checks once a second if we are confirmed yet
228 websub_checker = fn ->
229 helper = fn helper ->
230 :timer.sleep(1000)
231 websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
232 if websub, do: websub, else: helper.(helper)
233 end
234
235 helper.(helper)
236 end
237
238 task = Task.async(websub_checker)
239
240 with {:ok, %{status: 202}} <-
241 poster.(websub.hub, {:form, data}, "Content-type": "application/x-www-form-urlencoded"),
242 {:ok, websub} <- Task.yield(task, timeout) do
243 {:ok, websub}
244 else
245 e ->
246 Task.shutdown(task)
247
248 change = Ecto.Changeset.change(websub, %{state: "rejected"})
249 {:ok, websub} = Repo.update(change)
250
251 Logger.debug(fn -> "Couldn't confirm subscription: #{inspect(websub)}" end)
252 Logger.debug(fn -> "error: #{inspect(e)}" end)
253
254 {:error, websub}
255 end
256 end
257
258 def refresh_subscriptions(delta \\ 60 * 60 * 24) do
259 Logger.debug("Refreshing subscriptions")
260
261 cut_off = NaiveDateTime.add(NaiveDateTime.utc_now(), delta)
262
263 query = from(sub in WebsubClientSubscription, where: sub.valid_until < ^cut_off)
264
265 subs = Repo.all(query)
266
267 Enum.each(subs, fn sub ->
268 Pleroma.Web.Federator.enqueue(:request_subscription, sub)
269 end)
270 end
271
272 def publish_one(%{xml: xml, topic: topic, callback: callback, secret: secret} = params) do
273 signature = sign(secret || "", xml)
274 Logger.info(fn -> "Pushing #{topic} to #{callback}" end)
275
276 with {:ok, %{status: code}} when code in 200..299 <-
277 @httpoison.post(
278 callback,
279 xml,
280 [
281 {"Content-Type", "application/atom+xml"},
282 {"X-Hub-Signature", "sha1=#{signature}"}
283 ]
284 ) do
285 if !Map.has_key?(params, :unreachable_since) || params[:unreachable_since],
286 do: Instances.set_reachable(callback)
287
288 Logger.info(fn -> "Pushed to #{callback}, code #{code}" end)
289 {:ok, code}
290 else
291 {_post_result, response} ->
292 unless params[:unreachable_since], do: Instances.set_reachable(callback)
293 Logger.debug(fn -> "Couldn't push to #{callback}, #{inspect(response)}" end)
294 {:error, response}
295 end
296 end
297 end