Set valid_until date.
[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, "hub.lease_seconds" => lease_seconds}) do
23 with %WebsubClientSubscription{} = websub <- Repo.get_by(WebsubClientSubscription, id: id, topic: topic) do
24 valid_until = NaiveDateTime.add(NaiveDateTime.utc_now, String.to_integer(lease_seconds))
25 change = Ecto.Changeset.change(websub, %{state: "accepted", valid_until: valid_until})
26 {:ok, _websub} = Repo.update(change)
27 conn
28 |> send_resp(200, challenge)
29 else _e ->
30 conn
31 |> send_resp(500, "Error")
32 end
33 end
34
35 def websub_incoming(conn, %{"id" => id}) do
36 with "sha1=" <> signature <- hd(get_req_header(conn, "x-hub-signature")),
37 signature <- String.downcase(signature),
38 %WebsubClientSubscription{} = websub <- Repo.get(WebsubClientSubscription, id),
39 {:ok, body, _conn} = read_body(conn),
40 ^signature <- Websub.sign(websub.secret, body) do
41 Federator.enqueue(:incoming_doc, body)
42 conn
43 |> send_resp(200, "OK")
44 else _e ->
45 Logger.debug("Can't handle incoming subscription post")
46 conn
47 |> send_resp(500, "Error")
48 end
49 end
50 end