tusker_push/lib/tusker_push_web/controllers/app_registrations_controlle...

104 lines
2.7 KiB
Elixir

defmodule TuskerPushWeb.AppRegistrationsController do
alias TuskerPush.Registration
alias Ecto.Changeset
use TuskerPushWeb, :controller
require Logger
def create(conn, %{
"transaction_id" => transaction_id,
"environment" => env,
"device_token" => token,
"push_version" => version
}) do
with {:ok, %Registration{id: id}} <-
TuskerPush.register(%{
storekit_original_transaction_id: transaction_id,
apns_environment: env,
apns_device_token: token,
push_version: version
}) do
conn
|> json(%{
id: id,
endpoint: url(~p"/mastodon/v1/push/#{id}")
})
else
{:error, %Changeset{valid?: false} = changeset} ->
errors =
changeset.errors
|> Enum.map(fn {k, {reason, _}} -> %{key: k, reason: reason} end)
conn
|> put_status(400)
|> 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
|> json(%{id: id, endpoint: url(~p"/mastodon/v1/push/#{id}")})
else
{:registration, nil} ->
conn
|> put_status(404)
|> json(%{error: "not found", fields: []})
{:error, %Changeset{valid?: false} = changeset} ->
errors =
changeset.errors
|> Enum.map(fn {k, {reason, _}} -> %{key: k, reason: reason} end)
conn
|> put_status(400)
|> json(%{error: "validation failed", fields: errors})
{:error, reason} ->
Logger.error("Failed updating registration: #{inspect(reason)}")
conn
|> put_status(500)
|> json(%{error: "unknown error", fields: []})
end
end
def update(conn, _) do
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