aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/ui/assets.rs
blob: eae1b9bde3252c17916a26ae0f204e85b89b50e0 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
    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},
};
use anyhow::anyhow;
use async_std::task::spawn_blocking;
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/<id>/asset?<role>&<width>")]
pub async fn r_item_assets(
    _sess: Session,
    db: &State<Database>,
    id: String,
    role: AssetRole,
    width: Option<usize>,
) -> Result<(ContentType, CacheControlFile), MyError> {
    let node = db.node.get(&id)?.ok_or(anyhow!("node does not exist"))?;
    let mut asset = match role {
        AssetRole::Backdrop => node.private.backdrop,
        AssetRole::Poster => node.private.poster,
    };
    if let None = asset {
        if let Some(parent) = &node.public.parent {
            let parent = db.node.get(parent)?.ok_or(anyhow!("node does not exist"))?;
            asset = match role {
                AssetRole::Backdrop => parent.private.backdrop,
                AssetRole::Poster => parent.private.poster,
            };
        }
    };
    let asset = asset.unwrap_or(AssetLocation::Assets(
        PathBuf::from_str("fallback.jpeg").unwrap(),
    ));
    // fit the resolution into a finite set so the maximum cache is finite too.
    let width = 2usize.pow(width.unwrap_or(2048).clamp(128, 8196).ilog2());
    let path =
        spawn_blocking(move || jellytranscoder::image::transcode(asset, 50., 5, width)).await?;
    info!("loading asset from {path:?}");
    Ok((
        ContentType::AVIF,
        CacheControlFile::new(File::open(path).await?).await,
    ))
}