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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
/*
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>
*/
pub mod error;
use std::path::PathBuf;
use super::ui::{
account::{login_logic, LoginForm},
node::AssetRole,
};
use crate::{
database::Database,
library::{Library, Node},
routes::{api::error::ApiResult, ui::account::session::Session},
};
use anyhow::Context;
use jellycommon::api::ApiNode;
use log::info;
use rocket::{
get,
http::{ContentType, CookieJar},
post,
response::Redirect,
serde::json::Json,
State,
};
use serde_json::{json, Value};
use tokio::fs::File;
#[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 {
"1"
}
#[post("/api/account/login", data = "<data>")]
pub fn r_api_account_login(
database: &State<Database>,
jar: &CookieJar,
data: Json<LoginForm>,
) -> ApiResult<Value> {
login_logic(jar, database, &data.username, &data.password)?;
Ok(json!({ "ok": true }))
}
#[get("/api/assets/node/<path..>?<role>")]
pub async fn r_api_assets_node(
_sess: Session,
path: PathBuf,
role: AssetRole,
library: &State<Library>,
) -> ApiResult<(ContentType, File)> {
let node = library
.nested_path(&path)
.context("retrieving library node")?;
let path = node.get_asset(library, role);
info!("loading asset from {path:?}");
let ext = path.extension().unwrap().to_str().unwrap();
Ok((
ContentType::from_extension(ext).unwrap(),
File::open(path).await?,
))
}
#[get("/api/node/<path..>")]
pub fn r_api_node(
_sess: Session,
path: PathBuf,
library: &State<Library>,
) -> ApiResult<Json<ApiNode>> {
let node = library
.nested_path(&path)
.context("retrieving library node")?;
Ok(Json(match node.as_ref() {
Node::Directory(d) => ApiNode::Directory {
identifier: d.identifier.clone(),
info: d.info.clone(),
children: d
.children
.iter()
.map(|c| c.identifier().to_string())
.collect::<Vec<_>>(),
},
Node::Item(i) => ApiNode::Item {
identifier: i.identifier.clone(),
info: i.info.clone(),
},
}))
}
|