diff --git a/docs/FAQ.md b/docs/FAQ.md index e87dffd7..aab215a4 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -22,7 +22,7 @@ No. The launcher is free and open source under the GPL v3, and so is every recom ## Do I need an account? -No. Everything works without one. A free account adds cloud saves, so the same save follows you between your PC, your TV PC and a handheld, and keeps your library in sync. +No. Everything works without one. A free RecompStore account adds cloud saves and keeps your library in sync. You can also connect your own Google Drive for game saves without a RecompStore account, in builds configured for Google sign-in. See [Google Drive saves](GOOGLE-DRIVE.md). ## Where does it keep my files? diff --git a/docs/GOOGLE-DRIVE-PLAN.md b/docs/GOOGLE-DRIVE-PLAN.md new file mode 100644 index 00000000..440b5223 --- /dev/null +++ b/docs/GOOGLE-DRIVE-PLAN.md @@ -0,0 +1,174 @@ +# Google Drive saves completion plan + +Finish `feat/google-drive-saves` so players can use their own Google Drive for saves, +without a RecompStore account, from desktop and Big Picture. Preserve local backups, +explicit consent for each game, and the existing RecompStore save behavior. + +## Branch baseline + +Reconstructed from the branch at `49e81a1`, based on `main` at `b6516ab`: + +- `2cbc5cb` adds the Drive provider, OAuth, storage, save integration, UI and documentation. +- `49e81a1` fixes connection and sync races and adds browser smoke checks. +- The working tree was clean before this plan was added. + +Existing implementation: + +| Area | Files | Behavior already present | +| --- | --- | --- | +| Provider selection | `src-tauri/src/save_provider.rs` | RecompStore default; explicit switch; per-game consent reset; changes blocked while games run or start | +| Google connection | `src-tauri/src/drive.rs`, `secret.rs`, `win.rs` | Browser OAuth with PKCE and loopback callback; optional device flow; refresh; cancellation; separate credentials | +| Drive storage | `src-tauri/src/drive.rs` | Visible `RecompLauncher/Saves` folder; immutable ZIP snapshots; ancestry-based conflicts; resumable upload tickets; retention | +| Save lifecycle | `src-tauri/src/cloud.rs`, `saves.rs` | Check before play; backup/upload after play; retries; provider/account-scoped sync state; archive validation | +| UI | `ui/account.js`, `ui/tv.js` | Connection, provider choice, disconnect, per-game controls, conflict revision, cache refresh | +| Documentation | `docs/GOOGLE-DRIVE.md` and linked help | Player instructions, build variables, storage behavior and manual release checks | + +Code being present does not establish that live Google authorization and storage work. +The existing browser check simulates Tauri responses. + +## Scope and decisions to preserve + +- Players connect an account; the maintainer supplies the OAuth application configuration. +- Request only `drive.file`; saves and credentials go directly to Google. +- RecompStore remains available and remains the default for existing installations. +- Changing provider or active Google account requires enabling games again. Reconnecting + the same Google account should preserve consent. Existing copies stay where they are. +- Disconnect removes this PC's credentials and stops its Drive sync. It preserves local + and remote saves. Global Google revocation remains a separate account action. +- Keep the existing archive format, save discovery, managed-input exclusions, 95 MiB + upload limit, ten local backups and five ordinary remote copies. Preserve unresolved + branches until resolution. Concurrent saves must not be ordered solely by clocks. +- Desktop and Big Picture must expose equivalent actions. Browser authorization on the + same PC is the baseline. Device-code sign-in is conditional on an eligible Google client. +- No new manifest fields, shared input types, downloads, provider migration or library + synchronization through Drive are included in this feature. + +Google documents [desktop OAuth](https://developers.google.com/identity/protocols/oauth2/native-app), +the limited-input flow and its supported scopes in the +[device authorization guide](https://developers.google.com/identity/protocols/oauth2/limited-input-device), +and the narrow file permission in the +[Drive scope guide](https://developers.google.com/workspace/drive/api/guides/api-specific-auth). + +## Work order + +### 1 Make release configuration concrete + +The release workflows currently do not supply the `RL_GOOGLE_*` build variables consumed +by `drive.rs`. As written, those builds leave connection disabled. + +- Wire `RL_GOOGLE_CLIENT_ID` and `RL_GOOGLE_CLIENT_SECRET` into the intended release + builds. Handle the optional device client separately. Keep credential values out of logs. +- Check Windows, Linux and macOS packaging, plus the separate Arch and Flatpak build + paths. Document which distributions ship Drive configuration and make that choice explicit. +- Add a release configuration check so an intended Drive-enabled release cannot silently + ship without its client ID. Ordinary contributor builds should still work without it. +- The maintainer configures the Google project, Drive API, branding, consent audience and + Desktop client. Confirm applicable publishing requirements and connect a real test account. + Repository inspection cannot establish the current state of that external project. + +Completion: a packaged build reports the expected configuration and completes real consent. + +### 2 Verify account isolation and connection lifetime + +Review `drive.rs`, `save_provider.rs` and their callers together. Add focused regressions +for canceled or superseded connections, disconnect during refresh, reconnecting the same +account, replacing it with another account, and switching providers while sync waits. + +Verify that credentials, upload tickets, pending uploads, synced hashes and UI caches cannot +cross account/provider boundaries. Check restart migration from the existing RecompStore +state, grouped installations and games with their own saves. Verify that game startup and +provider changes cannot interleave into an upload to an unintended destination. + +Completion: each transition has an explicit expected consent/state result, and stale work +cannot restore credentials or upload under the wrong account. + +### 3 Prove interrupted uploads recover + +The current tests cover upload offsets and session URL validation, but do not exercise a +complete Drive HTTP exchange. Add a small test transport seam and deterministic local HTTP +tests for the actual upload logic, keeping production destinations fixed. + +Cover partial uploads, restart with a saved ticket, lost success responses, expired sessions, +authentication refresh, throttling, server errors and quota exhaustion. Verify idempotent +completion with the allocated file ID and checksum before creating another snapshot. + +Session invalidation after upload 4xx responses is fixed for both probes and data PUTs, with +the cleared URL persisted for launcher restarts. Quota and authorization messages and transient +retry classification are preserved. Broader end-to-end upload recovery remains to be tested. See +[Google's upload recovery rules](https://developers.google.com/workspace/drive/api/guides/manage-uploads). + +Completion: retry and restart preserve the local copy, eventually complete one intended +snapshot, and expose an actionable state when authorization or storage prevents progress. + +### 4 Prove conflicts and restoration preserve saves + +Exercise concurrent uploads from two and three clients, equal timestamps, clock skew, +identical contents, and another upload arriving while the conflict prompt is open. Test both +choices and a failed upload of the resolution. Review pruning against concurrent changes, +pagination, missing ancestors and externally modified metadata. + +Expand archive regressions where needed for duplicate entries, traversal, symlinks, damaged +contents, wrong game or destination, oversized expansion, and managed-input exclusions. +Check that failed validation leaves live saves untouched and that restoration preserves the +previous local save through the existing backup path. + +Completion: divergent saves stay discoverable until resolved; stale choices cannot silently +resolve unseen changes; an invalid archive cannot change live saves. + +### 5 Finish desktop and Big Picture behavior + +Extend the existing UI checks to cover reconnect-required state, missing configuration, +provider/account changes, cancellation, offline pending uploads, full storage and conflict +resolution. Check keyboard and controller focus, recovery actions and consistent wording. + +Verify actual native browser opening and loopback callbacks on Windows and Linux/Steam Deck, +plus macOS if shipped. Test packaged sandbox behavior for supported Linux distributions. +Only exercise phone authorization with an eligible configured device client. + +Completion: each failure has a usable recovery action in both interfaces, and Drive saves +work while signed out of RecompStore. + +### 6 Validate and prepare the release + +Run the Rust and JavaScript suites and the browser smoke tool. Use two real installations +with the same Google account to upload, restore, play offline, reconnect, interrupt uploads, +create conflicts, resolve each choice, change accounts and disconnect. Include damaged ZIPs, +revoked access, full storage and regression checks for RecompStore-only users. + +Update `docs/GOOGLE-DRIVE.md`, linked help and the next patch notes draft to match the final +behavior. No Drive player release note is present in the current branch. If implementation +adds any developer-writable manifest field or `FEATURES` value, update the schema, matching +SDK docs with an example, and the separate "For the website (SDK guide)" note in the same +commit, as required by `AGENTS.md`. + +Completion: automated checks pass, supported packages contain their intended configuration, +and recorded native/live results establish that saves survive the release scenarios. + +## Validation record + +- The three review findings are fixed: archive limits apply per save location, upload 4xx + responses invalidate persisted sessions, and Drive/OAuth use the launcher's dynamic proxy. +- Drive restores also reject non-save entries, installed release files, selected launch programs, + managed inputs, mismatched file/glob destinations and links in destination or staging paths. + The complete archive is validated before any backup or live restore begins. +- Pruning removes discarded ancestors oldest-first, preserving the head set after each deletion. + Choosing a cloud branch resolves from its validated archive even when extra local slots remain. + Manifest validation budgets entries, paths and locations instead of using a fixed 8 MiB cap. +- Regression tests include a launcher-generated backup with 20,000 files in each of two + locations, independent size budgets, rejected uploads, retained sessions after server errors, + and proxy changes on the existing Drive client. +- Further regressions cover interruption after each pruned ancestor, unresolved branch retention, + cloud resolution and retry with retained local slots, a large manifest with 100-character + filenames, and rejection of a compressed manifest padded out of proportion to its files. +- Restore regressions reject forged executable replacements with matching hashes and confirm + that a later invalid archive entry leaves earlier saves untouched. Valid file, glob and nested + folder restores still pass; release files, managed inputs and linked staging paths stay intact. +- JavaScript suite: all 271 tests passed after the fixes. +- Rust suite: 689 passed, one ignored. The full suite ran outside the filesystem sandbox + because an existing profile test creates and removes a temporary home-directory folder. +- Browser smoke check: desktop, connected account and Big Picture checks passed with no + reported errors. Artifacts from this run: `/tmp/rl-drive-ui-CgbXpt`. +- Native/live Google checks: still required before public release. + +Resume with step 1. Keep this plan updated with completed steps, concrete findings and test +results so work can resume from the repository after a context reset. diff --git a/docs/GOOGLE-DRIVE.md b/docs/GOOGLE-DRIVE.md new file mode 100644 index 00000000..f6346da1 --- /dev/null +++ b/docs/GOOGLE-DRIVE.md @@ -0,0 +1,138 @@ +# Google Drive saves + +Open **Settings → Account → Save destination → Connect Google Drive**. Choose your Google +account in the browser and approve access. Then choose **Use Google Drive** and enable cloud +saves in each game's **Manage** tab, or use **Back Up Every Game** in the save destination +settings. A RecompStore account is not required for Drive saves. + +The launcher creates a visible **RecompLauncher/Saves** folder in My Drive. Copies are ZIP +archives using the same `rlsave.json` format as local backups. The launcher requests only +`drive.file`: access to files it creates or the user explicitly opens with it. It does not +request access to the rest of your Drive. Files and credentials travel directly to Google; +RecompLauncher servers do not receive them. + +Google sign-in requests and save transfers follow **Settings → Network → Proxy**. Changes +apply without restarting the launcher, including choosing **Off** to bypass system proxies. + +Before play, the launcher checks for another PC's saves. After play it makes a local backup +and uploads changed saves. **Sync Now** checks immediately. Offline saves wait on this PC +and retry later, including after restarting the launcher. Connect the same Google account +on each PC and enable the same games there. + +When both PCs changed their saves, choose which to use. Simultaneous uploads are tracked by +snapshot ancestry, rather than assuming the PC with the later clock has the right save. +Choosing the cloud copy resolves from that snapshot, even when restoring into the game's +install folder retains extra local save slots. Those extra slots stay on this PC. +The other copies remain available in the Saves tab. The newest five ordinary cloud copies +are kept; unresolved branches retain their history until resolved. Removed old copies go +to Drive's Trash, which still uses Google storage until emptied. The launcher manages Drive +history automatically; individual cloud-copy deletion in the Saves tab is for RecompStore. Local backups retain their +existing limit of ten copies per game. The upload limit remains 95 MiB per archive, along +with the existing save discovery and file limits. + +Switching providers or connecting a different Google account turns off **Back Up Every Game** +and requires enabling games again. +Existing copies are not moved between providers. **Disconnect** stops this PC's Drive sync +and removes its Google credentials; local saves and remote copies remain. You can separately +remove RecompLauncher's access in your Google account's connected-app settings. Google's +revocation can disconnect other PCs too. + +Big Picture has the same connection, provider selection, per-game switch and sync controls. +It normally opens the browser on the same PC. Approved limited-input builds can offer a +Google device code and QR code for a phone. A phone cannot finish a desktop loopback callback. + +The save destination controls in desktop and Big Picture: + +![Desktop save destination settings](images/google-drive-desktop.webp) + +![Google Drive selected in Big Picture](images/google-drive-big-picture.webp) + +## Configuring a release build + +The project maintainer must configure one Google Cloud project, enable the Drive API, configure +Google Auth branding/audience/data access, and register a **Desktop app** OAuth client. Ordinary +players only connect their Google account; they do not create a Cloud project or paste credentials. + +Set these environment variables when building the launcher: + +```sh +export RL_GOOGLE_CLIENT_ID='your-desktop-client.apps.googleusercontent.com' +export RL_GOOGLE_CLIENT_SECRET='the-desktop-client-secret' +npm run build +``` + +These are installed-app client credentials, which are distributed with the binary and cannot +be treated as confidential. Keep development and production projects separate. Use the same +production Google project across platforms so the application can discover the same files. +The launcher embeds these build variables; changing them requires rebuilding. Without a desktop +client ID, desktop connection controls explain that this build has not configured Drive. + +Publish the OAuth application for external users and complete Google's applicable branding and +verification requirements before releasing it. In Google's Testing status, Drive refresh tokens +expire after seven days. Test denied consent, revoked access, and the production consent screen +before shipping. + +Only if the application qualifies for Google's TV/limited-input flow, register an additional +**TVs and Limited Input devices** client in that same project and set: + +```sh +export RL_GOOGLE_DEVICE_CLIENT_ID='your-approved-device-client.apps.googleusercontent.com' +export RL_GOOGLE_DEVICE_CLIENT_SECRET='the-device-client-secret' +``` + +Big Picture uses that client when configured and respects Google's polling interval and slow-down +responses. Without it, Big Picture uses the desktop browser flow. Do not register a desktop +application as a limited-input device merely to avoid browser sign-in. + +Google refresh tokens use a separate Windows Credential Manager entry. On Linux and macOS they +follow the launcher's existing convention: an atomically replaced file readable only by its owner +in the launcher data directory. Tokens and upload-session URLs are not sent to the UI or logged. +Native keychain integration on Linux/macOS is not included. Upload-session state stays in the +launcher data directory and is scoped to the Google account and game, even when the local backup +folder is on a synchronized drive. + +No `recomplauncher.json` changes are needed. Existing `saves` paths and managed-input exclusions +apply to Drive backups too. Downloads are checked against the archive manifest and individual +file hashes before restoration, and archive destinations must match this PC's known save folders +(or the folders the player explicitly picked). +Each entry must also pass the save-file exclusions and match its local file or wildcard template. +Installed release files, selected launch programs and managed inputs are protected from replacement. +Links in restore destinations or staging paths are rejected before any live saves are changed. +If the developer or catalog moves a save folder, old copies restore into the current named +location with the same file checks. A guessed save folder cannot authorize that remapping. +File-count and total-size limits are checked separately for each save location, matching backup +discovery when a game saves in several folders. +The manifest budget scales with the archive's entry count and path lengths, including full +backups from multiple save locations. Unrelated excess manifest data is still rejected. + +## Reviewing the UI without a Google account + +On Linux with Google Chrome installed, run: + +```sh +node tools/check-google-drive-ui.cjs +``` + +Set `RL_UI_CHROME` to another Chrome executable if needed. An optional directory argument chooses +where the check writes its screenshots and results; otherwise it uses a new temporary directory. +It exercises the shipped desktop and Big Picture UI with simulated Tauri responses, including +connection cancellation, missing OAuth configuration, connected account controls, and keyboard navigation. +It never signs into Google or changes your launcher data. The screenshots above use this simulated +state and a sample account address. Native launcher and live Google validation are separate checks. + +## Validation before a public release + +Run `cargo test --manifest-path src-tauri/Cargo.toml` and `node --test tests/*.test.cjs`. +With the production OAuth configuration, test two real installations on Windows and Linux/Steam +Deck: connect the same account, upload, restore, play offline and reconnect, interrupt an upload, +create simultaneous changes, resolve both choices, switch accounts, and disconnect. Also check +a full Drive, a manually damaged ZIP, expired/revoked authorization, and Big Picture controls. +Automated tests do not replace this live Google authorization and storage check. + +Google documentation: + +- [Desktop OAuth, PKCE and loopback redirects](https://developers.google.com/identity/protocols/oauth2/native-app) +- [Drive scopes](https://developers.google.com/workspace/drive/api/guides/api-specific-auth) +- [Resumable uploads](https://developers.google.com/workspace/drive/api/guides/manage-uploads) +- [Device authorization and supported scopes](https://developers.google.com/identity/protocols/oauth2/limited-input-device) +- [Refresh token expiration](https://developers.google.com/identity/protocols/oauth2#expiration) diff --git a/docs/LAUNCHER-API.md b/docs/LAUNCHER-API.md index 79873b61..f6897587 100644 --- a/docs/LAUNCHER-API.md +++ b/docs/LAUNCHER-API.md @@ -20,6 +20,10 @@ was signed out (from the account page, or the account is gone): the launcher for ## Cloud saves +This section describes RecompStore storage. Players can instead choose their own Google Drive +in Settings → Account; those saves go directly to Google and do not use the endpoints below. +See [Google Drive saves](GOOGLE-DRIVE.md) for connection, storage and release configuration. + | Call | | | --- | --- | | `GET ?a=me` | The account, and `saves: {used, quota}` | diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 66e099c2..e7423e85 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -82,7 +82,14 @@ It only needs the internet for the game list, updates, accounts and cloud saves. ## Cloud saves aren't syncing -Make sure you're signed in and cloud saves are on for that game in its **Saves** tab. If a sync fails, the launcher tries again by itself and shows when the next try is. +Check the selected provider in **Settings → Account → Save destination**, and make sure cloud saves +are on for that game in its **Saves** tab. If a sync fails, the launcher tries again by itself and +shows when the next try is. + +For Google Drive, reconnect there if Google access expired or was revoked. If Drive is full, +free space (including its Trash), then press **Sync Now**. Switching providers or Google accounts +requires enabling games again. A build that says Drive is not configured needs the maintainer's +Google OAuth configuration. See [Google Drive saves](GOOGLE-DRIVE.md). ## Resetting the launcher diff --git a/docs/images/google-drive-big-picture.webp b/docs/images/google-drive-big-picture.webp new file mode 100644 index 00000000..ff5ef463 Binary files /dev/null and b/docs/images/google-drive-big-picture.webp differ diff --git a/docs/images/google-drive-desktop.webp b/docs/images/google-drive-desktop.webp new file mode 100644 index 00000000..8ad9006e Binary files /dev/null and b/docs/images/google-drive-desktop.webp differ diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 28579ac4..238ef350 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4712,6 +4712,7 @@ dependencies = [ "flate2", "fs2", "futures-util", + "getrandom 0.2.17", "hex", "image", "lz4_flex", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 87fdd341..c1da9e94 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -31,6 +31,7 @@ aes = "0.8" lzxd = "0.2" hex = "0.4" base64 = "0.22" +getrandom = "0.2" zip = { version = "2", default-features = false, features = ["deflate", "bzip2", "zstd", "time"] } sevenz-rust = "0.6" # Plain copies of compressed game images (convert.rs): GameCube and Wii formats, CHD, CSO and ZSO. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 3ac87581..255ba4d0 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,4 +1,7 @@ fn main() { + for name in ["RL_GOOGLE_CLIENT_ID", "RL_GOOGLE_CLIENT_SECRET", "RL_GOOGLE_DEVICE_CLIENT_ID", "RL_GOOGLE_DEVICE_CLIENT_SECRET"] { + println!("cargo:rerun-if-env-changed={name}"); + } pack(); // Cross-building for Windows with MinGW: unrar's C++ is built without a C++ library, so // libstdc++ goes in statically (the program needs no MinGW DLLs), with the Windows libraries diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index 01698400..67aea9bd 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -225,6 +225,22 @@ fn is_full(e: &Error) -> bool { e.to_string().contains("cloud saves are full") } +fn using_drive(dir: &Path) -> bool { + crate::save_provider::current(dir) == crate::save_provider::Provider::GoogleDrive +} + +fn transport_drive_error() -> Error { + Error::Msg("Google Drive couldn't be reached. Your saves stay on this PC and will retry.".into()) +} + +pub(crate) fn reset_provider_status() { + PAUSED.store(false, std::sync::atomic::Ordering::Relaxed); + FULL_TOLD.store(false, std::sync::atomic::Ordering::Relaxed); + *FULL.lock().unwrap() = None; + *TRIES.lock().unwrap() = None; + *PEEKED.lock().unwrap() = None; +} + /// A copy that didn't go up whole (cut off, too slow, "didn't arrive whole"): tried again after 1, /// 5, 15 and then 60 minutes, so at most a few tries an hour, whatever else asks for it. static TRIES: Mutex>> = Mutex::new(None); @@ -498,7 +514,7 @@ pub struct LinkStart { expires: u64, } -fn qr_svg(text: &str) -> String { +pub(crate) fn qr_svg(text: &str) -> String { qrcode::QrCode::new(text.as_bytes()) .map(|q| { q.render::() @@ -683,7 +699,7 @@ pub fn shown_root(st: &App) -> PathBuf { } /// One game's saves at the same time: two backups of one game never overlap. -static BUSY: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +pub(crate) static BUSY: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); /// Waits its turn for the saves, but not forever: something else that's stuck can't keep a /// backup spinning. @@ -710,9 +726,18 @@ pub struct CloudCopy { pub device: String, #[serde(default)] pub played: u64, + #[serde(default)] + pub conflict: bool, + #[serde(default)] + pub revision: String, + #[serde(default)] + pub head: bool, } async fn cloud_list(app: &AppHandle, id: &str) -> Res<(Vec, Value)> { + if using_drive(&app.state::().dir) { + return crate::drive::list(app, id).await; + } let v = get(app, &[("a", "saves"), ("game", id)]).await?; let list: Vec = serde_json::from_value(v.get("versions").cloned().unwrap_or(json!([]))).unwrap_or_default(); let mut list = list; @@ -723,7 +748,7 @@ async fn cloud_list(app: &AppHandle, id: &str) -> Res<(Vec, Value)> { Ok((list, json!({"used": v.get("used"), "quota": v.get("quota")}))) } -const SYNC_CONFLICT: &str = "Both save copies changed. Choose one in Saves → Sync Now."; +pub(crate) const SYNC_CONFLICT: &str = "Both save copies changed. Choose one in Saves → Sync Now."; /// Before Play, the cloud's newer save couldn't be put in place (a save folder that's read-only /// on this PC, say). Why goes on the line under it. @@ -800,12 +825,14 @@ fn working(app: &AppHandle, id: &str, what: &str) -> Working { Working { app: app.clone(), id: id.to_string() } } -/// The kind of trouble behind a failed upload, as saves_status reports it. -fn problem_kind(e: &Error) -> &'static str { - if paused() { +/// The kind of trouble behind a failed upload, as saves_status reports it. `website`: the saves +/// go to RecompStore, whose pause applies; with Google Drive it doesn't. +fn problem_kind(e: &Error, website: bool) -> &'static str { + if website && paused() { return "paused"; } - if is_full(e) { + // RecompStore's 150 MB, or the player's Google Drive storage. + if is_full(e) || e.to_string().contains("Drive storage is full") { return "full"; } if e.to_string().starts_with("This save is too big") { @@ -818,13 +845,20 @@ fn problem_kind(e: &Error) -> &'static str { } /// Remembers why this game's saves didn't go up, so its page can still say so after the toast is -/// gone. A conflict is kept on its own (upload sets it), not as a problem. +/// gone. A conflict is kept on its own, not as a problem: upload sets it with the cloud copy's +/// version, and Google Drive, which only says so in its upload error, sets it here. fn note_failure(dir: &Path, id: &str, e: &Error) { + let mut s = saves::state(dir, id); if e.to_string() == SYNC_CONFLICT { + if s.conflict.is_some() { + return; + } + s.conflict = Some(String::new()); + saves::set_state(dir, id, &s); return; } - let mut s = saves::state(dir, id); - s.problem = Some(saves::Problem { kind: problem_kind(e).into(), text: e.to_string(), at: crate::library::now() }); + let kind = problem_kind(e, !using_drive(dir)); + s.problem = Some(saves::Problem { kind: kind.into(), text: e.to_string(), at: crate::library::now() }); saves::set_state(dir, id, &s); } @@ -839,19 +873,30 @@ async fn upload(app: &AppHandle, id: &str, name: &str) -> Res<()> { async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { let st = app.state::(); - // One account from the note to the request: a switch meanwhile must not send this note's - // copy with the next account's token. - let a = load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; + if game(&st, id)?.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { + return Err(Error::Msg("Turn on cloud saves for this game first.".into())); + } + let scope = crate::save_provider::scope(&st.dir); + let a = if using_drive(&st.dir) { None } else { Some(load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?) }; let mut state = saves::state(&st.dir, id); // Signed in to another account just now: this note isn't that account's to send (the log // says so). The copy stays on this PC and goes up with the new account's own sync. - if !still_signed_in_as(&st.dir, &a, id) { + if crate::save_provider::scope(&st.dir) != scope { return Ok(()); } let copy = saves::manifest(&copies_dir(&st, id).join(name)) .ok_or_else(|| Error::Msg("That copy is gone.".into()))?; let (list, _) = cloud_list(app, id).await?; - let Some(top) = list.first() else { return upload_copy(app, id, name, 0, &a).await }; + if crate::save_provider::scope(&st.dir) != scope { + return Ok(()); + } + let Some(top) = list.first() else { return upload_copy(app, id, name, 0, None, a.as_ref()).await }; + // Drive keeps both branches until the player picks. + if top.conflict { + state.conflict = Some(top.v.clone()); + saves::set_state(&st.dir, id, &state); + return Err(Error::Msg(SYNC_CONFLICT.into())); + } if top.hash == copy.hash { state.mark_synced(©.hash, top.made, &top.device); if state.pending.as_deref() == Some(name) { @@ -865,13 +910,35 @@ async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { saves::set_state(&st.dir, id, &state); return Err(Error::Msg(SYNC_CONFLICT.into())); } - upload_copy(app, id, name, top.made.saturating_add(1), &a).await + upload_copy(app, id, name, top.made.saturating_add(1), None, a.as_ref()).await } -async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64, a: &Account) -> Res<()> { +async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64, resolution: Option<&str>, account: Option<&Account>) -> Res<()> { let st = app.state::(); + let scope = crate::save_provider::scope(&st.dir); + let mut state = saves::state(&st.dir, id); let path = copies_dir(&st, id).join(name); let man = saves::manifest(&path).ok_or_else(|| Error::Msg("That copy is gone.".into()))?; + if using_drive(&st.dir) { + if !crate::net::forced() && copy_wait_left(id, name).is_some() { + return Err(Error::Net("Google Drive upload is waiting to retry.".into())); + } + let working = working(app, id, "up"); + if let Err(e) = crate::drive::upload(app, id, &path, resolution).await { + if matches!(e, Error::Net(_)) { copy_failed(id, name, "Google Drive unavailable"); } + return Err(e); + } + drop(working); + copy_went_up(id, name); + if crate::save_provider::scope(&st.dir) != scope { + return Ok(()); + } + state.mark_synced(&man.hash, man.made.max(earliest), &man.device); + state.pending = None; + saves::set_state(&st.dir, id, &state); + return Ok(()); + } + let a = account.cloned().or_else(|| load(&st.dir)).ok_or_else(|| Error::Msg("Sign in first.".into()))?; if paused() { return Err(Error::Msg(PAUSED_TEXT.into())); } @@ -994,7 +1061,8 @@ fn pending_ids(st: &App) -> Vec { pub async fn upload_pending(app: &AppHandle) { let st = app.state::(); let forced = crate::net::forced(); - if !signed_in(&st.dir) || (!forced && (crate::net::resting(&save_url("save-put"), false) || full_now())) || paused() { + let website = !using_drive(&st.dir); + if !crate::save_provider::ready(&st.dir) || (website && ((!forced && (crate::net::resting(&save_url("save-put"), false) || full_now())) || paused())) { return; } let ids = pending_ids(&st); @@ -1010,11 +1078,11 @@ pub async fn upload_pending(app: &AppHandle) { match upload(app, &id, &name).await { Ok(()) => {} // Paused on the site: the rest wait for the next start. - Err(_) if paused() => break, + Err(_) if !using_drive(&st.dir) && paused() => break, // Full: none of them go until there's room. Err(e) if is_full(&e) => break, // The site isn't answering for saves at all: the rest wait, and go when it does. - Err(Error::Net(_)) if crate::net::resting(&save_url("save-put"), false) => { + Err(Error::Net(_)) if using_drive(&st.dir) || crate::net::resting(&save_url("save-put"), false) => { no_answer = true; break; } @@ -1049,11 +1117,12 @@ fn retry_pending_later(app: &AppHandle) { let app = app.clone(); tauri::async_runtime::spawn(async move { // The site's own rest, or the soonest a copy that failed may be tried again. - let wait = crate::net::wait_left(&save_url("save-put")).max(next_copy_try().unwrap_or((30u64 << n).min(3600))); + let url = if using_drive(&app.state::().dir) { "https://www.googleapis.com/drive/v3/files".into() } else { save_url("save-put") }; + let wait = crate::net::wait_left(&url).max(next_copy_try().unwrap_or((30u64 << n).min(3600))); crate::trail::note(format!("Cloud saves: waiting uploads tried again in {wait}s")); tokio::time::sleep(crate::net::spread(wait, 0.3)).await; RETRY_PLANNED.store(false, std::sync::atomic::Ordering::SeqCst); - if paused() { + if !using_drive(&app.state::().dir) && paused() { return; } Box::pin(upload_pending(&app)).await; @@ -1071,7 +1140,7 @@ pub async fn after_session(app: &AppHandle, id: &str) -> Res let (dir, id2, g2) = (st.dir.clone(), id.to_string(), g.clone()); // The copy ends the session's wait (saves::backup); one that fails to go up is kept as pending. let copy = blocking(move || saves::backup(&dir, &id2, &spots, &g2)).await??; - if g.cloud == Some(true) && signed_in(&st.dir) { + if g.cloud == Some(true) && crate::save_provider::ready(&st.dir) { if let Some(l) = newest_unsent(&st.dir, id, &g) { if let Err(e) = upload(app, id, &l.name).await { let too_big = e.to_string().starts_with("This save is too big"); @@ -1165,23 +1234,28 @@ fn open_sessions(saves_dir: &Path) -> Vec { /// `checked`: the checksum of the saves the caller looked at before deciding. Then the copy goes /// in only over those saves, not over ones made while it downloaded. None: the player picked /// this cloud save themselves, over whatever is there. -async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&str>) -> Res { +async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&str>, resolve: bool) -> Res { let st = app.state::(); - let a = load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; + let scope = crate::save_provider::scope(&st.dir); let _working = working(app, id, "down"); - let url = api(); - let req = st - .http - .get(&url) - .query(&[("a", "save-get"), ("game", id), ("v", &c.v)]) - .bearer_auth(&a.token).header("X-RL-Token", a.token.as_str()) - .timeout(std::time::Duration::from_secs(300)); - let r = crate::net::send(req, &save_url("save-get"), true).await?; - if r.status().as_u16() != 200 { - answer(app, r).await?; - return Err(Error::Msg("That cloud save couldn't be downloaded.".into())); - } - let bytes = r.bytes().await.map_err(net)?; + let bytes = if using_drive(&st.dir) { + crate::drive::download(app, id, c).await? + } else { + let a = load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; + let url = api(); + let req = st + .http + .get(&url) + .query(&[("a", "save-get"), ("game", id), ("v", &c.v)]) + .bearer_auth(&a.token).header("X-RL-Token", a.token.as_str()) + .timeout(std::time::Duration::from_secs(300)); + let r = crate::net::send(req, &save_url("save-get"), true).await?; + if r.status().as_u16() != 200 { + answer(app, r).await?; + return Err(Error::Msg("That cloud save couldn't be downloaded.".into())); + } + r.bytes().await.map_err(net)?.to_vec() + }; let g = game(&st, id)?; // Checked after the download too: a big save takes a while, and the game can be opened // from its folder meanwhile. @@ -1196,15 +1270,24 @@ async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&s let spots = spots_of(&st, id, &g); let (dir, id2, t2) = (st.dir.clone(), id.to_string(), tmp.clone()); let checked = checked.map(String::from); - let n = blocking(move || match checked { - Some(h) => saves::restore_if_unchanged(&dir, &id2, &t2, &spots, &g, &h), - None => saves::restore(&dir, &id2, &t2, &spots, &g), - }).await; + let hash = c.hash.clone(); + let drive = using_drive(&st.dir); + let n = if drive { + restore_drive_copy(dir, id2, t2, hash, spots, g, checked, |archive| async move { + if resolve { crate::drive::upload(app, id, &archive, Some(&c.revision)).await?; } + Ok(()) + }).await + } else { + blocking(move || match checked { + Some(h) => saves::restore_if_unchanged(&dir, &id2, &t2, &spots, &g, &h), + None => saves::restore(&dir, &id2, &t2, &spots, &g), + }).await.and_then(|n| n) + }; let _ = tokio::fs::remove_file(&tmp).await; - let n = n??; + let n = n?; let mut s = saves::state(&st.dir, id); // The save is in place either way; only the new account's notes must not claim it as synced. - if !still_signed_in_as(&st.dir, &a, id) { + if crate::save_provider::scope(&st.dir) != scope { s.last_hash = c.hash.clone(); saves::set_state(&st.dir, id, &s); return Ok(n); @@ -1227,7 +1310,32 @@ fn incoming<'a>(s: &saves::State, list: &'a [CloudCopy]) -> Option<&'a CloudCopy return None; } let top = list.first()?; - should_restore(&s.last_hash, &s.synced_hash, &top.hash, false).then_some(top) + (!top.conflict && should_restore(&s.last_hash, &s.synced_hash, &top.hash, false)).then_some(top) +} + +async fn restore_drive_copy(dir: PathBuf, id: String, archive: PathBuf, hash: String, spots: Vec, g: Installed, checked: Option, resolve: F) -> Res +where + F: FnOnce(PathBuf) -> Fut, + Fut: std::future::Future>, +{ + let path = archive.clone(); + let restored = blocking(move || { + saves::validate_cloud_copy(&path, &id, &hash, &spots, &g)?; + match checked { + Some(h) => saves::restore_if_unchanged(&dir, &id, &path, &spots, &g, &h), + None => saves::restore(&dir, &id, &path, &spots, &g), + } + }).await??; + // The install-folder fallback retains extra local slots. Resolve the chosen archive itself, + // rather than requiring those live files to match the cloud branch exactly. + resolve(archive).await?; + Ok(restored) +} + +fn current_copy<'a>(list: &'a [CloudCopy], local: &str) -> Option<&'a CloudCopy> { + let top = list.first()?; + if !top.conflict { return Some(top); } + list.iter().find(|c| c.head && c.hash != local).or(Some(top)) } /// Whether the cloud copy can be put in place without replacing locally changed saves. @@ -1264,7 +1372,7 @@ fn reserve_sync(st: &App, id: &str) -> Res { } /// Upload the checked live save, even if a different save is still in the backup history. -async fn upload_current(app: &AppHandle, id: &str, g: Installed, spots: Vec, hash: String, after: u64) -> Res<()> { +async fn upload_current(app: &AppHandle, id: &str, g: Installed, spots: Vec, hash: String, after: u64, resolution: Option<&str>) -> Res<()> { let dir = app.state::().dir.clone(); let id2 = id.to_string(); let copy = blocking(move || { @@ -1273,8 +1381,9 @@ async fn upload_current(app: &AppHandle, id: &str, g: Installed, spots: Vec().dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; - let r = upload_copy(app, id, ©.name, after.saturating_add(1), &a).await; + let st = app.state::(); + let a = if using_drive(&st.dir) { None } else { Some(load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?) }; + let r = upload_copy(app, id, ©.name, after.saturating_add(1), resolution, a.as_ref()).await; if let Err(e) = &r { note_failure(&app.state::().dir, id, e); } @@ -1305,16 +1414,28 @@ pub async fn saves_check(app: AppHandle, id: String, manual: Option) -> Re check_saves(app, id, false).await } +async fn prepare_sync(st: &App, id: &str) -> Res, Installed)>> { + let g = game(st, id)?; + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { + return Ok(None); + } + let guard = busy().await?; + // Consent or the connected account may have changed while another save operation finished. + let g = game(st, id)?; + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { + return Ok(None); + } + Ok(Some((guard, g))) +} + async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { let st = app.state::(); - let g = game(&st, &id)?; - if g.cloud != Some(true) || !signed_in(&st.dir) { + let Some((_busy, g)) = prepare_sync(&st, &id).await? else { if manual { return Err(Error::Msg("Turn on cloud saves for this game first.".into())); } return Ok(json!({"action": "play"})); - } - let _busy = busy().await?; + }; let _reserved = reserve_sync(&st, &id)?; let _working = working(&app, &id, "check"); let (list, _) = match cloud_list(&app, &id).await { @@ -1355,14 +1476,14 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { } note_folder_too_big(&st.dir, &id, None); let s = saves::state(&st.dir, &id); - let Some(top) = top else { + let Some(top) = current_copy(&list, &local) else { if local.is_empty() { return Ok(json!({"action": "play"})); } - upload_current(&app, &id, g, spots, local, 0).await?; + upload_current(&app, &id, g, spots, local, 0, None).await?; return Ok(json!({"action": "uploaded"})); }; - if top.hash == local { + if !top.conflict && top.hash == local { // Already the same: a conflict or a problem noted before is over too. let stale = s.synced_hash != local || s.pending.is_some() || s.conflict.is_some() || s.problem.is_some(); if stale { @@ -1373,7 +1494,7 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { } return Ok(json!({"action": "play"})); } - if should_restore(&local, &s.synced_hash, &top.hash, entries.is_empty()) { + if !top.conflict && should_restore(&local, &s.synced_hash, &top.hash, entries.is_empty()) { // Before Play it doesn't stop the game: the program may be a mod tool, not the game. The // player is asked whether to play with this PC's save, as when a restore fails. if let Some(program) = open_outside(&id, &g).await? { @@ -1384,7 +1505,7 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { let why = format!("{PROGRAM_OPEN_PLAY}\n{program}"); return Ok(json!({"action": "not-restored", "why": why, "cloud": top})); } - let taken = take_cloud(&app, &id, top, Some(&local)).await; + let taken = take_cloud(&app, &id, top, Some(&local), false).await; // Sync Now says why. Before Play the player is asked whether to play with this PC's save // instead (saves_play_without_cloud); nothing about the sync changes until they say so. if let (Err(e), false) = (&taken, manual) { @@ -1394,9 +1515,9 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { let n = taken?; return Ok(json!({"action": "restored", "files": n, "cloud": top})); } - if top.hash == s.synced_hash { + if !top.conflict && top.hash == s.synced_hash { if manual { - upload_current(&app, &id, g, spots, local, top.made).await?; + upload_current(&app, &id, g, spots, local, top.made, None).await?; return Ok(json!({"action": "uploaded"})); } // After Play, the local changes go up at the end of the session. @@ -1460,18 +1581,23 @@ pub async fn sync_quiet(app: &AppHandle, id: &str) -> Res<()> { /// The player's pick after a conflict: keep this PC's save (it goes up as the newest), or the /// cloud's (this PC's is kept as a local copy first). #[tauri::command] -pub async fn saves_pick(app: AppHandle, id: String, keep: String, local_hash: String, cloud_version: String) -> Res<()> { +pub async fn saves_pick(app: AppHandle, id: String, keep: String, local_hash: String, cloud_version: String, cloud_revision: Option) -> Res<()> { let _busy = busy().await?; let st = app.state::(); let g = game(&st, &id)?; - if g.cloud != Some(true) || !signed_in(&st.dir) { + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { return Err(Error::Msg("Turn on cloud saves for this game first.".into())); } let _reserved = reserve_sync(&st, &id)?; crate::net::now(async { let changed = || Error::Msg("The saves changed. Try syncing again.".into()); let (list, _) = cloud_list(&app, &id).await?; - let top = list.first().filter(|c| c.v == cloud_version).ok_or_else(changed)?; + let top = if using_drive(&st.dir) { + list.iter().find(|c| c.v == cloud_version && c.head) + } else { + list.first().filter(|c| c.v == cloud_version) + }.ok_or_else(changed)?; + if using_drive(&st.dir) && cloud_revision.as_deref() != Some(top.revision.as_str()) { return Err(changed()); } let spots = spots_of(&st, &id, &g); let (g2, spots2) = (g.clone(), spots.clone()); let (entries, infos, hash, _) = blocking(move || saves::current(&spots2, &g2)).await?; @@ -1479,8 +1605,12 @@ pub async fn saves_pick(app: AppHandle, id: String, keep: String, local_hash: St return Err(changed()); } match keep.as_str() { - "cloud" => take_cloud(&app, &id, top, Some(&hash)).await.map(|_| ()), - "local" => upload_current(&app, &id, g, spots, hash, top.made).await, + "cloud" => { + let resolve = using_drive(&st.dir) && top.conflict; + take_cloud(&app, &id, top, Some(&hash), resolve).await?; + Ok(()) + } + "local" => upload_current(&app, &id, g, spots, hash, top.made, Some(&top.revision)).await, _ => Err(Error::Msg("Choose this PC or the cloud.".into())), } }).await @@ -1506,6 +1636,7 @@ fn follow_every_game(l: &mut crate::library::Library) { /// already has something newer, which the next Play sorts out). #[tauri::command] pub async fn saves_cloud(app: AppHandle, id: String, on: bool) -> Res { + let _busy = busy().await?; let st = app.state::(); let g = { let mut l = st.lib.lock().unwrap(); @@ -1515,12 +1646,18 @@ pub async fn saves_cloud(app: AppHandle, id: String, on: bool) -> Res let _ = l.save(&st.dir); g }; - if on && signed_in(&st.dir) { + if on && crate::save_provider::ready(&st.dir) { let app2 = app.clone(); let id2 = id.clone(); tauri::async_runtime::spawn(async move { - let has_cloud = cloud_list(&app2, &id2).await.map(|(l, _)| !l.is_empty()).unwrap_or(true); + let has_cloud = { + let _busy = BUSY.lock().await; + let st = app2.state::(); + if !crate::save_provider::ready(&st.dir) || game(&st, &id2).map(|g| g.cloud != Some(true)).unwrap_or(true) { return; } + cloud_list(&app2, &id2).await.map(|(l, _)| !l.is_empty()).unwrap_or(true) + }; if !has_cloud { + // after_session takes BUSY itself, and rechecks consent before uploading. let _ = after_session(&app2, &id2).await; let _ = app2.emit("saves", json!({"id": id2})); } @@ -1540,6 +1677,7 @@ pub struct SpotInfo { /// Everything the Saves tab shows. #[tauri::command] pub async fn saves_info(app: AppHandle, id: String) -> Res { + let _busy = busy().await?; let st = app.state::(); let g = game(&st, &id)?; let spots: Vec = spots_of(&st, &id, &g) @@ -1557,7 +1695,8 @@ pub async fn saves_info(app: AppHandle, id: String) -> Res { let mut space = Value::Null; let mut offline = false; let mut next = Value::Null; - if g.cloud == Some(true) && signed_in(&st.dir) { + let mut cloud_error = String::new(); + if g.cloud == Some(true) && crate::save_provider::ready(&st.dir) { match cloud_list(&app, &id).await { Ok((l, sp)) => { next = incoming(&state, &l).map(|c| json!(c)).unwrap_or(Value::Null); @@ -1566,15 +1705,17 @@ pub async fn saves_info(app: AppHandle, id: String) -> Res { cloud = serde_json::to_value(l).unwrap_or(Value::Null); space = sp; } - Err(Error::Net(_)) => offline = true, - Err(_) => {} + Err(e) => { + offline = matches!(e, Error::Net(_)); + cloud_error = e.to_string(); + } } } let waiting = waiting_copies(&local, &state); Ok(json!({ - "spots": spots, "local": local, "cloud": cloud, "space": space, "offline": offline, - "cloudOn": g.cloud, "signedIn": signed_in(&st.dir), "synced": state.synced_hash, "pending": state.pending.is_some(), - "waiting": waiting, "status": STATUS_PAGE, + "spots": spots, "local": local, "cloud": cloud, "space": space, "offline": offline, "cloudError": cloud_error, + "provider": crate::save_provider::name(&st.dir), "cloudOn": g.cloud, "signedIn": crate::save_provider::ready(&st.dir), "synced": state.synced_hash, "pending": state.pending.is_some(), + "waiting": waiting, "status": if using_drive(&st.dir) { "" } else { STATUS_PAGE }, // The save in the game's folder now (the last copy made or put back), and this PC's name: // the tab marks the copy that's current and the ones another PC made. "current": state.last_hash, "here": saves::device_name(), @@ -1582,7 +1723,7 @@ pub async fn saves_info(app: AppHandle, id: String) -> Res { "incoming": next, // Seconds until a copy that didn't get through is tried again, and whether the account's // cloud saves are full (no uploads until there's room). - "retryIn": state.pending.as_deref().and_then(|p| copy_wait_left(&id, p)), "full": full_now(), + "retryIn": state.pending.as_deref().and_then(|p| copy_wait_left(&id, p)), "full": !using_drive(&st.dir) && full_now(), "override": swap, })) } @@ -1622,19 +1763,22 @@ fn sync_status(app: &AppHandle, id: &str) -> Res { let st = app.state::(); let g = game(&st, id)?; let s = saves::state(&st.dir, id); - let signed = signed_in(&st.dir); + // Connected to whichever cloud the player picked (signed in, for RecompStore). + let ready = crate::save_provider::ready(&st.dir); + // Full and paused are what the RecompStore website said; Drive says its own in `problem`. + let website = !using_drive(&st.dir); let local = saves::list(&st.dir, id, &g); let retry = s.pending.as_deref().and_then(|p| copy_wait_left(id, p)); Ok(json!({ - "state": s.sync_state(g.cloud == Some(true), signed), - "cloudOn": g.cloud, "signedIn": signed, + "state": s.sync_state(g.cloud == Some(true), ready), + "cloudOn": g.cloud, "signedIn": ready, + "provider": crate::save_provider::current(&st.dir), "providerName": crate::save_provider::name(&st.dir), "syncedAt": s.synced_at, "syncedMade": s.synced_made, "syncedDevice": s.synced_device, - "waiting": waiting_copies(&local, &s), "retryIn": retry, "full": full_now(), "paused": paused(), + "waiting": waiting_copies(&local, &s), "retryIn": retry, + "full": website && full_now(), "paused": website && paused(), "problem": s.problem, "conflict": s.conflict.is_some(), "newest": local.first(), // False: nobody has said where it saves, so nothing of it is backed up or synced. "known": !spots_of(&st, id, &g).is_empty(), - // Where the saves go. Only RecompStore today; named so another cloud can say so later. - "provider": "recompstore", })) } @@ -1668,7 +1812,7 @@ fn keep_peek(id: &str, synced: &str, list: &[CloudCopy]) { pub async fn saves_peek(app: AppHandle, id: String) -> Res { let st = app.state::(); let g = game(&st, &id)?; - if g.cloud != Some(true) || !signed_in(&st.dir) || spots_of(&st, &id, &g).is_empty() { + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) || spots_of(&st, &id, &g).is_empty() { return Ok(Value::Null); } let state = saves::state(&st.dir, &id); @@ -1717,13 +1861,17 @@ pub async fn saves_upload_now(app: AppHandle, id: String) -> Res { let st = app.state::(); folder_free(&st, &id)?; let g = game(&st, &id)?; - if g.cloud != Some(true) || !signed_in(&st.dir) { + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { return Err(Error::Msg("Turn on cloud saves for this game first.".into())); } let running = st.running.lock().unwrap().contains_key(&id); let r: Res<()> = crate::net::now(async { { let _busy = busy().await?; + let g = game(&st, &id)?; + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { + return Err(Error::Msg("Turn on cloud saves for this game first.".into())); + } // A fresh copy of what's there now (a running game's saves wait until it closes). if !running { let spots = spots_of(&st, &id, &g); @@ -1753,6 +1901,7 @@ pub async fn saves_upload_now(app: AppHandle, id: String) -> Res { } match r { Ok(()) => crate::net::now(saves_info(app.clone(), id)).await, + Err(Error::Net(_)) if using_drive(&st.dir) => Err(transport_drive_error()), Err(Error::Net(_)) => Err(Error::Msg(format!("The website still can't be reached. Your saves are safe on this PC and go up when it's back. See {STATUS_PAGE} for whether it's on our side."))), Err(e) => Err(e), } @@ -1763,14 +1912,12 @@ pub async fn saves_upload_now(app: AppHandle, id: String) -> Res { #[tauri::command] pub async fn cloud_retry(app: AppHandle, id: Option) -> Res { let st = app.state::(); - if !signed_in(&st.dir) { + if !crate::save_provider::ready(&st.dir) { return Err(Error::Msg("Sign in first.".into())); } let r = crate::net::now(async { - let v = get(&app, &[("a", "me")]).await; - if let Err(Error::Net(e)) = v { - return Err(Error::Net(e)); - } + let v = if using_drive(&st.dir) { crate::drive::space(&app).await } else { get(&app, &[("a", "me")]).await }; + v?; upload_pending(&app).await; Ok(()) }) @@ -1780,6 +1927,7 @@ pub async fn cloud_retry(app: AppHandle, id: Option) -> Res { Some(id) => crate::net::now(saves_info(app.clone(), id)).await, None => Ok(json!({"ok": true})), }, + Err(e) if using_drive(&st.dir) => Err(e), Err(_) => Err(Error::Msg(format!("The website still can't be reached. Your saves are safe on this PC and go up when it's back. See {STATUS_PAGE} for whether it's on our side."))), } } @@ -1799,7 +1947,7 @@ fn overview(app: &AppHandle) -> Value { // Copies made beside the games while the player's folder was away go to it now that it's back. let installed: Vec = games.iter().map(|(_, g)| g.clone()).collect(); saves::gather(&st.dir, &installed); - let signed = signed_in(&st.dir); + let signed = crate::save_provider::ready(&st.dir); let mut out = Vec::new(); for (id, g) in games { let local = saves::list(&st.dir, &id, &g); @@ -1912,10 +2060,11 @@ pub async fn saves_restore(app: AppHandle, id: String, name: Option, v: } folder_free(&st, &id)?; let _busy = BUSY.lock().await; + let _reserved = reserve_sync(&st, &id)?; if let Some(v) = v { let (list, _) = cloud_list(&app, &id).await?; let c = list.into_iter().find(|c| c.v == v).ok_or_else(|| Error::Msg("That cloud save is gone.".into()))?; - return take_cloud(&app, &id, &c, None).await; + return take_cloud(&app, &id, &c, None, false).await; } let name = name.unwrap_or_default(); if name.contains('/') || name.contains('\\') || !name.ends_with(".zip") { @@ -1936,6 +2085,9 @@ pub async fn saves_restore(app: AppHandle, id: String, name: Option, v: #[tauri::command] pub async fn saves_cloud_delete(app: AppHandle, id: String, v: String) -> Res<()> { let _busy = BUSY.lock().await; + if using_drive(&app.state::().dir) { + return Err(Error::Msg("Google Drive keeps the newest five copies automatically. Manage its files in Drive.".into())); + } let (list, _) = cloud_list(&app, &id).await?; if !deletable(&list, &v) { return Err(Error::Msg("The newest cloud save stays: the next PC you play on brings it in.".into())); @@ -2281,6 +2433,18 @@ mod child_retry_tests { ]) } + #[test] + fn changing_provider_clears_inherited_cloud_consent() { + let fixture = Fixture::new(games()); + fixture.0.lib.lock().unwrap().settings.ui["cloud_all"] = true.into(); + crate::save_provider::clear_consent(&fixture.0).unwrap(); + let library = fixture.0.lib.lock().unwrap(); + let game = library.installed.get("series").unwrap(); + assert_eq!(game.cloud, None); + assert!(!game.cloud_on(&library.settings.ui)); + assert!(!Installed::default().cloud_on(&library.settings.ui)); + } + #[test] fn a_sync_is_refused_while_the_game_is_being_uninstalled() { let fixture = Fixture::new(games()); @@ -2307,6 +2471,66 @@ mod child_retry_tests { assert!(folder_free(st, "series--first").is_ok()); } + #[tokio::test] + async fn local_only_games_do_not_wait_for_another_save_operation() { + let fixture = Fixture::new(games()); + fixture.0.lib.lock().unwrap().installed.get_mut("series").unwrap().cloud = Some(false); + let _busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(matches!(futures_util::poll!(&mut check), std::task::Poll::Ready(Ok(None)))); + } + + #[tokio::test] + async fn games_without_cloud_consent_do_not_wait_for_another_save_operation() { + let fixture = Fixture::new(games()); + fixture.0.lib.lock().unwrap().installed.get_mut("series").unwrap().cloud = None; + let _busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(matches!(futures_util::poll!(&mut check), std::task::Poll::Ready(Ok(None)))); + } + + #[tokio::test] + async fn games_without_a_connected_provider_do_not_wait_for_another_save_operation() { + let fixture = Fixture::new(games()); + std::fs::write(fixture.0.dir.join("save-provider.json"), b"\"disabled\"").unwrap(); + let _busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(matches!(futures_util::poll!(&mut check), std::task::Poll::Ready(Ok(None)))); + } + + #[cfg(not(windows))] + #[tokio::test] + async fn a_waiting_sync_rechecks_cloud_consent() { + let fixture = Fixture::new(games()); + let account = Account { token: "test-token".into(), ..Default::default() }; + store(&fixture.0.dir, Some(&account)); + let busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(futures_util::poll!(&mut check).is_pending()); + fixture.0.lib.lock().unwrap().installed.get_mut("series").unwrap().cloud = Some(false); + drop(busy); + assert!(check.await.unwrap().is_none()); + } + + #[cfg(not(windows))] + #[tokio::test] + async fn a_waiting_sync_rechecks_the_connected_provider() { + let fixture = Fixture::new(games()); + let account = Account { token: "test-token".into(), ..Default::default() }; + store(&fixture.0.dir, Some(&account)); + let busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(futures_util::poll!(&mut check).is_pending()); + std::fs::write(fixture.0.dir.join("save-provider.json"), b"\"disabled\"").unwrap(); + drop(busy); + assert!(check.await.unwrap().is_none()); + } + #[tokio::test] async fn retries_find_each_games_queued_save_under_its_full_id() { let fixture = Fixture::new(games()); @@ -2824,23 +3048,23 @@ mod status_tests { #[test] fn a_full_cloud_is_its_own_problem() { - assert_eq!(problem_kind(&Error::Msg(FULL_TEXT.into())), "full"); + assert_eq!(problem_kind(&Error::Msg(FULL_TEXT.into()), true), "full"); } #[test] fn a_copy_over_the_limit_is_too_big() { let e = Error::Msg("This save is too big for cloud saves (over 95 MB). It's kept on this PC.".into()); - assert_eq!(problem_kind(&e), "too-big-copy"); + assert_eq!(problem_kind(&e, true), "too-big-copy"); } #[test] fn no_connection_is_offline() { - assert_eq!(problem_kind(&Error::Net("Can't reach recomplauncher.com right now.".into())), "offline"); + assert_eq!(problem_kind(&Error::Net("Can't reach recomplauncher.com right now.".into()), true), "offline"); } #[test] fn any_other_refusal_is_an_error() { - assert_eq!(problem_kind(&Error::Msg("That copy is gone.".into())), "error"); + assert_eq!(problem_kind(&Error::Msg("That copy is gone.".into()), true), "error"); } #[test] @@ -2855,7 +3079,7 @@ mod status_tests { } #[test] - fn a_conflict_is_not_recorded_as_a_problem() { + fn a_conflict_is_recorded_separately_from_a_problem() { let d = tmp("conflict"); note_failure(&d, "g", &Error::Msg(SYNC_CONFLICT.into())); assert!(saves::state(&d, "g").problem.is_none()); @@ -2889,6 +3113,30 @@ mod status_tests { let s = saves::State { synced_hash: "a".into(), ..Default::default() }; assert_eq!(waiting_copies(&local, &s), 0); } + #[test] + fn a_full_google_drive_is_full() { + let e = Error::Msg("Google Drive storage is full. Free space in Drive, then press Sync Now. Your saves stay on this PC.".into()); + assert_eq!(problem_kind(&e, false), "full"); + } + + #[test] + fn a_conflict_google_drive_reports_as_an_error_is_kept() { + let d = tmp("conflict-error"); + sign_in_for_tests(&d, "A"); + note_failure(&d, "g", &Error::Msg(SYNC_CONFLICT.into())); + assert_eq!(saves::state(&d, "g").sync_state(true, true), "conflict"); + std::fs::remove_dir_all(d).unwrap(); + } + + #[test] + fn a_conflict_with_a_known_version_keeps_it() { + let d = tmp("conflict-version"); + sign_in_for_tests(&d, "A"); + saves::set_state(&d, "g", &saves::State { conflict: Some("v7".into()), ..Default::default() }); + note_failure(&d, "g", &Error::Msg(SYNC_CONFLICT.into())); + assert_eq!(saves::state(&d, "g").conflict.as_deref(), Some("v7")); + std::fs::remove_dir_all(d).unwrap(); + } } #[cfg(test)] @@ -2911,3 +3159,105 @@ mod home_tests { assert!(!home_ok(&json!({"v": 1, "error": "Try again in a moment."}))); } } + +#[cfg(test)] +mod provider_conflict_tests { + use super::*; + + #[tokio::test] + async fn cloud_resolution_uses_the_selected_archive_when_local_slots_remain() { + let dir = std::env::temp_dir().join(format!("rl-cloud-resolution-retained-{}", std::process::id())); + let app = dir.join("app"); + let install = dir.join("game"); + std::fs::create_dir_all(&install).unwrap(); + std::fs::write(install.join("slot.sav"), b"cloud save").unwrap(); + let g = Installed { id: "g".into(), path: install.clone(), ..Default::default() }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let chosen = saves::backup(&app, "g", &spots, &g).unwrap().unwrap(); + let archive = saves::dir_of(&app, "g", &g).join(&chosen.name); + let expected = archive.clone(); + std::fs::write(install.join("slot.sav"), b"local change").unwrap(); + std::fs::write(install.join("extra.sav"), b"extra local slot").unwrap(); + let local_hash = saves::current(&spots, &g).2; + let checked_game = g.clone(); + let result = restore_drive_copy(app.clone(), "g".into(), archive, chosen.hash.clone(), spots.clone(), g.clone(), None, |upload| async move { + assert_eq!(upload, expected); + assert_eq!(saves::manifest(&upload).unwrap().hash, chosen.hash); + assert_ne!(saves::current(&spots, &checked_game).2, chosen.hash, "retained slots must not change the archive used for resolution"); + Ok(()) + }).await.unwrap(); + assert_eq!(result, 1); + assert_eq!(std::fs::read(install.join("slot.sav")).unwrap(), b"cloud save"); + assert_eq!(std::fs::read(install.join("extra.sav")).unwrap(), b"extra local slot"); + assert!(saves::list(&app, "g", &g).iter().any(|c| c.hash == local_hash)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn interrupted_cloud_resolution_can_retry_with_retained_local_slots() { + let dir = std::env::temp_dir().join(format!("rl-cloud-resolution-retry-{}", std::process::id())); + let app = dir.join("app"); + sign_in_for_tests(&app, "A"); + let install = dir.join("game"); + std::fs::create_dir_all(&install).unwrap(); + std::fs::write(install.join("slot.sav"), b"cloud save").unwrap(); + let g = Installed { id: "g".into(), path: install.clone(), ..Default::default() }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let chosen = saves::backup(&app, "g", &spots, &g).unwrap().unwrap(); + let archive = saves::dir_of(&app, "g", &g).join(&chosen.name); + std::fs::write(install.join("extra.sav"), b"extra local slot").unwrap(); + saves::set_state(&app, "g", &saves::State { synced_hash: "previous-cloud".into(), ..Default::default() }); + let interrupted = restore_drive_copy(app.clone(), "g".into(), archive.clone(), chosen.hash.clone(), spots.clone(), g.clone(), None, |_| async { + Err(Error::Net("interrupted resolution".into())) + }).await; + assert!(matches!(interrupted, Err(Error::Net(_)))); + assert_eq!(saves::state(&app, "g").synced_hash, "previous-cloud"); + restore_drive_copy(app, "g".into(), archive, chosen.hash.clone(), spots, g, None, |upload| async move { + assert_eq!(saves::manifest(&upload).unwrap().hash, chosen.hash); + Ok(()) + }).await.unwrap(); + assert_eq!(std::fs::read(install.join("extra.sav")).unwrap(), b"extra local slot"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn drive_restore_preserves_saves_changed_during_download() { + let dir = std::env::temp_dir().join(format!("rl-drive-restore-changed-{}", std::process::id())); + let app = dir.join("app"); + let install = dir.join("game"); + std::fs::create_dir_all(&install).unwrap(); + let slot = install.join("slot.sav"); + std::fs::write(&slot, b"cloud save").unwrap(); + let g = Installed { id: "g".into(), path: install, ..Default::default() }; + let spots = vec![Spot { template: "{install}/slot.sav".into(), from: "developer" }]; + let chosen = saves::backup(&app, "g", &spots, &g).unwrap().unwrap(); + let archive = saves::dir_of(&app, "g", &g).join(&chosen.name); + let checked = saves::current(&spots, &g).2; + std::fs::write(&slot, b"new local save").unwrap(); + let result = restore_drive_copy(app, "g".into(), archive, chosen.hash, spots, g, Some(checked), |_| async { + panic!("a changed local save must not resolve the cloud conflict"); + }).await; + assert_eq!(result.unwrap_err().to_string(), saves::CHANGED_SINCE_CHECK); + assert_eq!(std::fs::read(slot).unwrap(), b"new local save"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_drive_conflict_offers_the_other_devices_save() { + let list = vec![ + CloudCopy { v: "pc".into(), hash: "pc-save".into(), head: true, conflict: true, ..Default::default() }, + CloudCopy { v: "deck".into(), hash: "deck-save".into(), head: true, conflict: true, ..Default::default() }, + ]; + assert_eq!(current_copy(&list, "pc-save").unwrap().v, "deck"); + } + + #[test] + fn old_history_is_not_offered_as_an_unresolved_branch() { + let list = vec![ + CloudCopy { v: "pc".into(), hash: "pc-save".into(), head: true, conflict: true, ..Default::default() }, + CloudCopy { v: "old".into(), hash: "old-save".into(), head: false, conflict: true, ..Default::default() }, + CloudCopy { v: "deck".into(), hash: "deck-save".into(), head: true, conflict: true, ..Default::default() }, + ]; + assert_eq!(current_copy(&list, "pc-save").unwrap().v, "deck"); + } +} diff --git a/src-tauri/src/drive.rs b/src-tauri/src/drive.rs new file mode 100644 index 00000000..290f1a29 --- /dev/null +++ b/src-tauri/src/drive.rs @@ -0,0 +1,1204 @@ +//! Direct Google Drive storage. Immutable snapshots retain their parents so simultaneous uploads +//! remain visible as conflicts, even when the PCs disagree about the time. + +use crate::{cloud, save_provider, saves, App, Error}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Mutex, OnceLock, +}; +use std::time::{Duration, Instant}; +use tauri::{AppHandle, Manager}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +type Res = Result; +const API: &str = "https://www.googleapis.com/drive/v3"; +const TOKEN: &str = "https://oauth2.googleapis.com/token"; +const SCOPE: &str = "https://www.googleapis.com/auth/drive.file"; +pub const MAX_ARCHIVE: usize = 95 * 1024 * 1024; +const CREDENTIAL: &str = "google-drive"; +static NEEDS_RECONNECT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +const RECONNECT: &str = "Google Drive needs you to connect again in Settings → Account."; +static GENERATION: AtomicU64 = AtomicU64::new(0); +static CONNECT: Mutex> = Mutex::new(None); +static ACCESS: tokio::sync::Mutex> = tokio::sync::Mutex::const_new(None); + +#[derive(Clone, Serialize, Deserialize)] +struct Account { + id: String, + email: String, + refresh: String, + client_id: String, + client_secret: String, +} + +struct Access { + account: String, + token: String, + until: Instant, +} + +struct Connection { + generation: u64, + task: Option, + result: Value, +} + +fn client() -> &'static reqwest::Client { + static CLIENT: OnceLock = OnceLock::new(); + CLIENT.get_or_init(|| { + crate::net::with_proxy(reqwest::Client::builder()) + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(300)) + .build() + .expect("Google HTTP client") + }) +} + +fn load(dir: &Path) -> Option { + serde_json::from_slice(&crate::secret::load_named(dir, CREDENTIAL)?).ok() +} + +fn store(dir: &Path, account: &Account) -> Res<()> { + crate::secret::save_named( + dir, + CREDENTIAL, + &serde_json::to_vec(account).map_err(|_| Error::Msg("Couldn't save the Google sign-in.".into()))?, + )?; + Ok(()) +} + +pub fn identity(dir: &Path) -> String { + load(dir).map(|a| a.id).unwrap_or_default() +} + +pub fn connected(dir: &Path) -> bool { + load(dir).is_some() +} + +fn desktop_credentials() -> (&'static str, &'static str) { + (option_env!("RL_GOOGLE_CLIENT_ID").unwrap_or(""), option_env!("RL_GOOGLE_CLIENT_SECRET").unwrap_or("")) +} + +fn device_credentials() -> (&'static str, &'static str) { + (option_env!("RL_GOOGLE_DEVICE_CLIENT_ID").unwrap_or(""), option_env!("RL_GOOGLE_DEVICE_CLIENT_SECRET").unwrap_or("")) +} + +pub fn state(dir: &Path) -> Value { + let a = load(dir); + json!({"connected": a.is_some(), "email": a.map(|a| a.email), "configured": !desktop_credentials().0.is_empty(), "deviceConfigured": !device_credentials().0.is_empty(), "needsReconnect": NEEDS_RECONNECT.load(Ordering::Relaxed)}) +} + +fn transport(_: reqwest::Error) -> Error { + // Upload session URLs and OAuth responses may contain credentials. Never put them in logs. + Error::Net("Google Drive couldn't be reached. Your saves stay on this PC and will retry.".into()) +} + +async fn token_form(form: &[(&str, &str)]) -> Res { + let r = client().post(TOKEN).form(form).timeout(Duration::from_secs(20)).send().await.map_err(transport)?; + let status = r.status().as_u16(); + let value: Value = r.json().await.map_err(transport)?; + if status == 429 || status >= 500 { + return Err(Error::Net("Google sign-in is busy. Try again later.".into())); + } + if status >= 400 || value.get("error").is_some() { + return Err(Error::Msg(RECONNECT.into())); + } + Ok(value) +} + +async fn access(app: &AppHandle, force: bool) -> Res { + let mut cached = ACCESS.lock().await; + let st = app.state::(); + let mut a = load(&st.dir).ok_or_else(|| Error::Msg(RECONNECT.into()))?; + if !force { + if let Some(c) = cached.as_ref().filter(|c| c.account == a.id && c.until > Instant::now()) { + return Ok(c.token.clone()); + } + } + let refreshed = token_form(&[ + ("client_id", &a.client_id), + ("client_secret", &a.client_secret), + ("refresh_token", &a.refresh), + ("grant_type", "refresh_token"), + ]) + .await; + if matches!(&refreshed, Err(Error::Msg(message)) if message == RECONNECT) { + NEEDS_RECONNECT.store(true, Ordering::Relaxed); + } + let v = refreshed?; + NEEDS_RECONNECT.store(false, Ordering::Relaxed); + let token = v["access_token"].as_str().filter(|s| !s.is_empty()).ok_or_else(|| Error::Msg(RECONNECT.into()))?.to_string(); + if let Some(refresh) = v["refresh_token"].as_str().filter(|s| !s.is_empty()) { + a.refresh = refresh.to_string(); + store(&st.dir, &a)?; + } + let seconds = v["expires_in"].as_u64().unwrap_or(3600).saturating_sub(60).min(3600); + *cached = Some(Access { account: a.id, token: token.clone(), until: Instant::now() + Duration::from_secs(seconds) }); + Ok(token) +} + +fn api_error(status: u16, body: &Value) -> Error { + let reason = body.pointer("/error/errors/0/reason").and_then(Value::as_str).unwrap_or(""); + if reason == "storageQuotaExceeded" { + return Error::Msg("Google Drive storage is full. Free space in Drive, then press Sync Now. Your saves stay on this PC.".into()); + } + if status == 401 { + return Error::Msg(RECONNECT.into()); + } + if status == 429 || status >= 500 || matches!(reason, "rateLimitExceeded" | "userRateLimitExceeded") { + return Error::Net("Google Drive is busy. Your saves stay on this PC and will retry.".into()); + } + Error::Msg(format!("Google Drive refused the request ({status}). Check its connection in Settings → Account.")) +} + +async fn send_response(app: &AppHandle, request: reqwest::RequestBuilder) -> Res { + let url = request + .try_clone() + .ok_or_else(|| Error::Msg("Couldn't prepare the Drive request.".into()))? + .build() + .map_err(transport)? + .url() + .to_string(); + let token = access(app, false).await?; + let retry = request.try_clone(); + let mut r = crate::net::send(request.bearer_auth(token), &url, true).await.map_err(|_| transport_error())?; + if r.status().as_u16() == 401 { + let token = access(app, true).await?; + let request = retry.ok_or_else(|| Error::Msg(RECONNECT.into()))?; + r = request.bearer_auth(token).send().await.map_err(transport)?; + } + Ok(r) +} + +async fn check_response(r: reqwest::Response) -> Res { + let status = r.status().as_u16(); + if status < 400 { + return Ok(r); + } + let body = r.json().await.unwrap_or(Value::Null); + Err(api_error(status, &body)) +} + +async fn send(app: &AppHandle, request: reqwest::RequestBuilder) -> Res { + check_response(send_response(app, request).await?).await +} + +fn transport_error() -> Error { + Error::Net("Google Drive couldn't be reached. Your saves stay on this PC and will retry.".into()) +} + +async fn json_response(r: reqwest::Response) -> Res { + r.json().await.map_err(transport) +} + +async fn about_token(token: &str) -> Res { + let r = client() + .get(format!("{API}/about")) + .query(&[("fields", "user(permissionId,emailAddress),storageQuota")]) + .bearer_auth(token) + .send() + .await + .map_err(transport)?; + let status = r.status().as_u16(); + let v = r.json().await.map_err(transport)?; + if status >= 400 { + return Err(api_error(status, &v)); + } + Ok(v) +} + +pub async fn space(app: &AppHandle) -> Res { + let request = client().get(format!("{API}/about")).query(&[("fields", "storageQuota")]).timeout(Duration::from_secs(20)); + let v = json_response(send(app, request).await?).await?; + let number = |key: &str| v.pointer(key).and_then(Value::as_str).and_then(|s| s.parse::().ok()); + Ok(json!({"used": number("/storageQuota/usage"), "quota": number("/storageQuota/limit")})) +} + +fn random_text() -> Res { + let mut bytes = [0u8; 32]; + getrandom::getrandom(&mut bytes).map_err(|_| Error::Msg("Couldn't start Google sign-in securely.".into()))?; + Ok(URL_SAFE_NO_PAD.encode(bytes)) +} + +fn callback(request: &str, state: &str) -> Res> { + let target = request.lines().next().and_then(|line| line.strip_prefix("GET ")).and_then(|line| line.strip_suffix(" HTTP/1.1")); + let Some(target) = target else { return Ok(None) }; + let url = reqwest::Url::parse(&format!("http://127.0.0.1{target}")).map_err(|_| Error::Msg("Invalid Google callback.".into()))?; + if url.path() != "/oauth2callback" { + return Ok(None); + } + let pairs: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect(); + if pairs.get("state").map(String::as_str) != Some(state) { + return Ok(None); + } + if pairs.contains_key("error") { + return Err(Error::Msg("Google Drive connection was declined.".into())); + } + Ok(pairs.get("code").filter(|c| !c.is_empty()).cloned()) +} + +async fn browser_code(listener: tokio::net::TcpListener, state: String) -> Res { + loop { + let (mut stream, _) = listener.accept().await?; + let request = tokio::time::timeout(Duration::from_secs(5), async { + let mut bytes = Vec::new(); + let mut buffer = [0u8; 1024]; + while bytes.len() < 8192 { + let n = stream.read(&mut buffer).await?; + if n == 0 { + break; + } + bytes.extend_from_slice(&buffer[..n]); + if bytes.windows(4).any(|s| s == b"\r\n\r\n") { + break; + } + } + Ok::<_, std::io::Error>(String::from_utf8_lossy(&bytes).to_string()) + }) + .await; + let Ok(Ok(request)) = request else { continue }; + let result = callback(&request, &state); + let accepted = !matches!(&result, Ok(None)); + let body = if accepted { + "Return to RecompLauncher to finish connecting Google Drive. You can close this page." + } else { + "This isn't the Google sign-in this launcher is waiting for." + }; + let status = if accepted { "200 OK" } else { "400 Bad Request" }; + let response = format!( + "HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = tokio::time::timeout(Duration::from_secs(2), stream.write_all(response.as_bytes())).await; + if let Some(code) = result? { + return Ok(code); + } + } +} + +async fn finish(app: &AppHandle, generation: u64, tokens: Value, client_id: String, client_secret: String) -> Res<()> { + let token = tokens["access_token"].as_str().ok_or_else(|| Error::Msg("Google didn't return a sign-in token.".into()))?; + let refresh = tokens["refresh_token"] + .as_str() + .filter(|s| !s.is_empty()) + .ok_or_else(|| Error::Msg("Google didn't grant offline access. Connect again and approve access to Drive.".into()))?; + let about = about_token(token).await?; + let id = about + .pointer("/user/permissionId") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .ok_or_else(|| Error::Msg("Google didn't identify the connected account.".into()))?; + let email = about.pointer("/user/emailAddress").and_then(Value::as_str).unwrap_or("Google Drive"); + let _busy = cloud::BUSY.lock().await; + let st = app.state::(); + save_provider::ensure_idle(&st)?; + *ACCESS.lock().await = None; + let connection = CONNECT.lock().unwrap(); + if connection.as_ref().map(|c| c.generation) != Some(generation) { + return Err(Error::Msg("Google sign-in was cancelled.".into())); + } + if identity(&st.dir) != id && save_provider::current(&st.dir) == save_provider::Provider::GoogleDrive { + save_provider::clear_consent(&st)?; + } + store(&st.dir, &Account { id: id.into(), email: email.into(), refresh: refresh.into(), client_id, client_secret })?; + NEEDS_RECONNECT.store(false, Ordering::Relaxed); + Ok(()) +} + +fn launch_connection( + app: AppHandle, + generation: u64, + future: impl std::future::Future> + Send + 'static, +) { + let task = tauri::async_runtime::spawn(async move { + let result = match tokio::time::timeout(Duration::from_secs(600), future).await { + Ok(Ok((tokens, id, secret))) => finish(&app, generation, tokens, id, secret).await, + Ok(Err(e)) => Err(e), + Err(_) => Err(Error::Msg("Google sign-in expired. Try connecting again.".into())), + }; + { + let mut current = CONNECT.lock().unwrap(); + if let Some(c) = current.as_mut().filter(|c| c.generation == generation) { + c.result = match result { + Ok(()) => json!({"status": "ok"}), + Err(e) => json!({"status": "error", "error": e.to_string()}), + }; + c.task = None; + } + } + save_provider::emit(&app); + cloud::upload_pending(&app).await; + }); + // Tauri's handle supports cancellation without keeping this command open. + let mut current = CONNECT.lock().unwrap(); + if let Some(c) = current.as_mut().filter(|c| c.generation == generation && c.result["status"] == "pending") { + c.task = Some(task.inner().abort_handle()); + } +} + +#[tauri::command] +pub fn drive_connect_cancel() { + GENERATION.fetch_add(1, Ordering::SeqCst); + let mut current = CONNECT.lock().unwrap(); + if let Some(c) = current.take() { + if let Some(task) = c.task { + task.abort(); + } + } +} + +#[tauri::command] +pub fn drive_connect_poll() -> Value { + CONNECT.lock().unwrap().as_ref().map(|c| c.result.clone()).unwrap_or(json!({"status": "cancelled"})) +} + +#[tauri::command] +pub async fn drive_connect_start(app: AppHandle, tv: bool) -> Res { + save_provider::ensure_idle(&app.state::())?; + drive_connect_cancel(); + let generation = GENERATION.fetch_add(1, Ordering::SeqCst) + 1; + if tv && !device_credentials().0.is_empty() { + return start_device(app, generation).await; + } + let (id, secret) = desktop_credentials(); + if id.is_empty() { + return Err(Error::Msg("Google Drive isn't configured in this launcher build.".into())); + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let redirect = format!("http://127.0.0.1:{}/oauth2callback", listener.local_addr()?.port()); + let state = random_text()?; + let verifier = random_text()?; + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + let mut url = reqwest::Url::parse("https://accounts.google.com/o/oauth2/v2/auth").unwrap(); + url.query_pairs_mut().extend_pairs(&[ + ("client_id", id), + ("redirect_uri", &redirect), + ("response_type", "code"), + ("scope", SCOPE), + ("state", &state), + ("code_challenge", &challenge), + ("code_challenge_method", "S256"), + ("access_type", "offline"), + ("prompt", "consent select_account"), + ]); + { + let mut current = CONNECT.lock().unwrap(); + if GENERATION.load(Ordering::SeqCst) != generation { + return Err(Error::Msg("Google sign-in was cancelled.".into())); + } + *current = Some(Connection { generation, task: None, result: json!({"status": "pending"}) }); + } + launch_connection(app, generation, async move { + let code = browser_code(listener, state).await?; + let tokens = token_form(&[ + ("client_id", id), + ("client_secret", secret), + ("code", &code), + ("code_verifier", &verifier), + ("redirect_uri", &redirect), + ("grant_type", "authorization_code"), + ]) + .await?; + Ok((tokens, id.into(), secret.into())) + }); + Ok(json!({"url": url.as_str(), "device": false, "expires": 600})) +} + +async fn start_device(app: AppHandle, generation: u64) -> Res { + let (id, secret) = device_credentials(); + let r = client() + .post("https://oauth2.googleapis.com/device/code") + .form(&[("client_id", id), ("scope", SCOPE)]) + .timeout(Duration::from_secs(20)) + .send() + .await + .map_err(transport)?; + let status = r.status().as_u16(); + let value: Value = r.json().await.map_err(transport)?; + if status >= 400 { + return Err(Error::Msg("Google couldn't start device sign-in. Use the browser on this PC.".into())); + } + let code = value["device_code"].as_str().ok_or_else(|| Error::Msg("Google didn't return a device code.".into()))?.to_string(); + let url = value["verification_url"].as_str().unwrap_or("https://www.google.com/device"); + let mut interval = value["interval"].as_u64().unwrap_or(5).clamp(5, 60); + let expires = value["expires_in"].as_u64().unwrap_or(600).min(600); + let end = Instant::now() + Duration::from_secs(expires); + { + let mut current = CONNECT.lock().unwrap(); + if GENERATION.load(Ordering::SeqCst) != generation { + return Err(Error::Msg("Google sign-in was cancelled.".into())); + } + *current = Some(Connection { generation, task: None, result: json!({"status": "pending"}) }); + } + launch_connection(app, generation, async move { + while Instant::now() < end { + tokio::time::sleep(Duration::from_secs(interval)).await; + let r = client() + .post(TOKEN) + .form(&[ + ("client_id", id), + ("client_secret", secret), + ("device_code", &code), + ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), + ]) + .timeout(Duration::from_secs(20)) + .send() + .await + .map_err(transport)?; + let v: Value = r.json().await.map_err(transport)?; + match v["error"].as_str() { + Some("authorization_pending") => continue, + Some("slow_down") => { + interval = (interval + 5).min(60); + continue; + } + Some(_) => return Err(Error::Msg("Google device sign-in was declined or expired. Try again.".into())), + None => return Ok((v, id.into(), secret.into())), + } + } + Err(Error::Msg("Google device sign-in expired. Try again.".into())) + }); + Ok(json!({"url": url, "code": value["user_code"], "qr": cloud::qr_svg(url), "device": true, "expires": expires})) +} + +#[tauri::command] +pub async fn drive_disconnect(app: AppHandle) -> Res { + drive_connect_cancel(); + let _busy = cloud::BUSY.lock().await; + let st = app.state::(); + save_provider::ensure_idle(&st)?; + if save_provider::current(&st.dir) == save_provider::Provider::GoogleDrive { + save_provider::clear_consent(&st)?; + } + disconnect_account(&st.dir).await?; + save_provider::emit(&app); + Ok(save_provider::save_provider_state(app.clone())) +} + +async fn disconnect_account(dir: &Path) -> Res<()> { + // A refresh may replace the stored token. Let it finish before removing the credentials. + let mut cached = ACCESS.lock().await; + crate::secret::forget_named(dir, CREDENTIAL)?; + *cached = None; + NEEDS_RECONNECT.store(false, Ordering::Relaxed); + Ok(()) +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct Snapshot { + format: u32, + game: String, + hash: String, + made: u64, + device: String, + played: u64, + generation: u64, + parents: Vec, +} + +#[derive(Clone)] +struct Remote { + id: String, + size: u64, + snapshot: Snapshot, +} + +fn heads(files: &[Remote]) -> Vec<&Remote> { + let parents: HashSet<&str> = files.iter().flat_map(|f| f.snapshot.parents.iter().map(String::as_str)).collect(); + files.iter().filter(|f| !parents.contains(f.id.as_str())).collect() +} + +fn revision(files: &[Remote]) -> String { + let mut ids: Vec<_> = heads(files).iter().map(|f| f.id.as_str()).collect(); + ids.sort(); + hex::encode(Sha256::digest(ids.join("\n").as_bytes())) +} + +fn copies(files: &[Remote]) -> Vec { + let heads = heads(files); + let hashes: HashSet<&str> = heads.iter().map(|f| f.snapshot.hash.as_str()).collect(); + let conflict = hashes.len() > 1; + let head_ids: HashSet<&str> = heads.iter().map(|f| f.id.as_str()).collect(); + let mut ordered: Vec<_> = files.iter().collect(); + ordered.sort_by(|a, b| { + head_ids + .contains(b.id.as_str()) + .cmp(&head_ids.contains(a.id.as_str())) + .then_with(|| b.snapshot.generation.cmp(&a.snapshot.generation)) + .then_with(|| a.id.cmp(&b.id)) + }); + ordered + .into_iter() + .map(|f| cloud::CloudCopy { + v: f.id.clone(), + hash: f.snapshot.hash.clone(), + size: f.size, + made: f.snapshot.made, + device: f.snapshot.device.clone(), + played: f.snapshot.played, + conflict, + revision: revision(files), + head: head_ids.contains(f.id.as_str()), + }) + .collect() +} + +fn game_key(id: &str) -> String { + hex::encode(Sha256::digest(id.as_bytes())) +} + +async fn query(app: &AppHandle, q: &str) -> Res> { + let mut page = String::new(); + let mut out = Vec::new(); + loop { + let request = client().get(format!("{API}/files")).timeout(Duration::from_secs(20)).query(&[ + ("q", q), + ("fields", "nextPageToken,incompleteSearch,files(id,size,description)"), + ("pageSize", "1000"), + ("pageToken", &page), + ]); + let value = json_response(send(app, request).await?).await?; + if value["incompleteSearch"] == true { + return Err(Error::Msg("Google Drive returned an incomplete save list. Try again later.".into())); + } + let files = value["files"].as_array().ok_or_else(|| Error::Msg("Google Drive returned an incomplete save list.".into()))?; + out.extend(files.iter().cloned()); + if out.len() > 20_000 { + return Err(Error::Msg("Too many Drive snapshots to sync safely. Review your Drive save folder.".into())); + } + page = value["nextPageToken"].as_str().unwrap_or("").to_string(); + if page.is_empty() { + return Ok(out); + } + } +} + +async fn remote(app: &AppHandle, id: &str) -> Res> { + let key = game_key(id); + let q = format!( + "trashed = false and appProperties has {{ key='rl' and value='save-v1' }} and appProperties has {{ key='game' and value='{key}' }}" + ); + let values = query(app, &q).await?; + let mut files = Vec::new(); + for value in values { + let snapshot: Snapshot = value["description"] + .as_str() + .and_then(|s| serde_json::from_str(s).ok()) + .ok_or_else(|| Error::Msg("A Google Drive save has invalid metadata. Review its save folder before syncing.".into()))?; + if snapshot.format != 1 || snapshot.game != id || snapshot.hash.len() != 64 { + return Err(Error::Msg("A Google Drive save has incompatible metadata.".into())); + } + let file_id = value["id"].as_str().filter(|s| valid_id(s)).ok_or_else(|| Error::Msg("Invalid Google Drive file ID.".into()))?; + let size = + value["size"].as_str().and_then(|s| s.parse::().ok()).ok_or_else(|| Error::Msg("Incomplete Google Drive save.".into()))?; + files.push(Remote { id: file_id.into(), size, snapshot }); + } + let generations: std::collections::HashMap<_, _> = files.iter().map(|f| (f.id.as_str(), f.snapshot.generation)).collect(); + for file in &files { + let snapshot = &file.snapshot; + let bad_parent = snapshot + .parents + .iter() + .any(|p| !valid_id(p) || p == &file.id || generations.get(p.as_str()).map(|&n| n >= snapshot.generation).unwrap_or(false)); + if snapshot.generation == 0 || bad_parent { + return Err(Error::Msg("Google Drive save history is inconsistent. Review its save folder before syncing.".into())); + } + } + if !files.is_empty() && heads(&files).is_empty() { + return Err(Error::Msg("Google Drive save history is inconsistent. Review its save folder before syncing.".into())); + } + Ok(files) +} + +pub async fn list(app: &AppHandle, id: &str) -> Res<(Vec, Value)> { + Ok((copies(&remote(app, id).await?), space(app).await?)) +} + +fn valid_id(id: &str) -> bool { + !id.is_empty() && id.len() <= 200 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} + +async fn folder(app: &AppHandle, kind: &str, name: &str, parent: Option<&str>) -> Res { + let q = format!( + "trashed = false and mimeType = 'application/vnd.google-apps.folder' and appProperties has {{ key='rl' and value='{kind}' }}" + ); + let mut files = query(app, &q).await?; + files.sort_by(|a, b| a["id"].as_str().cmp(&b["id"].as_str())); + if let Some(id) = files.first().and_then(|v| v["id"].as_str()).filter(|s| valid_id(s)) { + return Ok(id.into()); + } + let mut metadata = json!({"name": name, "mimeType": "application/vnd.google-apps.folder", "appProperties": {"rl": kind}}); + if let Some(parent) = parent { + metadata["parents"] = json!([parent]); + } + let value = + json_response(send(app, client().post(format!("{API}/files")).timeout(Duration::from_secs(20)).json(&metadata)).await?).await?; + value["id"] + .as_str() + .filter(|s| valid_id(s)) + .map(String::from) + .ok_or_else(|| Error::Msg("Google couldn't create the save folder.".into())) +} + +#[derive(Serialize, Deserialize)] +struct Ticket { + id: String, + archive_hash: String, + snapshot: Snapshot, + url: Option, +} + +fn ticket_path(dir: &Path, id: &str) -> PathBuf { + dir.join("drive-uploads").join(game_key(&format!("{}:{id}", identity(dir)))) +} + +fn save_ticket(path: &Path, ticket: &Ticket) -> Res<()> { + std::fs::create_dir_all(path.parent().unwrap())?; + let temp = path.with_extension("tmp"); + crate::secret::write_private(&temp, &serde_json::to_vec(ticket).unwrap())?; + std::fs::rename(temp, path)?; + Ok(()) +} + +fn invalidate_session(path: &Path, ticket: &mut Ticket, status: u16) -> Res<()> { + if !(400..500).contains(&status) { return Ok(()); } + // Google requires a fresh session after upload 4xx errors, including after a restart. + ticket.url = None; + save_ticket(path, ticket) +} + +async fn upload_response(path: &Path, ticket: &mut Ticket, response: reqwest::Response) -> Res { + invalidate_session(path, ticket, response.status().as_u16())?; + check_response(response).await +} + +fn valid_session(url: &str) -> bool { + let Ok(url) = reqwest::Url::parse(url) else { return false }; + url.scheme() == "https" + && url.host_str() == Some("www.googleapis.com") + && url.port_or_known_default() == Some(443) + && url.username().is_empty() + && url.password().is_none() + && url.path() == "/upload/drive/v3/files" +} + +async fn complete(app: &AppHandle, ticket: &Ticket, size: usize) -> Res { + let token = access(app, false).await?; + let r = client() + .get(format!("{API}/files/{}", ticket.id)) + .timeout(Duration::from_secs(20)) + .query(&[("fields", "id,size,sha256Checksum")]) + .bearer_auth(token) + .send() + .await + .map_err(transport)?; + if r.status().as_u16() == 404 { + return Ok(false); + } + let status = r.status().as_u16(); + let v: Value = r.json().await.map_err(transport)?; + if status >= 400 { + return Err(api_error(status, &v)); + } + Ok(v["size"].as_str().and_then(|s| s.parse::().ok()) == Some(size) && v["sha256Checksum"].as_str() == Some(&ticket.archive_hash)) +} + +async fn upload_bytes(app: &AppHandle, ticket_path: &Path, ticket: &mut Ticket, bytes: Vec) -> Res<()> { + if complete(app, ticket, bytes.len()).await? { + return Ok(()); + } + let mut offset = 0; + if let Some(url) = ticket.url.as_deref().filter(|u| valid_session(u)) { + let token = access(app, false).await?; + let r = client() + .put(url) + .timeout(Duration::from_secs(20)) + .bearer_auth(token) + .header("Content-Length", "0") + .header("Content-Range", format!("bytes */{}", bytes.len())) + .send() + .await + .map_err(transport)?; + invalidate_session(ticket_path, ticket, r.status().as_u16())?; + match r.status().as_u16() { + 200 | 201 => { + return if complete(app, ticket, bytes.len()).await? { Ok(()) } else { Err(transport_error()) }; + } + 308 => offset = resume_offset(r.headers(), bytes.len())?, + 404 | 410 => {}, + status => return Err(api_error(status, &r.json().await.unwrap_or(Value::Null))), + } + } else { + ticket.url = None; + } + if ticket.url.is_none() { + let root = folder(app, "root-v1", "RecompLauncher", None).await?; + let parent = folder(app, "saves-v1", "Saves", Some(&root)).await?; + let metadata = json!({"id": ticket.id, "name": format!("{}-{}.zip", crate::library::folder_name(&ticket.snapshot.game), ticket.snapshot.made), "parents": [parent], "mimeType": "application/zip", "description": serde_json::to_string(&ticket.snapshot).unwrap(), "appProperties": {"rl": "save-v1", "game": game_key(&ticket.snapshot.game)}}); + let request = client() + .post("https://www.googleapis.com/upload/drive/v3/files") + .query(&[("uploadType", "resumable")]) + .header("X-Upload-Content-Type", "application/zip") + .header("X-Upload-Content-Length", bytes.len()) + .json(&metadata); + let r = send(app, request).await?; + let url = r + .headers() + .get("Location") + .and_then(|v| v.to_str().ok()) + .filter(|u| valid_session(u)) + .ok_or_else(|| Error::Msg("Google returned an invalid upload session.".into()))?; + ticket.url = Some(url.into()); + save_ticket(ticket_path, ticket)?; + } + if offset >= bytes.len() { + return Err(transport_error()); + } + let total = bytes.len(); + let request = client() + .put(ticket.url.as_ref().unwrap()) + .header("Content-Type", "application/zip") + .header("Content-Range", format!("bytes {offset}-{}/{total}", total - 1)) + .body(bytes[offset..].to_vec()); + let response = send_response(app, request).await?; + let r = upload_response(ticket_path, ticket, response).await?; + if !r.status().is_success() { + return Err(transport_error()); + } + if !complete(app, ticket, total).await? { + return Err(Error::Msg("Google Drive's uploaded copy didn't match. Your local save is kept.".into())); + } + Ok(()) +} + +fn resume_offset(headers: &reqwest::header::HeaderMap, total: usize) -> Res { + let Some(range) = headers.get("Range") else { return Ok(0) }; + let last = range.to_str().ok().and_then(|s| s.strip_prefix("bytes=0-")).and_then(|s| s.parse::().ok()); + let offset = last.and_then(|n| n.checked_add(1)).filter(|&n| n <= total); + offset.ok_or_else(|| Error::Msg("Google returned an invalid upload position.".into())) +} + +pub async fn upload(app: &AppHandle, id: &str, path: &Path, resolution: Option<&str>) -> Res<()> { + let bytes = tokio::fs::read(path).await?; + if bytes.len() > MAX_ARCHIVE { + return Err(Error::Msg("This save is too big for cloud saves (over 95 MB). It's kept on this PC.".into())); + } + let man = saves::manifest(path).ok_or_else(|| Error::Msg("That save copy is gone.".into()))?; + let files = remote(app, id).await?; + let path = ticket_path(&app.state::().dir, id); + let archive_hash = hex::encode(Sha256::digest(&bytes)); + let old: Option = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()); + if resolution.map(|expected| revision(&files) != expected).unwrap_or(false) { + return Err(Error::Msg("The saves changed. Try syncing again.".into())); + } + let current_heads: HashSet<_> = heads(&files).iter().map(|f| f.id.as_str()).collect(); + let mut ticket = match old.filter(|t| { + let parents: HashSet<_> = t.snapshot.parents.iter().map(String::as_str).collect(); + let reusable = + resolution.is_none() || parents == current_heads || (current_heads.len() == 1 && current_heads.contains(t.id.as_str())); + t.archive_hash == archive_hash && valid_id(&t.id) && reusable + }) { + Some(ticket) => ticket, + None => { + let value = json_response( + send( + app, + client() + .get(format!("{API}/files/generateIds")) + .timeout(Duration::from_secs(20)) + .query(&[("count", "1"), ("space", "drive")]), + ) + .await?, + ) + .await?; + let file_id = value["ids"][0] + .as_str() + .filter(|s| valid_id(s)) + .ok_or_else(|| Error::Msg("Google couldn't allocate a save copy.".into()))?; + let parents = heads(&files).iter().map(|f| f.id.clone()).collect(); + let generation = files.iter().map(|f| f.snapshot.generation).max().unwrap_or(0).saturating_add(1); + let snapshot = Snapshot { + format: 1, + game: id.into(), + hash: man.hash, + made: man.made, + device: man.device, + played: man.played, + generation, + parents, + }; + Ticket { id: file_id.into(), archive_hash, snapshot, url: None } + } + }; + let synced = saves::state(&app.state::().dir, id).synced_hash; + if resolution.is_none() && heads(&files).iter().any(|f| f.snapshot.hash != synced && f.snapshot.hash != ticket.snapshot.hash) { + return Err(Error::Msg(cloud::SYNC_CONFLICT.into())); + } + save_ticket(&path, &ticket)?; + upload_bytes(app, &path, &mut ticket, bytes).await?; + let current = remote(app, id).await?; + if copies(¤t).first().map(|c| c.conflict).unwrap_or(false) { + return Err(Error::Msg(cloud::SYNC_CONFLICT.into())); + } + let _ = std::fs::remove_file(&path); + prune(app, ¤t).await; + Ok(()) +} + +fn prune_candidates(files: &[Remote]) -> Vec<&Remote> { + // Conflicting branches and their ancestry are retained until the player resolves them. + if heads(files).len() != 1 { + return Vec::new(); + } + let mut ordered: Vec<_> = files.iter().collect(); + ordered.sort_by_key(|f| f.snapshot.generation); + ordered.truncate(files.len().saturating_sub(5)); + ordered +} + +async fn prune(app: &AppHandle, files: &[Remote]) { + // Removing older parents first keeps the head set intact if a later request fails. + for file in prune_candidates(files) { + let request = client().patch(format!("{API}/files/{}", file.id)).timeout(Duration::from_secs(20)).json(&json!({"trashed": true})); + if send(app, request).await.is_err() { + break; + } + } +} + +pub async fn download(app: &AppHandle, id: &str, copy: &cloud::CloudCopy) -> Res> { + if !valid_id(©.v) || copy.size > MAX_ARCHIVE as u64 { + return Err(Error::Msg("That Google Drive save is too large or invalid.".into())); + } + let files = remote(app, id).await?; + if !files.iter().any(|f| f.id == copy.v && f.snapshot.hash == copy.hash) { + return Err(Error::Msg("The saves changed. Try syncing again.".into())); + } + let mut r = send(app, client().get(format!("{API}/files/{}", copy.v)).query(&[("alt", "media")])).await?; + let mut bytes = Vec::new(); + while let Some(chunk) = r.chunk().await.map_err(transport)? { + if bytes.len().saturating_add(chunk.len()) > MAX_ARCHIVE { + return Err(Error::Msg("That Google Drive save is too large.".into())); + } + bytes.extend_from_slice(&chunk); + } + if bytes.len() as u64 != copy.size { + return Err(Error::Msg("The Google Drive save didn't arrive whole.".into())); + } + Ok(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn drive_client_observes_proxy_changes_without_being_rebuilt() { + let _guard = crate::net::PROXY_TEST_LOCK.lock().unwrap(); + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + runtime.block_on(async { + let proxy = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = proxy.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = proxy.accept().await.unwrap(); + let mut bytes = [0; 4096]; + let count = stream.read(&mut bytes).await.unwrap(); + stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\nproxy").await.unwrap(); + String::from_utf8_lossy(&bytes[..count]).to_string() + }); + let http = client(); + let target = "http://drive-proxy.invalid/save"; + crate::net::set_proxy("custom", &format!("http://{address}"), "", "").unwrap(); + let proxied = http.get(target).timeout(Duration::from_secs(2)).send().await; + crate::net::set_proxy("off", "", "", "").unwrap(); + let direct = http.get(target).timeout(Duration::from_secs(2)).send().await; + crate::net::set_proxy("system", "", "", "").unwrap(); + let request = tokio::time::timeout(Duration::from_secs(3), server).await.unwrap().unwrap(); + assert_eq!(proxied.unwrap().text().await.unwrap(), "proxy"); + assert!(request.starts_with("GET http://drive-proxy.invalid/save HTTP/1.1")); + assert!(direct.is_err(), "turning the proxy off must stop using the existing client connection"); + }); + } + + #[cfg(not(windows))] + #[tokio::test] + async fn disconnect_waits_for_refresh_before_removing_credentials() { + let dir = std::env::temp_dir().join(format!("rl-drive-disconnect-{}", random_text().unwrap())); + std::fs::create_dir_all(&dir).unwrap(); + let mut account = Account { + id: "player".into(), + email: "player@example.com".into(), + refresh: "original".into(), + client_id: "client".into(), + client_secret: "secret".into(), + }; + store(&dir, &account).unwrap(); + let mut refresh = ACCESS.lock().await; + *refresh = Some(Access { account: account.id.clone(), token: "access".into(), until: Instant::now() + Duration::from_secs(60) }); + let disconnect = disconnect_account(&dir); + tokio::pin!(disconnect); + assert!(futures_util::poll!(&mut disconnect).is_pending()); + assert!(connected(&dir), "credentials stay until the in-flight refresh finishes"); + account.refresh = "rotated".into(); + store(&dir, &account).unwrap(); + drop(refresh); + disconnect.await.unwrap(); + assert!(!connected(&dir), "a late refresh must not recreate the disconnected account"); + assert!(ACCESS.lock().await.is_none()); + std::fs::remove_dir_all(&dir).unwrap(); + } + + fn file(id: &str, hash: &str, generation: u64, parents: &[&str]) -> Remote { + Remote { + id: id.into(), + size: 32, + snapshot: Snapshot { + format: 1, + game: "game".into(), + hash: hash.into(), + made: 100, + device: id.into(), + played: 60, + generation, + parents: parents.iter().map(|p| p.to_string()).collect(), + }, + } + } + + #[test] + fn simultaneous_saves_are_conflicts_even_with_equal_times() { + let files = vec![file("base", "old", 1, &[]), file("pc", "pc-save", 2, &["base"]), file("deck", "deck-save", 2, &["base"])]; + assert_eq!(heads(&files).len(), 2); + assert!(copies(&files).iter().all(|c| c.conflict)); + } + + #[test] + fn resolution_covers_both_branches() { + let files = vec![ + file("pc", "pc-save", 2, &["base"]), + file("deck", "deck-save", 2, &["base"]), + file("resolved", "pc-save", 3, &["pc", "deck"]), + ]; + let copies = copies(&files); + assert_eq!(copies[0].v, "resolved"); + assert!(!copies[0].conflict); + } + + #[test] + fn identical_saves_from_two_devices_do_not_conflict() { + let files = vec![file("pc", "same", 2, &["base"]), file("deck", "same", 2, &["base"])]; + assert!(!copies(&files)[0].conflict); + } + + #[test] + fn clock_skew_cannot_make_an_ancestor_current() { + let mut old = file("old", "old", 1, &[]); + old.snapshot.made = u64::MAX; + let files = vec![old, file("new", "new", 2, &["old"])]; + assert_eq!(copies(&files)[0].v, "new"); + } + + #[test] + fn trimming_old_ancestors_keeps_the_current_head() { + let files = vec![file("four", "four", 4, &["three"]), file("five", "five", 5, &["four"])]; + assert_eq!(heads(&files).len(), 1); + assert_eq!(copies(&files)[0].v, "five"); + } + + #[test] + fn interrupted_pruning_preserves_the_head_after_every_deletion() { + let mut files = Vec::new(); + for generation in 1..=7 { + let id = format!("v{generation}"); + let parent = format!("v{}", generation - 1); + let parents = if generation == 1 { vec![] } else { vec![parent.as_str()] }; + files.push(file(&id, &id, generation, &parents)); + } + files.reverse(); + let expected = revision(&files); + let discarded: Vec<_> = prune_candidates(&files).iter().map(|f| f.id.clone()).collect(); + assert_eq!(discarded, ["v1", "v2"]); + for id in discarded { + files.retain(|f| f.id != id); + assert_eq!(revision(&files), expected); + assert_eq!(heads(&files)[0].id, "v7"); + assert!(!copies(&files)[0].conflict); + } + assert_eq!(files.len(), 5); + } + + #[test] + fn pruning_keeps_unresolved_branches_and_their_ancestors() { + let files = vec![ + file("v1", "old", 1, &[]), file("v2", "old", 2, &["v1"]), + file("v3", "old", 3, &["v2"]), file("v4", "old", 4, &["v3"]), + file("pc", "pc-save", 5, &["v4"]), file("deck", "deck-save", 5, &["v4"]), + ]; + assert!(prune_candidates(&files).is_empty()); + } + + #[test] + fn revision_changes_when_another_device_uploads() { + let files = vec![file("pc", "one", 2, &["base"])]; + let mut next = files.clone(); + next.push(file("deck", "two", 2, &["base"])); + assert_ne!(revision(&files), revision(&next)); + } + + #[test] + fn revisions_ignore_listing_order() { + let files = vec![file("pc", "one", 2, &["base"]), file("deck", "two", 2, &["base"])]; + let mut reordered = files.clone(); + reordered.reverse(); + assert_eq!(revision(&files), revision(&reordered)); + } + + #[test] + fn callback_requires_the_original_state() { + assert_eq!(callback("GET /oauth2callback?code=secret&state=other HTTP/1.1\r\n\r\n", "expected").unwrap(), None); + } + + #[test] + fn callback_requires_the_expected_path() { + assert_eq!(callback("GET /favicon.ico?code=secret&state=expected HTTP/1.1\r\n\r\n", "expected").unwrap(), None); + } + + #[test] + fn callback_decodes_the_authorization_code() { + let result = callback("GET /oauth2callback?code=abc%2Fdef&state=expected HTTP/1.1\r\n\r\n", "expected").unwrap(); + assert_eq!(result.as_deref(), Some("abc/def")); + } + + #[test] + fn consent_denial_does_not_return_a_code() { + assert!(callback("GET /oauth2callback?error=access_denied&state=expected HTTP/1.1\r\n\r\n", "expected").is_err()); + } + + #[tokio::test] + async fn browser_sign_in_accepts_the_loopback_callback() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(browser_code(listener, "expected".into())); + let mut stream = tokio::net::TcpStream::connect(address).await.unwrap(); + stream.write_all(b"GET /oauth2callback?code=approved&state=expected HTTP/1.1\r\nHost: localhost\r\n\r\n").await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + assert!(response.starts_with("HTTP/1.1 200 OK")); + assert_eq!(server.await.unwrap().unwrap(), "approved"); + } + + #[test] + fn resumable_upload_continues_after_the_last_received_byte() { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert("Range", "bytes=0-262143".parse().unwrap()); + assert_eq!(resume_offset(&headers, 524288).unwrap(), 262144); + } + + #[test] + fn resumable_upload_rejects_an_offset_past_the_archive() { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert("Range", "bytes=0-999999".parse().unwrap()); + assert!(resume_offset(&headers, 100).is_err()); + } + + #[test] + fn upload_sessions_cannot_send_tokens_to_another_host() { + assert!(valid_session("https://www.googleapis.com/upload/drive/v3/files?upload_id=abc")); + assert!(!valid_session("https://www.googleapis.com.attacker.example/upload/drive/v3/files")); + assert!(!valid_session("http://www.googleapis.com/upload/drive/v3/files")); + assert!(!valid_session("https://www.googleapis.com:444/upload/drive/v3/files")); + } + + fn upload_ticket() -> (PathBuf, Ticket) { + let dir = std::env::temp_dir().join(format!("rl-drive-ticket-{}", random_text().unwrap())); + let path = dir.join("ticket.json"); + let ticket = Ticket { + id: "allocated-file".into(), + archive_hash: "archive-hash".into(), + snapshot: file("allocated-file", "save-hash", 1, &[]).snapshot, + url: Some("https://www.googleapis.com/upload/drive/v3/files?upload_id=expired".into()), + }; + save_ticket(&path, &ticket).unwrap(); + (path, ticket) + } + + fn upload_reply(status: u16, body: Value) -> reqwest::Response { + tauri::http::Response::builder().status(status).body(body.to_string()).unwrap().into() + } + + #[test] + fn invalid_upload_probes_discard_the_persisted_session() { + let (path, mut ticket) = upload_ticket(); + invalidate_session(&path, &mut ticket, 400).unwrap(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(ticket.url.is_none()); + assert!(saved.url.is_none()); + assert_eq!(saved.id, "allocated-file"); + assert_eq!(saved.archive_hash, "archive-hash"); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[tokio::test] + async fn rejected_upload_data_discards_the_session_and_reports_quota() { + let (path, mut ticket) = upload_ticket(); + let response = upload_reply(403, json!({"error": {"errors": [{"reason": "storageQuotaExceeded"}]}})); + let error = upload_response(&path, &mut ticket, response).await.unwrap_err(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(error.to_string().contains("Google Drive storage is full")); + assert!(saved.url.is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[tokio::test] + async fn unauthorized_upload_data_discards_the_session_and_requests_reconnect() { + let (path, mut ticket) = upload_ticket(); + let response = upload_reply(401, Value::Null); + let error = upload_response(&path, &mut ticket, response).await.unwrap_err(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(error.to_string(), RECONNECT); + assert!(saved.url.is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[tokio::test] + async fn rate_limited_upload_data_discards_the_session_and_retries() { + let (path, mut ticket) = upload_ticket(); + let response = upload_reply(403, json!({"error": {"errors": [{"reason": "userRateLimitExceeded"}]}})); + let error = upload_response(&path, &mut ticket, response).await.unwrap_err(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(matches!(error, Error::Net(_))); + assert!(saved.url.is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[tokio::test] + async fn upload_server_errors_preserve_the_session_for_resume() { + let (path, mut ticket) = upload_ticket(); + let response = upload_reply(503, Value::Null); + let error = upload_response(&path, &mut ticket, response).await.unwrap_err(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(matches!(error, Error::Net(_))); + assert_eq!(saved.url, ticket.url); + assert!(saved.url.is_some()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[test] + fn rate_limit_errors_retry_without_pausing_the_website() { + let e = api_error(403, &json!({"error": {"errors": [{"reason": "userRateLimitExceeded"}]}})); + assert!(matches!(e, Error::Net(_))); + } + + #[test] + fn full_drive_gives_a_storage_error() { + let e = api_error(403, &json!({"error": {"errors": [{"reason": "storageQuotaExceeded"}]}})); + assert!(e.to_string().contains("Google Drive storage is full")); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c133cbd1..9a70ca5e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -16,6 +16,8 @@ pub mod assets; pub mod boot; pub mod catalog; pub mod cloud; +mod drive; +mod save_provider; pub mod devtools; pub mod display; pub mod dllcheck; @@ -10722,7 +10724,7 @@ pub fn run() { convert_plan, convert_copy, convert_cancel, looks_info, set_look, look_picture, ui_data, - reset_settings, tray::tray_words, tray::quit_launcher, ach::ach_access, ach::ach_status, ach::ach_apply, ach::ach_profile, ach::ach_games, ach::ach_board, ach::ach_game_web, ach::ach_report, ach::ach_tracker_get, ach::ach_game, ach::ach_set_disc, ach::ach_set_folder, ach::ach_sound, ach::ach_log, ach::ach_peek, ach::ach_rule, ach::ach_reset, ach::ach_test_toast, ach::ach_toast_take, ach::ach_toast_done, cloud::account_start, cloud::account_poll, cloud::account_cancel, cloud::account_state, cloud::account_signout, + reset_settings, tray::tray_words, tray::quit_launcher, ach::ach_access, ach::ach_status, ach::ach_apply, ach::ach_profile, ach::ach_games, ach::ach_board, ach::ach_game_web, ach::ach_report, ach::ach_tracker_get, ach::ach_game, ach::ach_set_disc, ach::ach_set_folder, ach::ach_sound, ach::ach_log, ach::ach_peek, ach::ach_rule, ach::ach_reset, ach::ach_test_toast, ach::ach_toast_take, ach::ach_toast_done, save_provider::save_provider_state, save_provider::save_provider_set, drive::drive_connect_start, drive::drive_connect_poll, drive::drive_connect_cancel, drive::drive_disconnect, cloud::account_start, cloud::account_poll, cloud::account_cancel, cloud::account_state, cloud::account_signout, cloud::saves_check, cloud::saves_pick, cloud::saves_play_without_cloud, cloud::saves_cloud, cloud::saves_cloud_follow_all, download_history, report_counts, play_reports, want_count, cloud::saves_info, cloud::saves_status, cloud::saves_peek, cloud::saves_upload_now, cloud::cloud_retry, cloud::saves_overview, cloud::saves_backup, cloud::saves_restore, cloud::saves_cloud_delete, cloud::saves_share, cloud::saves_set_place, cloud::saves_set_override, cloud::saves_add_place, cloud::saves_remove_place, cloud::saves_open, saves_set_root, saves_open_root, missing_files, missing_made, dll_check, dll_aside, gpu_choice, prefer_fast_gpu, copy_check, wine_tools, deck_scores, latest_counts, team_notes, trending, ig_info, ig_view, usage::pc_specs, usage::recomp_request, adopt::adopt_scan, adopt::migrate_scan, adopt::migrate_pick, adopt::adopt_pick, adopt::adopt_add, adopt::adopt_check, adopt::set_project, usage::usage_hello, usage::usage_event, usage::data_ids, usage::reset_ids, ping::usage_open, ping::usage_mode, usage::run_report, cloud::inbox, cloud::inbox_done, cloud::betas, cloud::beta_join, cloud::beta_leave, launcher_notes, scan_info, devtools::dev_add, devtools::add_any, devtools::dev_check, devtools::dev_starter, fs_places, fs_list, fs_extract, gb_mods, gb_mod, gb_install ]) diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index fcf6cfb9..0a36498e 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -658,6 +658,8 @@ pub enum Proxy { } static PROXY: std::sync::RwLock> = std::sync::RwLock::new(None); +#[cfg(test)] +pub(crate) static PROXY_TEST_LOCK: Mutex<()> = Mutex::new(()); /// Applies the player's setting: "off", "system" (or empty) or "custom" with its address and /// optional user and password (put into the address, which is how proxies are told). @@ -921,6 +923,7 @@ mod proxy_tests { #[test] fn a_dead_proxy_fails_fast_with_its_address() { + let _guard = PROXY_TEST_LOCK.lock().unwrap(); // Nothing listens on this port: the request through it fails at once (not a hang), and // the error names the proxy. let dead = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/src-tauri/src/save_provider.rs b/src-tauri/src/save_provider.rs new file mode 100644 index 00000000..d2b9d048 --- /dev/null +++ b/src-tauri/src/save_provider.rs @@ -0,0 +1,107 @@ +//! The save destination is independent of the RecompStore account used by other launcher features. + +use crate::{cloud, drive, App, Error}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::path::Path; +use tauri::{AppHandle, Emitter, Manager}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Provider { + #[default] + Recompstore, + GoogleDrive, + Disabled, +} + +pub fn current(dir: &Path) -> Provider { + match std::fs::read(dir.join("save-provider.json")) { + Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or(Provider::Disabled), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Provider::Recompstore, + Err(_) => Provider::Disabled, + } +} + +pub fn ready(dir: &Path) -> bool { + match current(dir) { + Provider::Recompstore => cloud::signed_in(dir), + Provider::GoogleDrive => drive::connected(dir), + Provider::Disabled => false, + } +} + +pub fn scope(dir: &Path) -> String { + match current(dir) { + Provider::Recompstore => format!("recompstore:{}", cloud::account_uid(dir)), + Provider::GoogleDrive => format!("google_drive:{}", drive::identity(dir)), + Provider::Disabled => "disabled".into(), + } +} + +pub fn name(dir: &Path) -> &'static str { + match current(dir) { + Provider::Recompstore => "RecompStore", + Provider::GoogleDrive => "Google Drive", + Provider::Disabled => "Unavailable", + } +} + +pub fn state(app: &AppHandle) -> Value { + let st = app.state::(); + json!({"provider": current(&st.dir), "name": name(&st.dir), "connected": ready(&st.dir), "google": drive::state(&st.dir)}) +} + +#[tauri::command] +pub fn save_provider_state(app: AppHandle) -> Value { + let st = app.state::(); + let state = state(&app); + let library = st.lib.lock().unwrap(); + json!({"state": state, "installed": library.installed, "cloudAll": library.settings.ui.get("cloud_all")}) +} + +pub fn emit(app: &AppHandle) { + let _ = app.emit("save-provider", save_provider_state(app.clone())); +} + +pub fn ensure_idle(st: &App) -> Result<(), Error> { + if !st.running.lock().unwrap().is_empty() || !st.pids.lock().unwrap().is_empty() || !crate::STARTING.lock().unwrap().is_empty() { + return Err(Error::Msg("Close your games before changing the cloud save account or provider.".into())); + } + Ok(()) +} + +/// A destination change needs fresh consent for each game. Local backups and remote history stay. +pub fn clear_consent(st: &App) -> Result<(), Error> { + let mut library = st.lib.lock().unwrap(); + let mut next = library.clone(); + for game in next.installed.values_mut() { + game.cloud = None; + } + next.settings.ui["cloud_all"] = false.into(); + next.save(&st.dir)?; + *library = next; + cloud::reset_provider_status(); + Ok(()) +} + +#[tauri::command] +pub async fn save_provider_set(app: AppHandle, provider: Provider) -> Result { + if provider == Provider::Disabled { + return Err(Error::Msg("Choose RecompStore or Google Drive.".into())); + } + let _guard = cloud::BUSY.lock().await; + let st = app.state::(); + ensure_idle(&st)?; + if provider == Provider::GoogleDrive && !drive::connected(&st.dir) { + return Err(Error::Msg("Connect Google Drive first.".into())); + } + if current(&st.dir) != provider { + clear_consent(&st)?; + let temp = st.dir.join("save-provider.json.tmp"); + crate::secret::write_private(&temp, &serde_json::to_vec(&provider).unwrap())?; + std::fs::rename(temp, st.dir.join("save-provider.json"))?; + } + emit(&app); + Ok(save_provider_state(app.clone())) +} diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index 7ae17092..9173518e 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -868,14 +868,13 @@ fn state_file(app_dir: &Path, id: &str) -> PathBuf { app_dir.join("saves").join(id).join("state.json") } -/// The key in state.json naming the sign-in its cloud fields belong to. Same name and form as the -/// Google Drive draft (PR #228) uses, ":", so the two read each other's notes. +/// The key in state.json naming the provider and account its cloud fields belong to. const SCOPE_KEY: &str = "cloud_scope"; /// The sign-in a note's cloud fields are written under now. Read from account.json without /// opening the sealed token, so it costs no trip to Windows' Credential Manager. fn scope_now(app_dir: &Path) -> String { - format!("recompstore:{}", crate::cloud::account_uid(app_dir)) + crate::save_provider::scope(app_dir) } /// A scope with no account id after the colon is nobody's: nothing in the cloud belongs to it. @@ -901,7 +900,9 @@ fn write_note(app_dir: &Path, id: &str, s: &State, scope: &str) { } let mut value = serde_json::to_value(s).unwrap_or_default(); value[SCOPE_KEY] = scope.into(); - let _ = fs::write(f, serde_json::to_vec_pretty(&value).unwrap_or_default()); + let temp = f.with_extension("json.tmp"); + let result = fs::write(&temp, serde_json::to_vec_pretty(&value).unwrap_or_default()).and_then(|_| fs::rename(&temp, &f)); + if result.is_err() { let _ = fs::remove_file(temp); } } /// What this PC knows about a game's saves, for whoever is signed in now. The cloud fields only @@ -921,7 +922,7 @@ pub fn state(app_dir: &Path, id: &str) -> State { }; s.read_under = Some(now.clone()); let Some(written) = written else { - if !owned(&now) { + if !owned(&now) || !now.starts_with("recompstore:") { s.forget_cloud(); } write_note(app_dir, id, &s, &now); @@ -1125,6 +1126,142 @@ fn not_written(path: &Path, e: io::Error) -> Error { Error::Msg(format!("{SAVE_NOT_WRITTEN}\n{}: {e}", path.display())) } +/// Drive files can be edited outside the launcher. Check every byte before changing live saves, +/// and only allow destinations this PC already knows belong to the game. +pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot], g: &Installed) -> Result<(), Error> { + let invalid = || Error::Msg("That cloud save is damaged or doesn't match this game's save folders. Nothing was restored.".into()); + let mut zip = zip::ZipArchive::new(fs::File::open(path)?).map_err(|_| invalid())?; + let max_entries = spots.len().saturating_mul(MAX_FILES).saturating_add(1); + if zip.len() > max_entries { return Err(invalid()); } + let manifest_limit = cloud_manifest_limit(&zip, spots.len()); + let man: Manifest = { + let mut entry = zip.by_name("rlsave.json").map_err(|_| invalid())?; + if entry.size() > manifest_limit { return Err(invalid()); } + let mut bytes = Vec::new(); + entry.by_ref().take(manifest_limit + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > manifest_limit { return Err(invalid()); } + serde_json::from_slice(&bytes).map_err(|_| invalid())? + }; + if man.format != 1 || man.game != id || man.hash != hash || set_hash(&man.files) != hash || man.files.is_empty() { + return Err(invalid()); + } + let picked = !spots.is_empty() && spots.iter().all(|s| s.from == "player"); + let moved = moved_places(&man.spots, spots).is_some(); + let same = man.spots.iter().zip(spots).all(|(a, b)| a == &b.template); + // Use the same trusted remapping as restore, while validating every file against the new roots. + if man.spots.len() != spots.len() || !(picked || moved || same) { + return Err(invalid()); + } + if !cloud_files_within_limits(&man.files, spots.len()) { return Err(invalid()); } + let mut protected = HashSet::new(); + for file in g.files.iter().chain(g.exe.iter()) { + let path = g.path.join(file); + protected.insert(lower(&path)); + if let Ok(real) = path.canonicalize() { protected.insert(lower(&real)); } + } + let mut expected = HashMap::new(); + for file in &man.files { + let (dest, base) = cloud_destination(file, &spots[file.spot], g).ok_or_else(invalid)?; + if !cloud_destination_allowed(&dest, &base, g, &protected) { return Err(invalid()); } + // Restore stages beside the destination; that write must not replace a protected file either. + if !cloud_destination_allowed(&dest.with_extension("rl-part"), &base, g, &protected) { return Err(invalid()); } + let name = format!("{}/{}", file.spot, file.rel); + if expected.insert(name, file).is_some() { return Err(invalid()); } + } + if zip.len() != expected.len() + 1 { return Err(invalid()); } + let mut seen = HashSet::new(); + for index in 0..zip.len() { + let mut entry = zip.by_index(index).map_err(|_| invalid())?; + let name = entry.name().to_string(); + if !seen.insert(name.clone()) { return Err(invalid()); } + if name == "rlsave.json" { continue; } + let file = expected.get(&name).ok_or_else(invalid)?; + let symlink = entry.unix_mode().map(|m| m & 0o170000 == 0o120000).unwrap_or(false); + if entry.size() != file.size || symlink { return Err(invalid()); } + let mut sha = Sha256::new(); + let mut buffer = [0u8; 64 * 1024]; + let mut count = 0u64; + loop { + let n = entry.read(&mut buffer)?; + if n == 0 { break; } + count += n as u64; + if count > file.size { return Err(invalid()); } + sha.update(&buffer[..n]); + } + if count != file.size || hex::encode(sha.finalize()) != file.sha256 { return Err(invalid()); } + } + Ok(()) +} + +fn cloud_manifest_limit(zip: &zip::ZipArchive, spots: usize) -> u64 { + // JSON may escape each path byte. Budget the entry fields too, plus source folder paths + // up to native path limits; picked folders can differ between the two PCs. + let names: u64 = zip.file_names().map(|name| name.len() as u64).sum(); + let paths = names.saturating_mul(6); + let fields = (zip.len() as u64).saturating_mul(256); + let folders = (spots as u64).saturating_mul(128 * 1024 * 6); + paths.saturating_add(fields).saturating_add(folders).saturating_add(64 * 1024) +} + +pub fn restore_cloud_copy(app_dir: &Path, id: &str, path: &Path, hash: &str, spots: &[Spot], g: &Installed) -> Result { + validate_cloud_copy(path, id, hash, spots, g)?; + restore(app_dir, id, path, spots, g) +} + +fn cloud_destination(file: &FileInfo, spot: &Spot, g: &Installed) -> Option<(PathBuf, PathBuf)> { + if !plain_save_path(&file.rel) { return None; } + // Windows strips these suffixes, which could disguise an installed program's filename. + if file.rel.split('/').any(|p| p.ends_with(['.', ' '])) { return None; } + let relative = Path::new(&file.rel); + let name = relative.file_name()?.to_str()?; + if !is_save_file(name, file.size) { return None; } + if relative.parent()?.components().any(|c| skip_dir(&c.as_os_str().to_string_lossy())) { return None; } + let root = resolve_for(&spot.template, g); + let last = root.file_name()?.to_str()?; + if spot.from == "player" { return Some((root.join(relative), root)); } + if last.contains('*') { + if file.rel.contains('/') || !wild(last, &file.rel) { return None; } + let base = root.parent()?.to_path_buf(); + return Some((base.join(relative), base)); + } + if root.is_file() && file.rel != last { return None; } + if file.rel == last && !root.is_dir() { + let base = root.parent()?.to_path_buf(); + return Some((root, base)); + } + Some((root.join(relative), root)) +} + +fn cloud_destination_allowed(path: &Path, base: &Path, g: &Installed, protected: &HashSet) -> bool { + if protected.contains(&lower(path)) || crate::inputs::excluded(g, path) { return false; } + if path.canonicalize().is_ok_and(|p| protected.contains(&lower(&p))) { return false; } + // A save subfolder or staging path may be a link to a program outside the named location. + for parent in path.ancestors() { + match fs::symlink_metadata(parent) { + Ok(m) if is_save_link(&m) => return false, + Ok(m) if parent == path && !m.is_file() => return false, + Ok(m) if parent != path && !m.is_dir() => return false, + Err(e) if e.kind() != io::ErrorKind::NotFound => return false, + _ => {}, + } + if parent == base { break; } + } + true +} + +fn cloud_files_within_limits(files: &[FileInfo], spots: usize) -> bool { + // Discovery budgets each save location separately, including when one backup covers several. + let mut counts = vec![0usize; spots]; + let mut sizes = vec![0u64; spots]; + for file in files { + if file.spot >= spots || file.size > MAX_FILE { return false; } + counts[file.spot] += 1; + sizes[file.spot] += file.size; + if counts[file.spot] > MAX_FILES || sizes[file.spot] > SPOT_MAX { return false; } + } + true +} + /// Puts a copy's files back where the game reads them, on this PC. Saves that are there now and /// aren't in the copy are taken away, so the game sees exactly what was copied; what was there is /// kept as a copy first, so this can be undone. @@ -1497,6 +1634,409 @@ pub fn share_save(app_dir: &Path, id: &str, spot: &Spot, g: &Installed, source: #[cfg(test)] mod tests { + fn cloud_archive(dir: &Path, template: &str, data: &[u8], actual: &[u8]) -> (PathBuf, String) { + cloud_archive_named(dir, template, "slot.sav", data, actual) + } + + fn cloud_archive_named(dir: &Path, template: &str, rel: &str, data: &[u8], actual: &[u8]) -> (PathBuf, String) { + let files = vec![FileInfo { spot: 0, rel: rel.into(), size: data.len() as u64, sha256: hex::encode(Sha256::digest(data)) }]; + let hash = set_hash(&files); + let manifest = Manifest { format: 1, game: "g".into(), hash: hash.clone(), spots: vec![template.into()], files, ..Default::default() }; + let path = dir.join("cloud.zip"); + let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + zip.start_file("rlsave.json", options).unwrap(); + zip.write_all(&serde_json::to_vec(&manifest).unwrap()).unwrap(); + zip.start_file(format!("0/{rel}"), options).unwrap(); + zip.write_all(actual).unwrap(); + zip.finish().unwrap(); + (path, hash) + } + + #[test] + fn cloud_copy_checks_every_file_before_restore() { + let dir = tmp("cloud-valid"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_ok()); + } + + #[test] + fn cloud_restore_rejects_an_executable_with_matching_hashes() { + let dir = tmp("cloud-executable"); + fs::write(dir.join("game.exe"), b"installed program").unwrap(); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "game.exe", b"replacement", b"replacement"); + let app = dir.join("app"); + assert!(restore_cloud_copy(&app, "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("game.exe")).unwrap(), b"installed program"); + assert!(!app.exists(), "validation must finish before backups or live save changes"); + } + + #[test] + fn cloud_restore_validates_every_entry_before_changing_live_saves() { + let dir = tmp("cloud-all-entries"); + fs::write(dir.join("slot.sav"), b"local save").unwrap(); + fs::write(dir.join("game.exe"), b"installed program").unwrap(); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let data = b"replacement"; + let files = ["slot.sav", "game.exe"].map(|rel| FileInfo { + spot: 0, rel: rel.into(), size: data.len() as u64, sha256: hex::encode(Sha256::digest(data)), + }); + let hash = set_hash(&files); + let manifest = Manifest { + format: 1, game: "g".into(), hash: hash.clone(), spots: vec!["{install}".into()], files: files.to_vec(), ..Default::default() + }; + let path = dir.join("cloud.zip"); + let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + zip.start_file("rlsave.json", options).unwrap(); + zip.write_all(&serde_json::to_vec(&manifest).unwrap()).unwrap(); + for file in &files { + zip.start_file(format!("0/{}", file.rel), options).unwrap(); + zip.write_all(data).unwrap(); + } + zip.finish().unwrap(); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("slot.sav")).unwrap(), b"local save"); + assert_eq!(fs::read(dir.join("game.exe")).unwrap(), b"installed program"); + assert!(!dir.join("app").exists()); + } + + #[test] + fn cloud_restore_rejects_an_installed_data_file_in_a_named_folder() { + let dir = tmp("cloud-release-data"); + fs::create_dir(dir.join("data")).unwrap(); + fs::write(dir.join("data/a.bin"), b"installed data").unwrap(); + let spots = vec![Spot { template: "{install}/data".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "a.bin", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("data/a.bin")).unwrap(), b"installed data"); + } + + #[test] + fn cloud_restore_rejects_an_imported_extensionless_program() { + let dir = tmp("cloud-imported-program"); + fs::write(dir.join("launch-game"), b"installed program").unwrap(); + let g = Installed { exe: Some("launch-game".into()), files: vec![], ..game(&dir) }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "launch-game", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); + assert_eq!(fs::read(dir.join("launch-game")).unwrap(), b"installed program"); + } + + #[test] + fn cloud_restore_rejects_an_absolute_selected_program() { + let dir = tmp("cloud-manual-program"); + let program = dir.join("launch-game"); + fs::write(&program, b"manual program").unwrap(); + let g = Installed { exe: Some(program.clone()), files: vec![], ..game(&dir) }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "launch-game", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); + assert_eq!(fs::read(program).unwrap(), b"manual program"); + } + + #[test] + fn cloud_restore_rejects_a_filename_outside_the_save_glob() { + let dir = tmp("cloud-glob-mismatch"); + fs::write(dir.join("settings.toml"), b"local settings").unwrap(); + let spots = vec![Spot { template: "{install}/*.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "settings.toml", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("settings.toml")).unwrap(), b"local settings"); + } + + #[test] + fn cloud_restore_rejects_nested_paths_in_a_save_glob() { + let dir = tmp("cloud-glob-nested"); + let spots = vec![Spot { template: "{install}/*.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "nested/slot.sav", b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert!(!dir.join("nested").exists()); + } + + #[test] + fn cloud_restore_rejects_a_different_name_for_a_single_save_file() { + let dir = tmp("cloud-file-mismatch"); + fs::write(dir.join("only.sav"), b"local save").unwrap(); + let spots = vec![Spot { template: "{install}/only.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("only.sav")).unwrap(), b"local save"); + } + + #[test] + fn cloud_restore_accepts_a_matching_glob_file() { + let dir = tmp("cloud-glob-valid"); + let spots = vec![Spot { template: "{install}/*.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert_eq!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).unwrap(), 1); + assert_eq!(fs::read(dir.join("slot.sav")).unwrap(), b"save"); + } + + #[test] + fn cloud_restore_accepts_a_missing_single_save_file() { + let dir = tmp("cloud-file-valid"); + let spots = vec![Spot { template: "{install}/slot.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert_eq!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).unwrap(), 1); + assert_eq!(fs::read(dir.join("slot.sav")).unwrap(), b"save"); + } + + #[test] + fn cloud_restore_accepts_nested_saves_in_a_missing_folder() { + let dir = tmp("cloud-folder-valid"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "profile/slot.sav", b"save", b"save"); + assert_eq!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).unwrap(), 1); + assert_eq!(fs::read(dir.join("saves/profile/slot.sav")).unwrap(), b"save"); + } + + #[test] + fn cloud_restore_rejects_files_from_excluded_subfolders() { + let dir = tmp("cloud-excluded-folder"); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "mods/slot.sav", b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert!(!dir.join("mods").exists()); + } + + #[test] + fn cloud_restore_rejects_a_managed_input_with_a_custom_name() { + let dir = tmp("cloud-managed-input"); + fs::write(dir.join("secret.dat"), b"managed input").unwrap(); + let mut g = game(&dir); + g.input_staged.insert("keys".into(), "secret.dat".into()); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "secret.dat", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); + assert_eq!(fs::read(dir.join("secret.dat")).unwrap(), b"managed input"); + } + + #[test] + fn cloud_restore_rejects_windows_filename_suffix_aliases() { + let dir = tmp("cloud-filename-alias"); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "game.exe. ", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + } + + #[test] + fn cloud_restore_cannot_stage_over_an_installed_release_file() { + let dir = tmp("cloud-stage-release"); + fs::write(dir.join("slot.rl-part"), b"installed data").unwrap(); + let g = Installed { files: vec!["slot.rl-part".into()], ..game(&dir) }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive(&dir, "{install}", b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); + assert_eq!(fs::read(dir.join("slot.rl-part")).unwrap(), b"installed data"); + } + + #[cfg(unix)] + #[test] + fn cloud_restore_rejects_a_link_in_the_destination_path() { + let dir = tmp("cloud-folder-link"); + fs::create_dir(dir.join("saves")).unwrap(); + fs::create_dir(dir.join("outside")).unwrap(); + fs::write(dir.join("outside/slot.sav"), b"outside data").unwrap(); + std::os::unix::fs::symlink(dir.join("outside"), dir.join("saves/profile")).unwrap(); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "profile/slot.sav", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("outside/slot.sav")).unwrap(), b"outside data"); + } + + #[cfg(unix)] + #[test] + fn cloud_restore_rejects_a_link_at_the_staging_path() { + let dir = tmp("cloud-stage-link"); + fs::write(dir.join("outside.dat"), b"outside data").unwrap(); + std::os::unix::fs::symlink(dir.join("outside.dat"), dir.join("slot.rl-part")).unwrap(); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive(&dir, "{install}", b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("outside.dat")).unwrap(), b"outside data"); + } + + #[test] + fn cloud_copy_accepts_a_backup_with_many_files_across_locations() { + let dir = tmp("cloud-many-files"); + let g = game(&dir); + let spots = vec![ + Spot { template: "{install}/saves-0".into(), from: "developer" }, + Spot { template: "{install}/saves-1".into(), from: "developer" }, + ]; + fs::create_dir_all(dir.join("saves-0")).unwrap(); + fs::create_dir_all(dir.join("saves-1")).unwrap(); + let count = MAX_FILES * 2; + let prefix = "s".repeat(90); + for n in 0..count { + let path = dir.join(format!("saves-{}/{prefix}-{n:05}.sav", n % 2)); + fs::write(path, b"save").unwrap(); + } + let copy = backup(&dir, "g", &spots, &g).unwrap().unwrap(); + assert_eq!(copy.files, count); + let archive = dir_of(&dir, "g", &g).join(copy.name); + let mut zip = zip::ZipArchive::new(fs::File::open(&archive).unwrap()).unwrap(); + assert!(zip.by_name("rlsave.json").unwrap().size() > 8 * 1024 * 1024); + drop(zip); + assert!(validate_cloud_copy(&archive, "g", ©.hash, &spots, &g).is_ok()); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn cloud_copy_rejects_a_manifest_bomb_disproportionate_to_its_files() { + let dir = tmp("cloud-manifest-bomb"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + let manifest = read_manifest(&path).unwrap(); + let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap()); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + zip.start_file("rlsave.json", options).unwrap(); + zip.write_all(&vec![b' '; 2 * 1024 * 1024]).unwrap(); + serde_json::to_writer(&mut zip, &manifest).unwrap(); + zip.start_file("0/slot.sav", options).unwrap(); + zip.write_all(b"save").unwrap(); + zip.finish().unwrap(); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_err()); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn cloud_file_counts_cannot_exceed_one_locations_limit() { + let file = FileInfo { spot: 0, rel: "slot.sav".into(), size: 4, sha256: String::new() }; + let files = vec![file; MAX_FILES + 1]; + assert!(!cloud_files_within_limits(&files, 2)); + } + + #[test] + fn cloud_file_sizes_are_budgeted_per_location() { + let count = (SPOT_MAX / MAX_FILE + 1) as usize; + let files: Vec<_> = (0..count).map(|n| FileInfo { + spot: n % 2, rel: format!("slot-{n}.sav"), size: MAX_FILE, sha256: String::new(), + }).collect(); + assert!(files.iter().map(|f| f.size).sum::() > SPOT_MAX); + assert!(cloud_files_within_limits(&files, 2)); + } + + #[test] + fn cloud_file_sizes_cannot_exceed_one_locations_budget() { + let count = (SPOT_MAX / MAX_FILE + 1) as usize; + let file = FileInfo { spot: 0, rel: "slot.sav".into(), size: MAX_FILE, sha256: String::new() }; + assert!(!cloud_files_within_limits(&vec![file; count], 2)); + } + + #[test] + fn cloud_files_reject_an_unknown_location() { + let file = FileInfo { spot: 2, rel: "slot.sav".into(), size: 4, sha256: String::new() }; + assert!(!cloud_files_within_limits(&[file], 2)); + } + + #[test] + fn cloud_files_reject_a_file_larger_than_the_discovery_limit() { + let file = FileInfo { spot: 0, rel: "slot.sav".into(), size: MAX_FILE + 1, sha256: String::new() }; + assert!(!cloud_files_within_limits(&[file], 1)); + } + + #[test] + fn cloud_copy_rejects_changed_file_contents() { + let dir = tmp("cloud-changed"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"evil"); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_err()); + } + + #[test] + fn cloud_copy_cannot_redirect_a_save_to_a_guessed_folder() { + let dir = tmp("cloud-redirect"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "found" }]; + let (path, hash) = cloud_archive(&dir, "{home}/Documents", b"save", b"save"); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_err()); + } + + #[test] + fn cloud_restore_uses_current_named_folders_instead_of_archive_destinations() { + let dir = tmp("cloud-redirect-named"); + let outside = dir.join("outside"); + fs::create_dir(&outside).unwrap(); + fs::write(outside.join("slot.sav"), b"keep this").unwrap(); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, outside.to_str().unwrap(), b"save", b"save"); + let g = game(&dir.join("game")); + assert_eq!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).unwrap(), 1); + assert_eq!(fs::read(g.path.join("saves/slot.sav")).unwrap(), b"save"); + assert_eq!(fs::read(outside.join("slot.sav")).unwrap(), b"keep this"); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn cloud_copy_accepts_a_different_folder_the_player_picked_on_this_pc() { + let dir = tmp("cloud-player-folder"); + let spots = vec![Spot { template: "{home}/my-saves".into(), from: "player" }]; + let (path, hash) = cloud_archive(&dir, "{home}/other-pc-saves", b"save", b"save"); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_ok()); + } + + #[test] + fn cloud_copy_rejects_another_games_archive() { + let dir = tmp("cloud-game"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert!(validate_cloud_copy(&path, "another-game", &hash, &spots, &game(&dir)).is_err()); + } + + #[test] + fn provider_changes_discard_the_sync_baseline_and_queue() { + let dir = tmp("cloud-provider"); + crate::cloud::sign_in_for_tests(&dir, "A"); + let state = State { last_hash: "local".into(), synced_hash: "cloud".into(), pending: Some("123.zip".into()), ..Default::default() }; + set_state(&dir, "g", &state); + fs::write(dir.join("save-provider.json"), b"\"google_drive\"").unwrap(); + let read = super::state(&dir, "g"); + assert_eq!(read.last_hash, "local"); + assert!(read.synced_hash.is_empty()); + assert!(read.pending.is_none()); + } + + #[test] + fn provider_changes_forget_the_old_clouds_conflict_and_problem() { + let dir = tmp("cloud-provider-status"); + crate::cloud::sign_in_for_tests(&dir, "A"); + let problem = Some(Problem { kind: "full".into(), text: String::new(), at: 1 }); + let state = State { synced_hash: "cloud".into(), synced_at: 5, conflict: Some("v1".into()), problem, ..Default::default() }; + set_state(&dir, "g", &state); + fs::write(dir.join("save-provider.json"), b"\"google_drive\"").unwrap(); + let read = super::state(&dir, "g"); + assert_eq!((read.synced_at, read.conflict.is_none(), read.problem.is_none()), (0, true, true)); + } + + #[test] + fn account_changes_discard_the_sync_baseline_and_queue() { + let dir = tmp("cloud-account"); + let value = serde_json::json!({"last_hash": "local", "synced_hash": "cloud", "pending": "123.zip", "cloud_scope": "google_drive:another-account"}); + fs::create_dir_all(dir.join("saves/g")).unwrap(); + fs::write(state_file(&dir, "g"), serde_json::to_vec(&value).unwrap()).unwrap(); + let read = super::state(&dir, "g"); + assert_eq!(read.last_hash, "local"); + assert!(read.synced_hash.is_empty()); + assert!(read.pending.is_none()); + } + + #[test] + fn legacy_website_sync_state_is_migrated() { + let dir = tmp("cloud-legacy"); + crate::cloud::sign_in_for_tests(&dir, "legacy"); + let value = serde_json::json!({"last_hash": "local", "synced_hash": "cloud", "pending": "123.zip"}); + fs::create_dir_all(dir.join("saves/g")).unwrap(); + fs::write(state_file(&dir, "g"), serde_json::to_vec(&value).unwrap()).unwrap(); + let read = super::state(&dir, "g"); + assert_eq!(read.synced_hash, "cloud"); + assert_eq!(read.pending.as_deref(), Some("123.zip")); + let migrated: serde_json::Value = serde_json::from_slice(&fs::read(state_file(&dir, "g")).unwrap()).unwrap(); + assert!(migrated["cloud_scope"].as_str().unwrap().starts_with("recompstore:")); + } + #[test] fn several_save_folders_the_player_picked() { let d = std::env::temp_dir().join(format!("rl-saves-many-{}", std::process::id())); @@ -2494,6 +3034,18 @@ mod tests { (g, archive, place) } + #[test] + fn cloud_restore_follows_a_save_folder_the_developer_moved() { + let d = tmp("cloud-restore-moved"); + let (g, archive) = copy_from_old_folder(&d); + let now = spots(&["{install}/new".into()], &[], &g); + let hash = manifest(&archive).unwrap().hash; + assert_eq!(restore_cloud_copy(&d.join("app"), "g", &archive, &hash, &now, &g).unwrap(), 1); + assert_eq!(fs::read_to_string(g.path.join("new/progress.sav")).unwrap(), "progress"); + assert!(!g.path.join("old").exists()); + fs::remove_dir_all(d).unwrap(); + } + #[test] fn restore_that_cant_write_says_so_first() { let d = tmp("restore-unwritable-first"); diff --git a/src-tauri/src/secret.rs b/src-tauri/src/secret.rs index bab4df78..70f483cb 100644 --- a/src-tauri/src/secret.rs +++ b/src-tauri/src/secret.rs @@ -2,6 +2,52 @@ //! Windows user only; account.json then just says so. Elsewhere the file it's in is readable by //! its owner only. +/// Separate providers must never replace or remove each other's credentials. +pub fn save_named(dir: &std::path::Path, name: &str, plain: &[u8]) -> std::io::Result<()> { + #[cfg(windows)] + { + let _ = dir; + let text = std::str::from_utf8(plain).map_err(std::io::Error::other)?; + if !crate::win::cred_write_named(&format!("RecompLauncher/{name}"), text) { + return Err(std::io::Error::other("Couldn't save the Google sign-in in Credential Manager.")); + } + return Ok(()); + } + #[cfg(not(windows))] + { + let path = dir.join(format!("{name}.json")); + let temp = dir.join(format!("{name}.json.tmp")); + write_private(&temp, plain)?; + std::fs::rename(temp, path) + } +} + +pub fn load_named(dir: &std::path::Path, name: &str) -> Option> { + #[cfg(windows)] + { + let _ = dir; + crate::win::cred_read_named(&format!("RecompLauncher/{name}")).map(String::into_bytes) + } + #[cfg(not(windows))] + std::fs::read(dir.join(format!("{name}.json"))).ok() +} + +pub fn forget_named(dir: &std::path::Path, name: &str) -> std::io::Result<()> { + #[cfg(windows)] + { + let _ = dir; + if !crate::win::cred_delete_named(&format!("RecompLauncher/{name}")) { + return Err(std::io::Error::other("Couldn't remove the Google sign-in from Credential Manager.")); + } + Ok(()) + } + #[cfg(not(windows))] + match std::fs::remove_file(dir.join(format!("{name}.json"))) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + result => result, + } +} + /// Where account.json says the token is kept. #[cfg(windows)] const IN_WINDOWS: &str = "credential-manager"; diff --git a/src-tauri/src/win.rs b/src-tauri/src/win.rs index 9381fe1b..891b0913 100644 --- a/src-tauri/src/win.rs +++ b/src-tauri/src/win.rs @@ -400,8 +400,12 @@ mod imp { /// Keeps a secret in Windows' Credential Manager, for this Windows user only. pub fn cred_write(secret: &str) -> bool { + cred_write_named(CRED, secret) + } + + pub fn cred_write_named(name: &str, secret: &str) -> bool { use windows::Win32::Security::Credentials::{CredWriteW, CREDENTIALW, CRED_PERSIST_LOCAL_MACHINE, CRED_TYPE_GENERIC}; - let mut target: Vec = CRED.encode_utf16().chain([0]).collect(); + let mut target: Vec = name.encode_utf16().chain([0]).collect(); let mut user: Vec = "RecompLauncher".encode_utf16().chain([0]).collect(); let mut blob = secret.as_bytes().to_vec(); let c = CREDENTIALW { @@ -417,9 +421,13 @@ mod imp { } pub fn cred_read() -> Option { + cred_read_named(CRED) + } + + pub fn cred_read_named(name: &str) -> Option { use windows::Win32::Security::Credentials::{CredFree, CredReadW, CREDENTIALW, CRED_TYPE_GENERIC}; let mut p: *mut CREDENTIALW = std::ptr::null_mut(); - unsafe { CredReadW(&HSTRING::from(CRED), CRED_TYPE_GENERIC, None, &mut p) }.ok()?; + unsafe { CredReadW(&HSTRING::from(name), CRED_TYPE_GENERIC, None, &mut p) }.ok()?; if p.is_null() { return None; } @@ -433,8 +441,15 @@ mod imp { } pub fn cred_delete() { + cred_delete_named(CRED); + } + + pub fn cred_delete_named(name: &str) -> bool { use windows::Win32::Security::Credentials::{CredDeleteW, CRED_TYPE_GENERIC}; - let _ = unsafe { CredDeleteW(&HSTRING::from(CRED), CRED_TYPE_GENERIC, None) }; + match unsafe { CredDeleteW(&HSTRING::from(name), CRED_TYPE_GENERIC, None) } { + Ok(()) => true, + Err(e) => e.code() == windows::core::HRESULT::from_win32(windows::Win32::Foundation::ERROR_NOT_FOUND.0), + } } // ---------- the administrator prompt ---------- diff --git a/tests/cloud-all.test.cjs b/tests/cloud-all.test.cjs index f225347b..3fb757eb 100644 --- a/tests/cloud-all.test.cjs +++ b/tests/cloud-all.test.cjs @@ -93,6 +93,7 @@ test('Play asks nothing about cloud saves for a game never switched', async () = const invoked = []; const S = { library: { g: { name: 'Game', cloud: null } }, account: { signedIn: true }, settings: { ui: {} } }; const context = { S, invoke: async (c) => { invoked.push(c); return { action: 'play' }; }, toast() {}, savesChanged() {}, fail: assert.fail, t: String, tf: String }; + context.cloudReady = () => S.account.signedIn; context.cloudOn = runInNewContext(cloudOnSrc + '\ncloudOn', context); const play = runInNewContext(playSrc + '\nbeforeCloudPlay', context); assert.equal(await play('g'), true); diff --git a/tests/google-drive.test.cjs b/tests/google-drive.test.cjs new file mode 100644 index 00000000..be530c87 --- /dev/null +++ b/tests/google-drive.test.cjs @@ -0,0 +1,142 @@ +const assert = require('node:assert/strict'); +const { readFileSync } = require('node:fs'); +const { join } = require('node:path'); +const test = require('node:test'); +const { runInNewContext } = require('node:vm'); + +const account = readFileSync(join(__dirname, '../ui/account.js'), 'utf8'); +const providerHelpers = account.slice(account.indexOf('S.saveProvider ='), account.indexOf('async function loadAccount(')); + +function providerSetup(picked) { + const S = { library: { game: { cloud: true } }, saves: {}, savesAll: {} }; + const calls = []; + const helpers = runInNewContext(providerHelpers + '\n({chooseSaveProvider, cloudReady})', { + S, window: {}, t: String, tf: String, tn: String, esc: String, + ask: async () => picked, + invoke: async (command, args) => { + calls.push([command, { ...args }]); + return { state: { provider: args.provider, connected: true }, installed: { game: { cloud: null } } }; + }, + renderAccountBits() {}, + expandLib() {}, forgetSaveStatus() {}, + }); + return { S, calls, ...helpers }; +} + +test('cancelling a provider change keeps the existing game consent', async () => { + const { chooseSaveProvider, calls, S } = providerSetup(false); + await chooseSaveProvider('google_drive'); + assert.deepEqual(calls, []); + assert.equal(S.library.game.cloud, true); +}); + +test('confirming a provider change uses the new consent returned by the backend', async () => { + const { chooseSaveProvider, calls, S } = providerSetup(true); + await chooseSaveProvider('google_drive'); + assert.deepEqual(calls, [['save_provider_set', { provider: 'google_drive' }]]); + assert.equal(S.library.game.cloud, null); + assert.equal(S.saveProvider.provider, 'google_drive'); +}); + +test('selecting the current provider does not reset consent', async () => { + const { chooseSaveProvider, calls, S } = providerSetup(true); + await chooseSaveProvider('recompstore'); + assert.deepEqual(calls, []); + assert.equal(S.library.game.cloud, true); +}); + +test('refreshing the provider keeps individual games from a shared installation', () => { + const games = readFileSync(join(__dirname, '../ui/games.js'), 'utf8'); + const S = { gameSets: { series: { games: [{ id: 'first', name: 'First' }] } }, library: {}, saves: {} }; + const apply = runInNewContext(games + '\n' + providerHelpers + '\napplySaveProvider', { S, window: {}, forgetSaveStatus() {} }); + apply({ state: { provider: 'google_drive' }, installed: { series: { id: 'series', cloud: null, games: { first: { played_secs: 60 } } } } }); + assert.equal(S.library['series--first'].name, 'First'); + assert.equal(S.library['series--first'].cloud, null); + assert.equal(S.library['series--first'].played_secs, 60); +}); + +test('provider refresh applies the reset global consent from the backend', () => { + const S = { settings: { ui: { cloud_all: true } }, library: {}, saves: {} }; + const apply = runInNewContext(providerHelpers + '\napplySaveProvider', { S, window: {}, expandLib() {}, forgetSaveStatus() {} }); + apply({ state: { provider: 'google_drive', connected: true }, cloudAll: false, installed: { game: { cloud: null } } }); + assert.equal(S.settings.ui.cloud_all, false); + assert.equal(S.library.game.cloud, null); +}); + +test('Drive sync before play does not need a RecompStore sign-in', async () => { + const source = account.slice(account.indexOf('async function beforeCloudPlay('), account.indexOf('async function pickCloudSave(')); + const calls = []; + const play = runInNewContext(source + '\nbeforeCloudPlay', { + S: { account: { signedIn: false }, library: { game: { cloud: true } } }, + cloudReady: () => true, + cloudOn: (g) => g.cloud === true, + invoke: async (command, args) => { calls.push([command, { ...args }]); return { action: 'play' }; }, + savesChanged() {}, toast() {}, fail: assert.fail, + }); + assert.equal(await play('game'), true); + assert.deepEqual(calls, [['saves_check', { id: 'game' }]]); +}); + +test('Drive conflict choices submit the revision the player reviewed', async () => { + const source = account.slice(account.indexOf('async function pickCloudSave('), account.indexOf('// ---------- actions ----------')); + const calls = []; + const pick = runInNewContext(source + '\npickCloudSave', { + invoke: async (command, args) => calls.push([command, { ...args }]), + ask: async () => 'local', + chooseSave: async () => 'local', + t: String, tf: String, esc: String, whenText: String, fmtTime: String, toast() {}, + }); + await pick('game', { local: { hash: 'local', when: 100 }, cloud: { v: 'file', revision: 'both-heads', made: 200 } }); + assert.deepEqual(calls, [['saves_pick', { id: 'game', keep: 'local', localHash: 'local', cloudVersion: 'file', cloudRevision: 'both-heads' }]]); +}); + +function connectionSetup({ pollResults, snapshotError = false }) { + const source = account.slice(account.indexOf('async function connectDrive('), account.indexOf('async function disconnectDrive(')); + const S = { saveProvider: { provider: 'google_drive' }, library: { game: { cloud: true } } }; + const calls = [], timers = [], errors = []; + const box = { isConnected: true, remove() { this.isConnected = false; } }; + const connect = runInNewContext(source + '\nconnectDrive', { + S, window: {}, document: { body: {} }, inTV: () => false, + t: String, tf: String, esc: String, + modal: () => box, + MutationObserver: class { observe() {} }, + setTimeout: (callback) => { timers.push(callback); return timers.length; }, + clearTimeout() {}, + invoke: async (command) => { + calls.push(command); + if (command === 'drive_connect_start') return { url: 'https://accounts.google.com/', device: false, expires: 600 }; + if (command === 'drive_connect_poll') return pollResults.shift(); + if (command === 'save_provider_state') { + if (snapshotError) throw new Error('Could not load the connected account'); + return { state: { provider: 'google_drive' }, installed: { game: { cloud: null } } }; + } + }, + applySaveProvider: (result) => { S.saveProvider = result.state; S.library = result.installed; }, + chooseSaveProvider: async (provider) => calls.push(`choose:${provider}`), + renderAccountBits() {}, toast() {}, fail: (error) => errors.push(String(error)), + }); + return { connect, timers, calls, errors, S, box }; +} + +test('finishing Drive sign-in refreshes consent without changing the provider', async () => { + const setup = connectionSetup({ pollResults: [{ status: 'pending' }, { status: 'ok' }] }); + await setup.connect(); + await setup.timers.shift()(); + await setup.timers.shift()(); + assert.equal(setup.S.library.game.cloud, null); + assert.equal(setup.calls.includes('save_provider_set'), false); + assert.equal(setup.calls.includes('save_provider_state'), true); + assert.equal(setup.calls.includes('choose:google_drive'), true); + assert.deepEqual(setup.errors, []); +}); + +test('errors on a later Drive sign-in poll close the dialog and are reported', async () => { + const setup = connectionSetup({ pollResults: [{ status: 'pending' }, { status: 'ok' }], snapshotError: true }); + await setup.connect(); + await setup.timers.shift()(); + await setup.timers.shift()(); + assert.equal(setup.box.isConnected, false); + assert.equal(setup.calls.includes('drive_connect_cancel'), true); + assert.equal(setup.calls.includes('choose:google_drive'), false); + assert.deepEqual(setup.errors, ['Error: Could not load the connected account']); +}); diff --git a/tests/save-badge.test.cjs b/tests/save-badge.test.cjs index bb2b5a50..bfddeadc 100644 --- a/tests/save-badge.test.cjs +++ b/tests/save-badge.test.cjs @@ -168,3 +168,11 @@ test('the cloud copy saved after this PC: the cloud one is newer', () => { test('saved at the same second: neither is marked', () => { assert.equal(newerSave({ when: 100 }, { made: 100 }), ''); }); + + +test('a disconnected Drive badge offers Google connection and retains backup details', () => { + const b = info.saveBadgeInfo(status('signed-out', { provider: 'google_drive', newest: { when: 100, device: 'PC' } }), undefined, false); + assert.equal(b.label, 'Connect Google Drive'); + assert.equal(b.tone, 'dim'); + assert.equal(b.rows.length, 1); +}); diff --git a/tests/saves-tab.test.cjs b/tests/saves-tab.test.cjs index 7e262123..ab4775cc 100644 --- a/tests/saves-tab.test.cjs +++ b/tests/saves-tab.test.cjs @@ -287,7 +287,7 @@ test('every button a status can show does something in Big Picture, or says to u assert.ok(tv.includes(`case '${tvAct[1]}'`), tvAct[1]); } assert.match(tv, /step\.act === 'report' \? ` \$\{t\('Report problems from the desktop view'\)\}\.`/); - assert.match(tv, /step\.act === 'url' \? ` \$\{t\('Free up space on your account page at recomplauncher\.com\.'\)\}`/); + assert.match(tv, /step\.act === 'url' \? ` \$\{storageHelp\}`/); }); test('any cloud save but the newest can be deleted', () => { @@ -379,3 +379,19 @@ test('the newer save can be synced now with Sync Now, on the desktop and in Big test('Big Picture gives the save coming in no Restore either', () => { assert.match(tv, /const act = r\.current \|\| r\.incoming \? '' :/); }); + + +test('a full Drive points to Google storage instead of RecompStore', () => { + const st = { ...problem('full'), provider: 'google_drive' }; + assert.equal(steps(st, undefined, false, false).url, 'https://drive.google.com/drive/quota'); +}); + +test('a disconnected Drive offers to reconnect Google', () => { + const st = { state: 'signed-out', provider: 'google_drive' }; + assert.equal(steps(st, undefined, false, false).act, 'acc-drive-connect'); +}); + +test('Drive history uses automatic cleanup without the RecompStore delete command', () => { + const rows = tab(fresh()).saveHistory({ provider: 'Google Drive', local: [], cloud: [cloud(200, 'b', 'v2'), cloud(100, 'a', 'v1')] }); + assert.deepEqual(rows.map((r) => r.deletable), [false, false]); +}); diff --git a/tools/check-google-drive-ui.cjs b/tools/check-google-drive-ui.cjs new file mode 100644 index 00000000..8e252018 --- /dev/null +++ b/tools/check-google-drive-ui.cjs @@ -0,0 +1,124 @@ +// Exercises the shipped desktop and Big Picture UI with simulated Tauri responses. No Google account is contacted. +const assert = require('node:assert/strict'); +const { spawn, spawnSync } = require('node:child_process'); +const { createServer } = require('node:http'); +const { readFile, mkdir, mkdtemp, writeFile } = require('node:fs/promises'); +const { resolve, extname } = require('node:path'); + +const { tmpdir } = require('node:os'); +const root = resolve(__dirname, '../ui'); +const browser = process.env.RL_UI_CHROME || 'google-chrome-stable'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +(async () => { + if (spawnSync(browser, ['--version']).status !== 0) throw new Error('Set RL_UI_CHROME to a Chrome executable to run this browser smoke check.'); + const output = process.argv[2] ? resolve(process.argv[2]) : await mkdtemp(resolve(tmpdir(), 'rl-drive-ui-')); + await mkdir(output, { recursive: true }); + const server = createServer(async (req, res) => { + const path = resolve(root, '.' + new URL(req.url, 'http://localhost').pathname); + if (!path.startsWith(root + '/') && path !== root) { res.writeHead(403).end(); return; } + try { + const file = path === root ? path + '/index.html' : path; + const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2' }; + res.setHeader('Content-Type', mime[extname(file)] || 'application/octet-stream'); + res.end(await readFile(file)); + } catch (_) { res.writeHead(404).end(); } + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const chrome = spawn(browser, ['--headless=new', '--no-sandbox', '--disable-gpu', '--no-first-run', '--disable-background-networking', '--disable-crash-reporter', `--user-data-dir=${output}/profile`, '--remote-debugging-pipe', 'about:blank'], { + stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'], + env: { ...process.env, XDG_CONFIG_HOME: output + '/config', XDG_CACHE_HOME: output + '/cache' }, + }); + let next = 0, bytes = '', session; + const pending = new Map(), errors = []; + chrome.stderr.on('data', (data) => writeFile(output + '/chrome.log', data, { flag: 'a' })); + chrome.stdio[4].on('data', (data) => { + bytes += data; + let end; + while ((end = bytes.indexOf('\0')) >= 0) { + const message = JSON.parse(bytes.slice(0, end)); bytes = bytes.slice(end + 1); + if (message.id) { + const waiter = pending.get(message.id); + if (waiter) { clearTimeout(waiter.timer); pending.delete(message.id); message.error ? waiter.reject(message.error) : waiter.resolve(message.result); } + } + if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails); + } + }); + const send = (method, params = {}, sessionId = session) => new Promise((resolve, reject) => { + const id = ++next; + const timer = setTimeout(() => { pending.delete(id); reject(new Error('Timed out: ' + method)); }, 10000); + pending.set(id, { resolve, reject, timer }); + chrome.stdio[3].write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0'); + }); + const evaluate = async (expression) => { + const result = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); + if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails)); + return result.result.value; + }; + try { + const target = await send('Target.createTarget', { url: 'about:blank' }); + session = (await send('Target.attachToTarget', { targetId: target.targetId, flatten: true })).sessionId; + await send('Page.enable'); await send('Runtime.enable'); + await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false }); + await send('Page.addScriptToEvaluateOnNewDocument', { source: ` + window.smokeCalls = []; + window.smokeState = { provider: 'recompstore', name: 'RecompStore', connected: false, google: { configured: true, deviceConfigured: false, connected: false } }; + window.smokeInstalled = {}; + const no = async () => {}; + const win = new Proxy({}, { get: (_, name) => name === 'isMaximized' ? async () => false : no }); + window.__TAURI__ = { core: { convertFileSrc: (u) => u, invoke: async (command, args) => { + window.smokeCalls.push([command, args]); + if (command === 'get_state') return { os: 'linux', arch: 'x64', version: '0.90.0-beta.53', site: '', library: window.smokeInstalled, settings: { setup_done: true, data_asked: true, check_updates: false, ui: { lang: 'en', reduce_motion: true, share_usage: false } } }; + if (command === 'get_catalog') return { data: { apps: [], origins: [] } }; + if (command === 'save_provider_state') return { state: window.smokeState, installed: window.smokeInstalled }; + if (command === 'account_state') return { signedIn: false }; + if (command === 'drive_connect_start') return { url: 'https://accounts.google.com/', device: false, expires: 600 }; + if (command === 'drive_connect_poll') return { status: 'pending' }; + if (['easy_setup', 'libraries', 'launcher_notes', 'team_notes', 'trending', 'game_sizes'].includes(command)) return []; + if (['take_link', 'take_setup_asked', 'launcher_update', 'pc_check', 'news', 'ig_info'].includes(command)) return null; + if (command === 'is_handheld') return false; + if (command === 'plugin_list') return { plugins: [], enabled: [] }; + if (command === 'ach_status') return { tester: false }; + return {}; + } }, event: { listen: async () => no }, window: { getCurrentWindow: () => win }, dpi: { PhysicalPosition: class {}, PhysicalSize: class {} } }; + ` }); + await send('Page.navigate', { url: `http://127.0.0.1:${server.address().port}/index.html` }); + await sleep(1300); + await evaluate("S.settings.setup_done = true; S.settings.data_asked = true; S.setTab = 'account'; go('settings');"); + await sleep(350); + const desktop = await evaluate("({ text: document.querySelector('#main').innerText, connect: !!document.querySelector('[data-act=acc-drive-connect]:not(:disabled)'), calls: window.smokeCalls })"); + assert(desktop.connect, 'desktop connection button enabled'); + assert(/save destination/i.test(desktop.text), 'save destination settings rendered'); + await evaluate("document.querySelector('[data-act=acc-drive-connect]').click()"); + await sleep(100); + assert(await evaluate("!!document.querySelector('[data-x=cancel]')"), 'connection dialog opens'); + await evaluate("document.querySelector('[data-x=cancel]').click()"); + await sleep(100); + assert(await evaluate("window.smokeCalls.some(([command]) => command === 'drive_connect_cancel')"), 'closing connection dialog cancels sign-in'); + await evaluate("window.smokeState.google.configured = false; applySaveProvider({state:window.smokeState,installed:{}}); renderAccountBits();"); + assert(await evaluate("document.querySelector('[data-act=acc-drive-connect]').disabled"), 'unconfigured builds disable Google sign-in'); + await evaluate("window.smokeState.google.configured = true; applySaveProvider({state:window.smokeState,installed:{}}); renderAccountBits();"); + await writeFile(output + '/desktop-settings.webp', Buffer.from((await send('Page.captureScreenshot', { format: 'webp', quality: 82 })).data, 'base64')); + await evaluate("window.smokeState = {provider:'google_drive',name:'Google Drive',connected:true,google:{configured:true,connected:true,email:'player@example.com'}}; window.smokeInstalled = {}; applySaveProvider({state:window.smokeState,installed:window.smokeInstalled}); renderAccountBits();"); + await sleep(200); + const connected = await evaluate("({ disconnect: !!document.querySelector('[data-act=acc-drive-disconnect]'), text:document.querySelector('#main').innerText })"); + assert(connected.disconnect, 'connected account has disconnect control'); + assert(connected.text.includes('player@example.com'), 'connected account displayed'); + await evaluate("window.startTV();"); + await sleep(4000); + await evaluate("window.tvGoto('settings');"); + await sleep(650); + const tv = await evaluate("({ text:document.querySelector('#tv').innerText, provider:!!document.querySelector('[data-tvact=save-provider]'), disconnect:!!document.querySelector('[data-tvact=drive-disconnect]') })"); + await writeFile(output + '/tv-debug.json', JSON.stringify({tv,errors,calls:await evaluate('window.smokeCalls')},null,2)); + assert(tv.provider && tv.disconnect, 'Big Picture provider and disconnect controls rendered'); + await send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 }); + await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 }); + await sleep(350); + assert(await evaluate("document.querySelector('[data-tvact=save-provider]').classList.contains('f')"), 'keyboard navigation reaches the save provider control'); + await writeFile(output + '/big-picture-settings.webp', Buffer.from((await send('Page.captureScreenshot', { format: 'webp', quality: 82 })).data, 'base64')); + await writeFile(output + '/results.json', JSON.stringify({ desktop, connected, tv, errors }, null, 2)); + console.log(JSON.stringify({ desktop: 'passed', connected: 'passed', bigPicture: 'passed', errors: errors.map((e) => e.exception?.description || e.text), output })); + if (errors.length) process.exitCode = 1; + } finally { + chrome.kill('SIGTERM'); server.close(); + } +})().catch((error) => { console.error(error); process.exitCode = 1; }); diff --git a/ui/account.js b/ui/account.js index efe95dea..449830d3 100644 --- a/ui/account.js +++ b/ui/account.js @@ -16,11 +16,112 @@ const whenText = (ts) => (ts ? new Date(ts * 1000).toLocaleString(curLocale(), t const avatar = (u, size = 28) => (u && u.avatar ? `` : `${esc(((u && u.username) || '?').slice(0, 1).toUpperCase())}`); const inTV = () => document.body.classList.contains('tv-on'); +S.saveProvider = { provider: 'recompstore', name: 'RecompStore', connected: false, google: {} }; +const cloudReady = () => !!S.saveProvider?.connected; + +function applySaveProvider(result) { + const previous = S.saveProvider; + S.saveProvider = result.state || result; + if (Object.hasOwn(result, 'cloudAll')) { S.settings.ui = S.settings.ui || {}; S.settings.ui.cloud_all = result.cloudAll; } + if (previous.provider !== S.saveProvider.provider || previous.connected !== S.saveProvider.connected || previous.google?.email !== S.saveProvider.google?.email) forgetSaveStatus(); + if (result.installed) { S.library = result.installed; expandLib(); } + S.saves = {}; S.savesAll = null; + if (window.tvSavesReset) window.tvSavesReset(); +} + +async function loadSaveProvider() { + try { applySaveProvider(await invoke('save_provider_state')); } catch (_) { /* The previous state stays until the next refresh. */ } +} + +async function chooseSaveProvider(provider) { + if (S.saveProvider.provider === provider) return; + const name = provider === 'google_drive' ? 'Google Drive' : 'RecompStore'; + const count = Object.values(S.library || {}).filter((g) => g.cloud === true).length; + const message = tf('Use {name} for cloud saves? Enable each game again on its Saves tab. Existing local backups and cloud copies are kept.', { name }); + const picked = await ask(t('Change save destination?'), `

