live.umm.gay/wish-server-rs/src/main.rs

92 lines
2.2 KiB
Rust

use miette::{Context, IntoDiagnostic, Result};
use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};
use std::{env::VarError, net::SocketAddr, sync::Arc};
use axum::{routing, Router};
use tower_http::{
cors::{Any, CorsLayer},
trace::TraceLayer,
};
mod streams;
mod util;
mod wish;
use crate::wish::{
channel_info::{self, get_channel_info},
setup_webrtc,
whep::handle_whep,
whip::handle_whip,
};
#[derive(Clone)]
pub struct AppState {
pub webrtc: Arc<webrtc::api::API>,
pub db: SqlitePool,
}
#[tokio::main]
async fn main() -> Result<()> {
let _ = dotenv::dotenv();
{
if let Err(VarError::NotPresent) = std::env::var("RUST_LOG") {
std::env::set_var(
"RUST_LOG",
"wish_server_rs=debug,tower_http=debug,webrtc=info",
)
}
}
tracing_subscriber::fmt::init();
let db = {
let database_url = std::env::var("DATABASE_URL")
.into_diagnostic()
.wrap_err("DATABASE_URL was not set")?;
SqlitePoolOptions::new()
.connect(&database_url)
.await
.into_diagnostic()
.wrap_err("Couldn't open SQLite database")?
};
let webrtc = Arc::new(setup_webrtc()?);
let app_state = AppState {
webrtc,
db, // TODO: sqlx
};
let app = Router::new()
.route("/api/wish-server/whip", routing::any(handle_whip))
.route("/api/wish-server/whep", routing::any(handle_whep))
.route(
"/api/wish-server/stream/:channel",
routing::get(get_channel_info),
)
.layer(TraceLayer::new_for_http())
.layer(
CorsLayer::new()
.allow_methods(Any)
.allow_origin(Any)
.allow_headers(Any),
)
.with_state(app_state);
let bind_addr: SocketAddr = std::env::var("BIND_ADDRESS")
.unwrap_or_else(|_| "127.0.0.1:3001".into())
.parse()
.into_diagnostic()
.wrap_err("Couldn't parse bind address")?;
println!("Listening at http://{bind_addr}/ ...");
axum::Server::bind(&bind_addr)
.serve(app.into_make_service())
.await
.into_diagnostic()
.wrap_err("Server listening failed")?;
Ok(())
}