551 lines
29 KiB
Rust
551 lines
29 KiB
Rust
//! The Game Boy Discord Activity's web side, served by the dashboard's web server under /activity (below the DASHBOARD_URL path, /dezio).
|
|
//!
|
|
//! The emulator itself (binjgb, WebAssembly) runs in each player's Discord client, so the bot only hands out the page,
|
|
//! the ROMs (once — the client keeps them in IndexedDB) and the saves.
|
|
//!
|
|
//! /activity/ the page (web/activity/)
|
|
//! /activity/static/… its scripts, styles and the vendored emulator + Discord SDK
|
|
//! GET /activity/api/config {client_id} for the SDK (and whether local test sign-in is on)
|
|
//! POST /activity/api/web-session outside Discord: uses the dashboard's Discord sign-in cookie instead
|
|
//! POST /activity/api/token {code} from the SDK's authorize → {access_token, session, user}
|
|
//! GET /activity/api/library the ROMs in assets/roms/<category>/ and what this player has saved
|
|
//! GET /activity/api/rom/<id>?v=… a ROM (cached by the browser forever: the version changes with the file)
|
|
//! GET|PUT /activity/api/save/<id> battery save (in-game saves), per player
|
|
//! GET|PUT|DELETE /activity/api/state/<id>/<slot> save states, slots 0-3 (0 = "resume where I left off")
|
|
//! GET /activity/api/legacy/<id> the old chat Game Boy's battery save, for importing once
|
|
//! GET /activity/api/art/<id> the game's cover (public): an image next to the ROM wins, else SteamGridDB
|
|
//! (STEAMGRIDDB_API_KEY), cached in data/gameboy/art
|
|
//!
|
|
//! Developer Portal setup (once): Activities → Settings → enable; Activities → URL Mappings → `/` → `<DASHBOARD_URL host + path>/activity` (e.g. astar76.com/dezio/activity)
|
|
//! (no https://); OAuth2 → Redirects needs at least one entry (the dashboard's /callback is there already).
|
|
//! DEZIO_ACTIVITY_DEV=1 adds POST /activity/api/dev-session, a test sign-in for requests from 127.0.0.1.
|
|
//! Everything else under /api needs the session from /api/token (`Authorization: Bearer …`).
|
|
use super::{now, random_token, sha, ApiError, Shared};
|
|
use crate::paths;
|
|
use crate::storage::JsonStore;
|
|
use axum::body::Bytes;
|
|
use axum::extract::{ConnectInfo, DefaultBodyLimit, Path, State as AxState};
|
|
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
|
use axum::response::{IntoResponse, Redirect, Response};
|
|
use axum::routing::{get, post, put};
|
|
use axum::{Json, Router};
|
|
use serde_json::{json, Value};
|
|
use sha1::{Digest, Sha1};
|
|
use std::collections::HashMap;
|
|
use std::net::SocketAddr;
|
|
use std::path::{Path as FsPath, PathBuf};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, Instant};
|
|
use tokio::sync::Semaphore;
|
|
use tower_http::services::ServeDir;
|
|
|
|
const SESSION_HOURS: u64 = 24;
|
|
const MAX_SAVE: usize = 256 * 1024; // cartridge RAM is at most 128 KB (+ RTC)
|
|
const MAX_STATE: usize = 1024 * 1024; // binjgb states are ~70 KB (GBC); room to spare
|
|
const ART_RETRY: u64 = 7 * 86400; // look a missing cover up again after a week
|
|
const ART_SIZE: (u32, u32) = (300, 450); // SteamGridDB "grids" are 2:3
|
|
const SGDB: &str = "https://www.steamgriddb.com/api/v2";
|
|
const ROM_EXTS: [&str; 2] = ["gb", "gbc"];
|
|
|
|
#[derive(Clone)]
|
|
pub struct Rom {
|
|
pub id: String,
|
|
pub version: String,
|
|
pub path: PathBuf,
|
|
pub title: String,
|
|
pub category: String,
|
|
pub cgb: bool,
|
|
pub size: u64,
|
|
}
|
|
|
|
fn hex(bytes: &[u8]) -> String {
|
|
use std::fmt::Write as _;
|
|
bytes.iter().fold(String::new(), |mut s, b| {
|
|
let _ = write!(s, "{b:02x}");
|
|
s
|
|
})
|
|
}
|
|
|
|
pub fn clean_title(stem: &str) -> String {
|
|
let no_tags = regex::Regex::new(r"\s*[\(\[][^)\]]*[\)\]]").unwrap().replace_all(stem, "").trim_matches(|c| c == ' ' || c == '-' || c == '_').to_string();
|
|
let t = regex::Regex::new(r"\s+").unwrap().replace_all(&no_tags, " ").to_string();
|
|
if t.is_empty() { stem.to_string() } else { t }
|
|
}
|
|
|
|
/// Comparable game name: no accents, punctuation, "Version" or a trailing "1".
|
|
fn norm(name: &str) -> String {
|
|
let lower: String = name.chars().map(|c| match c { 'é' | 'è' | 'ê' => 'e', 'á' | 'à' | 'â' => 'a', 'ó' | 'ò' | 'ô' => 'o', 'í' | 'ì' => 'i', 'ú' | 'ù' => 'u', c => c }).collect::<String>().to_lowercase();
|
|
let t = regex::Regex::new(r"\b(version|special pikachu edition)\b").unwrap().replace_all(&lower, " ").to_string();
|
|
let t = regex::Regex::new(r"[^a-z0-9]+").unwrap().replace_all(&t, " ").trim().to_string();
|
|
regex::Regex::new(r"\s1$").unwrap().replace(&t, "").to_string()
|
|
}
|
|
|
|
impl Rom {
|
|
fn load(path: &FsPath, root: &FsPath) -> Option<Rom> {
|
|
let meta = std::fs::metadata(path).ok()?;
|
|
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
|
|
let mtime = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs();
|
|
let id = hex(&Sha1::digest(rel.as_bytes()))[..16].to_string();
|
|
let version = hex(&Sha1::digest(format!("{}\0{mtime}", meta.len()).as_bytes()))[..8].to_string();
|
|
let parent = path.parent()?;
|
|
let category = if parent != root { parent.file_name()?.to_string_lossy().to_string() } else { "other".into() };
|
|
let flag = std::fs::read(path).ok().and_then(|b| b.get(0x143).copied());
|
|
let cgb = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("gbc")) || matches!(flag, Some(0x80 | 0xC0));
|
|
Some(Rom { id, version, path: path.to_path_buf(), title: clean_title(&path.file_stem()?.to_string_lossy()), category, cgb, size: meta.len() })
|
|
}
|
|
|
|
/// Battery save the old PyBoy chat Game Boy left next to the ROM.
|
|
fn legacy_save(&self) -> PathBuf {
|
|
let mut name = self.path.file_name().map(|n| n.to_os_string()).unwrap_or_default();
|
|
name.push(".ram");
|
|
self.path.with_file_name(name)
|
|
}
|
|
}
|
|
|
|
pub struct Activity {
|
|
sessions: Arc<JsonStore>,
|
|
library: Mutex<(Option<Instant>, Arc<HashMap<String, Rom>>)>,
|
|
sgdb: Semaphore,
|
|
locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
|
|
}
|
|
|
|
impl Activity {
|
|
pub fn new() -> Self {
|
|
Self { sessions: JsonStore::open(paths::data(&["activity_sessions.json"])), library: Mutex::new((None, Arc::new(HashMap::new()))), sgdb: Semaphore::new(2), locks: Default::default() }
|
|
}
|
|
|
|
fn roms_dir() -> PathBuf {
|
|
paths::asset(&["roms"])
|
|
}
|
|
|
|
fn library(&self) -> Arc<HashMap<String, Rom>> {
|
|
let mut g = self.library.lock().unwrap_or_else(|e| e.into_inner());
|
|
if g.0.is_some_and(|t| t.elapsed() < Duration::from_secs(60)) {
|
|
return g.1.clone();
|
|
}
|
|
let root = Self::roms_dir();
|
|
let mut found = HashMap::new();
|
|
let mut stack = vec![root.clone()];
|
|
while let Some(d) = stack.pop() {
|
|
let Ok(rd) = std::fs::read_dir(&d) else { continue };
|
|
for e in rd.flatten() {
|
|
let p = e.path();
|
|
if p.is_dir() {
|
|
stack.push(p);
|
|
} else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| ROM_EXTS.contains(&x.to_lowercase().as_str())) {
|
|
if let Some(r) = Rom::load(&p, &root) {
|
|
found.insert(r.id.clone(), r);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
*g = (Some(Instant::now()), Arc::new(found));
|
|
g.1.clone()
|
|
}
|
|
|
|
fn rom(&self, id: &str) -> Result<Rom, ApiError> {
|
|
self.library().get(id).cloned().ok_or_else(|| ApiError::new(404, "No such game"))
|
|
}
|
|
|
|
pub fn new_session(&self, user: u64, name: &str) -> String {
|
|
let t = now();
|
|
let dead: Vec<String> = self.sessions.snapshot().iter().filter(|(_, v)| v["expires"].as_u64().unwrap_or(0) < t).map(|(k, _)| k.clone()).collect();
|
|
for k in dead {
|
|
self.sessions.pop(k);
|
|
}
|
|
let raw = random_token(32);
|
|
self.sessions.set(sha(&raw), json!({"user_id": user, "name": name, "expires": t + SESSION_HOURS * 3600}));
|
|
raw
|
|
}
|
|
|
|
fn user_id(&self, headers: &HeaderMap) -> Result<u64, ApiError> {
|
|
let token = headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|a| a.strip_prefix("Bearer ")).unwrap_or("");
|
|
let data = (!token.is_empty()).then(|| self.sessions.get(sha(token))).flatten();
|
|
match data {
|
|
Some(d) if d["expires"].as_u64().unwrap_or(0) >= now() => d["user_id"].as_u64().ok_or_else(|| ApiError::new(401, "Sign in again")),
|
|
_ => Err(ApiError::new(401, "Sign in again")),
|
|
}
|
|
}
|
|
|
|
fn folder(user: u64) -> PathBuf {
|
|
paths::data(&["gameboy", "activity", &user.to_string(), "x"]).parent().map(FsPath::to_path_buf).unwrap_or_default()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub fn folder_for_tests(user: u64) -> PathBuf {
|
|
Self::folder(user)
|
|
}
|
|
|
|
fn art_dir() -> PathBuf {
|
|
paths::data(&["gameboy", "art", "x"]).parent().map(FsPath::to_path_buf).unwrap_or_default()
|
|
}
|
|
|
|
// ---- cover art + tidy names -------------------------------------------------------------------
|
|
// Per ROM, data/gameboy/art/<rom id>.json = {"name": SteamGridDB's name or null, "art": bool, "checked": time}
|
|
// and <rom id>.jpg = the cover. A miss is looked up again after ART_RETRY.
|
|
fn local_art(rom: &Rom) -> Option<PathBuf> {
|
|
for ext in ["webp", "png", "jpg", "jpeg"] {
|
|
let a = rom.path.with_extension(ext);
|
|
let mut b = rom.path.file_name()?.to_os_string();
|
|
b.push(format!(".{ext}"));
|
|
for p in [a, rom.path.with_file_name(b)] {
|
|
if p.exists() {
|
|
return Some(p);
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn search_words(rom: &Rom) -> Value {
|
|
if let Some(o) = crate::storage::read_json(&Self::roms_dir().join("art.json")) {
|
|
if let Some(v) = rom.path.file_name().and_then(|n| o.get(n.to_string_lossy().as_ref())) {
|
|
return v.clone();
|
|
}
|
|
}
|
|
let w = rom.title.replace(" - ", " ").replace("Pokemon", "Pokémon");
|
|
let w = regex::Regex::new(r"\b(Version|Special Pikachu Edition)\b").unwrap().replace_all(&w, "").to_string();
|
|
let w = regex::Regex::new(r"([a-z])([A-Z])").unwrap().replace_all(&w, "$1 $2").to_string();
|
|
let w = regex::Regex::new(r"\s1$").unwrap().replace(&w, "").to_string();
|
|
json!(regex::Regex::new(r"\s+").unwrap().replace_all(&w, " ").trim())
|
|
}
|
|
|
|
fn meta(rom: &Rom) -> Value {
|
|
crate::storage::read_json(&Self::art_dir().join(format!("{}.json", rom.id))).unwrap_or(Value::Null)
|
|
}
|
|
|
|
fn display_name(rom: &Rom) -> String {
|
|
if let Some(n) = Self::meta(rom)["name"].as_str() {
|
|
return n.replace(" - ", ": ");
|
|
}
|
|
let t = regex::Regex::new(r"([a-z])([A-Z])").unwrap().replace_all(&rom.title, "$1 $2").replace("Pokemon", "Pokémon");
|
|
regex::Regex::new(r"\s1$").unwrap().replace(&t, "").to_string()
|
|
}
|
|
|
|
fn needs_lookup(rom: &Rom) -> bool {
|
|
if std::env::var("STEAMGRIDDB_API_KEY").unwrap_or_default().is_empty() {
|
|
return false;
|
|
}
|
|
let m = Self::meta(rom);
|
|
if m.is_null() {
|
|
return true;
|
|
}
|
|
let found = m["name"].is_string() && (m["art"] == json!(true) || Self::local_art(rom).is_some());
|
|
!found && now().saturating_sub(m["checked"].as_u64().unwrap_or(0)) > ART_RETRY
|
|
}
|
|
|
|
fn art_path(rom: &Rom) -> Option<PathBuf> {
|
|
Self::local_art(rom).or_else(|| ["jpg", "webp"].iter().map(|e| Self::art_dir().join(format!("{}.{e}", rom.id))).find(|p| p.exists()))
|
|
}
|
|
|
|
async fn sgdb_json(&self, web: &reqwest::Client, path: &str, key: &str) -> Option<Value> {
|
|
let _s = self.sgdb.acquire().await.ok()?;
|
|
let r = web.get(format!("{SGDB}{path}")).bearer_auth(key).timeout(Duration::from_secs(15)).send().await.ok()?;
|
|
r.status().is_success().then_some(())?;
|
|
r.json().await.ok()
|
|
}
|
|
|
|
/// Find the game on SteamGridDB: its proper name and a 2:3 cover (shrunk to a small JPEG).
|
|
async fn lookup_inner(&self, web: &reqwest::Client, rom: &Rom) {
|
|
let Ok(key) = std::env::var("STEAMGRIDDB_API_KEY") else { return };
|
|
let query = Self::search_words(rom);
|
|
let (mut name, mut art) = (None::<String>, false);
|
|
let game = if let Some(id) = query.as_u64().or_else(|| query.as_str().and_then(|s| s.parse().ok())) {
|
|
self.sgdb_json(web, &format!("/games/id/{id}"), &key).await.map(|d| d["data"].clone()).unwrap_or(Value::Null)
|
|
} else {
|
|
let q = query.as_str().unwrap_or("");
|
|
let Some(found) = self.sgdb_json(web, &format!("/search/autocomplete/{}", urlencoding::encode(q)), &key).await else { return };
|
|
let games = found["data"].as_array().cloned().unwrap_or_default();
|
|
// an exact name match wins (the first result can be a sequel or a ROM hack); else the best guess
|
|
let want = norm(q);
|
|
games.iter().find(|g| norm(g["name"].as_str().unwrap_or("")) == want).or_else(|| games.first()).cloned().unwrap_or(Value::Null)
|
|
};
|
|
if let Some(gid) = game["id"].as_u64() {
|
|
name = game["name"].as_str().map(str::to_string);
|
|
if Self::local_art(rom).is_none() {
|
|
let grids = self.sgdb_json(web, &format!("/grids/game/{gid}?dimensions=600x900,342x482,660x930&nsfw=false&humor=false"), &key).await;
|
|
let items: Vec<Value> = grids.and_then(|g| g["data"].as_array().cloned()).unwrap_or_default().into_iter().filter(|g| g["nsfw"] != json!(true) && g["humor"] != json!(true)).collect();
|
|
if let Some(best) = items.iter().max_by_key(|g| g["score"].as_i64().unwrap_or(0)) {
|
|
let url = best["thumb"].as_str().or_else(|| best["url"].as_str()).unwrap_or("");
|
|
if let Ok(r) = web.get(url).timeout(Duration::from_secs(20)).send().await {
|
|
if let Ok(raw) = r.bytes().await {
|
|
if let Some(jpg) = tokio::task::spawn_blocking(move || shrink(&raw)).await.ok().flatten() {
|
|
write_file(&Self::art_dir().join(format!("{}.jpg", rom.id)), &jpg);
|
|
art = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
tracing::info!("No SteamGridDB match for {} ({query})", rom.path.display());
|
|
}
|
|
write_file(&Self::art_dir().join(format!("{}.json", rom.id)), json!({"name": name, "art": art, "checked": now()}).to_string().as_bytes());
|
|
}
|
|
|
|
async fn lookup(&self, web: &reqwest::Client, rom: &Rom) {
|
|
let lock = self.locks.lock().unwrap_or_else(|e| e.into_inner()).entry(rom.id.clone()).or_default().clone();
|
|
let _g = lock.lock().await;
|
|
if Self::needs_lookup(rom) {
|
|
self.lookup_inner(web, rom).await;
|
|
}
|
|
}
|
|
|
|
/// Look up new games; wait up to `wait` seconds so a first visit already shows them.
|
|
async fn warm_art(self: &Arc<Self>, web: &reqwest::Client, roms: Vec<Rom>, wait: u64) {
|
|
let todo: Vec<Rom> = roms.into_iter().filter(Self::needs_lookup).collect();
|
|
if todo.is_empty() {
|
|
return;
|
|
}
|
|
let (me, web) = (self.clone(), web.clone());
|
|
let task = tokio::spawn(async move {
|
|
futures::future::join_all(todo.iter().map(|r| me.lookup(&web, r))).await;
|
|
});
|
|
let _ = tokio::time::timeout(Duration::from_secs(wait), task).await;
|
|
}
|
|
}
|
|
|
|
fn shrink(raw: &[u8]) -> Option<Vec<u8>> {
|
|
let img = image::load_from_memory(raw).ok()?.to_rgb8();
|
|
let img = if (img.width(), img.height()) != ART_SIZE { image::imageops::resize(&img, ART_SIZE.0, ART_SIZE.1, image::imageops::FilterType::Lanczos3) } else { img };
|
|
let mut out = std::io::Cursor::new(Vec::new());
|
|
img.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 82)).ok()?;
|
|
Some(out.into_inner())
|
|
}
|
|
|
|
fn write_file(path: &FsPath, data: &[u8]) {
|
|
if let Some(p) = path.parent() {
|
|
let _ = std::fs::create_dir_all(p);
|
|
}
|
|
let tmp = path.with_file_name(format!(".{}.{}.tmp", path.file_name().and_then(|n| n.to_str()).unwrap_or("f"), random_token(4)));
|
|
if std::fs::write(&tmp, data).is_ok() {
|
|
let _ = std::fs::rename(&tmp, path);
|
|
}
|
|
}
|
|
|
|
// ---- the page ---------------------------------------------------------------------------------------------------------
|
|
|
|
/// index.html with `static/x?v=<content hash>` links: Discord's proxy keeps static files for hours, so an update would
|
|
/// otherwise mix a new page with old scripts and styles.
|
|
fn page_html() -> String {
|
|
let dir = paths::web(&["activity"]);
|
|
let html = std::fs::read_to_string(dir.join("index.html")).unwrap_or_default();
|
|
regex::Regex::new(r#"((?:src|href)=")(static/[^"?]+)""#).unwrap().replace_all(&html, |c: ®ex::Captures| {
|
|
let digest = std::fs::read(dir.join(&c[2])).map(|b| hex(&Sha1::digest(&b))[..10].to_string()).unwrap_or_else(|_| "0".into());
|
|
format!("{}{}?v={digest}\"", &c[1], &c[2])
|
|
}).into_owned()
|
|
}
|
|
|
|
async fn page() -> Response {
|
|
([(header::CONTENT_TYPE, "text/html; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], page_html()).into_response()
|
|
}
|
|
|
|
async fn slash_redirect(AxState(w): AxState<Shared>, uri: axum::http::Uri) -> Redirect {
|
|
Redirect::to(&format!("{}/activity/{}", w.cfg.base, uri.query().map(|q| format!("?{q}")).unwrap_or_default()))
|
|
}
|
|
|
|
/// Dev sessions only for a browser on this machine. Behind `tailscale serve` every request comes from 127.0.0.1 too,
|
|
/// so a forwarded request (X-Forwarded-For) or a non-local Host never counts, even if DEZIO_ACTIVITY_DEV is left on.
|
|
fn dev_mode(addr: &SocketAddr, headers: &HeaderMap) -> bool {
|
|
let host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or("");
|
|
let local_host = ["127.0.0.1", "localhost", "[::1]"].iter().any(|h| host == *h || host.starts_with(&format!("{h}:")));
|
|
std::env::var("DEZIO_ACTIVITY_DEV").as_deref() == Ok("1") && addr.ip().is_loopback() && local_host && !headers.contains_key("x-forwarded-for")
|
|
}
|
|
|
|
async fn config(AxState(w): AxState<Shared>, ConnectInfo(addr): ConnectInfo<SocketAddr>, headers: HeaderMap) -> Response {
|
|
([(header::CACHE_CONTROL, "no-store")], Json(json!({"client_id": w.state.app_id().to_string(), "dev": dev_mode(&addr, &headers)}))).into_response()
|
|
}
|
|
|
|
async fn dev_session(AxState(w): AxState<Shared>, ConnectInfo(addr): ConnectInfo<SocketAddr>, headers: HeaderMap) -> Result<Json<Value>, ApiError> {
|
|
if !dev_mode(&addr, &headers) {
|
|
return Err(ApiError::new(404, "Not found"));
|
|
}
|
|
Ok(Json(json!({"session": w.activity.new_session(1, "Tester"), "user": {"id": "1", "name": "Tester"}})))
|
|
}
|
|
|
|
/// In a normal browser: trade the dashboard's sign-in cookie for an Activity session.
|
|
async fn web_session(AxState(w): AxState<Shared>, headers: HeaderMap) -> Response {
|
|
let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()).unwrap_or("");
|
|
let host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or("");
|
|
if origin != w.cfg.origin && origin != format!("{}://{host}", if w.cfg.secure { "https" } else { "http" }) {
|
|
return ApiError::new(403, "Cross-site request refused").into_response();
|
|
}
|
|
let Some(s) = w.session(&headers) else { return (StatusCode::UNAUTHORIZED, Json(json!({"error": "Sign in with Discord first", "login": format!("{}/login?next=/activity/", w.cfg.base)}))).into_response() };
|
|
Json(json!({"session": w.activity.new_session(s.user_id, &s.name), "user": {"id": s.user_id.to_string(), "name": s.name}})).into_response()
|
|
}
|
|
|
|
async fn token(AxState(w): AxState<Shared>, Json(v): Json<Value>) -> Result<Json<Value>, ApiError> {
|
|
if !w.sign_in_ready() {
|
|
return Err(ApiError::new(503, "The bot's owner hasn't set DASHBOARD_CLIENT_SECRET yet"));
|
|
}
|
|
let code = v["code"].as_str().filter(|c| !c.is_empty() && c.len() <= 200).ok_or_else(|| ApiError::new(400, "Missing code"))?;
|
|
if !w.sign_ins.allow(now()) {
|
|
return Err(ApiError::new(429, "Too many sign-ins right now. Try again in a minute"));
|
|
}
|
|
let app = w.state.app_id().to_string();
|
|
let web = &w.state.web;
|
|
let tok: Option<Value> = async { web.post(format!("{}/oauth2/token", super::DISCORD)).form(&[("client_id", app.as_str()), ("client_secret", w.cfg.client_secret.as_str()), ("grant_type", "authorization_code"), ("code", code)]).send().await.ok()?.json().await.ok() }.await;
|
|
let Some(access) = tok.as_ref().and_then(|t| t["access_token"].as_str()).map(str::to_string) else {
|
|
tracing::warn!("Activity sign-in: Discord refused the code");
|
|
return Err(ApiError::new(401, "Discord refused the sign-in"));
|
|
};
|
|
let me: Option<Value> = async { web.get(format!("{}/users/@me", super::DISCORD)).bearer_auth(&access).send().await.ok()?.json().await.ok() }.await;
|
|
let Some(me) = me.filter(|m| m["id"].is_string()) else { return Err(ApiError::new(502, "Couldn't reach Discord")) };
|
|
let name = me["global_name"].as_str().or(me["username"].as_str()).unwrap_or("Player").to_string();
|
|
let uid: u64 = me["id"].as_str().and_then(|i| i.parse().ok()).unwrap_or(0);
|
|
let raw = w.activity.new_session(uid, &name);
|
|
tracing::info!("Game Boy Activity: {} ({}) signed in", me["username"], me["id"]);
|
|
Ok(Json(json!({"access_token": access, "session": raw, "user": {"id": me["id"], "name": name}})))
|
|
}
|
|
|
|
async fn library(AxState(w): AxState<Shared>, headers: HeaderMap) -> Result<Response, ApiError> {
|
|
let uid = w.activity.user_id(&headers)?;
|
|
let folder = Activity::folder(uid);
|
|
let roms: Vec<Rom> = w.activity.library().values().cloned().collect();
|
|
w.activity.warm_art(&w.state.web, roms.clone(), 8).await; // new games: proper names + covers
|
|
let mut roms = roms;
|
|
roms.sort_by(|a, b| a.path.cmp(&b.path));
|
|
let mtime = |p: &FsPath| std::fs::metadata(p).ok().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs());
|
|
let games: Vec<Value> = roms.iter().map(|rom| {
|
|
let states: serde_json::Map<String, Value> = (0..4).filter_map(|s| Some((s.to_string(), json!(mtime(&folder.join(format!("{}.state{s}", rom.id)))?)))).collect();
|
|
json!({"id": rom.id, "version": rom.version, "title": Activity::display_name(rom), "file": rom.path.file_name().map(|n| n.to_string_lossy().to_string()), "category": rom.category, "cgb": rom.cgb,
|
|
"size": rom.size, "states": states, "save": mtime(&folder.join(format!("{}.sav", rom.id))), "legacy": rom.legacy_save().exists(), "art": Activity::art_path(rom).is_some()})
|
|
}).collect();
|
|
let pending = roms.iter().any(Activity::needs_lookup);
|
|
Ok(([(header::CACHE_CONTROL, "no-store")], Json(json!({"games": games, "pending": pending}))).into_response())
|
|
}
|
|
|
|
fn file_response(path: &FsPath, content_type: &str, cache: &str) -> Response {
|
|
match std::fs::read(path) {
|
|
Ok(bytes) => ([(header::CONTENT_TYPE, content_type.to_string()), (header::CACHE_CONTROL, cache.to_string())], bytes).into_response(),
|
|
Err(_) => (StatusCode::NO_CONTENT, [(header::CACHE_CONTROL, "no-store")]).into_response(),
|
|
}
|
|
}
|
|
|
|
async fn rom_file(AxState(w): AxState<Shared>, headers: HeaderMap, Path(id): Path<String>) -> Result<Response, ApiError> {
|
|
w.activity.user_id(&headers)?;
|
|
let rom = w.activity.rom(&id)?;
|
|
let bytes = tokio::fs::read(&rom.path).await.map_err(|_| ApiError::new(404, "No such game"))?;
|
|
Ok(([(header::CONTENT_TYPE, "application/octet-stream"), (header::CACHE_CONTROL, "private, max-age=31536000, immutable")], bytes).into_response())
|
|
}
|
|
|
|
async fn art(AxState(w): AxState<Shared>, Path(id): Path<String>) -> Result<Response, ApiError> {
|
|
let rom = w.activity.rom(&id)?;
|
|
if Activity::art_path(&rom).is_none() && Activity::needs_lookup(&rom) {
|
|
w.activity.lookup(&w.state.web, &rom).await;
|
|
}
|
|
let Some(path) = Activity::art_path(&rom) else { return Ok((StatusCode::NOT_FOUND, [(header::CACHE_CONTROL, "public, max-age=3600")]).into_response()) };
|
|
let mime = mime_guess::from_path(&path).first_or_octet_stream().to_string();
|
|
Ok(file_response(&path, &mime, "public, max-age=604800"))
|
|
}
|
|
|
|
fn limit_check(body: &Bytes, limit: usize) -> Result<(), ApiError> {
|
|
if body.is_empty() {
|
|
return Err(ApiError::new(400, "Empty upload"));
|
|
}
|
|
if body.len() > limit {
|
|
return Err(ApiError::new(413, "That file is too big"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn save_get(AxState(w): AxState<Shared>, headers: HeaderMap, Path(id): Path<String>) -> Result<Response, ApiError> {
|
|
let uid = w.activity.user_id(&headers)?;
|
|
let rom = w.activity.rom(&id)?;
|
|
Ok(file_response(&Activity::folder(uid).join(format!("{}.sav", rom.id)), "application/octet-stream", "no-store"))
|
|
}
|
|
|
|
async fn save_put(AxState(w): AxState<Shared>, headers: HeaderMap, Path(id): Path<String>, body: Bytes) -> Result<Json<Value>, ApiError> {
|
|
let uid = w.activity.user_id(&headers)?;
|
|
let rom = w.activity.rom(&id)?;
|
|
limit_check(&body, MAX_SAVE)?;
|
|
write_file(&Activity::folder(uid).join(format!("{}.sav", rom.id)), &body);
|
|
Ok(Json(json!({"ok": true, "saved": now()})))
|
|
}
|
|
|
|
async fn legacy(AxState(w): AxState<Shared>, headers: HeaderMap, Path(id): Path<String>) -> Result<Response, ApiError> {
|
|
w.activity.user_id(&headers)?;
|
|
Ok(file_response(&w.activity.rom(&id)?.legacy_save(), "application/octet-stream", "no-store"))
|
|
}
|
|
|
|
fn slot_of(slot: &str) -> Result<u8, ApiError> {
|
|
slot.parse::<u8>().ok().filter(|s| *s < 4).ok_or_else(|| ApiError::new(404, "No such slot"))
|
|
}
|
|
|
|
async fn state_get(AxState(w): AxState<Shared>, headers: HeaderMap, Path((id, slot)): Path<(String, String)>) -> Result<Response, ApiError> {
|
|
let uid = w.activity.user_id(&headers)?;
|
|
let rom = w.activity.rom(&id)?;
|
|
Ok(file_response(&Activity::folder(uid).join(format!("{}.state{}", rom.id, slot_of(&slot)?)), "application/octet-stream", "no-store"))
|
|
}
|
|
|
|
async fn state_put(AxState(w): AxState<Shared>, headers: HeaderMap, Path((id, slot)): Path<(String, String)>, body: Bytes) -> Result<Json<Value>, ApiError> {
|
|
let uid = w.activity.user_id(&headers)?;
|
|
let rom = w.activity.rom(&id)?;
|
|
limit_check(&body, MAX_STATE)?;
|
|
write_file(&Activity::folder(uid).join(format!("{}.state{}", rom.id, slot_of(&slot)?)), &body);
|
|
Ok(Json(json!({"ok": true, "saved": now()})))
|
|
}
|
|
|
|
async fn state_delete(AxState(w): AxState<Shared>, headers: HeaderMap, Path((id, slot)): Path<(String, String)>) -> Result<Json<Value>, ApiError> {
|
|
let uid = w.activity.user_id(&headers)?;
|
|
let rom = w.activity.rom(&id)?;
|
|
let _ = std::fs::remove_file(Activity::folder(uid).join(format!("{}.state{}", rom.id, slot_of(&slot)?)));
|
|
Ok(Json(json!({"ok": true})))
|
|
}
|
|
|
|
pub fn routes() -> Router<Shared> {
|
|
let big = DefaultBodyLimit::max(MAX_STATE + 1024);
|
|
Router::new()
|
|
.route("/activity", get(slash_redirect))
|
|
.route("/activity/", get(page))
|
|
.route("/activity/index.html", get(page))
|
|
.route("/activity/api/config", get(config))
|
|
.route("/activity/api/token", post(token))
|
|
.route("/activity/api/dev-session", post(dev_session))
|
|
.route("/activity/api/web-session", post(web_session))
|
|
.route("/activity/api/library", get(library))
|
|
.route("/activity/api/rom/{id}", get(rom_file))
|
|
.route("/activity/api/art/{id}", get(art))
|
|
.route("/activity/api/legacy/{id}", get(legacy))
|
|
.route("/activity/api/save/{id}", get(save_get).merge(put(save_put).layer(big.clone())))
|
|
.route("/activity/api/state/{id}/{slot}", get(state_get).merge(put(state_put).layer(big)).delete(state_delete))
|
|
.nest_service("/activity/static", ServeDir::new(paths::web(&["activity", "static"])).append_index_html_on_directories(false))
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
fn _hv(_: HeaderValue) {}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn names_are_tidied() {
|
|
assert_eq!(clean_title("Pokemon Red (USA, Europe) [!]"), "Pokemon Red");
|
|
assert_eq!(norm("Pokémon Red Version"), "pokemon red");
|
|
assert_eq!(norm("Kirby's Dream Land 1"), "kirby s dream land");
|
|
}
|
|
|
|
#[test]
|
|
fn rom_ids_follow_the_path_like_the_python_version() {
|
|
let dir = std::env::temp_dir().join(format!("dezio-rom-{}", std::process::id()));
|
|
std::fs::create_dir_all(dir.join("pokemon")).unwrap();
|
|
let p = dir.join("pokemon").join("Red.gb");
|
|
std::fs::write(&p, vec![0u8; 0x200]).unwrap();
|
|
let rom = Rom::load(&p, &dir).unwrap();
|
|
assert_eq!(rom.id, hex(&Sha1::digest(b"pokemon/Red.gb"))[..16]);
|
|
assert_eq!((rom.category.as_str(), rom.title.as_str(), rom.cgb), ("pokemon", "Red", false));
|
|
assert_eq!(rom.legacy_save().file_name().unwrap(), "Red.gb.ram");
|
|
let _ = std::fs::remove_dir_all(dir);
|
|
}
|
|
|
|
#[test]
|
|
fn covers_are_shrunk_to_2_to_3() {
|
|
let img = image::RgbImage::from_pixel(600, 900, image::Rgb([10, 200, 30]));
|
|
let mut png = std::io::Cursor::new(Vec::new());
|
|
img.write_to(&mut png, image::ImageFormat::Png).unwrap();
|
|
let jpg = shrink(png.get_ref()).unwrap();
|
|
let back = image::load_from_memory(&jpg).unwrap();
|
|
assert_eq!((back.width(), back.height()), ART_SIZE);
|
|
}
|
|
}
|