Handle cases where we don't get lease_seconds returned.
[akkoma] / lib / pleroma / web / websub / websub_controller.ex
1 defmodule Pleroma.Web.Websub.WebsubController do
2 use Pleroma.Web, :controller
3 alias Pleroma.{Repo, User}
4 alias Pleroma.Web.{Websub, Federator}
5 alias Pleroma.Web.Websub.WebsubClientSubscription
6 require Logger
7
8 def websub_subscription_request(conn, %{"nickname" => nickname} = params) do
9 user = User.get_cached_by_nickname(nickname)
10
11 with {:ok, _websub} <- Websub.incoming_subscription_request(user, params)
12 do
13 conn
14 |> send_resp(202, "Accepted")
15 else {:error, reason} ->
16 conn
17 |> send_resp(500, reason)
18 end
19 end
20
21 # TODO: Extract this into the Websub module
22 def websub_subscription_confirmation(conn, %{"id" => id, "hub.mode" => "subscribe", "hub.challenge" => challenge, "hub.topic" => topic} = params) do
23 lease_seconds = if params["hub.lease_seconds"] do
24 String.to_integer(params["hub.lease_seconds"])
25 else
26 # Guess 3 days
27 60 * 24 * 3
28 end
29
30 with %WebsubClientSubscription{} = websub <- Repo.get_by(WebsubClientSubscription, id: id, topic: topic) do
31 valid_until = NaiveDateTime.add(NaiveDateTime.utc_now, lease_seconds)
32 change = Ecto.Changeset.change(websub, %{state: "accepted", valid_until: valid_until})
33 {:ok, _websub} = Repo.update(change)
34 conn
35 |> send_resp(200, challenge)
36 else _e ->
37 conn
38 |> send_resp(500, "Error")
39 end
40 end
41
42 def websub_incoming(conn, %{"id" => id}) do
43 with "sha1=" <> signature <- hd(get_req_header(conn, "x-hub-signature")),
44 signature <- String.downcase(signature),
45 %WebsubClientSubscription{} = websub <- Repo.get(WebsubClientSubscription, id),
46 {:ok, body, _conn} = read_body(conn),
47 ^signature <- Websub.sign(websub.secret, body) do
48 Federator.enqueue(:incoming_doc, body)
49 conn
50 |> send_resp(200, "OK")
51 else _e ->
52 Logger.debug("Can't handle incoming subscription post")
53 conn
54 |> send_resp(500, "Error")
55 end
56 end
57 end