${esc(message)}

`, [ + { label: t('Cancel'), v: false, focus: true }, + { label: tf('Use {name}', { name }), sub: message + ' ' + tn(count, '1 game currently syncs', '{n} games currently sync'), v: true }, + ]); + if (!picked) return; + applySaveProvider(await invoke('save_provider_set', { provider })); + renderAccountBits(); +} + +async function connectDrive() { + let start; + try { start = await invoke('drive_connect_start', { tv: inTV() }); } catch (e) { return fail(e); } + const hint = start.device + ? tf('Open {url} on your phone and enter this code:', { url: start.url }) + : t('Finish connecting Google Drive in the browser on this PC. Return here when you have approved access.'); + let closed = false, timer, box, tv; + const cancel = () => { closed = true; clearTimeout(timer); invoke('drive_connect_cancel').catch(() => {}); }; + if (inTV() && window.tvSignIn) { + tv = window.tvSignIn({ title: t('Connect Google Drive'), hint, qr: start.qr || '', code: start.code || '', onClose: cancel }); + } else { + box = modal(`

${esc(t('Connect Google Drive'))}

${esc(hint)}

${esc(t('Waiting for Google…'))}

`, (el, close) => { + if (el.dataset.x === 'open') return invoke('open_url', { url: start.url }).catch(fail); + cancel(); close(); + }, t('Connect Google Drive')); + new MutationObserver((_m, observer) => { if (!box.isConnected) { observer.disconnect(); if (!closed) cancel(); } }).observe(document.body, { childList: true }); + } + if (!start.device) invoke('open_url', { url: start.url }).catch(fail); + const until = Date.now() + start.expires * 1000; + const poll = async () => { + if (closed) return; + let result; + try { result = await invoke('drive_connect_poll'); } catch (e) { result = { status: 'error', error: String(e) }; } + if (closed) return; + if (result.status === 'pending' && Date.now() < until) { schedule(); return; } + closed = true; + if (tv) tv.close(true); + if (box) box.remove(); + if (result.status !== 'ok') { cancel(); return fail(result.error || t('Google sign-in expired. Try connecting again.')); } + // The backend may have cleared consent when a different Google account replaced the old one. + applySaveProvider(await invoke('save_provider_state')); + renderAccountBits(); + toast(t('Google Drive connected.')); + await chooseSaveProvider('google_drive'); + }; + const schedule = () => { timer = setTimeout(() => poll().catch((e) => { + cancel(); + if (tv) tv.close(true); + if (box) box.remove(); + fail(e); + }), 1000); }; + schedule(); +} + +async function disconnectDrive() { + const message = t('Stop Google Drive sync on this PC? Local saves and copies already in Drive are kept.'); + const picked = await ask(t('Disconnect Google Drive?'), `

