aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/ui/assets.rs
blob: 2c0b85af88526f228c0b81906e7b29be2601cd15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
    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 <metamuffin.org>
*/
use crate::{
    database::Database,
    routes::ui::{account::session::Session, error::MyError, CacheControlFile},
    CONF,
};
use anyhow::anyhow;
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 {
    Poster,
    Backdrop,
}

#[get("/item_assets/<id>?<role>")]
pub async fn r_item_assets(
    _sess: Session,
    id: String,
    role: AssetRole,
    db: &State<Database>,
) -> Result<(ContentType, CacheControlFile), MyError> {
    let node = db.node.get(&id)?.ok_or(anyhow!("node does not exist"))?;
    let path = CONF.asset_path.join(
        match role {
            AssetRole::Backdrop => node.private.backdrop,
            AssetRole::Poster => node.private.poster,
        }
        .unwrap_or_else(|| PathBuf::from_str("fallback.jpeg").unwrap()),
    );
    info!("loading asset from {path:?}");
    let ext = path.extension().unwrap().to_str().unwrap();
    Ok((
        ContentType::from_extension(ext).unwrap(),
        CacheControlFile::new(File::open(path).await?).await,
    ))
}