char/live.umm.gay

git clone https://git.t4t.associates/char/live.umm.gay

videogame hacker[wish-server-rs] Add endpoint to see view count11496ff

main
2.2 KiB91 linesraw
1use miette::{Context, IntoDiagnostic, Result};
2use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};
3use std::{env::VarError, net::SocketAddr, sync::Arc};
4
5use axum::{routing, Router};
6use tower_http::{
7    cors::{Any, CorsLayer},
8    trace::TraceLayer,
9};
10
11mod streams;
12mod util;
13mod wish;
14
15use crate::wish::{
16    channel_info::{self, get_channel_info},
17    setup_webrtc,
18    whep::handle_whep,
19    whip::handle_whip,
20};
21
22#[derive(Clone)]
23pub struct AppState {
24    pub webrtc: Arc<webrtc::api::API>,
25    pub db: SqlitePool,
26}
27
28#[tokio::main]
29async fn main() -> Result<()> {
30    let _ = dotenv::dotenv();
31    {
32        if let Err(VarError::NotPresent) = std::env::var("RUST_LOG") {
33            std::env::set_var(
34                "RUST_LOG",
35                "wish_server_rs=debug,tower_http=debug,webrtc=info",
36            )
37        }
38    }
39
40    tracing_subscriber::fmt::init();
41
42    let db = {
43        let database_url = std::env::var("DATABASE_URL")
44            .into_diagnostic()
45            .wrap_err("DATABASE_URL was not set")?;
46
47        SqlitePoolOptions::new()
48            .connect(&database_url)
49            .await
50            .into_diagnostic()
51            .wrap_err("Couldn't open SQLite database")?
52    };
53
54    let webrtc = Arc::new(setup_webrtc()?);
55    let app_state = AppState {
56        webrtc,
57        db, // TODO: sqlx
58    };
59
60    let app = Router::new()
61        .route("/api/wish-server/whip", routing::any(handle_whip))
62        .route("/api/wish-server/whep", routing::any(handle_whep))
63        .route(
64            "/api/wish-server/stream/:channel",
65            routing::get(get_channel_info),
66        )
67        .layer(TraceLayer::new_for_http())
68        .layer(
69            CorsLayer::new()
70                .allow_methods(Any)
71                .allow_origin(Any)
72                .allow_headers(Any),
73        )
74        .with_state(app_state);
75
76    let bind_addr: SocketAddr = std::env::var("BIND_ADDRESS")
77        .unwrap_or_else(|_| "127.0.0.1:3001".into())
78        .parse()
79        .into_diagnostic()
80        .wrap_err("Couldn't parse bind address")?;
81
82    println!("Listening at http://{bind_addr}/ ...");
83
84    axum::Server::bind(&bind_addr)
85        .serve(app.into_make_service())
86        .await
87        .into_diagnostic()
88        .wrap_err("Server listening failed")?;
89
90    Ok(())
91}