${esc(message)}

`, [ + { label: t('Cancel'), v: false, focus: true }, { label: t('Disconnect'), sub: message, v: true }, + ]); + if (!picked) return; + applySaveProvider(await invoke('drive_disconnect')); + renderAccountBits(); +} +window.connectDrive = connectDrive; +window.chooseSaveProvider = chooseSaveProvider; +window.disconnectDrive = disconnectDrive; + +function saveProviderSection(group, row) { + const p = S.saveProvider, google = p.google || {}; + const button = (label, act, disabled = false) => ``; + const info = tf('Current destination: {name}. Enable cloud saves separately for each game.', { name: p.name }); + const googleHelp = google.needsReconnect ? t('Google Drive needs you to connect again.') : google.connected ? google.email : google.configured ? t('Connect your Google account. Save copies go directly to your Drive.') : t('Google Drive is not configured in this launcher build.'); + return group(t('Save Destination'), `

${esc(info)}

` + + row('RecompStore', t('Use your RecompStore account for game saves.'), button(p.provider === 'recompstore' ? 'Selected' : 'Use RecompStore', 'provider-recompstore', p.provider === 'recompstore')) + + row('Google Drive', googleHelp, `${google.connected ? button('Reconnect', 'drive-connect') + button('Disconnect', 'drive-disconnect') + button(p.provider === 'google_drive' ? 'Selected' : 'Use Google Drive', 'provider-google', p.provider === 'google_drive') : button('Connect Google Drive', 'drive-connect', !google.configured)}`) + + (p.connected ? row(t('Back Up Every Game'), t('Turn them on or off for one game in its Manage tab. The newest five copies of each game are kept.'), ``) : '') + + deviceNameRow()); +} + async function loadAccount(fresh) { const was = !!(S.account && S.account.signedIn); try { S.account = await invoke('account_state', { fresh: !!fresh }); } catch (e) { S.account = S.account || { signedIn: false }; } // Signed in (or out) just now: what each game's Saves tab knew is out of date. if (was !== !!S.account.signedIn) { S.saves = {}; S.savesAll = null; S.myReports = null; forgetSaveStatus(); } + await loadSaveProvider(); renderAccountBits(); if (S.account.signedIn && !S.myReports && !S.account.offline) loadMyReports(); // The saved list, kept with the account. @@ -136,6 +237,9 @@ async function signOut() { // ---------- Settings > Account ---------- function accountSection(group, row) { + return saveProviderSection(group, row) + recompAccountSection(group, row); +} +function recompAccountSection(group, row) { const a = S.account || {}; if (!a.signedIn) { return group(t('Account'), `
${CLOUD_ICON}
${esc(t('Keep your saves safe'))}${esc(t('With a RecompStore account, your saves go to the cloud after you play and are there on any PC. It\'s free, and the launcher works the same without one.'))}
@@ -143,15 +247,10 @@ function accountSection(group, row) { + group(t('Save backups'), row(t('On this PC'), t('After every session the launcher keeps a copy of each game\'s saves, the newest ten. They\'re on each game\'s Saves tab.'), '')); } const used = a.used || 0, quota = a.quota || 150 * 1024 * 1024, pct = Math.min(100, Math.round((used / quota) * 100)); - // Back Up Every Game says what it does now, like a game's own switch in its Manage tab. - const all = (S.settings.ui || {}).cloud_all === true; - const allNow = all ? t('On. Cloud saves are activated for all games. Turning it off disables cloud saves for every game. Saves stay intact.') : t('Off. Cloud saves are only active for the games you turn on in their Manage tab. Turning it on activates them for every game.'); return group(t('Account'), `
${avatar(a.user, 48)}
${esc(a.user.username)}${esc(a.offline ? t('Signed in on this PC. The website can\'t be reached right now.') : t('Signed in on this PC'))}${a.offline && a.why ? `${esc(a.why)}` : ''}
${a.offline ? `` : ''}
`) + group(t('Cloud saves'), `
${esc(tf('{used} of {quota} used', { used: fmtB(used) || '0 KB', quota: fmtB(quota) }))}
-

