1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Websub do
8 alias Pleroma.Instances
11 alias Pleroma.Web.ActivityPub.Visibility
12 alias Pleroma.Web.Endpoint
13 alias Pleroma.Web.Federator
14 alias Pleroma.Web.Federator.Publisher
15 alias Pleroma.Web.OStatus
16 alias Pleroma.Web.OStatus.FeedRepresenter
17 alias Pleroma.Web.Router.Helpers
18 alias Pleroma.Web.Websub.WebsubClientSubscription
19 alias Pleroma.Web.Websub.WebsubServerSubscription
25 @behaviour Pleroma.Web.Federator.Publisher
27 @httpoison Application.get_env(:pleroma, :httpoison)
29 def verify(subscription, getter \\ &@httpoison.get/3) do
30 challenge = Base.encode16(:crypto.strong_rand_bytes(8))
31 lease_seconds = NaiveDateTime.diff(subscription.valid_until, subscription.updated_at)
32 lease_seconds = lease_seconds |> to_string
35 "hub.challenge": challenge,
36 "hub.lease_seconds": lease_seconds,
37 "hub.topic": subscription.topic,
38 "hub.mode": "subscribe"
41 url = hd(String.split(subscription.callback, "?"))
42 query = URI.parse(subscription.callback).query || ""
43 params = Map.merge(params, URI.decode_query(query))
45 with {:ok, response} <- getter.(url, [], params: params),
46 ^challenge <- response.body do
47 changeset = Changeset.change(subscription, %{state: "active"})
48 Repo.update(changeset)
51 Logger.debug("Couldn't verify subscription")
52 Logger.debug(inspect(e))
53 {:error, subscription}
57 @supported_activities [
66 def is_representable?(%Activity{data: %{"type" => type}} = activity)
67 when type in @supported_activities,
68 do: Visibility.is_public?(activity)
70 def is_representable?(_), do: false
72 def publish(topic, user, %{data: %{"type" => type}} = activity)
73 when type in @supported_activities do
76 |> FeedRepresenter.to_simple_form([activity], [user])
77 |> :xmerl.export_simple(:xmerl_xml)
82 sub in WebsubServerSubscription,
83 where: sub.topic == ^topic and sub.state == "active",
84 where: fragment("? > (NOW() at time zone 'UTC')", sub.valid_until)
87 subscriptions = Repo.all(query)
89 callbacks = Enum.map(subscriptions, & &1.callback)
90 reachable_callbacks_metadata = Instances.filter_reachable(callbacks)
91 reachable_callbacks = Map.keys(reachable_callbacks_metadata)
94 |> Enum.filter(&(&1.callback in reachable_callbacks))
95 |> Enum.each(fn sub ->
99 callback: sub.callback,
101 unreachable_since: reachable_callbacks_metadata[sub.callback]
104 Publisher.enqueue_one(__MODULE__, data)
108 def publish(_, _, _), do: ""
110 def publish(actor, activity), do: publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
112 def sign(secret, doc) do
113 :crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16() |> String.downcase()
116 def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
117 with {:ok, topic} <- valid_topic(params, user),
118 {:ok, lease_time} <- lease_time(params),
119 secret <- params["hub.secret"],
120 callback <- params["hub.callback"] do
121 subscription = get_subscription(topic, callback)
124 state: subscription.state || "requested",
130 change = Changeset.change(subscription, data)
131 websub = Repo.insert_or_update!(change)
134 Changeset.change(websub, %{valid_until: NaiveDateTime.add(websub.updated_at, lease_time)})
136 websub = Repo.update!(change)
138 Federator.verify_websub(websub)
143 Logger.debug("Couldn't create subscription")
144 Logger.debug(inspect(reason))
150 def incoming_subscription_request(user, params) do
151 Logger.info("Unhandled WebSub request for #{user.nickname}: #{inspect(params)}")
153 {:error, "Invalid WebSub request"}
156 defp get_subscription(topic, callback) do
157 Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) ||
158 %WebsubServerSubscription{}
161 # Temp hack for mastodon.
162 defp lease_time(%{"hub.lease_seconds" => ""}) do
164 {:ok, 60 * 60 * 24 * 3}
167 defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
168 {:ok, String.to_integer(lease_seconds)}
171 defp lease_time(_) do
173 {:ok, 60 * 60 * 24 * 3}
176 defp valid_topic(%{"hub.topic" => topic}, user) do
177 if topic == OStatus.feed_path(user) do
178 {:ok, OStatus.feed_path(user)}
180 {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
184 def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
185 topic = subscribed.info.topic
186 # FIXME: Race condition, use transactions
187 {:ok, subscription} =
188 with subscription when not is_nil(subscription) <-
189 Repo.get_by(WebsubClientSubscription, topic: topic) do
190 subscribers = [subscriber.ap_id | subscription.subscribers] |> Enum.uniq()
191 change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
195 subscription = %WebsubClientSubscription{
197 hub: subscribed.info.hub,
198 subscribers: [subscriber.ap_id],
200 secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64(),
204 Repo.insert(subscription)
207 requester.(subscription)
210 def gather_feed_data(topic, getter \\ &@httpoison.get/1) do
211 with {:ok, response} <- getter.(topic),
212 status when status in 200..299 <- response.status,
213 body <- response.body,
214 doc <- XML.parse_document(body),
215 uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
216 hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
217 name = XML.string_from_xpath("/feed/author[1]/name", doc)
218 preferred_username = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
219 display_name = XML.string_from_xpath("/feed/author[1]/poco:displayName", doc)
220 avatar = OStatus.make_avatar_object(doc)
221 bio = XML.string_from_xpath("/feed/author[1]/summary", doc)
227 "nickname" => preferred_username || name,
228 "name" => display_name || name,
229 "host" => URI.parse(uri).host,
239 def request_subscription(websub, poster \\ &@httpoison.post/3, timeout \\ 10_000) do
241 "hub.mode": "subscribe",
242 "hub.topic": websub.topic,
243 "hub.secret": websub.secret,
244 "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
247 # This checks once a second if we are confirmed yet
248 websub_checker = fn ->
249 helper = fn helper ->
251 websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
252 if websub, do: websub, else: helper.(helper)
258 task = Task.async(websub_checker)
260 with {:ok, %{status: 202}} <-
261 poster.(websub.hub, {:form, data}, "Content-type": "application/x-www-form-urlencoded"),
262 {:ok, websub} <- Task.yield(task, timeout) do
268 change = Ecto.Changeset.change(websub, %{state: "rejected"})
269 {:ok, websub} = Repo.update(change)
271 Logger.debug(fn -> "Couldn't confirm subscription: #{inspect(websub)}" end)
272 Logger.debug(fn -> "error: #{inspect(e)}" end)
278 def refresh_subscriptions(delta \\ 60 * 60 * 24) do
279 Logger.debug("Refreshing subscriptions")
281 cut_off = NaiveDateTime.add(NaiveDateTime.utc_now(), delta)
283 query = from(sub in WebsubClientSubscription, where: sub.valid_until < ^cut_off)
285 subs = Repo.all(query)
287 Enum.each(subs, fn sub ->
288 Federator.request_subscription(sub)
292 def publish_one(%{xml: xml, topic: topic, callback: callback, secret: secret} = params) do
293 signature = sign(secret || "", xml)
294 Logger.info(fn -> "Pushing #{topic} to #{callback}" end)
296 with {:ok, %{status: code}} when code in 200..299 <-
301 {"Content-Type", "application/atom+xml"},
302 {"X-Hub-Signature", "sha1=#{signature}"}
305 if !Map.has_key?(params, :unreachable_since) || params[:unreachable_since],
306 do: Instances.set_reachable(callback)
308 Logger.info(fn -> "Pushed to #{callback}, code #{code}" end)
311 {_post_result, response} ->
312 unless params[:unreachable_since], do: Instances.set_reachable(callback)
313 Logger.debug(fn -> "Couldn't push to #{callback}, #{inspect(response)}" end)
318 def gather_webfinger_links(%User{} = user) do
321 "rel" => "http://schemas.google.com/g/2010#updates-from",
322 "type" => "application/atom+xml",
323 "href" => OStatus.feed_path(user)
326 "rel" => "http://ostatus.org/schema/1.0/subscribe",
327 "template" => OStatus.remote_follow_path()