/* 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 crate::{ database::Database, routes::ui::{account::session::Session, error::MyError, CacheControlFile}, CONF, }; use anyhow::anyhow; use jellycommon::AssetLocation; use log::info; use rocket::{get, http::ContentType, FromFormField, State, UriDisplayQuery}; use std::{path::PathBuf, str::FromStr}; use tokio::fs::File; #[derive(FromFormField, UriDisplayQuery)] pub enum AssetRole { #[field(value = "poster")] Poster, #[field(value = "backdrop")] Backdrop, } #[get("/n//asset?")] pub async fn r_item_assets( _sess: Session, id: String, role: AssetRole, db: &State, ) -> Result<(ContentType, CacheControlFile), MyError> { let node = db.node.get(&id)?.ok_or(anyhow!("node does not exist"))?; let path = match role { AssetRole::Backdrop => node.private.backdrop, AssetRole::Poster => node.private.poster, } .map(|e| e.path()) .unwrap_or_else(|| { CONF.asset_path .join(PathBuf::from_str("fallback.jpeg").unwrap()) }); info!("loading asset from {path:?}"); let ext = path .extension() .map(|e| e.to_str().unwrap()) .unwrap_or("jpeg"); Ok(( ContentType::from_extension(ext).unwrap(), CacheControlFile::new(File::open(path).await?).await, )) } pub trait AssetLocationExt { fn path(&self) -> PathBuf; } impl AssetLocationExt for AssetLocation { fn path(&self) -> PathBuf { match self { AssetLocation::Assets(p) => CONF.asset_path.join(p), AssetLocation::Cache(p) => CONF.cache_path.join(p), AssetLocation::Library(p) => CONF.library_path.join(p), } } }