${esc(t('Turn them on or off for one game in its Manage tab. The newest five copies of each game are kept.'))}

` - + row(t('Back Up Every Game'), allNow, ``) - + deviceNameRow()) +

${esc(t('Turn them on or off for one game in its Manage tab. The newest five copies of each game are kept.'))}

`) + (window.betasGroup ? window.betasGroup(group, row) : ''); } // ---------- Settings > Reviews ---------- @@ -359,7 +458,7 @@ function saveStatusCard(id, s) { const text = statusCardText(st, b, picked); const offline = st.problem && st.problem.kind === 'offline' && s.status; const help = offline ? `

${esc(t('Still no answer. Check whether the website is having trouble:'))}

` : ''; - const space = s.signedIn && s.cloudOn === true ? cloudSpace() : ''; + const space = s.signedIn && s.cloudOn === true && st.provider !== 'google_drive' ? cloudSpace() : ''; const step = next ? INCOMING_STEP : saveNextStep(st, phase, running, picked); const url = step && step.url ? ` data-url="${esc(step.url)}"` : ''; const btn = step ? `` : ''; @@ -403,10 +502,12 @@ function statusCardText(st, b, picked) { function saveNextStep(st, phase, running, picked) { if (phase || running) return null; if (st.known === false) return { act: 'saves-place', label: N_('Pick a Folder') }; + if (st.state === 'signed-out' && st.provider === 'google_drive') return { act: 'acc-drive-connect', label: N_('Connect Google Drive') }; if (st.state === 'signed-out') return { act: 'acc-signin', label: N_('Sign in') }; // saves-cloud turns them on when the button has no switch state to read. if (st.state === 'off') return { act: 'saves-cloud', label: N_('Turn On') }; if (st.state === 'conflict') return { act: 'saves-sync', label: N_('Choose a Save') }; + if (st.state === 'problem' && st.provider === 'google_drive' && st.problem?.kind === 'full') return { act: 'url', label: N_('Free Up Space'), url: 'https://drive.google.com/drive/quota' }; if (st.state === 'problem') return problemStep((st.problem && st.problem.kind) || 'error', picked); if (st.state === 'waiting' || st.state === 'up-to-date') return { act: 'saves-sync', label: N_('Sync Now') }; return null; @@ -456,7 +557,7 @@ function saveHistory(s) { for (const r of rows) r.incoming = !r.current && !!next && r.v === next; // Any cloud save but the newest can be deleted (saves_cloud_delete says why not that one). const newestCloud = Array.isArray(s.cloud) && s.cloud.length ? s.cloud.reduce((p, q) => (q.made > p.made ? q : p)).v : ''; - for (const r of rows) r.deletable = !!r.v && r.v !== newestCloud; + for (const r of rows) r.deletable = s.provider !== 'Google Drive' && !!r.v && r.v !== newestCloud; return rows; } @@ -675,6 +776,7 @@ function saveBadgeInfo(st, phase, running) { if (st.known === false) return { tone: 'dim', mark: 'off', label: t('Saves not backed up'), note: '', head: t('The launcher doesn\'t know where this game saves'), text: t('Nothing of it is backed up or sent to the cloud. Pick its save folder on its Saves tab.'), rows: [] }; const synced = st.syncedAt ? [[t('Last synced'), whenText(st.syncedAt)], [t('Saved on'), st.syncedDevice || t('this PC')]] : []; const newest = st.newest ? [[t('Last backup'), `${whenText(st.newest.when)}${st.newest.device ? ' · ' + st.newest.device : ''}`]] : []; + if (st.state === 'signed-out' && st.provider === 'google_drive') return { tone: 'dim', mark: 'dash', label: t('Connect Google Drive'), note: '', head: t('Keep this save on any PC'), text: t('Google Drive needs you to connect again.'), rows: newest }; if (st.state === 'signed-out') return { tone: 'dim', mark: 'dash', label: t('Not signed in'), note: '', head: t('Keep this save on any PC'), text: t('Sign in to RecompStore and your saves go to the cloud after you play. It\'s free.'), rows: newest }; if (st.state === 'off') return { tone: 'dim', mark: 'off', label: t('Cloud saves off'), note: '', head: t('Saves stay on this PC'), text: t('The launcher still keeps a copy after every session. Turn cloud saves on in its Saves tab.'), rows: newest }; if (st.state === 'conflict') return { tone: 'warn', mark: 'conflict', label: t('Choose a save'), note: t('press Play to pick'), head: t('Both saves changed'), text: t('This PC and the cloud both changed since they last synced. Press Play, or Sync Now in its Saves tab, to pick the one to keep; the other stays as a backup on this PC.'), rows: synced }; @@ -812,7 +914,7 @@ function rootCard(o) { function pageSaves() { const o = S.savesAll; if (!o) { loadSavesAll(); return `
${esc(t('Loading…'))}
`; } - const acc = S.account || {}; + const acc = S.saveProvider.provider === 'google_drive' ? { signedIn: cloudReady(), drive: true } : S.account || {}; const games = (o.games || []).map((x) => ({ ...x, g: S.library[x.id] || {}, a: byId(x.id) })).filter((x) => x.g.name || x.a); const withSaves = games.filter((x) => x.copies).sort((a, b) => (b.newest?.when || 0) - (a.newest?.when || 0)); const none = games.filter((x) => !x.copies).sort((a, b) => (a.g.name || '').localeCompare(b.g.name || '')); @@ -822,7 +924,9 @@ function pageSaves() { const pcCard = `
${CARD_ICON}
${esc(t('On this PC'))}${esc(tn(withSaves.length, '1 game with saves', '{n} games with saves'))}
${esc(fmtB(size) || '0 KB')}
${blocks(withSaves.length ? withSaves.length / Math.max(games.length, 1) : 0)}

