aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/ui/admin/mod.rs
blob: 60ed416508eda34023abc5a79c0e86e3d9a3af07 (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
/*
    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 log;
pub mod user;

use super::account::session::AdminSession;
use crate::{
    database::DataAcid,
    routes::ui::{
        admin::log::rocket_uri_macro_r_admin_log,
        error::MyResult,
        layout::{DynLayoutPage, FlashDisplay, LayoutPage},
    },
    uri,
};
use anyhow::anyhow;
use jellybase::{
    database::{ReadableTable, TableExt, T_INVITE},
    federation::Federation,
    CONF,
};
use jellyimport::import;
use rand::Rng;
use rocket::{form::Form, get, post, FromForm, State};
use std::time::Instant;
use user::rocket_uri_macro_r_admin_users;

#[get("/admin/dashboard")]
pub fn r_admin_dashboard(
    _session: AdminSession,
    database: &State<DataAcid>,
) -> MyResult<DynLayoutPage<'static>> {
    admin_dashboard(database, None)
}

pub fn admin_dashboard<'a>(
    database: &DataAcid,
    flash: Option<MyResult<String>>,
) -> MyResult<DynLayoutPage<'a>> {
    let invites = {
        let txn = database.begin_read()?;
        let table = txn.open_table(T_INVITE)?;
        let i = table
            .iter()?
            .map(|a| {
                let (x, _) = a.unwrap();
                x.value().to_owned()
            })
            .collect::<Vec<_>>();
        drop(table);
        i
    };
    let flash = flash.map(|f| f.map_err(|e| format!("{e:?}")));

    Ok(LayoutPage {
        title: "Admin Dashboard".to_string(),
        content: markup::new! {
            h1 { "Admin Panel" }
            @FlashDisplay { flash: flash.clone() }
            ul {
                li{a[href=uri!(r_admin_log(true))] { "Server Log (Warnings only)" }}
                li{a[href=uri!(r_admin_log(false))] { "Server Log (Full) " }}
            }
            h2 { "Library" }
            form[method="POST", action=uri!(r_admin_import())] {
                input[type="submit", value="(Re-)Import Library"];
            }
            form[method="POST", action=uri!(r_admin_delete_cache())] {
                input[type="submit", value="Delete Cache"];
            }
            h2 { "Users" }
            p { a[href=uri!(r_admin_users())] "Manage Users" }
            h2 { "Invitations" }
            form[method="POST", action=uri!(r_admin_invite())] {
                input[type="submit", value="Generate new invite code"];
            }
            ul { @for t in &invites {
                li {
                    form[method="POST", action=uri!(r_admin_remove_invite())] {
                        span { @t }
                        input[type="text", name="invite", value=&t, hidden];
                        input[type="submit", value="Invalidate"];
                    }
                }
            }}
        },
        ..Default::default()
    })
}

#[post("/admin/generate_invite")]
pub fn r_admin_invite(
    _session: AdminSession,
    database: &State<DataAcid>,
) -> MyResult<DynLayoutPage<'static>> {
    let i = format!("{}", rand::thread_rng().gen::<u128>());
    T_INVITE.insert(&database, &*i, ())?;

    admin_dashboard(database, Some(Ok(format!("Invite: {}", i))))
}

#[derive(FromForm)]
pub struct DeleteInvite {
    invite: String,
}

#[post("/admin/remove_invite", data = "<form>")]
pub fn r_admin_remove_invite(
    session: AdminSession,
    database: &State<DataAcid>,
    form: Form<DeleteInvite>,
) -> MyResult<DynLayoutPage<'static>> {
    drop(session);
    T_INVITE
        .remove(&database, form.invite.as_str())?
        .ok_or(anyhow!("invite did not exist"))?;

    admin_dashboard(database, Some(Ok("Invite invalidated".into())))
}

#[post("/admin/import")]
pub async fn r_admin_import(
    session: AdminSession,
    database: &State<DataAcid>,
    federation: &State<Federation>,
) -> MyResult<DynLayoutPage<'static>> {
    drop(session);
    let t = Instant::now();
    let r = import(&database, &federation).await;
    admin_dashboard(
        &database,
        Some(
            r.map_err(|e| e.into())
                .map(|_| format!("Import successful; took {:?}", t.elapsed())),
        ),
    )
}

#[post("/admin/delete_cache")]
pub async fn r_admin_delete_cache(
    session: AdminSession,
    database: &State<DataAcid>,
) -> MyResult<DynLayoutPage<'static>> {
    drop(session);
    let t = Instant::now();
    let r = tokio::fs::remove_dir_all(&CONF.cache_path).await;
    tokio::fs::create_dir(&CONF.cache_path).await?;
    admin_dashboard(
        &database,
        Some(
            r.map_err(|e| e.into())
                .map(|_| format!("Cache deleted; took {:?}", t.elapsed())),
        ),
    )
}