tusker_push/lib/tusker_push_web/controllers/registrations_controller.ex

104 lines
2.7 KiB
Elixir
Raw Normal View History

2024-04-05 19:04:38 +00:00
defmodule TuskerPushWeb.RegistrationsController do
alias TuskerPush.Registration
alias Ecto.Changeset
use TuskerPushWeb, :controller
require Logger
def create(conn, %{
"transaction_id" => transaction_id,
"environment" => env,
2024-04-06 19:26:44 +00:00
"device_token" => token,
"push_version" => version
2024-04-05 19:04:38 +00:00
}) do
with {:ok, %Registration{id: id}} <-
TuskerPush.register(%{
storekit_original_transaction_id: transaction_id,
apns_environment: env,
2024-04-06 19:26:44 +00:00
apns_device_token: token,
push_version: version
2024-04-05 19:04:38 +00:00
}) do
2024-04-05 22:26:10 +00:00
conn
|> json(%{
id: id,
2024-04-07 16:08:17 +00:00
endpoint: url(~p"/mastodon/v1/push/#{id}")
2024-04-05 22:26:10 +00:00
})
2024-04-05 19:04:38 +00:00
else
2024-04-07 14:56:23 +00:00
{:error, %Changeset{valid?: false} = changeset} ->
errors =
changeset.errors
|> Enum.map(fn {k, {reason, _}} -> %{key: k, reason: reason} end)
2024-04-05 19:04:38 +00:00
conn
|> put_status(400)
2024-04-07 14:56:23 +00:00
|> json(%{error: "validation failed", fields: errors})
{:error, reason} ->
Logger.error("Failed creating registration: #{inspect(reason)}")
conn
|> put_status(500)
|> json(%{error: "unknown error", fields: []})
end
end
def create(conn, _) do
conn
|> put_status(400)
|> json(%{error: "missing required parameters"})
end
def update(conn, %{
"id" => id,
"environment" => env,
"device_token" => token,
"push_version" => version
}) do
params = %{
apns_environment: env,
apns_device_token: token,
push_version: version
}
with {:registration, registration} when not is_nil(registration) <-
{:registration, TuskerPush.get_registration(id)},
{:ok, _} <- TuskerPush.update_registration(registration, params) do
conn
2024-04-07 16:08:17 +00:00
|> json(%{id: id, endpoint: url(~p"/mastodon/v1/push/#{id}")})
2024-04-07 14:56:23 +00:00
else
{:registration, nil} ->
conn
|> put_status(404)
|> json(%{error: "not found", fields: []})
2024-04-05 19:04:38 +00:00
{:error, %Changeset{valid?: false} = changeset} ->
errors =
changeset.errors
|> Enum.map(fn {k, {reason, _}} -> %{key: k, reason: reason} end)
conn
|> put_status(400)
2024-04-07 14:56:23 +00:00
|> json(%{error: "validation failed", fields: errors})
2024-04-05 19:04:38 +00:00
{:error, reason} ->
2024-04-07 14:56:23 +00:00
Logger.error("Failed updating registration: #{inspect(reason)}")
2024-04-05 19:04:38 +00:00
conn
|> put_status(500)
2024-04-07 14:56:23 +00:00
|> json(%{error: "unknown error", fields: []})
2024-04-05 19:04:38 +00:00
end
end
2024-04-07 14:56:23 +00:00
def update(conn, _) do
2024-04-05 19:04:38 +00:00
conn
|> put_status(400)
|> json(%{error: "missing required parameters"})
end
def delete(conn, %{"id" => id}) do
TuskerPush.unregister(id)
json(conn, %{status: "ok"})
end
end