~aleteoryx/lfm_embed

ref: 7d8d5fa6f9bfafe07932728fe86ba14713377b7b lfm_embed/src/main.rs -rw-r--r-- 2.0 KiB
7d8d5fa6alyx Fix README typos 1 year, 3 months ago
                                                                                
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
#![feature(lazy_cell)]

use dotenv::var;
use log::LevelFilter;
use std::collections::BTreeMap;
use std::fs::File;
use std::sync::Arc;
use lfm_embed::{STATE, ResponseCtx};
use warp::Filter;

#[derive(serde::Deserialize, Debug)]
struct UserQuery {
    #[serde(default)]
    theme: Option<Arc<str>>,
    #[serde(flatten)]
    rest: BTreeMap<String, String>
}

#[tokio::main]
async fn main() {
    env_logger::Builder::new()
        .filter_level(LevelFilter::Warn)
        .parse_filters(&var("LFME_LOG_LEVEL").unwrap_or_default())
        .target(
            var("LFME_LOG_FILE").ok()
                .map(
                    |f| env_logger::Target::Pipe(
                        Box::new(File::options()
                                 .append(true)
                                 .open(f)
                                 .expect("couldn't open LFME_LOG_FILE")))
                )
                .unwrap_or(env_logger::Target::Stderr)
        ).init();

    std::sync::LazyLock::force(&STATE);

    let user = warp::path!("user" / String)
        .and(warp::query::<UserQuery>())
        .then(|s, q: UserQuery| async move {
            log::debug!(target: "lfm::server::user", "Handling request for user `{s}` with {q:?}");
            let (ctx, dur) = STATE.get_userinfo(&s).await;
            let ResponseCtx(mut data, status) = (ctx, q.rest).into();
            
            let theme = q.theme.filter(|a| STATE.handlebars().has_template(&a)).unwrap_or_else(|| STATE.default_theme());
            log::debug!(target: "lfm::server::user", "Using theme {theme}");
            warp::reply::with_header(
                warp::reply::with_header(
                    warp::reply::with_status(
                        warp::reply::html(
                            STATE.handlebars().render(&theme, &data).unwrap()
                        ), status
                    ), "Refresh", dur.as_secs()
                ), "X-Selected-Theme", theme.as_ref()
            )
        });

    warp::serve(user)
        .bind(([127,0,0,1], STATE.port())).await;
}