${esc(tn(copies, '1 copy kept', '{n} copies kept'))} · ${esc(t('The newest ten of each game'))}

`; - const cloudCard = acc.signedIn + const cloudCard = acc.drive && acc.signedIn + ? `
${CLOUD_ICON}
Google Drive${esc(S.saveProvider.google?.email || '')}

${esc(tn(cloudGames, '1 game syncs to Drive', '{n} games sync to Drive'))}

` + : acc.signedIn ? `
${CLOUD_ICON}
${esc(t('Cloud saves'))}${esc(tn(cloudGames, '1 game backs up to your account', '{n} games back up to your account'))}
${esc(fmtB(used) || '0 KB')}
${blocks(used / quota)}

${esc(tf('{used} of {quota} used', { used: fmtB(used) || '0 KB', quota: fmtB(quota) }))}

` @@ -988,7 +1092,7 @@ async function beforePlay(id) { // whether a game's saves go up was picked once for every game (askCloudAll), or in its Manage tab. async function beforeCloudPlay(id) { const g = S.library[id]; - if (!g || !(S.account && S.account.signedIn)) return true; + if (!g || !cloudReady()) return true; if (!cloudOn(g)) return true; let r; try { r = await invoke('saves_check', { id }); } catch (e) { fail(e); return false; } @@ -1022,7 +1126,7 @@ async function playWithoutCloud(id, r) { async function pickCloudSave(id, { local, cloud }) { const v = await chooseSave(local, cloud); if (v !== 'local' && v !== 'cloud') return false; - await invoke('saves_pick', { id, keep: v, localHash: local.hash, cloudVersion: cloud.v }); + await invoke('saves_pick', { id, keep: v, localHash: local.hash, cloudVersion: cloud.v, ...(cloud.revision ? { cloudRevision: cloud.revision } : {}) }); toast(t(v === 'cloud' ? 'The cloud save is in place.' : 'Your save is in the cloud.')); return true; } @@ -1063,6 +1167,11 @@ async function syncCloudNow(id) { window.accountAct = async (act, el) => { const id = el.dataset.id; switch (act) { + case 'acc-save-settings': S.setTab = 'account'; return go('settings'); + case 'acc-drive-connect': return connectDrive().catch(fail); + case 'acc-drive-disconnect': return disconnectDrive().catch(fail); + case 'acc-provider-google': return chooseSaveProvider('google_drive').catch(fail); + case 'acc-provider-recompstore': return chooseSaveProvider('recompstore').catch(fail); case 'acc-signin': return signIn(false); case 'acc-create': return signIn(true); case 'acc-signout': return signOut(); @@ -1210,7 +1319,11 @@ window.accountAct = async (act, el) => { return null; }; -T.event.listen('account', ({ payload }) => { if (payload && payload.signedIn === false) { S.account = { signedIn: false }; S.saves = {}; forgetSaveStatus(); renderAccountBits(); } else loadAccount(true); }); +T.event.listen('save-provider', async ({ payload }) => { + applySaveProvider(payload); + renderAccountBits(); +}); +T.event.listen('account', async ({ payload }) => { if (payload && payload.signedIn === false) { S.account = { signedIn: false }; S.saves = {}; forgetSaveStatus(); await loadSaveProvider(); renderAccountBits(); } else loadAccount(true); }); T.event.listen('saves', ({ payload }) => { if (S.view === 'saves') loadSavesAll(); if (payload && payload.id) { delete S.saves[payload.id]; loadSaveStatus(payload.id); if (S.view === 'game' && S.arg === payload.id && S.tab === 'saves') loadSaves(payload.id); } }); // A check, upload or download for a game started or ended: the badge says so, and asks for the // outcome once it's over. diff --git a/ui/app.js b/ui/app.js index 13d8b41a..2ed218a0 100644 --- a/ui/app.js +++ b/ui/app.js @@ -3311,7 +3311,8 @@ function manageFileRows(id, inst) { const rows = [`
${esc(t('Folder'))}${esc(inst.path)}
${inst.local ? '' : ``}
`]; if (!inst.local) rows.push(`
${esc(t('Backups of your saves'))}${esc(t('Taken before every update: the saves in its folder.'))}
`); // Cloud saves is switched here only; the Saves tab just offers to turn it on. - if (S.account && S.account.signedIn) { + const ready = S.saveProvider ? S.saveProvider.connected : S.account && S.account.signedIn; + if (ready) { const on = cloudOn(inst); rows.push(`
${esc(t('Cloud saves'))}${esc(on ? t('On. Saves for this game are synced to the cloud.') : t('Off. Saves for this game are not synced to the cloud.'))}
`); } diff --git a/ui/tv.js b/ui/tv.js index a29d4f3a..8a40ad39 100644 --- a/ui/tv.js +++ b/ui/tv.js @@ -1396,6 +1396,11 @@ ${S.account && S.account.signedIn ? `` : ``} + ${head(t('Save Destination'))} + + + ${S.saveProvider?.google?.connected ? `` : ''} + ${S.saveProvider?.connected ? `` : ''} ${head(t('Display'))} ${(() => { const m = window.monitorPicked(S.monitors, S.settings.tv_monitor); @@ -1485,7 +1490,7 @@ if (TV.on && TV.view === 'gsaves' && TV.arg === id) draw(true); } // The desktop's next steps as this page's actions. Reporting a problem stays in the desktop view. - const TV_STEP = { 'acc-signin': 'account', 'saves-cloud': 'gs-cloud', 'saves-sync': 'gs-sync', 'saves-place': 'gs-place' }; + const TV_STEP = { 'acc-drive-connect': 'drive-connect', 'acc-signin': 'account', 'saves-cloud': 'gs-cloud', 'saves-sync': 'gs-sync', 'saves-place': 'gs-place' }; // The status, as the item that leads the page. function savesStatusItem(id, sv) { const b = window.saveBadgeFor(id); @@ -1499,7 +1504,8 @@ const step = next ? INCOMING_STEP : saveNextStep(st, phase, running, picked); const act = step && !sv.busy && TV_STEP[step.act]; // Reporting stays in the desktop view, and the account page needs a browser: said instead. - const desk = !step ? '' : step.act === 'report' ? ` ${t('Report problems from the desktop view')}.` : step.act === 'url' ? ` ${t('Free up space on your account page at recomplauncher.com.')}` : ''; + const storageHelp = st.provider === 'google_drive' ? st.problem?.text || '' : t('Free up space on your account page at recomplauncher.com.'); + const desk = !step ? '' : step.act === 'report' ? ` ${t('Report problems from the desktop view')}.` : step.act === 'url' ? ` ${storageHelp}` : ''; const tvact = act ? ` data-tvact="${act}" data-id="${esc(id)}"` : ''; const pill = act ? `${esc(t(step.label))}` : ''; const note = b.note ? ` · ${esc(b.note)}` : ''; @@ -2010,7 +2016,7 @@ // No Add to desktop on a Mac: the shortcut the launcher makes is Linux's .desktop file, which a Mac ignores. ...(S.steam || S.os !== 'macos' ? [{ gap: true, ...(S.steam ? { label: t('Add to Steam'), sub: t('With its art'), icon: 'steam', run: () => addToSteam(id, false) } : { label: t('Add to desktop'), sub: t('A shortcut that starts it'), icon: 'desk', run: async () => { try { await invoke('desktop_shortcut', { id }); toast(tf('{name} is on your desktop.', { name: g.name })); } catch (e) { fail(e); } } }) }] : []), ...(S.steam && S.os !== 'macos' ? [{ label: t('Add to desktop'), sub: t('A shortcut that starts it'), icon: 'desk', run: async () => { try { await invoke('desktop_shortcut', { id }); toast(tf('{name} is on your desktop.', { name: g.name })); } catch (e) { fail(e); } } }] : []), - ...(S.account && S.account.signedIn ? [{ label: cloudOn(g) ? t('Turn off cloud saves') : t('Turn on cloud saves'), sub: cloudOn(g) ? t('Its saves stay on this PC from now on') : t('Its saves go to your account after you play'), icon: 'cloud', run: async () => { try { S.library[id] = await invoke('saves_cloud', { id, on: !cloudOn(g) }); toast(cloudOn(g) ? t('Cloud saves are off for it. What\'s in the cloud stays there.') : t('Cloud saves are on for it.')); } catch (e) { fail(e); } } }] : []), + ...(cloudReady() ? [{ label: cloudOn(g) ? t('Turn off cloud saves') : t('Turn on cloud saves'), sub: cloudOn(g) ? t('Its saves stay on this PC from now on') : t('Its saves go to your account after you play'), icon: 'cloud', run: async () => { try { S.library[id] = await invoke('saves_cloud', { id, on: !cloudOn(g) }); toast(cloudOn(g) ? t('Cloud saves are off for it. What\'s in the cloud stays there.') : t('Cloud saves are on for it.')); } catch (e) { fail(e); } } }] : []), ...(window.tvBetaItem && window.tvBetaItem(id) ? [window.tvBetaItem(id)] : []), // The same switch as the game's Manage tab on the desktop, and the same skip list under Settings. ...(!g.local && window.autoUpdates ? [(() => { const on = window.autoUpdates(id); return { label: on ? t('Turn off automatic updates') : t('Update automatically'), sub: on ? t('Updates wait for you in Downloads') : t('Installs new releases as soon as the launcher finds them. Your saves are backed up first.'), icon: 'refresh', run: async () => { await window.toggleAutoUpdate(id); draw(true); } }; })()] : []), @@ -2148,7 +2154,7 @@ TV.sheet = { items: [{ label: t('Cancel') }], prev: (focused() || {}).dataset?.key, onClose: () => s.onClose && s.onClose() }; const el = document.createElement('div'); el.className = 'tv-sheet tv-signin'; - el.innerHTML = `

