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.WebsubController do
6 use Pleroma.Web, :controller
8 alias Pleroma.{Repo, User}
9 alias Pleroma.Web.{Websub, Federator}
10 alias Pleroma.Web.Websub.WebsubClientSubscription
15 Pleroma.Web.FederatingPlug
17 :websub_subscription_request,
18 :websub_subscription_confirmation,
23 def websub_subscription_request(conn, %{"nickname" => nickname} = params) do
24 user = User.get_cached_by_nickname(nickname)
26 with {:ok, _websub} <- Websub.incoming_subscription_request(user, params) do
28 |> send_resp(202, "Accepted")
32 |> send_resp(500, reason)
36 # TODO: Extract this into the Websub module
37 def websub_subscription_confirmation(
41 "hub.mode" => "subscribe",
42 "hub.challenge" => challenge,
46 Logger.debug("Got WebSub confirmation")
47 Logger.debug(inspect(params))
50 if params["hub.lease_seconds"] do
51 String.to_integer(params["hub.lease_seconds"])
57 with %WebsubClientSubscription{} = websub <-
58 Repo.get_by(WebsubClientSubscription, id: id, topic: topic) do
59 valid_until = NaiveDateTime.add(NaiveDateTime.utc_now(), lease_seconds)
60 change = Ecto.Changeset.change(websub, %{state: "accepted", valid_until: valid_until})
61 {:ok, _websub} = Repo.update(change)
64 |> send_resp(200, challenge)
68 |> send_resp(500, "Error")
72 def websub_subscription_confirmation(conn, params) do
73 Logger.info("Invalid WebSub confirmation request: #{inspect(params)}")
76 |> send_resp(500, "Invalid parameters")
79 def websub_incoming(conn, %{"id" => id}) do
80 with "sha1=" <> signature <- hd(get_req_header(conn, "x-hub-signature")),
81 signature <- String.downcase(signature),
82 %WebsubClientSubscription{} = websub <- Repo.get(WebsubClientSubscription, id),
83 {:ok, body, _conn} = read_body(conn),
84 ^signature <- Websub.sign(websub.secret, body) do
85 Federator.enqueue(:incoming_doc, body)
88 |> send_resp(200, "OK")
91 Logger.debug("Can't handle incoming subscription post")
94 |> send_resp(500, "Error")