Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       1201pub mod battler;2pub mod debug;3pub mod guard;4pub mod layout;5pub mod pokedex;67use actix_web::{HttpRequest, HttpResponse, Responder, get, post, web};8use serde::{Deserialize, Serialize};910use crate::auth;11use crate::config::Config;12use crate::db::{DuckDb, SqliteDb};13use crate::session::{SESSION_COOKIE_NAME, SessionStore};14use debug::DbTableSummary;15use layout::page_shell;1617pub fn is_htmx(req: &HttpRequest) -> bool {18    req.headers().contains_key("hx-request")19}2021const PAGE_SIZE: usize = 24;2223#[derive(Deserialize, Serialize)]24pub struct SearchQuery {25    #[serde(default)]26    pub q: String,27}2829#[derive(Deserialize, Serialize)]30pub struct PageQuery {31    #[serde(default)]32    pub offset: usize,33    #[serde(default)]34    pub q: String,35}3637#[derive(Deserialize, Serialize)]38pub struct PinForm {39    pub pin: String,40}4142#[get("/")]43pub async fn index(duck_db: web::Data<DuckDb>) -> impl Responder {44    let pokemon_list = duck_db45        .search_pokemon("", PAGE_SIZE, 0)46        .await47        .unwrap_or_default();48    let total = duck_db.total_pokemon_count("").await.unwrap_or(0);49    let has_more = total > PAGE_SIZE;5051    let content = pokedex::pokedex_tab_view(&pokemon_list, "", total, has_more, PAGE_SIZE);52    HttpResponse::Ok()53        .content_type("text/html; charset=utf-8")54        .body(page_shell("Pokédex • FireRed & LeafGreen", "pokedex", &content).into_string())55}5657#[get("/pokedex")]58pub async fn pokedex_tab(req: HttpRequest, duck_db: web::Data<DuckDb>) -> impl Responder {59    let pokemon_list = duck_db60        .search_pokemon("", PAGE_SIZE, 0)61        .await62        .unwrap_or_default();63    let total = duck_db.total_pokemon_count("").await.unwrap_or(0);64    let has_more = total > PAGE_SIZE;6566    let content = pokedex::pokedex_tab_view(&pokemon_list, "", total, has_more, PAGE_SIZE);67    if is_htmx(&req) {68        HttpResponse::Ok()69            .content_type("text/html; charset=utf-8")70            .body(content.into_string())71    } else {72        HttpResponse::Ok()73            .content_type("text/html; charset=utf-8")74            .body(page_shell("Pokédex • FireRed & LeafGreen", "pokedex", &content).into_string())75    }76}7778#[get("/pokedex/search")]79pub async fn pokedex_search(80    query: web::Query<SearchQuery>,81    duck_db: web::Data<DuckDb>,82) -> impl Responder {83    let q = query.q.trim();84    let pokemon_list = duck_db85        .search_pokemon(q, PAGE_SIZE, 0)86        .await87        .unwrap_or_default();88    let total = duck_db.total_pokemon_count(q).await.unwrap_or(0);89    let has_more = total > PAGE_SIZE;9091    let content = pokedex::pokemon_grid_items(&pokemon_list, q, has_more, PAGE_SIZE);92    HttpResponse::Ok()93        .content_type("text/html; charset=utf-8")94        .body(content.into_string())95}9697#[get("/pokedex/page")]98pub async fn pokedex_page(99    query: web::Query<PageQuery>,100    duck_db: web::Data<DuckDb>,101) -> impl Responder {102    let q = query.q.trim();103    let offset = query.offset;104    let pokemon_list = duck_db105        .search_pokemon(q, PAGE_SIZE, offset)106        .await107        .unwrap_or_default();108    let total = duck_db.total_pokemon_count(q).await.unwrap_or(0);109    let next_offset = offset + pokemon_list.len();110    let has_more = total > next_offset;111112    let content = pokedex::pokemon_grid_items(&pokemon_list, q, has_more, next_offset);113    HttpResponse::Ok()114        .content_type("text/html; charset=utf-8")115        .body(content.into_string())116}117118#[get("/pokemon/{id}")]119pub async fn pokemon_detail(120    req: HttpRequest,121    path: web::Path<i32>,122    duck_db: web::Data<DuckDb>,123) -> impl Responder {124    let id = path.into_inner();125    match duck_db.get_pokemon_by_id(id).await {126        Ok(Some(p)) => {127            let content = pokedex::pokemon_detail_page(&p);128            if is_htmx(&req) {129                HttpResponse::Ok()130                    .content_type("text/html; charset=utf-8")131                    .body(content.into_string())132            } else {133                HttpResponse::Ok()134                    .content_type("text/html; charset=utf-8")135                    .body(136                        page_shell(137                            &format!("{} • Pokédex", p.display_name),138                            "pokedex",139                            &content,140                        )141                        .into_string(),142                    )143            }144        }145        Ok(None) => HttpResponse::NotFound().body("Pokémon not found"),146        Err(e) => {147            log::error!("Failed to get pokemon {id}: {e}");148            HttpResponse::InternalServerError().finish()149        }150    }151}152153#[get("/battler")]154pub async fn battler_tab(req: HttpRequest) -> impl Responder {155    let content = battler::battler_view();156    if is_htmx(&req) {157        HttpResponse::Ok()158            .content_type("text/html; charset=utf-8")159            .body(content.into_string())160    } else {161        HttpResponse::Ok()162            .content_type("text/html; charset=utf-8")163            .body(page_shell("AutoBattler Arena • Coming Soon", "battler", &content).into_string())164    }165}166167#[get("/battler/ticket")]168pub async fn battler_ticket() -> impl Responder {169    let pin = crate::battle_ticket::generate_battle_pin();170    let qr_svg =171        crate::battle_ticket::generate_qr_svg(&format!("/battle?pin={pin}")).unwrap_or_default();172    let content = battler::battle_ticket_card(&pin, &qr_svg);173    HttpResponse::Ok()174        .content_type("text/html; charset=utf-8")175        .body(content.into_string())176}177178#[derive(Deserialize, Serialize)]179pub struct BattleQuery {180    pub pin: Option<String>,181}182183#[get("/battle")]184pub async fn battle_entry(req: HttpRequest, query: web::Query<BattleQuery>) -> impl Responder {185    let content = battler::battle_coming_soon_view(query.pin.as_deref());186    if is_htmx(&req) {187        HttpResponse::Ok()188            .content_type("text/html; charset=utf-8")189            .body(content.into_string())190    } else {191        HttpResponse::Ok()192            .content_type("text/html; charset=utf-8")193            .body(page_shell("Match Lobby • Coming Soon", "battler", &content).into_string())194    }195}196197#[get("/debug")]198pub async fn debug_tab(199    req: HttpRequest,200    config: web::Data<Config>,201    session_store: web::Data<SessionStore>,202    duck_db: web::Data<DuckDb>,203    sqlite_db: web::Data<SqliteDb>,204) -> impl Responder {205    if !auth::is_admin(&req, &config, &session_store) {206        let guard_html = guard::admin_pin_guard(None);207        return if is_htmx(&req) {208            HttpResponse::Ok()209                .content_type("text/html; charset=utf-8")210                .body(guard_html.into_string())211        } else {212            HttpResponse::Ok()213                .content_type("text/html; charset=utf-8")214                .body(page_shell("Admin Access • Pokédex", "debug", &guard_html).into_string())215        };216    }217218    let duck_summary = fetch_duck_summary(&duck_db).await;219    let sqlite_summary = fetch_sqlite_summary(&sqlite_db).await;220221    let content = debug::debug_view(222        duck_db.db_path(),223        sqlite_db.db_path(),224        &duck_summary,225        &sqlite_summary,226        None,227    );228229    if is_htmx(&req) {230        HttpResponse::Ok()231            .content_type("text/html; charset=utf-8")232            .body(content.into_string())233    } else {234        HttpResponse::Ok()235            .content_type("text/html; charset=utf-8")236            .body(page_shell("Debug Diagnostics • Pokédex", "debug", &content).into_string())237    }238}239240#[post("/pin")]241pub async fn verify_pin(242    form: web::Form<PinForm>,243    config: web::Data<Config>,244    session_store: web::Data<SessionStore>,245    duck_db: web::Data<DuckDb>,246    sqlite_db: web::Data<SqliteDb>,247) -> impl Responder {248    if config.is_valid_pin(&form.pin) {249        let token = session_store.create_session();250        let cookie = actix_web::cookie::Cookie::build(SESSION_COOKIE_NAME, token)251            .path("/")252            .http_only(true)253            .same_site(actix_web::cookie::SameSite::Lax)254            .finish();255256        let duck_summary = fetch_duck_summary(&duck_db).await;257        let sqlite_summary = fetch_sqlite_summary(&sqlite_db).await;258259        let content = debug::debug_view(260            duck_db.db_path(),261            sqlite_db.db_path(),262            &duck_summary,263            &sqlite_summary,264            None,265        );266267        HttpResponse::Ok()268            .cookie(cookie)269            .content_type("text/html; charset=utf-8")270            .body(content.into_string())271    } else {272        let guard_html = guard::admin_pin_guard(Some("Invalid PIN code. Please try again."));273        HttpResponse::Ok()274            .content_type("text/html; charset=utf-8")275            .body(guard_html.into_string())276    }277}278279#[post("/logout")]280pub async fn logout(req: HttpRequest, session_store: web::Data<SessionStore>) -> impl Responder {281    session_store.destroy_session(&req);282    let cookie = actix_web::cookie::Cookie::build(SESSION_COOKIE_NAME, "")283        .path("/")284        .max_age(actix_web::cookie::time::Duration::seconds(0))285        .finish();286287    let guard_html = guard::admin_pin_guard(None);288    HttpResponse::Ok()289        .cookie(cookie)290        .content_type("text/html; charset=utf-8")291        .body(guard_html.into_string())292}293294#[post("/debug/sync")]295pub async fn debug_sync(296    req: HttpRequest,297    config: web::Data<Config>,298    session_store: web::Data<SessionStore>,299    duck_db: web::Data<DuckDb>,300) -> impl Responder {301    if !auth::is_admin(&req, &config, &session_store) {302        return HttpResponse::Unauthorized().finish();303    }304305    match duck_db.seed_if_empty().await {306        Ok(count) => {307            let msg = format!("✓ DuckDB verified ({count} Pokémon active)");308            HttpResponse::Ok()309                .content_type("text/html; charset=utf-8")310                .body(format!("<span class='text-xs font-semibold px-2 py-1 bg-green-100 text-green-800 rounded'>{msg}</span>"))311        }312        Err(e) => HttpResponse::InternalServerError().body(format!(313            "<span class='text-xs text-red-600'>Sync error: {e}</span>"314        )),315    }316}317318async fn fetch_duck_summary(duck_db: &DuckDb) -> Vec<DbTableSummary> {319    let mut list = Vec::new();320    if let Ok(tables) = duck_db.list_tables().await {321        for table in tables {322            let row_count = duck_db.table_row_count(&table).await.unwrap_or(0);323            let columns = duck_db.describe_table(&table).await.unwrap_or_default();324            let preview = duck_db.preview_table(&table, 10).await.unwrap_or_else(|_| {325                crate::db::TablePreview {326                    table_name: table.clone(),327                    total_rows: 0,328                    columns: Vec::new(),329                    rows: Vec::new(),330                }331            });332            list.push(DbTableSummary {333                name: table,334                row_count,335                columns,336                preview,337            });338        }339    }340    list341}342343async fn fetch_sqlite_summary(sqlite_db: &SqliteDb) -> Vec<DbTableSummary> {344    let mut list = Vec::new();345    if let Ok(tables) = sqlite_db.list_tables().await {346        for table in tables {347            let row_count = sqlite_db.table_row_count(&table).await.unwrap_or(0);348            let columns = sqlite_db.describe_table(&table).await.unwrap_or_default();349            let preview = sqlite_db350                .preview_table(&table, 10)351                .await352                .unwrap_or_else(|_| crate::db::TablePreview {353                    table_name: table.clone(),354                    total_rows: 0,355                    columns: Vec::new(),356                    rows: Vec::new(),357                });358            list.push(DbTableSummary {359                name: table,360                row_count,361                columns,362                preview,363            });364        }365    }366    list367}