ryuk-cli 0.1.1

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
use super::owner;
use crate::AppState;
use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
};
use ryuk::{
    api::{ApiAuth, ApiError},
    push::{DeviceInfo, Platform, PushError},
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use utoipa::ToSchema;

#[derive(Deserialize, ToSchema)]
pub struct DeviceInput {
    /// `ios` or `android`.
    platform: String,
    /// The APNs / FCM registration token. Never returned or logged.
    token: String,
    app_id: Option<String>,
    name: Option<String>,
}

#[derive(Serialize, ToSchema)]
pub struct DeviceOut {
    id: i64,
    platform: String,
    app_id: Option<String>,
    name: Option<String>,
    created_at: i64,
    last_seen_at: i64,
    /// Set when the push provider rejected the token; register again to clear it.
    invalid_at: Option<i64>,
}

impl From<DeviceInfo> for DeviceOut {
    fn from(d: DeviceInfo) -> Self {
        DeviceOut {
            id: d.id,
            platform: d.platform.as_str().into(),
            app_id: d.app_id,
            name: d.name,
            created_at: d.created_at,
            last_seen_at: d.last_seen_at,
            invalid_at: d.invalid_at,
        }
    }
}

fn invalid(field: &str, msg: &str) -> ApiError {
    ApiError::validation(BTreeMap::from([(field.to_string(), vec![msg.to_string()])]))
}

/// The user's devices, newest first. Tokens are never returned.
#[utoipa::path(get, path = "/devices", security(("api_key" = []), ("oauth2" = ["devices"])),
    responses((status = 200, body = Vec<DeviceOut>), (status = 401, description = "Missing or invalid credential"), (status = 403, description = "Missing scope devices, or no user")))]
pub async fn index(State(s): State<AppState>, ApiAuth(p): ApiAuth) -> Result<Json<Vec<DeviceOut>>, ApiError> {
    p.require("devices")?;
    let list = s.push.devices().list(owner(&p)?).await?;
    Ok(Json(list.into_iter().map(Into::into).collect()))
}

/// Register or refresh a device. A token already registered to another user moves to the caller (the phone changed hands).
#[utoipa::path(post, path = "/devices", request_body = DeviceInput, security(("api_key" = []), ("oauth2" = ["devices"])),
    responses((status = 201, body = DeviceOut), (status = 401, description = "Missing or invalid credential"), (status = 403, description = "Missing scope devices, or no user"), (status = 422, description = "Validation failed")))]
pub async fn store(State(s): State<AppState>, ApiAuth(p): ApiAuth, Json(i): Json<DeviceInput>) -> Result<(StatusCode, Json<DeviceOut>), ApiError> {
    p.require("devices")?;
    let uid = owner(&p)?;
    let platform = Platform::parse(&i.platform).ok_or_else(|| invalid("platform", "Platform must be ios or android"))?;
    match s.push.devices().register(uid, platform, &i.token, i.app_id.as_deref(), i.name.as_deref()).await {
        Ok(d) => Ok((StatusCode::CREATED, Json(d.into()))),
        // The library's messages are fixed strings (they never contain the token).
        Err(PushError::Invalid(m)) => {
            let field = ["name", "app_id"].into_iter().find(|f| m.starts_with(f)).unwrap_or("token");
            Err(invalid(field, &m))
        }
        Err(e) => Err(e.into()),
    }
}

/// Remove one of the caller's devices; someone else's id is 404.
#[utoipa::path(delete, path = "/devices/{id}", params(("id" = i64, Path, description = "Device id")),
    security(("api_key" = []), ("oauth2" = ["devices"])),
    responses((status = 204, description = "Removed"), (status = 404, description = "Not found")))]
pub async fn destroy(State(s): State<AppState>, ApiAuth(p): ApiAuth, Path(id): Path<i64>) -> Result<StatusCode, ApiError> {
    p.require("devices")?;
    if s.push.devices().unregister(owner(&p)?, id).await? { Ok(StatusCode::NO_CONTENT) } else { Err(ApiError::not_found()) }
}