2022-04-02 20:56:51 +02:00
|
|
|
use axum::{extract::Extension, http::StatusCode, routing::get_service, Router};
|
2022-04-01 11:31:32 +02:00
|
|
|
use std::net::SocketAddr;
|
2022-04-01 13:29:34 +02:00
|
|
|
use tower_http::{auth::RequireAuthorizationLayer, services::ServeDir, trace::TraceLayer};
|
2022-04-01 11:31:32 +02:00
|
|
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
|
|
|
|
2022-04-02 20:56:51 +02:00
|
|
|
mod api;
|
|
|
|
mod matrix;
|
|
|
|
|
2022-04-02 13:01:49 +02:00
|
|
|
const STATIC_DIR_NAME: &str = "static";
|
|
|
|
|
2022-04-01 11:31:32 +02:00
|
|
|
#[tokio::main]
|
|
|
|
async fn main() {
|
|
|
|
// Enable tracing
|
|
|
|
tracing_subscriber::registry()
|
|
|
|
.with(tracing_subscriber::EnvFilter::new(
|
2022-04-02 20:56:51 +02:00
|
|
|
std::env::var("RUST_LOG").unwrap_or_else(|_| "site=debug,tower_http=debug".into()),
|
2022-04-01 11:31:32 +02:00
|
|
|
))
|
|
|
|
.with(tracing_subscriber::fmt::layer())
|
|
|
|
.init();
|
|
|
|
|
2022-04-01 13:29:34 +02:00
|
|
|
// Get required variables from env vars
|
|
|
|
let api_key = std::env::var("API_KEY").expect("No API_KEY was provided.");
|
|
|
|
let data_dir = std::env::var("DATA_DIR").expect("No DATA_DIR was provided.");
|
2022-04-02 13:01:49 +02:00
|
|
|
let static_dir = format!("{}/{}", data_dir, STATIC_DIR_NAME);
|
2022-04-01 13:29:34 +02:00
|
|
|
|
2022-04-02 13:01:49 +02:00
|
|
|
std::fs::create_dir_all(&static_dir);
|
2022-04-01 13:29:34 +02:00
|
|
|
|
2022-04-01 11:31:32 +02:00
|
|
|
let app = Router::new()
|
2022-04-02 20:56:51 +02:00
|
|
|
// Handle Matrix .well-known files
|
|
|
|
.nest("/", matrix::router())
|
|
|
|
// Routes under /api path
|
|
|
|
.nest(
|
|
|
|
"/api",
|
|
|
|
api::router().layer(RequireAuthorizationLayer::bearer(&api_key)),
|
2022-04-01 13:29:34 +02:00
|
|
|
)
|
|
|
|
// The fallback option is to serve the actual static files
|
2022-04-02 13:01:49 +02:00
|
|
|
.fallback(get_service(ServeDir::new(static_dir)).handle_error(
|
|
|
|
|error: std::io::Error| async move {
|
|
|
|
(
|
|
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
format!("Unhandled internal error: {}", error),
|
|
|
|
)
|
|
|
|
},
|
|
|
|
))
|
|
|
|
.layer(TraceLayer::new_for_http())
|
|
|
|
.layer(Extension(data_dir));
|
2022-04-01 11:31:32 +02:00
|
|
|
|
|
|
|
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
|
|
|
|
tracing::debug!("listening on {}", addr);
|
|
|
|
axum::Server::bind(&addr)
|
|
|
|
.serve(app.into_make_service())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
}
|