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