aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/ui/admin/mod.rs
blob: 55ac75de192a3510e19069b118b596b6be38f5d6 (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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
    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) 2024 metamuffin <metamuffin.org>
*/
pub mod log;
pub mod user;

use super::{
    account::session::AdminSession,
    assets::{resolve_asset, AVIF_QUALITY, AVIF_SPEED},
};
use crate::{
    database::DataAcid,
    routes::ui::{
        admin::log::rocket_uri_macro_r_admin_log,
        error::MyResult,
        layout::{DynLayoutPage, FlashDisplay, LayoutPage},
    },
    uri,
};
use anyhow::{anyhow, Context};
use jellybase::{
    assetfed::AssetInner,
    database::{redb::ReadableTable, TableExt, T_INVITE, T_NODE},
    federation::Federation,
    CONF,
};
use jellyimport::{import, is_importing};
use rand::Rng;
use rocket::{form::Form, get, post, FromForm, State};
use std::time::Instant;
use tokio::sync::Semaphore;
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" }
            @if is_importing() {
                section.message { p.warn { "An import is currently running." } }
            }
            @if is_transcoding() {
                section.message { p.warn { "Currently transcoding posters." } }
            }
            form[method="POST", action=uri!(r_admin_import())] {
                input[type="submit", disabled=is_importing(), value="(Re-)Import Library"];
            }
            form[method="POST", action=uri!(r_admin_transcode_posters())] {
                input[type="submit", disabled=is_transcoding(), value="Transcode all posters with low resolution"];
            }
            form[method="POST", action=uri!(r_admin_delete_cache())] {
                input.danger[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())),
        ),
    )
}

static SEM_TRANSCODING: Semaphore = Semaphore::const_new(1);
fn is_transcoding() -> bool {
    SEM_TRANSCODING.available_permits() == 0
}

#[post("/admin/transcode_posters")]
pub async fn r_admin_transcode_posters(
    session: AdminSession,
    database: &State<DataAcid>,
) -> MyResult<DynLayoutPage<'static>> {
    drop(session);
    let _permit = SEM_TRANSCODING
        .try_acquire()
        .context("transcoding in progress")?;

    let t = Instant::now();

    {
        let txn = database.begin_read()?;
        let nodes = txn.open_table(T_NODE)?;
        for node in nodes.iter()? {
            let (_, node) = node?;
            if let Some(poster) = &node.value().0.public.poster {
                let asset = AssetInner::deser(&poster.0)?;
                if asset.is_federated() {
                    continue;
                }
                let source = resolve_asset(asset).await.context("resolving asset")?;
                jellytranscoder::image::transcode(source, AVIF_QUALITY, AVIF_SPEED, 1024)
                    .await
                    .context("transcoding asset")?;
            }
        }
    }
    drop(_permit);

    admin_dashboard(
        &database,
        Some(Ok(format!(
            "All posters pre-transcoded; took {:?}",
            t.elapsed()
        ))),
    )
}