aboutsummaryrefslogtreecommitdiff
path: root/server/src/main.rs
blob: 4986d4ae53f4df4735f301e77a775bcf4962b232 (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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/*
    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) 2026 metamuffin <metamuffin.org>
*/
#![feature(never_type, exit_status_error)]
#![allow(clippy::needless_borrows_for_generic_args)]
#![recursion_limit = "4096"]

use crate::{
    auth::{hash_password, token::SessionKey},
    logger::setup_logger,
};
use anyhow::{Result, anyhow};
use base64::{Engine, prelude::BASE64_STANDARD};
use jellycache::Cache;
use jellycommon::{
    USER_ADMIN, USER_LOGIN, USER_PASSWORD, USER_PASSWORD_REQUIRE_CHANGE,
    internal::SESSION_KEY,
    jellyobject::{EMPTY, OBB, Path},
};
use jellydb::{Database, Filter, Query};
use log::{error, info};
use rand::random;
use routes::build_rocket;
use serde::Deserialize;
use std::{
    env::args,
    fs::read_to_string,
    path::PathBuf,
    process::{Command, exit},
    sync::Arc,
};

pub mod auth;
pub mod logger;
pub mod request_info;
pub mod responders;
pub mod routes;

#[rocket::main]
async fn main() {
    setup_logger();
    info!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
    let state = match create_state() {
        Ok(s) => s,
        Err(e) => {
            error!("unable to start: {e:#}");
            exit(1);
        }
    };
    let r = build_rocket(state).launch().await;
    match r {
        Ok(_) => info!("server shutdown"),
        Err(e) => {
            error!("server exited: {e}");
            exit(1);
        }
    }
}

pub struct State {
    pub config: Config,
    pub cache: Arc<Cache>,
    pub database: Arc<dyn Database>,
    pub session_key: SessionKey,
}

#[derive(Debug, Deserialize)]
#[rustfmt::skip]
pub struct Config {
    pub import: jellyimport::Config,
    #[serde(default)] pub ui: jellyui::Config,
    #[serde(default)] pub stream: Arc<jellystream::Config>,
    #[serde(default = "defaults::base_path")] pub base_path: PathBuf,
    #[serde(default = "defaults::asset_path")] pub asset_path: PathBuf,
    #[serde(default = "defaults::database_path")] pub database_path: PathBuf,
    #[serde(default = "defaults::cache_path")] pub cache_path: PathBuf,
    #[serde(default = "defaults::admin_password")] pub admin_password: String,
    #[serde(default = "defaults::max_memory_cache_size")] pub max_memory_cache_size: usize,
    pub session_key: Option<String>,
}
mod defaults {
    use std::path::PathBuf;
    pub fn base_path() -> PathBuf {
        ".".into()
    }
    pub fn asset_path() -> PathBuf {
        "assets".into()
    }
    pub fn database_path() -> PathBuf {
        "db".into()
    }
    pub fn cache_path() -> PathBuf {
        "cachedb".into()
    }
    pub fn max_memory_cache_size() -> usize {
        100_000_000
    }
    pub fn admin_password() -> String {
        "admin".to_string()
    }
}

pub fn create_state() -> Result<Arc<State>> {
    info!("loading config...");
    let config_path = args()
        .nth(1)
        .ok_or(anyhow!("first argument (config path) missing"))?;
    let mut config: Config = serde_yaml_ng::from_str(&read_to_string(config_path)?)?;

    config.cache_path = config.base_path.join(config.cache_path);
    config.asset_path = config.base_path.join(config.asset_path);
    config.database_path = config.base_path.join(config.database_path);

    init_asset_dir(&config.asset_path)?;
    info!("opening cache...");
    let cache_storage = jellykv::rocksdb::new(&config.cache_path)?;
    info!("opening database...");
    let db_storage = jellykv::rocksdb::new(&config.database_path)?;

    let session_key = config
        .session_key
        .clone()
        .map(Ok)
        .unwrap_or_else(|| session_key_from_db(&db_storage))?;

    let state = Arc::new(State {
        cache: Cache::new(Box::new(cache_storage), config.max_memory_cache_size).into(),
        database: Arc::new(db_storage),
        session_key: SessionKey::parse(&session_key)?,
        config,
    });

    create_admin_user(&state)?;

    info!("ready");
    Ok(state)
}

fn create_admin_user(state: &State) -> Result<()> {
    info!("checking admin user...");
    state.database.transaction(&mut |txn| {
        let admin_row = txn.query_single(Query {
            filter: Filter::Match(Path(vec![USER_LOGIN.0]), "admin".into()),
            ..Default::default()
        })?;
        if admin_row.is_none() {
            info!("Creating new admin user");
            let pwhash = hash_password("admin", &state.config.admin_password);
            let mut user = OBB::new()
                .with(USER_LOGIN, "admin")
                .with(USER_PASSWORD, &pwhash)
                .with(USER_ADMIN, ())
                .finish();
            if state.config.admin_password == "admin" {
                user = user.insert(USER_PASSWORD_REQUIRE_CHANGE, ());
            }
            txn.insert(user)?;
        }

        Ok(())
    })?;
    Ok(())
}

fn session_key_from_db(db: &dyn Database) -> Result<String> {
    info!("retrieving session key...");
    let mut sk = None;
    db.transaction(&mut |txn| match txn.query_single(Query {
        filter: Filter::Has(Path(vec![SESSION_KEY.0])),
        ..Default::default()
    })? {
        Some(r) => {
            sk = Some(txn.get(r)?.unwrap().get(SESSION_KEY).unwrap().to_string());
            Ok(())
        }
        None => {
            let k = BASE64_STANDARD.encode([(); 32].map(|()| random()));
            txn.insert(EMPTY.insert(SESSION_KEY, &k))?;
            sk = Some(k);
            Ok(())
        }
    })?;
    Ok(sk.unwrap())
}

fn init_asset_dir(path: &std::path::Path) -> Result<()> {
    if path.exists() {
        return Ok(());
    }
    info!("git-cloning assets repo to {path:?}");
    Command::new("git")
        .arg("clone")
        .arg("https://codeberg.org/metamuffin/jellything-assets.git")
        .arg(path)
        .output()?
        .exit_ok()?;
    info!("done");
    Ok(())
}