aboutsummaryrefslogtreecommitdiff
path: root/server/src/ui/admin/mod.rs
blob: b15512110f19ef1e80bbda7c997415d0fe429a61 (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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*
    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) 2025 metamuffin <metamuffin.org>
*/
pub mod log;
pub mod user;

use super::{
    assets::{resolve_asset, AVIF_QUALITY, AVIF_SPEED},
    error::MyResult,
};
use crate::{database::Database, locale::AcceptLanguage};
use anyhow::{anyhow, Context};
use jellybase::{assetfed::AssetInner, federation::Federation, CONF};
use jellycommon::routes::u_admin_dashboard;
use jellyimport::{import_wrap, is_importing, IMPORT_ERRORS};
use jellylogic::session::AdminSession;
use jellyui::{
    admin::AdminDashboardPage,
    render_page,
    scaffold::{RenderInfo, SessionInfo},
};
use rand::Rng;
use rocket::{
    form::Form,
    get, post,
    response::{content::RawHtml, Redirect},
    FromForm, State,
};
use std::time::Instant;
use tokio::{sync::Semaphore, task::spawn_blocking};

#[get("/admin/dashboard")]
pub async fn r_admin_dashboard(
    session: AdminSession,
    database: &State<Database>,
    lang: AcceptLanguage,
) -> MyResult<RawHtml<String>> {
    let AcceptLanguage(lang) = lang;
    let invites = database.list_invites()?;
    let flash = None;

    let last_import_err = IMPORT_ERRORS.read().await.to_owned();

    let busy = if is_importing() {
        Some("An import is currently running.")
    } else if is_transcoding() {
        Some("Currently transcoding posters.")
    } else {
        None
    };

    Ok(RawHtml(render_page(
        &AdminDashboardPage {
            busy,
            last_import_err: &last_import_err,
            invites: &invites,
            flash,
            lang: &lang,
        },
        RenderInfo {
            importing: is_importing(),
            session: Some(SessionInfo {
                user: session.0.user,
            }),
        },
        lang,
    )))
}

#[post("/admin/generate_invite")]
pub async fn r_admin_invite(
    _session: AdminSession,
    database: &State<Database>,
) -> MyResult<Redirect> {
    let i = format!("{}", rand::rng().random::<u128>());
    database.create_invite(&i)?;
    // admin_dashboard(database, Some(Ok(format!("Invite: {}", i)))).await
    Ok(Redirect::temporary(u_admin_dashboard()))
}

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

#[post("/admin/remove_invite", data = "<form>")]
pub async fn r_admin_remove_invite(
    session: AdminSession,
    database: &State<Database>,
    form: Form<DeleteInvite>,
) -> MyResult<Redirect> {
    drop(session);
    if !database.delete_invite(&form.invite)? {
        Err(anyhow!("invite does not exist"))?;
    };
    // admin_dashboard(database, Some(Ok("Invite invalidated".into()))).await
    Ok(Redirect::temporary(u_admin_dashboard()))
}

#[post("/admin/import?<incremental>")]
pub async fn r_admin_import(
    session: AdminSession,
    database: &State<Database>,
    _federation: &State<Federation>,
    incremental: bool,
) -> MyResult<Redirect> {
    drop(session);
    let t = Instant::now();
    if !incremental {
        database.clear_nodes()?;
    }
    let r = import_wrap((*database).clone(), incremental).await;
    // let flash = r
    //     .map_err(|e| e.into())
    //     .map(|_| format!("Import successful; took {:?}", t.elapsed()));
    // admin_dashboard(database, Some(flash)).await
    Ok(Redirect::temporary(u_admin_dashboard()))
}

#[post("/admin/update_search")]
pub async fn r_admin_update_search(
    _session: AdminSession,
    database: &State<Database>,
) -> MyResult<Redirect> {
    let db2 = (*database).clone();
    let r = spawn_blocking(move || db2.search_create_index())
        .await
        .unwrap();
    // admin_dashboard(
    //     database,
    //     Some(
    //         r.map_err(|e| e.into())
    //         .map(|_| "Search index updated".to_string()),
    //     ),
    // )
    // .await
    Ok(Redirect::temporary(u_admin_dashboard()))
}

#[post("/admin/delete_cache")]
pub async fn r_admin_delete_cache(
    session: AdminSession,
    database: &State<Database>,
) -> MyResult<Redirect> {
    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())),
    //     ),
    // )
    // .await
    Ok(Redirect::temporary(u_admin_dashboard()))
}

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<Database>,
) -> MyResult<Redirect> {
    drop(session);
    let _permit = SEM_TRANSCODING
        .try_acquire()
        .context("transcoding in progress")?;

    let t = Instant::now();

    {
        let nodes = database.list_nodes_with_udata("")?;
        for (node, _) in nodes {
            if let Some(poster) = &node.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()
    //     ))),
    // )
    // .await
    Ok(Redirect::temporary(u_admin_dashboard()))
}

// fn db_stats(_db: &Database) -> anyhow::Result<DynRender> {
//     // TODO
//     // let txn = db.inner.begin_read()?;
//     // let stats = [
//     //     ("node", txn.open_table(T_NODE)?.stats()?),
//     //     ("user", txn.open_table(T_USER_NODE)?.stats()?),
//     //     ("user-node", txn.open_table(T_USER_NODE)?.stats()?),
//     //     ("invite", txn.open_table(T_INVITE)?.stats()?),
//     // ];

//     // let cache_stats = db.node_index.reader.searcher().doc_store_cache_stats();
//     // let ft_total_docs = db.node_index.reader.searcher().total_num_docs()?;

//     Ok(markup::new! {
//         // h3 { "Key-Value-Store Statistics" }
//         // table.border {
//         //     tbody {
//         //         tr {
//         //             th { "table name" }
//         //             th { "tree height" }
//         //             th { "stored bytes" }
//         //             th { "metadata bytes" }
//         //             th { "fragmented bytes" }
//         //             th { "branch pages" }
//         //             th { "leaf pages" }
//         //         }
//         //         @for (name, stats) in &stats { tr {
//         //             td { @name }
//         //             td { @stats.tree_height() }
//         //             td { @format_size(stats.stored_bytes(), DECIMAL) }
//         //             td { @format_size(stats.metadata_bytes(), DECIMAL) }
//         //             td { @format_size(stats.fragmented_bytes(), DECIMAL) }
//         //             td { @stats.branch_pages() }
//         //             td { @stats.leaf_pages() }
//         //         }}
//         //     }
//         // }
//         // h3 { "Search Engine Statistics" }
//         // ul {
//         //     li { "Total documents: " @ft_total_docs }
//         //     li { "Cache misses: " @cache_stats.cache_misses }
//         //     li { "Cache hits: " @cache_stats.cache_hits }
//         // }
//     })
// }