e860ec9e5381c180dde61df581a892cba7a345d3
[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
5 alias Pleroma.Web.Websub.WebsubClientSubscription
6 require Logger
7
8 @ostatus Application.get_env(:pleroma, :ostatus)
9
10 def websub_subscription_request(conn, %{"nickname" => nickname} = params) do
11 user = User.get_cached_by_nickname(nickname)
12
13 with {:ok, _websub} <- Websub.incoming_subscription_request(user, params)
14 do
15 conn
16 |> send_resp(202, "Accepted")
17 else {:error, reason} ->
18 conn
19 |> send_resp(500, reason)
20 end
21 end
22
23 def websub_subscription_confirmation(conn, %{"id" => id, "hub.mode" => "subscribe", "hub.challenge" => challenge, "hub.topic" => topic}) do
24 with %WebsubClientSubscription{} = websub <- Repo.get_by(WebsubClientSubscription, id: id, topic: topic) do
25 change = Ecto.Changeset.change(websub, %{state: "accepted"})
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 @ostatus.handle_incoming(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