Merge branch 'feld-varnish' into 'develop'
[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) do
12 conn
13 |> send_resp(202, "Accepted")
14 else
15 {: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(
23 conn,
24 %{
25 "id" => id,
26 "hub.mode" => "subscribe",
27 "hub.challenge" => challenge,
28 "hub.topic" => topic
29 } = params
30 ) do
31 Logger.debug("Got WebSub confirmation")
32 Logger.debug(inspect(params))
33
34 lease_seconds =
35 if params["hub.lease_seconds"] do
36 String.to_integer(params["hub.lease_seconds"])
37 else
38 # Guess 3 days
39 60 * 60 * 24 * 3
40 end
41
42 with %WebsubClientSubscription{} = websub <-
43 Repo.get_by(WebsubClientSubscription, id: id, topic: topic) do
44 valid_until = NaiveDateTime.add(NaiveDateTime.utc_now(), lease_seconds)
45 change = Ecto.Changeset.change(websub, %{state: "accepted", valid_until: valid_until})
46 {:ok, _websub} = Repo.update(change)
47
48 conn
49 |> send_resp(200, challenge)
50 else
51 _e ->
52 conn
53 |> send_resp(500, "Error")
54 end
55 end
56
57 def websub_incoming(conn, %{"id" => id}) do
58 with "sha1=" <> signature <- hd(get_req_header(conn, "x-hub-signature")),
59 signature <- String.downcase(signature),
60 %WebsubClientSubscription{} = websub <- Repo.get(WebsubClientSubscription, id),
61 {:ok, body, _conn} = read_body(conn),
62 ^signature <- Websub.sign(websub.secret, body) do
63 Federator.enqueue(:incoming_doc, body)
64
65 conn
66 |> send_resp(200, "OK")
67 else
68 _e ->
69 Logger.debug("Can't handle incoming subscription post")
70
71 conn
72 |> send_resp(500, "Error")
73 end
74 end
75 end