aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/ui/search.rs
blob: bc84e57484b3e9f0d5afe0f1b649a8e7990344d2 (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
/*
    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>
*/
use super::{
    account::session::Session,
    error::MyResult,
    layout::{trs, DynLayoutPage, LayoutPage},
    node::{DatabaseNodeUserDataExt, NodeCard},
};
use crate::routes::{api::AcceptJson, locale::AcceptLanguage};
use anyhow::anyhow;
use jellybase::{database::Database, locale::tr};
use jellycommon::{api::ApiSearchResponse, Visibility};
use rocket::{get, serde::json::Json, Either, State};
use std::time::Instant;

#[get("/search?<query>&<page>")]
pub async fn r_search<'a>(
    session: Session,
    db: &State<Database>,
    aj: AcceptJson,
    query: Option<&str>,
    page: Option<usize>,
    lang: AcceptLanguage,
) -> MyResult<Either<DynLayoutPage<'a>, Json<ApiSearchResponse>>> {
    let AcceptLanguage(lang) = lang;
    let results = if let Some(query) = query {
        let timing = Instant::now();
        let (count, ids) = db.search(query, 32, page.unwrap_or_default() * 32)?;
        let mut nodes = ids
            .into_iter()
            .map(|id| db.get_node_with_userdata(id, &session))
            .collect::<Result<Vec<_>, anyhow::Error>>()?;
        nodes.retain(|(n, _)| n.visibility >= Visibility::Reduced);
        let search_dur = timing.elapsed();
        Some((count, nodes, search_dur))
    } else {
        None
    };
    let query = query.unwrap_or_default().to_string();

    Ok(if *aj {
        let Some((count, results, _)) = results else {
            Err(anyhow!("no query"))?
        };
        Either::Right(Json(ApiSearchResponse { count, results }))
    } else {
        Either::Left(LayoutPage {
            title: tr(lang, "search.title").to_string(),
            class: Some("search"),
            content: markup::new! {
                h1 { @trs(&lang, "search.title") }
                form[action="", method="GET"] {
                    input[type="text", name="query", placeholder=&*tr(lang, "search.placeholder"), value=&query];
                    input[type="submit", value="Search"];
                }
                @if let Some((count, results, search_dur)) = &results {
                    h2 { @trs(&lang, "search.results.title") }
                    p.stats { @tr(lang, "search.results.stats").replace("{count}", &count.to_string()).replace("{dur}", &format!("{search_dur:?}")) }
                    ul.children {@for (node, udata) in results.iter() {
                        li { @NodeCard { node, udata, lang: &lang } }
                    }}
                    // TODO pagination
                }
            },
        })
    })
}