diff --git a/src-tauri/src/cache/db.rs b/src-tauri/src/cache/db.rs index da002e6..001633b 100644 --- a/src-tauri/src/cache/db.rs +++ b/src-tauri/src/cache/db.rs @@ -570,11 +570,6 @@ pub fn put_info( Ok(()) } -pub fn delete_info(conn: &Connection, key: &str, kind: &str) -> Result<(), Error> { - conn.execute("DELETE FROM info WHERE key = ?1 AND kind = ?2", [key, kind])?; - Ok(()) -} - /// Replaces every cached game of `provider` with `games` in one transaction. pub fn replace(conn: &mut Connection, provider: ProviderKind, games: &[Game]) -> Result<(), Error> { let tx = conn.transaction()?; diff --git a/src-tauri/src/commands/game.rs b/src-tauri/src/commands/game.rs index 9371ad5..910f05e 100644 --- a/src-tauri/src/commands/game.rs +++ b/src-tauri/src/commands/game.rs @@ -8,7 +8,7 @@ use rusqlite::Connection; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Manager, State}; -use super::library::rescan; +use super::library::rescan_local; use super::{ AppState, Process, Res, Shared, Watch, allow, blocking, open_db, queue_view, unix_now, }; @@ -395,7 +395,7 @@ fn act_blocking( } if game.provider == ProviderKind::Gog { let result = act_gog(&state, action, game, dlc, dest); - rescan(app, true); + rescan_local(app); return result .map(|()| None) .map_err(|e| store_error(ProviderKind::Gog, e)); @@ -403,7 +403,7 @@ fn act_blocking( if game.provider == ProviderKind::Amazon { let result = act_amazon(&state, action, game, dest); if !matches!(action, Action::Play | Action::PlayOutdated) { - rescan(app, true); + rescan_local(app); } return result .map(|()| None) @@ -465,7 +465,7 @@ fn act_blocking( Action::Install | Action::Update | Action::Verify => unreachable!("queued above"), }; if !matches!(action, Action::Play | Action::PlayOutdated) { - rescan(app, true); + rescan_local(app); } result .map(|()| None) @@ -748,12 +748,12 @@ fn run_queue(app: &AppHandle) { let (toast, repaired) = finish_job(&mut s, &key, result, store); save_queue(&state, &s.queue); drop(s); - // In the background: the next job need not wait for a full online scan. Only that scan shows a store game - // as installed, so the finished job's progress and its toast wait for it. + // In the background: the next job need not wait for the scan. Only that scan shows a store game as + // installed, so the finished job's progress and its toast wait for it. Local: a job changes installs only. let scan = app.clone(); let action = job.action; tauri::async_runtime::spawn_blocking(move || { - let changed = rescan(&scan, true); + let changed = rescan_local(&scan); let state = scan.state::(); let mut s = state.lock(); s.library_changed |= changed; diff --git a/src-tauri/src/commands/library.rs b/src-tauri/src/commands/library.rs index ff9f341..a227fa0 100644 --- a/src-tauri/src/commands/library.rs +++ b/src-tauri/src/commands/library.rs @@ -678,79 +678,180 @@ fn owned(state: &AppState) -> Option> { Some(games) } +/// How much a rescan looks at. Each covers the ones before it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(super) enum Scan { + /// Steam's installs and the games the owner added. + Steam, + /// Also the Epic, GOG and Amazon installs, from their local files, over the owned games last scanned: after a + /// store job, where only installs changed. + Local, + /// Also the Epic, GOG and Amazon owned games and logins, online. + Online, +} + /// Scans, merges and saves; Epic, GOG and Amazon only when `online`. Runs on a blocking thread and waits for a rescan /// already running (`ScanTurns`). Returns whether the library changed since the call. pub(super) fn rescan(app: &AppHandle, online: bool) -> bool { - let scans = &app.state::().scans; - scans.run(scans.ask(), online, || rescan_now(app, online)) + if online { + rescan_as(app, Scan::Online, &STORES) + } else { + rescan_as(app, Scan::Steam, &[]) + } +} + +/// `rescan` for `Scan::Local`. +pub(super) fn rescan_local(app: &AppHandle) -> bool { + rescan_as(app, Scan::Local, &[]) +} + +/// A `Scan::Local` that also fetches `store`'s owned games and login online: after a login or logout there, which +/// changes no other store. +pub(super) fn rescan_store(app: &AppHandle, store: ProviderKind) -> bool { + rescan_as(app, Scan::Local, &[store]) +} + +const STORES: [ProviderKind; 3] = [ProviderKind::Epic, ProviderKind::Gog, ProviderKind::Amazon]; + +/// Fetches `stores` online, if any, then rescans as `kind`. +fn rescan_as(app: &AppHandle, kind: Scan, stores: &[ProviderKind]) -> bool { + let state = app.state::(); + let scans = &state.scans; + scans.run( + scans.ask(), + kind, + (!stores.is_empty()).then_some(|| scan_online(stores, &state.dirs, &state.http)), + |fetched| rescan_now(app, kind, fetched.unwrap_or_default()), + ) } -/// Rescans one at a time, so a slow older scan never overwrites a newer result. A rescan asked for while one runs -/// waits, then skips when a scan that started after it asked (and online, if it asked for online) already ran: any -/// number of callers waiting behind one scan make one more. +/// Rescans one at a time, so a slow older scan never overwrites a newer result. The slow online fetch runs outside +/// that turn (one fetch at a time), so a quick local rescan never waits behind it; the online scan then takes its turn +/// as a `Scan::Local` over what it fetched, so the installs it saves are never older than a rescan that ran during the +/// fetch. A rescan asked for while one runs waits, then skips when a scan that started after it asked, and covers its +/// `Scan`, already ran: any number of callers waiting behind one scan make one more. #[derive(Default)] pub(super) struct ScanTurns { turn: Mutex<()>, - /// Scans started. - started: AtomicU64, - /// `started` as it was after the last online scan started. - online_started: AtomicU64, + fetch: Mutex<()>, + /// By `Scan`: the scans started that cover it. An online scan counts as online when its fetch starts. + started: [AtomicU64; 3], /// Scans that changed the library. changes: AtomicU64, } +/// `ScanTurns` counters as a caller saw them when it asked. +#[derive(Clone, Copy)] +struct Asked { + started: [u64; 3], + changes: u64, +} + impl ScanTurns { /// The scans started and changes made so far, read without waiting. - fn ask(&self) -> (u64, u64) { - ( - self.started.load(Ordering::SeqCst), - self.changes.load(Ordering::SeqCst), - ) + fn ask(&self) -> Asked { + Asked { + started: self.started.each_ref().map(|n| n.load(Ordering::SeqCst)), + changes: self.changes.load(Ordering::SeqCst), + } } /// Runs `scan` (which returns whether it changed the library) in turn, unless a scan started after `asked` - /// covered it. Returns whether the library changed since `asked`. - fn run(&self, asked: (u64, u64), online: bool, scan: impl FnOnce() -> bool) -> bool { - let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner()); - let latest = if online { - &self.online_started - } else { - &self.started - }; - if latest.load(Ordering::SeqCst) <= asked.0 { - let started = self.started.fetch_add(1, Ordering::SeqCst) + 1; - if online { - self.online_started.store(started, Ordering::SeqCst); - } - if scan() { - self.changes.fetch_add(1, Ordering::SeqCst); + /// covered it. With `fetch`, first runs it outside the turn (one fetch at a time) and hands its result to `scan`, + /// which then counts as `Scan::Local`; only a `Scan::Online` fetch can be covered. Returns whether the library + /// changed since `asked`. + fn run( + &self, + asked: Asked, + kind: Scan, + fetch: Option T>, + scan: impl FnOnce(Option) -> bool, + ) -> bool { + let covered = + || self.started[kind as usize].load(Ordering::SeqCst) > asked.started[kind as usize]; + let Some(fetch) = fetch else { + let _turn = lock(&self.turn); + if !covered() { + self.scan(kind, scan, None); } + return self.changed(asked); + }; + let fetch_turn = lock(&self.fetch); + if kind == Scan::Online && covered() { + drop(fetch_turn); + // Covered by an online scan that may still be saving: wait for it, so its change is counted. + drop(lock(&self.turn)); + return self.changed(asked); + } + if kind == Scan::Online { + self.started[Scan::Online as usize].fetch_add(1, Ordering::SeqCst); } - self.changes.load(Ordering::SeqCst) != asked.1 + let fetched = fetch(); + let _turn = lock(&self.turn); + // Released only once in turn, so a rescan waiting to fetch saves after this one. + drop(fetch_turn); + self.scan(Scan::Local, scan, Some(fetched)); + self.changed(asked) + } + + /// Runs `scan` as a scan covering `kind` and the kinds before it. + fn scan(&self, kind: Scan, scan: impl FnOnce(T) -> bool, fetched: T) { + for started in &self.started[..=kind as usize] { + started.fetch_add(1, Ordering::SeqCst); + } + if scan(fetched) { + self.changes.fetch_add(1, Ordering::SeqCst); + } + } + + fn changed(&self, asked: Asked) -> bool { + self.changes.load(Ordering::SeqCst) != asked.changes } } -fn rescan_now(app: &AppHandle, online: bool) -> bool { +fn lock(m: &Mutex<()>) -> std::sync::MutexGuard<'_, ()> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// What `scan_online` found: per store, its owned games and its login. +type Fetched = Vec<(ProviderKind, Result, ScanError>, StoreLogin)>; + +/// Scans the local stores, and for `Scan::Local` the Epic, GOG and Amazon installs over the owned games in `fetched` +/// or else the cached ones; merges and saves. +fn rescan_now(app: &AppHandle, kind: Scan, fetched: Fetched) -> bool { let state = app.state::(); let owned = owned(&state); - let (results, logins) = scan(online, owned.as_deref(), &state.dirs, &state.http); - let signed_out = logins.map(|(e, g, a)| { - signed_out( - &state, - [ - e == StoreLogin::LoggedIn, - g == StoreLogin::LoggedIn, - a == StoreLogin::LoggedIn, - ], - ) - }); + let mut results = scan_local(owned.as_deref(), &state.dirs); + let logins: Vec<(ProviderKind, StoreLogin)> = fetched.iter().map(|f| (f.0, f.2)).collect(); + if kind >= Scan::Local { + let mut fetched: HashMap = fetched + .into_iter() + .map(|(p, games, _)| (p, games)) + .collect(); + let cached = state.lock().games.clone(); + let lists = STORES.map(|p| { + let list = fetched.remove(&p).unwrap_or_else(|| { + Ok(cached.iter().filter(|g| g.provider == p).cloned().collect()) + }); + (p, list) + }); + results.extend(with_installs(lists.into(), &state.dirs, &state.http)); + } + let logged_in = STORES.map(|p| logins.contains(&(p, StoreLogin::LoggedIn))); + let signed_out = (!logins.is_empty()).then(|| signed_out(&state, logged_in)); let mut s = state.lock(); - if let Some((login, gog_login, amazon_login)) = logins { - s.epic_login = Some(login); - s.gog_login = Some(gog_login); - s.amazon_login = Some(amazon_login); - s.signed_out = signed_out.unwrap_or_default(); - note_epic_login(&state, &mut s, login); + for (p, login) in logins { + match p { + ProviderKind::Epic => { + s.epic_login = Some(login); + note_epic_login(&state, &mut s, login); + } + ProviderKind::Gog => s.gog_login = Some(login), + _ => s.amazon_login = Some(login), + } + } + if let Some(flags) = signed_out { + s.signed_out = flags; } let mut merged = merge(&s.games, results); match cache::db::open(&state.dirs.db) { @@ -817,12 +918,7 @@ fn signed_out(state: &AppState, logged_in: [bool; 3]) -> [bool; 3] { flags } -fn scan( - online: bool, - owned: Option<&[Game]>, - dirs: &cache::Dirs, - http: &reqwest::Client, -) -> (ScanResults, Option<(StoreLogin, StoreLogin, StoreLogin)>) { +fn scan_local(owned: Option<&[Game]>, dirs: &cache::Dirs) -> ScanResults { let steam = steam::list_games() .map_err(|e| ScanError::Shown(e.into())) .map(|installed| match owned { @@ -830,24 +926,71 @@ fn scan( None => installed, }); let custom = crate::library::custom::list(dirs).map_err(|e| ScanError::Shown(e.into())); - let mut results = vec![(ProviderKind::Steam, steam), (ProviderKind::Custom, custom)]; - if !online { - return (results, None); - } - let login = epic::login_state(); - let games = epic_result(login, || epic::list_games().map_err(Msg::from)); - results.push((ProviderKind::Epic, games)); - let (gog_login, creds) = gog::login(); - let games = match creds { - Some(creds) => gog::list(http, dirs, &creds).map_err(|e| ScanError::Quiet(e.into())), - None => Err(ScanError::Quiet(Msg::system(format!("{gog_login:?}")))), - }; - results.push((ProviderKind::Gog, games)); - let games = amazon::list(dirs).map_err(|e| ScanError::Quiet(e.into())); - // After the list: its sync is what says whether the login still works. - let amazon_login = amazon::login(); - results.push((ProviderKind::Amazon, games)); - (results, Some((login, gog_login, amazon_login))) + vec![(ProviderKind::Steam, steam), (ProviderKind::Custom, custom)] +} + +/// Syncs `stores` (Epic, GOG or Amazon) at the same time: each store's tool is slow (up to minutes) and independent. +fn scan_online(stores: &[ProviderKind], dirs: &cache::Dirs, http: &reqwest::Client) -> Fetched { + std::thread::scope(|s| { + let scans: Vec<_> = stores + .iter() + .map(|&p| s.spawn(move || scan_store(p, dirs, http))) + .collect(); + // A store thread that panicked would have panicked the sequential scan too. + scans + .into_iter() + .map(|h| h.join().expect("store scan")) + .collect() + }) +} + +fn scan_store( + store: ProviderKind, + dirs: &cache::Dirs, + http: &reqwest::Client, +) -> (ProviderKind, Result, ScanError>, StoreLogin) { + match store { + ProviderKind::Epic => { + let login = epic::login_state(); + let games = epic_result(login, || epic::list_games().map_err(Msg::from)); + (store, games, login) + } + ProviderKind::Gog => { + let (login, creds) = gog::login(); + let games = match creds { + Some(creds) => { + gog::list(http, dirs, &creds).map_err(|e| ScanError::Quiet(e.into())) + } + None => Err(ScanError::Quiet(Msg::system(format!("{login:?}")))), + }; + (store, games, login) + } + _ => { + let games = amazon::list(dirs).map_err(|e| ScanError::Quiet(e.into())); + // After the list: its sync is what says whether the login still works. + (store, games, amazon::login()) + } + } +} + +/// The Epic, GOG and Amazon `lists` with their installs read again from local files. A store whose files can't be +/// read is a quiet error, so `merge` keeps its cached games. +fn with_installs(lists: ScanResults, dirs: &cache::Dirs, http: &reqwest::Client) -> ScanResults { + lists + .into_iter() + .map(|(p, list)| { + let fresh = list.and_then(|games| { + match p { + ProviderKind::Epic => epic::local_games(games), + ProviderKind::Gog => gog::local_games(http, dirs, games), + ProviderKind::Amazon => amazon::local_games(dirs), + _ => Ok(games), + } + .map_err(|e| ScanError::Quiet(e.into())) + }); + (p, fresh) + }) + .collect() } /// Only a logged-in Epic is listed. Any other state is a quiet error, so `merge` keeps the cached Epic games. @@ -1239,39 +1382,103 @@ mod tests { let turns = ScanTurns::default(); let runs = Cell::new(0); let mut waiting = Vec::new(); - turns.run(turns.ask(), false, || { + let run = |asked, kind| { + turns.run(asked, kind, (kind == Scan::Online).then_some(|| ()), |_| { + runs.set(runs.get() + 1); + false + }) + }; + let covered = |asked, kind| { + turns.run(asked, kind, (kind == Scan::Online).then_some(|| ()), |_| { + panic!("covered") + }) + }; + turns.run(turns.ask(), Scan::Steam, None::, |_| { runs.set(runs.get() + 1); waiting.extend([ - (turns.ask(), false), - (turns.ask(), false), - (turns.ask(), true), - (turns.ask(), true), + (turns.ask(), Scan::Steam), + (turns.ask(), Scan::Steam), + (turns.ask(), Scan::Online), + (turns.ask(), Scan::Online), ]); true }); let changed: Vec = waiting .into_iter() - .map(|(asked, online)| { - turns.run(asked, online, || { - runs.set(runs.get() + 1); - false - }) - }) + .map(|(asked, kind)| run(asked, kind)) .collect(); - // One offline run covers the second offline ask but not the online ones; one online run covers both. + // One Steam run covers the second Steam ask but not the online ones; one online run covers both. assert_eq!(runs.get(), 3); // Each waiter hears of the change the scan it waited behind made. assert_eq!(changed, [true; 4]); - // An online scan covers an offline ask made before it started. + // An online scan covers a Steam or local ask made before it started. let asked = turns.ask(); - turns.run(turns.ask(), true, || false); - turns.run(asked, false, || panic!("covered by the online scan")); - // A new ask after everything finished runs. - assert!(!turns.run(turns.ask(), false, || { - runs.set(runs.get() + 1); - false - })); - assert_eq!(runs.get(), 4); + run(turns.ask(), Scan::Online); + covered(asked, Scan::Steam); + covered(asked, Scan::Local); + // A local scan covers a Steam ask, not an online one. + let asked = turns.ask(); + run(turns.ask(), Scan::Local); + covered(asked, Scan::Steam); + run(asked, Scan::Online); + // A Steam scan covers no local ask. + let asked = turns.ask(); + run(turns.ask(), Scan::Steam); + run(asked, Scan::Local); + // A one-store fetch always runs and covers a local ask, never an online one. + let asked = turns.ask(); + let store = |asked| { + turns.run(asked, Scan::Local, Some(|| ()), |_| { + runs.set(runs.get() + 1); + false + }) + }; + store(asked); + store(asked); + covered(asked, Scan::Local); + run(asked, Scan::Online); + assert_eq!(runs.get(), 11); + } + + #[test] + fn a_local_rescan_does_not_wait_for_an_online_fetch() { + use std::sync::mpsc; + let turns = ScanTurns::default(); + let (fetching, fetch_started) = mpsc::channel(); + let (finish_fetch, fetch_may_finish) = mpsc::channel::<()>(); + let saved = Mutex::new(Vec::new()); + std::thread::scope(|s| { + let (turns, saved) = (&turns, &saved); + let online = s.spawn(move || { + turns.run( + turns.ask(), + Scan::Online, + Some(|| { + fetching.send(()).unwrap(); + fetch_may_finish.recv().unwrap(); + "online" + }), + |found| { + saved.lock().unwrap().push(found.unwrap()); + true + }, + ) + }); + fetch_started.recv().unwrap(); + // Runs while the fetch is still going. + let asked = turns.ask(); + assert!( + turns.run(asked, Scan::Local, None:: &'static str>, |found| { + saved.lock().unwrap().push(found.unwrap_or_default()); + true + }) + ); + assert_eq!(*saved.lock().unwrap(), [""]); + finish_fetch.send(()).unwrap(); + assert!(online.join().unwrap()); + }); + // The online scan saved last, with a fresh local scan of its own. + assert_eq!(*saved.lock().unwrap(), ["", "online"]); } #[test] diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rs index 8b60424..4310bcc 100644 --- a/src-tauri/src/commands/settings.rs +++ b/src-tauri/src/commands/settings.rs @@ -17,7 +17,7 @@ use tauri::ipc::Channel; use tauri::{AppHandle, Manager, State}; use tauri_plugin_autostart::ManagerExt; -use super::library::{fill_twins, refresh_owned, rescan}; +use super::library::{fill_twins, refresh_owned, rescan, rescan_local, rescan_store}; use super::{AppState, Res, blocking}; use crate::amazon_login; use crate::cache; @@ -43,7 +43,7 @@ pub async fn epic_log_in(app: AppHandle) -> Res<()> { return Ok(()); }; epic::log_in(&code)?; - rescan(&app, true); + rescan_store(&app, ProviderKind::Epic); Ok(()) }) .await @@ -62,7 +62,7 @@ pub async fn epic_log_out(app: AppHandle) -> Res<()> { blocking(move || { epic::log_out()?; note_signed_out(&app, "epic"); - rescan(&app, true); + rescan_store(&app, ProviderKind::Epic); // The user did this; it isn't news. app.state::().lock().epic_notice = false; Ok(()) @@ -79,7 +79,7 @@ pub async fn gog_log_in(app: AppHandle) -> Res<()> { return Ok(()); }; gog::log_in(&code)?; - rescan(&app, true); + rescan_store(&app, ProviderKind::Gog); fill_twins(app.clone()); Ok(()) }) @@ -93,7 +93,7 @@ pub async fn gog_log_out(app: AppHandle) -> Res<()> { blocking(move || { gog::log_out()?; note_signed_out(&app, "gog"); - rescan(&app, true); + rescan_store(&app, ProviderKind::Gog); Ok(()) }) .await @@ -112,7 +112,7 @@ pub async fn amazon_log_in(app: AppHandle) -> Res<()> { return Ok(()); }; amazon::register(&sign_in, &code)?; - rescan(&app, true); + rescan_store(&app, ProviderKind::Amazon); fill_twins(app.clone()); Ok(()) }) @@ -126,7 +126,7 @@ pub async fn amazon_log_out(app: AppHandle) -> Res<()> { blocking(move || { amazon::log_out()?; note_signed_out(&app, "amazon"); - rescan(&app, true); + rescan_store(&app, ProviderKind::Amazon); Ok(()) }) .await @@ -197,7 +197,7 @@ pub async fn amazon_import(app: AppHandle, key: String, path: String) -> Res<()> std::path::Path::new(&path), ) .map_err(Msg::from); - rescan(&app, true); + rescan_local(&app); result }) .await @@ -214,7 +214,7 @@ pub async fn epic_import(app: AppHandle, key: String, path: String) -> Res<()> { .ok_or(msg!(cantImport))?; blocking(move || { let result = epic::import(&game.external_id, &path).map_err(Msg::from); - rescan(&app, true); + rescan_local(&app); result }) .await @@ -226,7 +226,7 @@ pub async fn epic_import(app: AppHandle, key: String, path: String) -> Res<()> { pub async fn epic_egl_sync(app: AppHandle) -> Res<()> { blocking(move || { let result = epic::egl_sync().map_err(Msg::from); - rescan(&app, true); + rescan_local(&app); result }) .await @@ -247,7 +247,7 @@ pub async fn gog_import(app: AppHandle, path: String) -> Res { .ok_or(msg!(notInGogLibrary))?; let conn = cache::db::open(&state.dirs.db)?; gog::record_install(&conn, &id, std::path::Path::new(&path))?; - rescan(&app, true); + rescan_local(&app); Ok(title) }) .await @@ -265,22 +265,25 @@ pub async fn install_tool(app: AppHandle, name: String, on_percent: Channel) }) .await?; let quick = app.clone(); - blocking(move || { + let store = blocking(move || { let state = quick.state::(); if tool.name == tools::LEGENDARY.name { let login = epic::login_state(); state.lock().epic_login = Some(login); + ProviderKind::Epic } else if tool.name == tools::GOGDL.name { let login = gog::login().0; state.lock().gog_login = Some(login); + ProviderKind::Gog } else { let login = amazon::login(); state.lock().amazon_login = Some(login); + ProviderKind::Amazon } }) .await; tauri::async_runtime::spawn(blocking(move || { - rescan(&app, true); + rescan_store(&app, store); app.state::().lock().library_changed = true; })); Ok(()) diff --git a/src-tauri/src/library/amazon.rs b/src-tauri/src/library/amazon.rs index d8a7b31..972b3e1 100644 --- a/src-tauri/src/library/amazon.rs +++ b/src-tauri/src/library/amazon.rs @@ -311,6 +311,16 @@ fn forget_login(cfg: &Path) -> std::io::Result<()> { /// (a download), so the cached games and the login state stay. With games installed, it also asks which have an /// update, at most every `UPDATES_MAX_AGE_SECS`. Blocks: call from a blocking thread. pub fn list(dirs: &Dirs) -> Result, Error> { + read(dirs, true) +} + +/// The owned Amazon games as nile's last sync left them, with their installs read again: no sync and no update +/// check, for a rescan after a job. +pub fn local_games(dirs: &Dirs) -> Result, Error> { + read(dirs, false) +} + +fn read(dirs: &Dirs, sync: bool) -> Result, Error> { if tools::version(&tools::NILE).is_none() { return Err("Nile isn't installed".into()); } @@ -323,23 +333,24 @@ pub fn list(dirs: &Dirs) -> Result, Error> { let now = super::unix_now(); let (library, installed) = { let _nile = try_lock().ok_or("busy")?; - let output = run_short(nile(["library", "sync"]), SYNC_TIMEOUT); - let login = classify_sync(output.as_ref()); - set_synced(login); - if login != StoreLogin::LoggedIn { - if let Some(error) = output - .as_ref() - .and_then(|o| last_error(&String::from_utf8_lossy(&o.stderr)).map(str::to_owned)) - { - tracing::warn!("nile library sync: {error}"); + if sync { + let output = run_short(nile(["library", "sync"]), SYNC_TIMEOUT); + let login = classify_sync(output.as_ref()); + set_synced(login); + if login != StoreLogin::LoggedIn { + if let Some(error) = output.as_ref().and_then(|o| { + last_error(&String::from_utf8_lossy(&o.stderr)).map(str::to_owned) + }) { + tracing::warn!("nile library sync: {error}"); + } + return Err(format!("{login:?}").into()); } - return Err(format!("{login:?}").into()); } let library = read_json(&cfg.join("library.json")).ok_or("no library.json")?; // Under the lock too: every nile run rewrites it in place. let installed = parse_installed(&fs_err::read(cfg.join("installed.json")).unwrap_or_default()); - if !installed.is_empty() && cached(&conn, UPDATES_MAX_AGE_SECS, now).is_none() { + if sync && !installed.is_empty() && cached(&conn, UPDATES_MAX_AGE_SECS, now).is_none() { check_updates(Some(&conn)); } (library, installed) @@ -579,9 +590,16 @@ fn check_updates(conn: Option<&Connection>) -> Option> { Some(ids) } -/// Forgets the last update answer after a change to the installs, so the next scan asks again. -fn forget_updates(conn: Option<&Connection>) { - if let Some(Err(e)) = conn.map(|c| db::delete_info(c, UPDATES_KEY, UPDATES)) { +/// After a change to `id`'s install: takes it out of the last update answer and makes that answer due, so the next +/// online scan asks again while a local one keeps showing the other games' updates. +fn forget_update(conn: Option<&Connection>, id: &str) { + let Some(conn) = conn else { return }; + let Some(mut ids) = cached(conn, FOREVER, super::unix_now()) else { + return; + }; + ids.retain(|u| u != id); + let json = serde_json::to_string(&ids).unwrap_or_default(); + if let Err(e) = db::put_info(conn, UPDATES_KEY, UPDATES, &json, 0) { tracing::warn!("amazon updates: {e}"); } } @@ -856,7 +874,7 @@ pub fn update( leftover_patch(dir, start), installed_path(id).is_some(), )?; - forget_updates(conn); + forget_update(conn, id); Ok(()) } @@ -910,7 +928,7 @@ pub fn uninstall(conn: Option<&Connection>, id: &str) -> Result<(), Error> { let _nile = lock_between_downloads()?; let output = run_short(nile(["uninstall", id]), UNINSTALL_TIMEOUT).ok_or(msg!(nileNoReason))?; said(&output.stderr, "Game removed successfully")?; - forget_updates(conn); + forget_update(conn, id); Ok(()) } @@ -924,7 +942,7 @@ pub fn import(conn: Option<&Connection>, id: &str, path: &Path) -> Result<(), Er let output = run_short(nile(job_args("import", "--path", path, id)), IMPORT_TIMEOUT) .ok_or(msg!(cantReachAmazon))?; said(&output.stderr, "[IMPORT]:\t Imported ")?; - forget_updates(conn); + forget_update(conn, id); Ok(()) } @@ -1845,8 +1863,14 @@ mod tests { cached(&conn, FOREVER, 1_001 + UPDATES_MAX_AGE_SECS), Some(vec!["a".to_string()]) ); - forget_updates(Some(&conn)); - assert_eq!(cached(&conn, FOREVER, 1_000), None); + db::put_info(&conn, UPDATES_KEY, UPDATES, r#"["a","b"]"#, 1_000).unwrap(); + forget_update(Some(&conn), "a"); + // Due for a check, still showing the others. + assert_eq!( + cached(&conn, UPDATES_MAX_AGE_SECS, UPDATES_MAX_AGE_SECS + 1), + None + ); + assert_eq!(cached(&conn, FOREVER, 1_000), Some(vec!["b".to_string()])); } #[test] diff --git a/src-tauri/src/library/epic.rs b/src-tauri/src/library/epic.rs index 0d30060..dadbc88 100644 --- a/src-tauri/src/library/epic.rs +++ b/src-tauri/src/library/epic.rs @@ -3,7 +3,8 @@ //! its CLI; Legendary keeps the login tokens, downloads and launches. //! JSON shapes are from Legendary 0.21's `cli.py` and `models/game.py`: //! - `list --json`: `[{app_name, app_title, metadata: , …}]` -//! - `list-installed --json`: `[{app_name, title, install_path, …}]` +//! - `installed.json` in its config folder: `{app_name: {app_name, title, install_path, …}}`, the entries +//! `list-installed --json` prints, read directly to skip starting Legendary. //! - `status --json`: `{account: "" | name, …}` use std::collections::{HashMap, HashSet}; @@ -24,7 +25,57 @@ use super::tool::{ use super::{Art, Dlc, Error, Game, Image, Progress, ProgressAction, ProviderKind}; pub fn list_games() -> Result, Error> { - Ok(games(&json(&["list", "--json"])?, &installed_list()?)) + Ok(games(&json(&["list", "--json"])?, &installed()?)) +} + +/// The cached Epic games with their install state read again from `installed.json`, without starting Legendary. +/// Installed games missing from the cache are added, as `games` does. +// shortcut: an installed non-game (kept only while installed) stays as an uninstalled card until the next online scan. +pub fn local_games(cached: Vec) -> Result, Error> { + Ok(with_installed(cached, &installed()?)) +} + +fn with_installed(cached: Vec, installed: &Value) -> Vec { + let mut installed = by_app_name(installed); + let mut games: Vec = cached + .into_iter() + .map(|mut g| { + for d in &mut g.dlc { + d.installed = installed.remove(d.id.as_str()).is_some(); + } + let fresh = game( + &g.external_id, + &g.title, + installed.remove(g.external_id.as_str()), + Art::default(), + ); + Game { + installed: fresh.installed, + install_dir: fresh.install_dir, + size_bytes: fresh.size_bytes, + update_available: fresh.update_available, + ..g + } + }) + .collect(); + games.extend(installed.into_iter().map(|(name, local)| { + game( + name, + local["title"].as_str().unwrap_or(name), + Some(local), + Art::default(), + ) + })); + games +} + +fn by_app_name(installed: &Value) -> HashMap<&str, &Value> { + installed + .as_array() + .into_iter() + .flatten() + .filter_map(|g| Some((g["app_name"].as_str()?, g))) + .collect() } /// `legendary launch` arguments. Flags from `legendary launch --help` (0.21.1); its "additional arguments @@ -183,23 +234,20 @@ fn has_cloud_saves(metadata: &Value) -> bool { !metadata["customAttributes"]["CloudSaveFolder"].is_null() } -/// Installed games with their update flags. The update check is online, so when it fails -/// (e.g. offline) the plain list still answers, with no updates marked. -fn installed_list() -> Result { - with_fallback( - json(&["list-installed", "--check-updates", "--json"]), - || json(&["list-installed", "--json"]), - ) +/// Legendary's installed games, as `list-installed --json` lists them: the values of its `installed.json`. No file +/// means nothing is installed; an unreadable one is an error, so a scan keeps what it knew. +fn installed() -> Result { + let path = config_dir().ok_or("no home folder")?.join("installed.json"); + match std::fs::read(&path) { + Ok(bytes) => installed_from(&bytes), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(Value::Array(Vec::new())), + Err(e) => Err(e.into()), + } } -fn with_fallback( - checked: Result, - plain: impl FnOnce() -> Result, -) -> Result { - checked.or_else(|e| { - tracing::warn!("legendary list-installed --check-updates: {e}"); - plain() - }) +fn installed_from(bytes: &[u8]) -> Result { + let map: serde_json::Map = serde_json::from_slice(bytes)?; + Ok(Value::Array(map.into_iter().map(|(_, g)| g).collect())) } /// Runs a hidden `legendary install` of a game or a DLC (Legendary's app name), reporting its pid and @@ -492,9 +540,9 @@ pub fn catalog() -> Result { json(&["list", "--json"]) } -/// File name of an installed game's main executable (from `list-installed`), to spot it in the process list. +/// File name of an installed game's main executable (from `installed.json`), to spot it in the process list. pub fn executable(game: &Game) -> Result, Error> { - let installed = json(&["list-installed", "--json"])?; + let installed = installed()?; let exe = installed .as_array() .into_iter() @@ -659,12 +707,7 @@ fn is_game(item: &Value) -> bool { /// installed, so nothing installed disappears. A DLC (any item whose `mainGameItem` names another /// item's catalog id) goes under that base game when the base is listed; otherwise the rules above apply to it. fn games(owned: &Value, installed: &Value) -> Vec { - let mut installed: HashMap<&str, &Value> = installed - .as_array() - .into_iter() - .flatten() - .filter_map(|g| Some((g["app_name"].as_str()?, g))) - .collect(); + let mut installed = by_app_name(installed); // `list --json` nests DLC in its base game's `dlcs`; flattened, the catalog id finds the base either way. let items: Vec<&Value> = owned .as_array() @@ -770,8 +813,7 @@ fn game(name: &str, title: &str, installed: Option<&Value>, art: Art) -> Game { } } -/// `list-installed --check-updates --json` marks an update with `update_available`, or by a `remote_version` -/// that differs from `version`. // shortcut: both spellings are read because no real capture with an update exists yet. +/// An installed entry marks an update with `update_available`, or by a `remote_version` that differs from `version`. // shortcut: both spellings are read because no real capture with an update exists yet. fn has_update(local: &Value) -> bool { local["update_available"].as_bool().unwrap_or_else(|| { local["remote_version"] @@ -930,17 +972,38 @@ mod tests { } #[test] - fn failed_update_check_falls_back_to_the_plain_list() { - let plain = || Ok(serde_json::json!([{ "app_name": "A" }])); + fn installed_json_lists_its_entries() { + let bytes = br#"{"Fortnite": {"app_name": "Fortnite", "install_path": "C:\\Fn"}}"#; + assert_eq!( + installed_from(bytes).unwrap(), + serde_json::json!([{ "app_name": "Fortnite", "install_path": "C:\\Fn" }]) + ); + assert_eq!(installed_from(b"{}").unwrap(), serde_json::json!([])); + assert!(installed_from(b"{\"Fortn").is_err()); + } + + #[test] + fn local_scan_marks_cached_games_from_installed() { + let cached = sorted_games(); + // Fortnite uninstalled, Goo installed, the base game's art and title kept. + let installed = serde_json::json!([{ "app_name": "Goo", "title": "Goo", "install_path": "C:\\Goo", "install_size": 7 }]); + let mut local = with_installed(cached.clone(), &installed); + local.sort_by(|a, b| a.external_id.cmp(&b.external_id)); + let goo = &local[1]; + assert!(goo.installed && goo.size_bytes == Some(7)); + assert_eq!((&goo.title, &goo.art), (&cached[1].title, &cached[1].art)); + assert!(!local[0].installed && local[0].install_dir.is_none()); + // The same installs give back the online scan's games. assert_eq!( - with_fallback(Err("offline".into()), plain).unwrap(), - serde_json::json!([{ "app_name": "A" }]) + with_installed(cached.clone(), &fixture("list-installed.json")), + cached ); + // A game installed outside the cache is added. + let new = serde_json::json!([{ "app_name": "New", "title": "New Game" }]); assert_eq!( - with_fallback(Ok(Value::Null), || Err("unused".into())).unwrap(), - Value::Null + with_installed(cached, &new).last().unwrap().title, + "New Game" ); - assert!(with_fallback(Err("a".into()), || Err("b".into())).is_err()); } #[test] diff --git a/src-tauri/src/library/gog.rs b/src-tauri/src/library/gog.rs index c2d9437..2d660e5 100644 --- a/src-tauri/src/library/gog.rs +++ b/src-tauri/src/library/gog.rs @@ -243,15 +243,7 @@ pub fn list(http: &reqwest::Client, dirs: &Dirs, creds: &Creds) -> Result = installs - .iter() - .filter_map(|(key, dir)| { - key.strip_prefix("gog-")? - .parse() - .ok() - .filter(|&id| has_info(dir, id)) - }) - .collect(); + let installed = installed_ids(&installs); let (owned, products, latest, saves) = tauri::async_runtime::block_on(async { let owned = owned_ids( &get_json( @@ -306,6 +298,70 @@ pub fn list(http: &reqwest::Client, dirs: &Dirs, creds: &Creds) -> Result, +) -> Result, Error> { + let conn = db::open(&dirs.db)?; + let now = super::unix_now(); + let installs = db::gog_installs(&conn)?; + let installed = installed_ids(&installs); + let (latest, saves) = tauri::async_runtime::block_on(async { + let latest = latest_builds(http, &conn, &installed, now).await; + ( + latest, + with_cloud_saves(http, &conn, &installs, &installed, now).await, + ) + }); + Ok(cached + .into_iter() + .map(|mut g| { + mark_installed(&mut g, &installs, &latest); + g.cloud_saves = + g.installed && g.external_id.parse().is_ok_and(|id| saves.contains(&id)); + g + }) + .collect()) +} + +/// The ids in `installs` whose folder holds their game. +fn installed_ids(installs: &HashMap) -> Vec { + installs + .iter() + .filter_map(|(key, dir)| { + key.strip_prefix("gog-")? + .parse() + .ok() + .filter(|&id| has_info(dir, id)) + }) + .collect() +} + +/// Marks `g` installed when `installs` has a folder for it that holds its `goggame-.info`, and so each of its +/// DLC. An installed game has an update when its folder's build isn't the `latest` one. +fn mark_installed( + g: &mut Game, + installs: &HashMap, + latest: &HashMap, +) { + let id = g.external_id.parse::().ok(); + let dir = id.and_then(|id| installs.get(&g.key()).filter(|dir| has_info(dir, id))); + for d in &mut g.dlc { + d.installed = dir.is_some_and(|dir| has_info(dir, &d.id)); + } + g.update_available = dir + .zip(id.and_then(|id| latest.get(&id))) + .is_some_and(|(dir, build)| { + installed_build(dir, &g.external_id).is_some_and(|local| local != *build) + }); + g.installed = dir.is_some(); + g.install_dir = dir.cloned(); +} + /// The newest public build of each installed game (GOG's builds list needs no login), cached 6 h and asked one game /// at a time. A failure is logged and leaves that game without an update mark. async fn latest_builds( @@ -402,9 +458,8 @@ fn trim(p: &Value) -> Value { }) } -/// Owned products that are games (packs and DLC are left out), by trimmed product (`trim`). A game is installed -/// when it has an install folder that holds its `goggame-.info`; so is each owned DLC. An installed game has an -/// update when its folder's build isn't the `latest` one. `covers` are GamesDB's portrait covers by key; without +/// Owned products that are games (packs and DLC are left out), by trimmed product (`trim`), marked installed by +/// `mark_installed`. `covers` are GamesDB's portrait covers by key; without /// one the grid shows the landscape logo art. fn games( owned: &[u64], @@ -426,7 +481,6 @@ fn games( .filter_map(|&id| { let p = products.get(&id).filter(|p| p["game_type"] == "game")?; let key = key(id); - let dir = installs.get(&key).filter(|dir| has_info(dir, id)); // GOG's image URLs are protocol-relative. let image = |field: &str| Image { path: None, @@ -447,16 +501,16 @@ fn games( .get(&d) .and_then(title) .unwrap_or_else(|| d.to_string()), - installed: dir.is_some_and(|dir| has_info(dir, d)), + installed: false, }) .collect(); dlc.sort_by(|a, b| a.title.cmp(&b.title)); - Some(Game { + let mut game = Game { provider: ProviderKind::Gog, external_id: id.to_string(), title: title(p)?, - installed: dir.is_some(), - install_dir: dir.cloned(), + installed: false, + install_dir: None, // Playtime comes from `epic_playtime::merge`, cloud saves from `list`. // shortcut: the size on disk isn't measured. playtime_minutes: None, @@ -471,11 +525,11 @@ fn games( hero: image("background"), }, dlc, - update_available: dir.zip(latest.get(&id)).is_some_and(|(dir, build)| { - installed_build(dir, &id.to_string()).is_some_and(|local| local != *build) - }), + update_available: false, cloud_saves: false, - }) + }; + mark_installed(&mut game, installs, latest); + Some(game) }) .collect() }