tusker_push/lib/tusker_push_web/controllers/push_controller.ex

89 lines
2.5 KiB
Elixir
Raw Normal View History

2024-04-05 22:26:10 +00:00
defmodule TuskerPushWeb.PushController do
2024-04-06 19:02:18 +00:00
alias TuskerPush.Forwarder
2024-04-05 22:26:10 +00:00
use TuskerPushWeb, :controller
require Logger
2024-04-12 20:16:46 +00:00
def push(conn, %{"env" => env, "apns_device_token" => apns_device_token, "ctx" => context}) do
2024-04-25 18:36:31 +00:00
OpenTelemetry.Tracer.set_attribute(:request_id, conn.assigns.request_id)
2024-04-12 20:16:46 +00:00
with {:apns_env, apns_env} <- {:apns_env, get_apns_env(env)},
2024-04-06 19:02:18 +00:00
{:encoding, ["aesgcm"]} <- {:encoding, get_req_header(conn, "content-encoding")},
{:body, {:ok, body, conn}} <- {:body, read_body(conn)},
{:salt, salt} when not is_nil(salt) <- get_salt(conn),
{:key, key} when not is_nil(key) <- get_key(conn),
2024-04-12 20:16:46 +00:00
{:forward, :ok} <-
{:forward, Forwarder.forward(apns_env, apns_device_token, body, salt, key, context)} do
2024-04-05 22:26:10 +00:00
send_resp(conn, 200, "ok")
else
2024-04-12 20:16:46 +00:00
{:apns_env, nil} ->
Logger.error("Bad environment: #{env}")
send_resp(conn, 400, "bad env")
2024-04-05 22:26:10 +00:00
2024-04-06 19:02:18 +00:00
{:encoding, encoding} ->
Logger.warning("Unexpected encoding: #{inspect(encoding)}")
send_resp(conn, 400, "bad encoding")
2024-04-05 22:26:10 +00:00
2024-04-06 19:02:18 +00:00
{:body, {:more, _, conn}} ->
Logger.error("Didn't finish reading")
2024-04-05 22:26:10 +00:00
send_resp(conn, 500, "failed to read body")
2024-04-06 19:02:18 +00:00
{:body, {:error, reason}} ->
2024-04-05 22:26:10 +00:00
Logger.error("Reading body: #{inspect(reason)}")
send_resp(conn, 500, "failed to read body")
2024-04-06 19:02:18 +00:00
{:salt, nil} ->
Logger.warning("Missing salt")
send_resp(conn, 400, "missing salt")
{:key, nil} ->
Logger.warning("Missing key")
send_resp(conn, 400, "missing key")
{:forward, {:error, :device_token_unregistered}} ->
Logger.debug("APNS device token unregistered, removing registration")
send_resp(conn, 400, "apns unregistered")
2024-04-06 19:02:18 +00:00
{:forward, {:error, reason}} ->
Logger.error("Sending notification: #{inspect(reason)}")
send_resp(conn, 500, "failed to send")
end
end
2024-04-12 20:16:46 +00:00
defp get_apns_env("development"), do: :development
defp get_apns_env("production"), do: :production
defp get_apns_env(_), do: nil
2024-04-06 19:02:18 +00:00
defp get_salt(conn) do
conn
|> get_req_header("encryption")
|> case do
["salt=" <> salt] ->
{:salt, salt}
_ ->
{:salt, nil}
end
end
defp get_key(conn) do
conn
|> get_req_header("crypto-key")
|> case do
[value] ->
dh =
value
|> String.split(";")
|> Enum.find_value(fn
"dh=" <> val -> val
_ -> false
end)
{:key, dh}
_ ->
{:key, nil}
2024-04-05 22:26:10 +00:00
end
end
end