Skip to content
1        10        20        30        40        50        60        70        80        901#![warn(clippy::pedantic)]2#![allow(clippy::missing_errors_doc)]3#![allow(clippy::missing_panics_doc)]4#![allow(clippy::module_name_repetitions)]5#![allow(clippy::must_use_candidate)]67use actix_web::{App, HttpResponse, HttpServer, Responder, get, web};89mod assets;10mod auth;11mod battle_ticket;12mod config;13mod db;14mod models;15mod pokeapi;16mod session;17mod view;1819use db::{DuckDb, SqliteDb};20use session::SessionStore;2122#[get("/up")]23async fn up() -> impl Responder {24    HttpResponse::Ok().body("OK")25}2627fn init_logging() {28    let mut builder = env_logger::Builder::from_env(29        env_logger::Env::default().default_filter_or("info,duckdb=warn,libsql=warn,turso=warn"),30    );31    let env_logger = builder.build();32    let _ = log::set_boxed_logger(Box::new(env_logger));33    log::set_max_level(log::LevelFilter::Debug);34}3536fn spawn_duckdb_init(db: DuckDb) {37    actix_web::rt::spawn(async move {38        loop {39            match db.init().await {40                Ok(()) => {41                    log::info!("DuckDB initialized successfully");42                    if let Err(e) = db.seed_if_empty().await {43                        log::warn!("DuckDB seed warning: {e}");44                    }45                    return;46                }47                Err(e) => {48                    log::warn!("DuckDB init failed (retrying in 1s): {e}");49                    actix_web::rt::time::sleep(std::time::Duration::from_secs(1)).await;50                }51            }52        }53    });54}5556fn spawn_sqlite_init(db: SqliteDb) {57    actix_web::rt::spawn(async move {58        loop {59            match db.init().await {60                Ok(()) => {61                    log::info!("SQLite initialized successfully");62                    return;63                }64                Err(e) => {65                    log::warn!("SQLite init failed (retrying in 1s): {e}");66                    actix_web::rt::time::sleep(std::time::Duration::from_secs(1)).await;67                }68            }69        }70    });71}7273#[actix_web::main]74async fn main() -> std::io::Result<()> {75    init_logging();76    let config = config::from_env();77    config.maybe_reset_databases();7879    let duck_db = DuckDb::new(&config.duckdb_path).map_err(std::io::Error::other)?;80    spawn_duckdb_init(duck_db.clone());8182    let sqlite_db = SqliteDb::new(&config.sqlite_path);83    spawn_sqlite_init(sqlite_db.clone());8485    let port = config.port;86    let config_data = web::Data::new(config);87    let session_store = web::Data::new(SessionStore::new());88    let duck_data = web::Data::new(duck_db);89    let sqlite_data = web::Data::new(sqlite_db);9091    log::info!("Starting Pokédex & AutoBattler server on port {port}...");9293    HttpServer::new(move || {94        App::new()95            .app_data(config_data.clone())96            .app_data(session_store.clone())97            .app_data(duck_data.clone())98            .app_data(sqlite_data.clone())99            .service(up)100            .service(assets::serve_asset)101            .service(view::index)102            .service(view::pokedex_tab)103            .service(view::pokedex_search)104            .service(view::pokedex_page)105            .service(view::pokemon_detail)106            .service(view::battler_tab)107            .service(view::battler_ticket)108            .service(view::battle_entry)109            .service(view::debug_tab)110            .service(view::verify_pin)111            .service(view::logout)112            .service(view::debug_sync)113    })114    .bind(("0.0.0.0", port))?115    .run()116    .await117}118119#[cfg(test)]120mod tests {121    use super::*;122    use crate::session::SESSION_COOKIE_NAME;123    use actix_web::test as aw_test;124125    async fn create_test_databases() -> (config::Config, DuckDb, SqliteDb) {126        let nanos = std::time::SystemTime::now()127            .duration_since(std::time::UNIX_EPOCH)128            .unwrap()129            .as_nanos();130        let config = config::Config::new(131            8090,132            None,133            ":memory:".to_string(),134            format!("/tmp/test_main_{nanos}.db"),135            "123456".to_string(),136        );137138        let duck_db = DuckDb::new(":memory:").unwrap();139        duck_db.init().await.unwrap();140        duck_db.seed_test_data().await.unwrap();141142        let sqlite_db = SqliteDb::new(&config.sqlite_path);143        sqlite_db.init().await.unwrap();144145        (config, duck_db, sqlite_db)146    }147148    macro_rules! init_test_app {149        ($config:expr, $duck_db:expr, $sqlite_db:expr) => {150            aw_test::init_service(151                App::new()152                    .app_data(web::Data::new($config.clone()))153                    .app_data(web::Data::new(SessionStore::new()))154                    .app_data(web::Data::new($duck_db.clone()))155                    .app_data(web::Data::new($sqlite_db.clone()))156                    .service(up)157                    .service(assets::serve_asset)158                    .service(view::index)159                    .service(view::pokedex_tab)160                    .service(view::pokedex_search)161                    .service(view::pokedex_page)162                    .service(view::pokemon_detail)163                    .service(view::battler_tab)164                    .service(view::battler_ticket)165                    .service(view::battle_entry)166                    .service(view::debug_tab)167                    .service(view::verify_pin)168                    .service(view::logout)169                    .service(view::debug_sync),170            )171            .await172        };173    }174175    #[actix_web::test]176    async fn test_up_endpoint() {177        let (config, duck_db, sqlite_db) = create_test_databases().await;178        let app = init_test_app!(config, duck_db, sqlite_db);179        let req = aw_test::TestRequest::get().uri("/up").to_request();180        let resp = aw_test::call_service(&app, req).await;181        assert!(resp.status().is_success());182    }183184    #[actix_web::test]185    async fn test_home_and_pokedex_view() {186        let (config, duck_db, sqlite_db) = create_test_databases().await;187        let app = init_test_app!(config, duck_db, sqlite_db);188189        let req = aw_test::TestRequest::get().uri("/").to_request();190        let resp = aw_test::call_service(&app, req).await;191        assert!(resp.status().is_success());192193        let body = aw_test::read_body(resp).await;194        let body_str = String::from_utf8(body.to_vec()).unwrap();195        assert!(body_str.contains("Pokédex"));196        assert!(body_str.contains("Bulbasaur"));197        assert!(body_str.contains("/assets/h.js"));198        assert!(body_str.contains("/assets/app.css"));199    }200201    #[actix_web::test]202    async fn test_pokedex_search_endpoint() {203        let (config, duck_db, sqlite_db) = create_test_databases().await;204        let app = init_test_app!(config, duck_db, sqlite_db);205206        let req = aw_test::TestRequest::get()207            .uri("/pokedex/search?q=pikachu")208            .to_request();209        let resp = aw_test::call_service(&app, req).await;210        assert!(resp.status().is_success());211212        let body = aw_test::read_body(resp).await;213        let body_str = String::from_utf8(body.to_vec()).unwrap();214        assert!(body_str.contains("Pikachu"));215        assert!(!body_str.contains("Bulbasaur"));216    }217218    #[actix_web::test]219    async fn test_pokemon_detail_modal() {220        let (config, duck_db, sqlite_db) = create_test_databases().await;221        let app = init_test_app!(config, duck_db, sqlite_db);222223        // Direct full page load224        let req = aw_test::TestRequest::get().uri("/pokemon/1").to_request();225        let resp = aw_test::call_service(&app, req).await;226        assert!(resp.status().is_success());227228        let body = aw_test::read_body(resp).await;229        let body_str = String::from_utf8(body.to_vec()).unwrap();230        assert!(body_str.contains("Bulbasaur"));231        assert!(body_str.contains("Seed Pokémon"));232        assert!(body_str.contains("Combat Characteristics"));233        assert!(body_str.contains("Level-Up Moves"));234        assert!(body_str.contains("Back to Pokédex"));235236        // HTMX fragment request237        let req_htmx = aw_test::TestRequest::get()238            .uri("/pokemon/1")239            .insert_header(("hx-request", "true"))240            .to_request();241        let resp_htmx = aw_test::call_service(&app, req_htmx).await;242        assert!(resp_htmx.status().is_success());243        let body_htmx = aw_test::read_body(resp_htmx).await;244        let body_htmx_str = String::from_utf8(body_htmx.to_vec()).unwrap();245        assert!(body_htmx_str.contains("Bulbasaur"));246        assert!(body_htmx_str.contains("Back to Pokédex"));247        // Fragment should not contain DOCTYPE or full page shell248        assert!(!body_htmx_str.contains("<!DOCTYPE html>"));249    }250251    #[actix_web::test]252    async fn test_battler_coming_soon() {253        let (config, duck_db, sqlite_db) = create_test_databases().await;254        let app = init_test_app!(config, duck_db, sqlite_db);255256        let req = aw_test::TestRequest::get().uri("/battler").to_request();257        let resp = aw_test::call_service(&app, req).await;258        assert!(resp.status().is_success());259260        let body = aw_test::read_body(resp).await;261        let body_str = String::from_utf8(body.to_vec()).unwrap();262        assert!(body_str.contains("AutoBattler Arena"));263        assert!(264            body_str.to_lowercase().contains("coming soon") || body_str.contains("Comming soon")265        );266        // Generated QR code and player PIN under it267        assert!(body_str.contains("<svg"));268        assert!(body_str.contains("Player Battle PIN"));269270        // Test dynamic ticket generation271        let req_ticket = aw_test::TestRequest::get()272            .uri("/battler/ticket")273            .to_request();274        let resp_ticket = aw_test::call_service(&app, req_ticket).await;275        assert!(resp_ticket.status().is_success());276        let body_ticket = aw_test::read_body(resp_ticket).await;277        let body_ticket_str = String::from_utf8(body_ticket.to_vec()).unwrap();278        assert!(body_ticket_str.contains("<svg"));279        assert!(body_ticket_str.contains("Player Battle PIN"));280281        // Test player arriving at battle entry says coming soon282        let req_entry = aw_test::TestRequest::get()283            .uri("/battle?pin=987654")284            .to_request();285        let resp_entry = aw_test::call_service(&app, req_entry).await;286        assert!(resp_entry.status().is_success());287        let body_entry = aw_test::read_body(resp_entry).await;288        let body_entry_str = String::from_utf8(body_entry.to_vec()).unwrap();289        assert!(body_entry_str.to_lowercase().contains("coming soon"));290        assert!(body_entry_str.contains("987654"));291    }292293    #[actix_web::test]294    async fn test_debug_guard_and_unlock() {295        let (config, duck_db, sqlite_db) = create_test_databases().await;296        let sqlite_path = config.sqlite_path.clone();297        let app = init_test_app!(config, duck_db, sqlite_db);298299        // Unauthenticated debug returns guard300        let req = aw_test::TestRequest::get().uri("/debug").to_request();301        let resp = aw_test::call_service(&app, req).await;302        assert!(resp.status().is_success());303304        let body = aw_test::read_body(resp).await;305        let body_str = String::from_utf8(body.to_vec()).unwrap();306        assert!(body_str.contains("Admin Access"));307        assert!(body_str.contains("Unlock Admin Area"));308309        // Valid pin unlocks debug310        let req_pin = aw_test::TestRequest::post()311            .uri("/pin")312            .set_form(view::PinForm {313                pin: "123456".to_string(),314            })315            .to_request();316        let resp_pin = aw_test::call_service(&app, req_pin).await;317        assert!(resp_pin.status().is_success());318319        let cookie = resp_pin320            .response()321            .cookies()322            .find(|c| c.name() == SESSION_COOKIE_NAME);323        assert!(cookie.is_some());324325        let body_pin = aw_test::read_body(resp_pin).await;326        let body_pin_str = String::from_utf8(body_pin.to_vec()).unwrap();327        assert!(body_pin_str.contains("Architecture Explorer"));328        assert!(body_pin_str.contains("DuckDB Database Engine"));329        assert!(body_pin_str.contains("SQLite Database Engine"));330331        let _ = std::fs::remove_file(&sqlite_path);332    }333}