/* This file is part of jellything (https://codeberg.org/metamuffin/jellything) which is licensed under the GNU Affero General Public License (version 3); see /COPYING. Copyright (C) 2023 metamuffin */ use super::ui::{ account::{login_logic, session::AdminSession}, error::MyResult, }; use crate::database::DataAcid; use anyhow::{anyhow, Context}; use jellybase::database::{TableExt, T_NODE}; use jellycommon::{user::CreateSessionParams, Node}; use rocket::{ get, http::MediaType, outcome::Outcome, post, request::{self, FromRequest}, response::Redirect, serde::json::Json, Request, State, }; use serde_json::{json, Value}; use std::ops::Deref; #[get("/api")] pub fn r_api_root() -> Redirect { Redirect::moved("https://codeberg.org/metamuffin/jellything/src/branch/master/api.md") } #[get("/api/version")] pub fn r_api_version() -> &'static str { env!("CARGO_PKG_VERSION") } #[post("/api/create_session", data = "")] pub fn r_api_account_login( database: &State, data: Json, ) -> MyResult { let token = login_logic( database, &data.username, &data.password, data.expire, data.drop_permissions.clone(), )?; Ok(json!(token)) } #[get("/api/node_raw/")] pub fn r_api_node_raw( admin: AdminSession, database: &State, id: &str, ) -> MyResult> { drop(admin); let node = T_NODE .get(database, id) .context("retrieving library node")? .ok_or(anyhow!("node does not exist"))?; Ok(Json(node)) } pub struct AcceptJson(bool); impl Deref for AcceptJson { type Target = bool; fn deref(&self) -> &Self::Target { &self.0 } } impl<'r> FromRequest<'r> for AcceptJson { type Error = (); fn from_request<'life0, 'async_trait>( request: &'r Request<'life0>, ) -> ::core::pin::Pin< Box< dyn ::core::future::Future> + ::core::marker::Send + 'async_trait, >, > where 'r: 'async_trait, 'life0: 'async_trait, Self: 'async_trait, { Box::pin(async move { Outcome::Success(AcceptJson( request .accept() .map(|a| a.preferred().exact_eq(&MediaType::JSON)) .unwrap_or(false), )) }) } }