aboutsummaryrefslogtreecommitdiff
path: root/server/src/database.rs
blob: bfb5d4757d2cf062a9c02b5f8b3475ddaca7e2b9 (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
/*
    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::{routes::ui::account::hash_password, CONF};
use anyhow::Context;
use jellycommon::SeekIndex;
use log::info;
use serde::{Deserialize, Serialize};
use std::path::Path;
use typed_sled::Tree;

pub struct Database {
    pub db: sled::Db,

    pub users: Tree<String, User>,
    pub invites: Tree<String, ()>,
    pub items: Tree<String, Item>,
    pub seek_index: Tree<(String, usize), SeekIndex>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub name: String,
    pub display_name: String,
    pub password: Vec<u8>,
    pub admin: bool,
}

impl Database {
    pub fn open(path: &Path) -> Result<Self, anyhow::Error> {
        info!("opening database… (might take up to O(n) time)");
        let db = sled::open(path).context("opening database")?;
        info!("creating trees");
        let r = Ok(Self {
            users: Tree::open(&db, "users"),
            invites: Tree::open(&db, "invites"),
            items: Tree::open(&db, "items"),
            seek_index: Tree::open(&db, "seek_index"),
            db,
        });
        info!("ready");
        r
    }
    pub fn create_admin(&self) {
        self.users
            .insert(
                &CONF.admin_username,
                &User {
                    admin: true,
                    display_name: "Admin".to_string(),
                    name: CONF.admin_username.clone(),
                    password: hash_password(&CONF.admin_username, &CONF.admin_password),
                },
            )
            .unwrap();
    }
}