${esc(t('Sign in with your phone'))}

+ el.innerHTML = `

${esc(s.title || t('Sign in with your phone'))}

`; stage().append(el); focus($('[data-sheet="0"]', el), true); @@ -2682,6 +2688,7 @@ const cls = `tv-ambient m-${m}`; if (el.className !== cls) { el.className = cls; el.innerHTML = m === 'grid' ? '' : m === 'drift' ? '' : ''; } } + window.tvSavesReset = () => { TV.saves = {}; TV.savesAll = null; }; window.tvRefresh = () => soon(); // A game moved to another id (one added by link, now on the official list): the page on and // the pages behind it follow. @@ -3164,6 +3171,13 @@ // Asking for a review after a long session, as Settings > Reviews has it on the desktop. case 'reviewask': sfx('select'); await window.setReviewAsk(!window.reviewAskOn()); return draw(true); case 'lang': sfx('open'); return pickLang(); + case 'drive-connect': return window.connectDrive().catch(fail); + case 'drive-disconnect': return window.disconnectDrive().catch(fail); + case 'cloud-all': await window.setCloudAll((S.settings.ui || {}).cloud_all !== true); return draw(true); + case 'save-provider': return sheet(t('Save Destination'), [ + { label: 'RecompStore', sub: t('Enable each game again after changing providers'), run: () => window.chooseSaveProvider('recompstore').catch(fail) }, + { label: 'Google Drive', sub: t('Connect Google Drive first; enable each game again after changing providers'), run: () => S.saveProvider?.google?.connected ? window.chooseSaveProvider('google_drive').catch(fail) : window.connectDrive().catch(fail) }, + ]); case 'account': sfx('open'); if (!(S.account && S.account.signedIn)) return window.signIn && window.signIn(false);