1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Websub do
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
16 @httpoison Application.get_env(:pleroma, :httpoison)
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
24 "hub.challenge": challenge,
25 "hub.lease_seconds": lease_seconds,
26 "hub.topic": subscription.topic,
27 "hub.mode": "subscribe"
30 url = hd(String.split(subscription.callback, "?"))
31 query = URI.parse(subscription.callback).query || ""
32 params = Map.merge(params, URI.decode_query(query))
34 with {:ok, response} <- getter.(url, [], params: params),
35 ^challenge <- response.body do
36 changeset = Changeset.change(subscription, %{state: "active"})
37 Repo.update(changeset)
40 Logger.debug("Couldn't verify subscription")
41 Logger.debug(inspect(e))
42 {:error, subscription}
46 @supported_activities [
54 def publish(topic, user, %{data: %{"type" => type}} = activity)
55 when type in @supported_activities do
56 # TODO: Only send to still valid subscriptions.
59 sub in WebsubServerSubscription,
60 where: sub.topic == ^topic and sub.state == "active",
61 where: fragment("? > NOW()", sub.valid_until)
64 subscriptions = Repo.all(query)
66 Enum.each(subscriptions, fn sub ->
69 |> FeedRepresenter.to_simple_form([activity], [user])
70 |> :xmerl.export_simple(:xmerl_xml)
76 callback: sub.callback,
80 Pleroma.Web.Federator.enqueue(:publish_single_websub, data)
84 def publish(_, _, _), do: ""
86 def sign(secret, doc) do
87 :crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16() |> String.downcase()
90 def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
91 with {:ok, topic} <- valid_topic(params, user),
92 {:ok, lease_time} <- lease_time(params),
93 secret <- params["hub.secret"],
94 callback <- params["hub.callback"] do
95 subscription = get_subscription(topic, callback)
98 state: subscription.state || "requested",
104 change = Changeset.change(subscription, data)
105 websub = Repo.insert_or_update!(change)
108 Changeset.change(websub, %{valid_until: NaiveDateTime.add(websub.updated_at, lease_time)})
110 websub = Repo.update!(change)
112 Pleroma.Web.Federator.enqueue(:verify_websub, websub)
117 Logger.debug("Couldn't create subscription")
118 Logger.debug(inspect(reason))
124 defp get_subscription(topic, callback) do
125 Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) ||
126 %WebsubServerSubscription{}
129 # Temp hack for mastodon.
130 defp lease_time(%{"hub.lease_seconds" => ""}) do
132 {:ok, 60 * 60 * 24 * 3}
135 defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
136 {:ok, String.to_integer(lease_seconds)}
139 defp lease_time(_) do
141 {:ok, 60 * 60 * 24 * 3}
144 defp valid_topic(%{"hub.topic" => topic}, user) do
145 if topic == OStatus.feed_path(user) do
146 {:ok, OStatus.feed_path(user)}
148 {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
152 def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
153 topic = subscribed.info.topic
154 # FIXME: Race condition, use transactions
155 {:ok, subscription} =
156 with subscription when not is_nil(subscription) <-
157 Repo.get_by(WebsubClientSubscription, topic: topic) do
158 subscribers = [subscriber.ap_id | subscription.subscribers] |> Enum.uniq()
159 change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
163 subscription = %WebsubClientSubscription{
165 hub: subscribed.info.hub,
166 subscribers: [subscriber.ap_id],
168 secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64(),
172 Repo.insert(subscription)
175 requester.(subscription)
178 def gather_feed_data(topic, getter \\ &@httpoison.get/1) do
179 with {:ok, response} <- getter.(topic),
180 status when status in 200..299 <- response.status,
181 body <- response.body,
182 doc <- XML.parse_document(body),
183 uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
184 hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
185 name = XML.string_from_xpath("/feed/author[1]/name", doc)
186 preferredUsername = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
187 displayName = XML.string_from_xpath("/feed/author[1]/poco:displayName", doc)
188 avatar = OStatus.make_avatar_object(doc)
189 bio = XML.string_from_xpath("/feed/author[1]/summary", doc)
195 "nickname" => preferredUsername || name,
196 "name" => displayName || name,
197 "host" => URI.parse(uri).host,
207 def request_subscription(websub, poster \\ &@httpoison.post/3, timeout \\ 10_000) do
209 "hub.mode": "subscribe",
210 "hub.topic": websub.topic,
211 "hub.secret": websub.secret,
212 "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
215 # This checks once a second if we are confirmed yet
216 websub_checker = fn ->
217 helper = fn helper ->
219 websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
220 if websub, do: websub, else: helper.(helper)
226 task = Task.async(websub_checker)
228 with {:ok, %{status: 202}} <-
229 poster.(websub.hub, {:form, data}, "Content-type": "application/x-www-form-urlencoded"),
230 {:ok, websub} <- Task.yield(task, timeout) do
236 change = Ecto.Changeset.change(websub, %{state: "rejected"})
237 {:ok, websub} = Repo.update(change)
239 Logger.debug(fn -> "Couldn't confirm subscription: #{inspect(websub)}" end)
240 Logger.debug(fn -> "error: #{inspect(e)}" end)
246 def refresh_subscriptions(delta \\ 60 * 60 * 24) do
247 Logger.debug("Refreshing subscriptions")
249 cut_off = NaiveDateTime.add(NaiveDateTime.utc_now(), delta)
251 query = from(sub in WebsubClientSubscription, where: sub.valid_until < ^cut_off)
253 subs = Repo.all(query)
255 Enum.each(subs, fn sub ->
256 Pleroma.Web.Federator.enqueue(:request_subscription, sub)
260 def publish_one(%{xml: xml, topic: topic, callback: callback, secret: secret}) do
261 signature = sign(secret || "", xml)
262 Logger.info(fn -> "Pushing #{topic} to #{callback}" end)
264 with {:ok, %{status: code}} <-
269 {"Content-Type", "application/atom+xml"},
270 {"X-Hub-Signature", "sha1=#{signature}"}
273 Logger.info(fn -> "Pushed to #{callback}, code #{code}" end)
277 Logger.debug(fn -> "Couldn't push to #{callback}, #{inspect(e)}" end)