diff --git a/.github/workflows/drive.yml b/.github/workflows/drive.yml
new file mode 100644
index 0000000..c898638
--- /dev/null
+++ b/.github/workflows/drive.yml
@@ -0,0 +1,24 @@
+name: Drive backup
+on:
+ push:
+ branches: [master]
+ pull_request:
+ workflow_dispatch:
+permissions:
+ contents: read
+jobs:
+ drive-policy:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: '17'
+ - name: Fake Drive transport and edition boundary
+ run: python3 android/tests/test_adapter.py
+ google-free:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: kryonlabs/kryon/.github/actions/google-free@7217475dfa7f462939e47e3f0bc918aef248b179
diff --git a/Makefile b/Makefile
index 8e78488..2205bd5 100644
--- a/Makefile
+++ b/Makefile
@@ -204,3 +204,14 @@ test: game-reward-client-test
profile-routes-test:
python3 scripts/profile_routes_test.py
test: profile-routes-test
+
+# The shared Drive policy runs against a fake transport without Google services.
+.PHONY: drive-backup-test
+drive-backup-test:
+ python3 android/tests/test_adapter.py
+ mkdir -p build/drive-native-test
+ $(ZIRAN) build --root . $(MODULE_PATHS) --target=c --entry drive_backup_test:main -o build/drive-native-test tests/drive_backup_test.zi
+ $(CC) -std=c11 -O1 -ffunction-sections -fdata-sections -Wl,--gc-sections -I$(ZIRAN_ROOT)/include -Ibuild/drive-native-test $$(rg --files build/drive-native-test -g '*.c') -o build/drive-native-test/test
+ env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS build/drive-native-test/test
+
+test: drive-backup-test
diff --git a/android/README.md b/android/README.md
new file mode 100644
index 0000000..eb06a1c
--- /dev/null
+++ b/android/README.md
@@ -0,0 +1,146 @@
+# Google Drive account backups (Play only)
+
+Entity owns this optional Android adapter and the fake-transport policy tests.
+Only a Google Play host includes it. Normal/F-Droid hosts neither load its
+Gradle file nor include its Java, resources, manifest activity, Google scopes,
+or Google dependencies. The existing local backup path remains independent.
+
+The adapter sends the existing `RecoveryEncode` v3 text unchanged. No password,
+private key, login proof, or unsealed account data crosses the Android bridge.
+The file is visible in My Drive as `Waozi Account Backup.waozi-account`, with
+MIME type `application/octet-stream` and public metadata property
+`waoziBackup=entity-v3`. "Public" here means cross-client metadata; it does not
+make the file publicly readable. No permissions/sharing API is used.
+
+A new app/phone uses Google Picker rather than assuming another client's
+`drive.file` grant. Each app stores the selected file ID and observed version
+privately. Renaming a file does not break the link. An existing different
+backup always requires an explicit keep/replace decision, followed by a fresh
+content/revision comparison. Unknown formats are never replaced. Creation is
+explicit, re-lists accessible marked files, and refuses to create if any exist.
+A generated file ID is persisted before creation so an uncertain result does
+not trigger a fresh duplicate. That pending ID survives app restarts.
+
+## Google Cloud setup by the owner
+
+1. Create or select **one** [Google Cloud project](https://console.cloud.google.com/projectselector2/home/dashboard)
+ for all Waozi Play apps. Record its numeric project number (not project ID).
+2. In [API Library](https://console.cloud.google.com/apis/library), enable
+ [Google Drive API](https://console.cloud.google.com/apis/library/drive.googleapis.com)
+ and [Google Picker API](https://console.cloud.google.com/apis/library/picker.googleapis.com).
+3. Configure one [Google Auth Platform consent identity](https://console.cloud.google.com/auth/branding):
+ Waozi name, support email, owned domain, homepage/privacy links and audience.
+ In Data Access request **only** `https://www.googleapis.com/auth/drive.file`.
+ Add test users while the app is in Testing. See Google's
+ [consent setup](https://developers.google.com/workspace/guides/configure-oauth-consent).
+4. In [Clients](https://console.cloud.google.com/auth/clients), create one
+ **Android OAuth client for every package/signing-certificate pair**.
+ Breeze Play production package is `xyz.waozi.inbe`. Copy its **Play App Signing
+ certificate SHA-1** from Play Console > Test and release > Setup > App signing;
+ an upload certificate is a different identity. Create additional clients for
+ other Play apps using their real package IDs and Play App Signing SHA-1s.
+ For this task's debug build, use `xyz.waozi.inbe.gplay.debug` and the local debug
+ certificate SHA-1 (`droid/gradlew -p droid :app:signingReport`). Never copy a
+ keystore/password/client secret into the repository. See
+ [Android authorization setup](https://developer.android.com/identity/authorization)
+ and [Play app signing](https://support.google.com/googleplay/android-developer/answer/9842756).
+5. In [Credentials](https://console.cloud.google.com/apis/credentials), create a
+ separate **public browser API key for Picker**. Restrict its API access to
+ Google Picker API and its HTTP referrers to `https://waozi.xyz/*` (or the exact
+ owned HTTPS origin you configure). This is a browser key, not the Android
+ package-restricted key and not an OAuth client secret. See
+ [Picker prerequisites and sample](https://developers.google.com/workspace/drive/picker/guides/web-picker-sample).
+6. Pass the following properties to the Play build using private local Gradle
+ configuration or CI configuration. No populated configuration is committed:
+
+ ```properties
+ waozi.drivePickerKey=YOUR_RESTRICTED_PUBLIC_PICKER_API_KEY
+ waozi.driveProjectNumber=YOUR_NUMERIC_CLOUD_PROJECT_NUMBER
+ waozi.drivePickerOrigin=https://waozi.xyz
+ ```
+
+ Native AuthorizationClient discovers its Android client through package plus
+ signing certificate. There is no embedded client secret, refresh token, or
+ service account. The Picker uses the native access token directly; this
+ implementation does not run a separate web OAuth flow or need a web client ID.
+7. Install each configured Play build and test with the intended Google account.
+ Save in one app, choose that same file with Picker in another app/phone, and
+ enter its original backup password. Test different signing identities,
+ accounts, file rename/deletion, revoke/re-authorize, expiry, quota and offline
+ behavior before advertising cross-app recovery as verified.
+
+## Host integration
+
+Breeze includes this now. Another Play host needs the same initial APK wiring;
+Java/manifest changes cannot arrive through a `.zx` package update alone.
+After that initial integration the shared Entity package owns policy and UI.
+Within **only** the host's Play build configuration:
+
+```groovy
+ext.waoziEntityDir = /* Entity package directory resolved by this host */
+apply from: new File(waoziEntityDir, 'android/gplay.gradle')
+```
+
+The script expects a `gplay` build type. Hosts using another variant shape
+should attach these source/resource directories and the `gplayImplementation`
+auth dependency to their Play-only source set. In the **Play-only manifest** add:
+
+```xml
+
+```
+
+The shared Gradle script keeps the JNI entrypoint from shrinking using Entity’s own rules:
+
+```proguard
+-keep class xyz.waozi.entity.DriveBackup {
+ public static java.lang.String call(android.app.Activity, java.lang.String);
+}
+```
+
+The existing Entity management provider detects this class only in Android
+`GOOGLE_PLAY` builds and offers branded Drive buttons. Restored text goes through
+`ProviderImportText`, the existing password prompt, `RecoveryDecode`, and the
+existing merge/replace workflow. The format and cryptography are unchanged.
+
+## Local tests and current limits
+
+Run `build-queue -- python3 android/tests/test_adapter.py`. It compiles the
+shared policy with plain Java and a fake Drive transport. It tests envelope
+bounds/version/hex, duplicate resolution, unchanged data, changed revision or
+bytes during confirmation, invalid files, file-ID stability and failure mapping.
+Native recovery/provider tests remain in `build-queue -- make native-test`.
+
+Real authorization, file I/O and cross-client grants have not been proven without
+owner Cloud setup. The Picker is embedded in an isolated HTTPS-origin WebView,
+uses no JavaScript/native bridge, permits no file/content access or external
+app navigation, and does not perform OAuth login in the WebView. Whether Google
+Picker accepts this native-token/origin combination on all supported devices
+remains to be tested. The token stays in memory and is never in a URL or log.
+
+Drive v3 does not document atomic compare-and-swap for this flow. We compare
+metadata/download/metadata and recheck immediately before PATCH, but a small
+race between that check and the server update remains. Two independent apps
+can explicitly create at once before either sees the other's new file; the next
+list requires an explicit selection. We do not promise global uniqueness.
+
+Retries are manual, except one cache-cleared reauthorization after HTTP 401 or denied/revoked access (403).
+No background synchronization, quota backoff, or offline queue is implemented.
+An interrupted write can have succeeded remotely: it is reported as uncertain,
+never retried blindly, and reconciled by ID before another create. Process death
+cancels the interactive flow; no password is persisted. Initial host inclusion
+and signed APK updates are still needed in apps other than Breeze. This change
+does not publish to Google Play or any other store.
+
+Breeze's stable Play debug build (run from Breeze) is:
+
+```sh
+build-queue -- droid/gradlew -p droid --no-daemon -Dorg.gradle.jvmargs= :app:assembleGplayDebug :app:assembleGplayDebugAndroidTest -Papp.onlyAbi=armeabi-v7a
+```
+
+Its native code uses the
+same `GOOGLE_PLAY` gate, with a separate package, signing key and output path;
+it does not overwrite the production Play APK. `assembleGplayDebugAndroidTest`
+builds the shared unconfigured-flow test for the Moto.
diff --git a/android/gplay.gradle b/android/gplay.gradle
new file mode 100644
index 0000000..dfd82d7
--- /dev/null
+++ b/android/gplay.gradle
@@ -0,0 +1,22 @@
+// Apply only while building the Play edition, after resolving Entity's package.
+// No secret credentials. Picker key is a restricted public browser API key.
+def driveEntityRoot = project.ext.waoziEntityDir
+['gplay', 'gplayDebug'].findAll { android.buildTypes.findByName(it) != null }.each { edition ->
+ android.sourceSets.getByName(edition).java.srcDir new File(driveEntityRoot, 'android/gplay/java')
+ android.sourceSets.getByName(edition).res.srcDir new File(driveEntityRoot, 'android/gplay/res')
+ android.buildTypes.getByName(edition).with {
+ proguardFile new File(driveEntityRoot, 'android/gplay/proguard-rules.pro')
+ resValue 'string', 'waozi_drive_picker_key', (project.findProperty('waozi.drivePickerKey') ?: '').toString()
+ resValue 'string', 'waozi_drive_project_number', (project.findProperty('waozi.driveProjectNumber') ?: '').toString()
+ resValue 'string', 'waozi_drive_picker_origin', (project.findProperty('waozi.drivePickerOrigin') ?: 'https://waozi.xyz').toString()
+ }
+}
+// 21.4 retains Android 6 support; 22 requires API 24.
+dependencies {
+ gplayImplementation 'com.google.android.gms:play-services-auth:21.4.0'
+
+}
+if (gradle.startParameter.taskNames.any { it.toLowerCase().contains('gplaydebug') }) {
+ android.testBuildType 'gplayDebug'
+ android.sourceSets.androidTest.java.srcDir new File(driveEntityRoot, 'android/gplayTest/java')
+}
diff --git a/android/gplay/java/xyz/waozi/entity/DriveActivity.java b/android/gplay/java/xyz/waozi/entity/DriveActivity.java
new file mode 100644
index 0000000..997c32e
--- /dev/null
+++ b/android/gplay/java/xyz/waozi/entity/DriveActivity.java
@@ -0,0 +1,372 @@
+package xyz.waozi.entity;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.net.Uri;
+import android.os.Bundle;
+import android.webkit.WebResourceRequest;
+import android.webkit.WebSettings;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+import com.google.android.gms.auth.api.identity.AuthorizationRequest;
+import com.google.android.gms.auth.api.identity.ClearTokenRequest;
+import com.google.android.gms.auth.api.identity.AuthorizationResult;
+import com.google.android.gms.auth.api.identity.Identity;
+import com.google.android.gms.common.GoogleApiAvailability;
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.Scope;
+import org.json.JSONObject;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/** Private Play-only authorization and Picker surface, shared by all Waozi apps. */
+public final class DriveActivity extends Activity {
+ private static final int AUTHORIZE = 6041;
+ private static final int ACCOUNT = 6042;
+ private final ExecutorService worker = Executors.newSingleThreadExecutor();
+ private SharedPreferences preferences;
+ private DriveBackupFlow flow;
+ private byte[] local;
+ private String token;
+ private android.accounts.Account account;
+ private volatile boolean finished;
+ private volatile boolean writing;
+ private boolean retried;
+ private WebView picker;
+ private Job retry;
+ private interface Job { void run() throws IOException; }
+
+ @Override public void onCreate(Bundle state) {
+ super.onCreate(state);
+ if (!DriveBackup.attach(this, getIntent().getIntExtra("waoziDriveRequest", -1))) {
+ finished = true;
+ finish();
+ return;
+ }
+ preferences = getSharedPreferences("waozi-drive-backup-v3", MODE_PRIVATE);
+ String command = DriveBackup.takeCommand();
+ if (state != null || command == null) {
+ done("cancelled", "");
+ return;
+ }
+ if (command.startsWith("save\n")) {
+ local = command.substring(5).getBytes(StandardCharsets.UTF_8);
+ if (!DriveBackupFlow.sealed(local)) {
+ done("invalid", "");
+ return;
+ }
+ }
+ // A default/unconfigured build must never start an account or Google network flow.
+ if (config("picker_key").isEmpty() || !config("project_number").matches("[0-9]+")) {
+ fail("setup");
+ return;
+ }
+ if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) != ConnectionResult.SUCCESS) {
+ fail("unavailable");
+ return;
+ }
+ retry = this::start;
+ // Never reuse an implicit account when several Google accounts are present.
+ startActivityForResult(android.accounts.AccountManager.newChooseAccountIntent(
+ null, null, new String[]{"com.google"}, null, null, null, null), ACCOUNT);
+ }
+ private String text(String name) {
+ int id = getResources().getIdentifier("waozi_drive_" + name, "string", getPackageName());
+ return id == 0 ? "Google Drive" : getString(id);
+ }
+ private String config(String name) {
+ int id = getResources().getIdentifier("waozi_drive_" + name, "string", getPackageName());
+ return id == 0 ? "" : getString(id);
+ }
+ private void authorize() {
+ if (finished) {
+ return;
+ }
+ AuthorizationRequest request = AuthorizationRequest.builder()
+ .setAccount(account)
+ .setRequestedScopes(java.util.Collections.singletonList(new Scope("https://www.googleapis.com/auth/drive.file")))
+ .build();
+ Identity.getAuthorizationClient(this).authorize(request)
+ .addOnSuccessListener(result -> authorized(result))
+ .addOnFailureListener(error -> fail("unauthorized"));
+ }
+ private void authorized(AuthorizationResult result) {
+ if (finished) {
+ return;
+ }
+ if (result.hasResolution()) {
+ try {
+ startIntentSenderForResult(result.getPendingIntent().getIntentSender(), AUTHORIZE, null, 0, 0, 0);
+ } catch (android.content.IntentSender.SendIntentException error) {
+ fail("unauthorized");
+ }
+ return;
+ }
+ token = result.getAccessToken();
+ if (token == null || token.isEmpty()) {
+ fail("unauthorized");
+ return;
+ }
+ flow = new DriveBackupFlow(new DriveRest(token, preferences, () -> !finished));
+ work(retry);
+ }
+ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ if (finished) {
+ return;
+ }
+ if (requestCode == ACCOUNT) {
+ if (resultCode != RESULT_OK || data == null) {
+ done("cancelled", "");
+ return;
+ }
+ String name = data.getStringExtra(android.accounts.AccountManager.KEY_ACCOUNT_NAME);
+ String type = data.getStringExtra(android.accounts.AccountManager.KEY_ACCOUNT_TYPE);
+ if (name == null || name.isEmpty() || !"com.google".equals(type)) {
+ fail("unauthorized");
+ return;
+ }
+ account = new android.accounts.Account(name, type);
+ authorize();
+ return;
+ }
+ if (requestCode != AUTHORIZE) {
+ return;
+ }
+ if (resultCode != RESULT_OK || data == null) {
+ done("cancelled", "");
+ return;
+ }
+ try {
+ authorized(Identity.getAuthorizationClient(this).getAuthorizationResultFromIntent(data));
+ } catch (com.google.android.gms.common.api.ApiException error) {
+ fail("unauthorized");
+ }
+ }
+ private void work(Job job) {
+ if (finished) {
+ return;
+ }
+ retry = job;
+ worker.execute(() -> {
+ try {
+ job.run();
+ } catch (DriveBackupFlow.Failure error) {
+ writing = false;
+ if (("unauthorized".equals(error.code) || "forbidden".equals(error.code)) && !retried) {
+ retried = true;
+ runOnUiThread(() -> Identity.getAuthorizationClient(this)
+ .clearToken(ClearTokenRequest.builder().setToken(token).build())
+ .addOnSuccessListener(ignored -> authorize())
+ .addOnFailureListener(ignored -> fail("unauthorized")));
+ } else {
+ fail(error.code);
+ }
+ } catch (IOException | RuntimeException error) {
+ fail("error");
+ }
+ });
+ }
+ private void start() throws IOException {
+ String linked = preferences.getString("file_id", "");
+ // Restore always shows Picker: never assume a grant from another Play app.
+ if (local == null) {
+ runOnUiThread(this::pick);
+ } else if (!linked.isEmpty()) {
+ selected(linked);
+ } else {
+ choices();
+ }
+ }
+ private void choices() throws IOException {
+ List files = flow.candidates();
+ String[] labels = new String[files.size() + 1];
+ for (int i = 0; i < files.size(); i++) {
+ DriveBackupFlow.File file = files.get(i);
+ labels[i] = file.name + "\n" + file.id;
+ }
+ labels[files.size()] = text("pick");
+ runOnUiThread(() -> {
+ AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle(text("select"))
+ .setItems(labels, (ignored, index) -> {
+ if (index == files.size()) {
+ pick();
+ } else {
+ work(() -> selected(files.get(index).id));
+ }
+ }).setNegativeButton(android.R.string.cancel, (ignored, which) -> done("cancelled", ""))
+ .setOnCancelListener(ignored -> done("cancelled", ""));
+ if (files.isEmpty() && local != null) {
+ dialog.setPositiveButton(text("create"), (ignored, which) -> work(() -> {
+ writing = true;
+ DriveBackupFlow.File created = flow.create(local);
+ writing = false;
+ link(created);
+ done("saved", "");
+ }));
+ }
+ dialog.show();
+ });
+ }
+ private void selected(String id) throws IOException {
+ DriveBackupFlow.Blob remote = flow.read(id);
+ if (local == null) {
+ link(remote.file);
+ done("restored", new String(remote.bytes, StandardCharsets.UTF_8));
+ return;
+ }
+ if (Arrays.equals(local, remote.bytes)) {
+ link(remote.file);
+ done("saved", "");
+ return;
+ }
+ runOnUiThread(() -> new AlertDialog.Builder(this).setTitle("Google Drive")
+ .setMessage(text("conflict"))
+ .setPositiveButton(text("replace"), (dialog, which) -> work(() -> {
+ writing = true;
+ DriveBackupFlow.File updated = flow.replace(remote, local);
+ writing = false;
+ link(updated);
+ done("saved", "");
+ }))
+ .setNeutralButton(text("pick"), (dialog, which) -> pick())
+ .setNegativeButton(text("keep"), (dialog, which) -> done("cancelled", ""))
+ .setOnCancelListener(dialog -> done("cancelled", "")).show());
+ }
+ private void link(DriveBackupFlow.File file) throws IOException {
+ if (!preferences.edit().putString("file_id", file.id).putString("version", file.version).commit()) {
+ throw new DriveBackupFlow.Failure("error");
+ }
+ }
+ private void pick() {
+ String key = config("picker_key");
+ String project = config("project_number");
+ String origin = config("picker_origin");
+ Uri base = Uri.parse(origin);
+ if (key.isEmpty() || !project.matches("[0-9]+") || !"https".equals(base.getScheme())
+ || base.getHost() == null || base.getUserInfo() != null || base.getPort() != -1
+ || !(base.getPath().isEmpty() || "/".equals(base.getPath())) || base.getQuery() != null || base.getFragment() != null) {
+ fail("setup");
+ return;
+ }
+ final String callback = origin.replaceAll("/$", "") + "/entity-drive-picked";
+ picker = new WebView(this);
+ picker.setSaveEnabled(false);
+ WebSettings settings = picker.getSettings();
+ settings.setJavaScriptEnabled(true);
+ settings.setDomStorageEnabled(true);
+ settings.setAllowFileAccess(false);
+ settings.setAllowContentAccess(false);
+ settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
+ settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
+ settings.setSaveFormData(false);
+ picker.setWebViewClient(new WebViewClient() {
+ @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
+ return navigate(request.getUrl(), request.isForMainFrame());
+ }
+ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
+ // Android 6 calls this overload rather than WebResourceRequest.
+ return navigate(Uri.parse(url), true);
+ }
+ private boolean navigate(Uri uri, boolean mainFrame) {
+ if (mainFrame) {
+ if (callback.equals(uri.buildUpon().fragment(null).build().toString())) {
+ String id = uri.getFragment();
+ if (id != null && id.matches("[A-Za-z0-9_-]{1,256}")) {
+ closePicker();
+ work(() -> selected(id));
+ } else {
+ done("cancelled", "");
+ }
+ }
+ return true;
+ }
+ // Picker frames can contact Google over HTTPS; never open another application.
+ return !"https".equals(uri.getScheme());
+ }
+ });
+ String html = ""
+ + "";
+ setContentView(picker);
+ picker.loadDataWithBaseURL(origin + "/entity-drive-picker/", html, "text/html", "UTF-8", null);
+ }
+ private void closePicker() {
+ if (picker != null) {
+ picker.stopLoading();
+ picker.loadUrl("about:blank");
+ picker.destroy();
+ picker = null;
+ }
+ }
+ private void fail(String code) {
+ runOnUiThread(() -> {
+ if (finished || isFinishing()) {
+ return;
+ }
+ closePicker();
+ new AlertDialog.Builder(this).setTitle("Google Drive").setMessage(text(code))
+ .setPositiveButton(android.R.string.ok, (dialog, which) -> done(code, ""))
+ .setNeutralButton(text("missing".equals(code) ? "select" : "pick"), (dialog, which) -> {
+ if (token == null || "setup".equals(code) || "unavailable".equals(code)) {
+ done(code, "");
+ } else if ("missing".equals(code) && local != null) {
+ // An explicit new selection can find another file or offer creation.
+ // Keep the old ID until the user successfully chooses its replacement.
+ work(this::choices);
+ } else {
+ pick();
+ }
+ })
+ .setOnCancelListener(dialog -> done(code, "")).show();
+ });
+ }
+ private void done(String status, String content) {
+ runOnUiThread(() -> {
+ if (finished) {
+ return;
+ }
+ finished = true;
+ if ("saved".equals(status)) {
+ android.widget.Toast.makeText(this, text("saved"), android.widget.Toast.LENGTH_LONG).show();
+ }
+ DriveBackup.finish(this, status, content);
+ finish();
+ });
+ }
+ void cancelOperation() {
+ done(writing ? "uncertain" : "cancelled", "");
+ }
+ @Override public void onBackPressed() {
+ cancelOperation();
+ }
+ @Override protected void onDestroy() {
+ if (!finished) {
+ DriveBackup.finish(this, "cancelled", "");
+ }
+ finished = true;
+ closePicker();
+ token = null;
+ if (local != null) {
+ Arrays.fill(local, (byte) 0);
+ local = null;
+ }
+ worker.shutdownNow();
+ DriveBackup.detach(this);
+ super.onDestroy();
+ }
+}
diff --git a/android/gplay/java/xyz/waozi/entity/DriveBackup.java b/android/gplay/java/xyz/waozi/entity/DriveBackup.java
new file mode 100644
index 0000000..112dfa6
--- /dev/null
+++ b/android/gplay/java/xyz/waozi/entity/DriveBackup.java
@@ -0,0 +1,90 @@
+package xyz.waozi.entity;
+
+import android.app.Activity;
+import android.content.Intent;
+import org.json.JSONObject;
+import org.json.JSONException;
+
+/** Class-loader bridge: only a Play source set includes this class. */
+public final class DriveBackup {
+ private static String command;
+ private static String answer = "{\"status\":\"idle\"}";
+ private static boolean busy;
+ private static DriveActivity current;
+ private static int serial;
+
+ private DriveBackup() {}
+ public static synchronized String call(Activity activity, String request) {
+ if (request == null) {
+ return "{\"status\":\"invalid\"}";
+ }
+ if ("available".equals(request)) {
+ return "yes";
+ }
+ if ("poll".equals(request)) {
+ return answer;
+ }
+ if ("cancel".equals(request)) {
+ if (current != null) {
+ current.cancelOperation();
+ } else {
+ serial++;
+ finish("cancelled", "");
+ }
+ return answer;
+ }
+ if (busy) {
+ return "{\"status\":\"busy\"}";
+ }
+ if (!("restore".equals(request) || request.startsWith("save\n")) || request.length() > 17700) {
+ return "{\"status\":\"invalid\"}";
+ }
+ busy = true;
+ final int ticket = ++serial;
+ command = request;
+ answer = "{\"status\":\"pending\"}";
+ activity.runOnUiThread(() -> {
+ try {
+ activity.startActivity(new Intent(activity, DriveActivity.class).putExtra("waoziDriveRequest", ticket));
+ } catch (RuntimeException error) {
+ synchronized (DriveBackup.class) {
+ if (ticket == serial) {
+ finish("unavailable", "");
+ }
+ }
+ }
+ });
+ return answer;
+ }
+ static synchronized boolean attach(DriveActivity activity, int ticket) {
+ if (ticket != serial || !busy || current != null) {
+ return false;
+ }
+ current = activity;
+ return true;
+ }
+ static synchronized void detach(DriveActivity activity) {
+ if (current == activity) {
+ current = null;
+ }
+ }
+ static synchronized String takeCommand() {
+ String result = command;
+ command = null;
+ return result;
+ }
+ static synchronized void finish(DriveActivity activity, String status, String content) {
+ if (current == activity) {
+ finish(status, content);
+ }
+ }
+ private static synchronized void finish(String status, String content) {
+ try {
+ answer = new JSONObject().put("status", status).put("content", content).toString();
+ } catch (JSONException error) {
+ answer = "{\"status\":\"error\"}";
+ }
+ busy = false;
+ command = null;
+ }
+}
diff --git a/android/gplay/java/xyz/waozi/entity/DriveBackupFlow.java b/android/gplay/java/xyz/waozi/entity/DriveBackupFlow.java
new file mode 100644
index 0000000..4a4de52
--- /dev/null
+++ b/android/gplay/java/xyz/waozi/entity/DriveBackupFlow.java
@@ -0,0 +1,152 @@
+package xyz.waozi.entity;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.List;
+
+/** Storage policy shared by every Play host. Transport never receives a password or key. */
+public final class DriveBackupFlow {
+ public static final int MAX_BYTES = 17663;
+ public static final String MARKER = "entity-v3";
+ public static final String NAME = "Waozi Account Backup.waozi-account";
+ public static final String PREFIX = "waozi-account-backup-v3\nalgorithm=ML-DSA-44\nkdf=Argon2id\nmemory_kib=65536\npasses=3\nlanes=1\nsalt=";
+
+ public static final class Failure extends IOException {
+ public final String code;
+ public Failure(String code) {
+ super(code);
+ this.code = code;
+ }
+ }
+ public static final class File {
+ public final String id;
+ public final String name;
+ public final String version;
+ public File(String id, String name, String version) {
+ this.id = id;
+ this.name = name;
+ this.version = version;
+ }
+ }
+ public static final class Blob {
+ public final File file;
+ public final byte[] bytes;
+ public Blob(File file, byte[] bytes) {
+ this.file = file;
+ this.bytes = bytes;
+ }
+ }
+ public interface Transport {
+ List list() throws IOException;
+ Blob read(String id) throws IOException;
+ File create(byte[] sealed) throws IOException;
+ File replace(String id, String version, byte[] sealed) throws IOException;
+ }
+ private final Transport transport;
+ public DriveBackupFlow(Transport transport) {
+ this.transport = transport;
+ }
+
+ // Structural check only. Entity's unchanged RecoveryDecode authenticates restore.
+ public static boolean sealed(byte[] bytes) {
+ if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) {
+ return false;
+ }
+ String text = new String(bytes, StandardCharsets.UTF_8);
+ if (!Arrays.equals(bytes, text.getBytes(StandardCharsets.UTF_8)) || !text.startsWith(PREFIX)) {
+ return false;
+ }
+ int at = PREFIX.length();
+ if (!hex(text, at, 32)) {
+ return false;
+ }
+ at += 32;
+ if (!text.startsWith("\nnonce=", at)) {
+ return false;
+ }
+ at += 7;
+ if (!hex(text, at, 24)) {
+ return false;
+ }
+ at += 24;
+ if (!text.startsWith("\nciphertext=", at)) {
+ return false;
+ }
+ at += 12;
+ int end = text.endsWith("\n") ? text.length() - 1 : text.length();
+ return end - at > 32 && (end - at) % 2 == 0 && hex(text, at, end - at);
+ }
+ private static boolean hex(String text, int at, int count) {
+ if (at < 0 || count <= 0 || at + count > text.length()) {
+ return false;
+ }
+ for (int i = at; i < at + count; i++) {
+ char c = text.charAt(i);
+ if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) {
+ return false;
+ }
+ }
+ return true;
+ }
+ public Blob read(String id) throws IOException {
+ Blob remote = transport.read(id);
+ if (!sealed(remote.bytes)) {
+ throw new Failure("invalid");
+ }
+ return remote;
+ }
+ public List candidates() throws IOException {
+ return transport.list();
+ }
+ // Creation is always an explicit choice, with a fresh duplicate check.
+ public File create(byte[] local) throws IOException {
+ if (!sealed(local)) {
+ throw new Failure("invalid");
+ }
+ byte[] snapshot = local.clone();
+ if (!transport.list().isEmpty()) {
+ throw new Failure("duplicate");
+ }
+ return transport.create(snapshot);
+ }
+ // A confirmed comparison is single-use. Changes during the dialog require another choice.
+ public File replace(Blob confirmed, byte[] local) throws IOException {
+ if (!sealed(local)) {
+ throw new Failure("invalid");
+ }
+ byte[] snapshot = local.clone();
+ Blob current = read(confirmed.file.id);
+ if (!current.file.version.equals(confirmed.file.version) || !Arrays.equals(current.bytes, confirmed.bytes)) {
+ throw new Failure("changed");
+ }
+ if (Arrays.equals(current.bytes, snapshot)) {
+ return current.file;
+ }
+ return transport.replace(current.file.id, current.file.version, snapshot);
+ }
+ public static String failure(int status, String reason) {
+ if (status == 401) {
+ return "unauthorized";
+ }
+ if (status == 404) {
+ return "missing";
+ }
+ if (status == 409 || status == 412) {
+ return "changed";
+ }
+ if ("storageQuotaExceeded".equals(reason)) {
+ return "full";
+ }
+ if (status == 429 || "rateLimitExceeded".equals(reason) || "userRateLimitExceeded".equals(reason)) {
+ return "quota";
+ }
+ if (status == 403) {
+ return "forbidden";
+ }
+ if (status >= 500) {
+ return "offline";
+ }
+ return "error";
+ }
+}
diff --git a/android/gplay/java/xyz/waozi/entity/DriveRest.java b/android/gplay/java/xyz/waozi/entity/DriveRest.java
new file mode 100644
index 0000000..193c0a3
--- /dev/null
+++ b/android/gplay/java/xyz/waozi/entity/DriveRest.java
@@ -0,0 +1,213 @@
+package xyz.waozi.entity;
+
+import android.content.SharedPreferences;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Bounded Drive v3 I/O. No Google SDK for storage; no tokens on disk or in URLs. */
+final class DriveRest implements DriveBackupFlow.Transport {
+ private static final String API = "https://www.googleapis.com/drive/v3/files";
+ private static final String UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
+ private static final String FIELDS = "id,name,version,size,trashed,ownedByMe,properties";
+ private final String token;
+ interface Active { boolean get(); }
+ private final Active active;
+ private final SharedPreferences preferences;
+
+ DriveRest(String token, SharedPreferences preferences, Active active) {
+ this.token = token;
+ this.active = active;
+ this.preferences = preferences;
+ }
+ private static String encode(String value) throws IOException {
+ return URLEncoder.encode(value, "UTF-8");
+ }
+ private static void id(String id) throws IOException {
+ if (id == null || !id.matches("[A-Za-z0-9_-]{1,256}")) {
+ throw new DriveBackupFlow.Failure("invalid");
+ }
+ }
+ private byte[] request(String method, String url, String type, byte[] body, int cap) throws IOException {
+ if (!active.get()) {
+ throw new DriveBackupFlow.Failure("cancelled");
+ }
+ HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
+ connection.setInstanceFollowRedirects(false);
+ connection.setConnectTimeout(15000);
+ connection.setReadTimeout(20000);
+ connection.setRequestMethod(method);
+ connection.setRequestProperty("Authorization", "Bearer " + token);
+ connection.setRequestProperty("Accept", "application/json");
+ boolean submitted = false;
+ try {
+ if (body != null) {
+ connection.setDoOutput(true);
+ connection.setRequestProperty("Content-Type", type);
+ connection.setFixedLengthStreamingMode(body.length);
+ if (!active.get()) {
+ throw new DriveBackupFlow.Failure("cancelled");
+ }
+ submitted = true;
+ try (java.io.OutputStream output = connection.getOutputStream()) {
+ output.write(body);
+ }
+ }
+ int status = connection.getResponseCode();
+ if (status < 200 || status > 299) {
+ String reason = "";
+ try {
+ JSONObject error = new JSONObject(new String(read(connection.getErrorStream(), 8192), StandardCharsets.UTF_8));
+ JSONArray errors = error.optJSONObject("error").optJSONArray("errors");
+ if (errors != null && errors.length() > 0) {
+ reason = errors.getJSONObject(0).optString("reason");
+ }
+ } catch (JSONException | NullPointerException ignored) {
+ // Never echo response bodies: error text can contain private request data.
+ }
+ throw new DriveBackupFlow.Failure(DriveBackupFlow.failure(status, reason));
+ }
+ return read(connection.getInputStream(), cap);
+ } catch (DriveBackupFlow.Failure error) {
+ throw error;
+ } catch (IOException error) {
+ throw new DriveBackupFlow.Failure(submitted ? "uncertain" : "offline");
+ } finally {
+ connection.disconnect();
+ }
+ }
+ private static byte[] read(InputStream input, int cap) throws IOException {
+ if (input == null) {
+ return new byte[0];
+ }
+ try (InputStream stream = input; ByteArrayOutputStream output = new ByteArrayOutputStream()) {
+ byte[] block = new byte[2048];
+ int count;
+ while ((count = stream.read(block)) != -1) {
+ if (output.size() + count > cap) {
+ throw new DriveBackupFlow.Failure("invalid");
+ }
+ output.write(block, 0, count);
+ }
+ return output.toByteArray();
+ }
+ }
+ private JSONObject json(String method, String url, String type, byte[] body) throws IOException {
+ try {
+ return new JSONObject(new String(request(method, url, type, body, 32768), StandardCharsets.UTF_8));
+ } catch (JSONException error) {
+ throw new DriveBackupFlow.Failure("invalid");
+ }
+ }
+ private DriveBackupFlow.File file(JSONObject item) throws IOException {
+ String id = item.optString("id");
+ id(id);
+ String version = item.optString("version");
+ JSONObject properties = item.optJSONObject("properties");
+ if (version.isEmpty() || item.optBoolean("trashed") || !item.optBoolean("ownedByMe") || properties == null
+ || !DriveBackupFlow.MARKER.equals(properties.optString("waoziBackup"))) {
+ throw new DriveBackupFlow.Failure("invalid");
+ }
+ return new DriveBackupFlow.File(id, item.optString("name"), version);
+ }
+ private JSONObject metadata(String id) throws IOException {
+ id(id);
+ return json("GET", API + "/" + id + "?fields=" + encode(FIELDS), null, null);
+ }
+ @Override public List list() throws IOException {
+ String query = "trashed = false and 'me' in owners and properties has { key='waoziBackup' and value='entity-v3' }";
+ JSONObject result = json("GET", API + "?q=" + encode(query) + "&spaces=drive&pageSize=16&fields="
+ + encode("nextPageToken,files(" + FIELDS + ")"), null, null);
+ if (!result.optString("nextPageToken").isEmpty()) {
+ throw new DriveBackupFlow.Failure("duplicate");
+ }
+ List files = new ArrayList<>();
+ JSONArray items = result.optJSONArray("files");
+ if (items == null) {
+ throw new DriveBackupFlow.Failure("invalid");
+ }
+ for (int index = 0; index < items.length(); index++) {
+ try {
+ files.add(file(items.getJSONObject(index)));
+ } catch (JSONException error) {
+ throw new DriveBackupFlow.Failure("invalid");
+ }
+ }
+ return files;
+ }
+ @Override public DriveBackupFlow.Blob read(String id) throws IOException {
+ JSONObject before = metadata(id);
+ DriveBackupFlow.File selected = file(before);
+ long size = before.optLong("size", -1);
+ if (size <= 0 || size > DriveBackupFlow.MAX_BYTES) {
+ throw new DriveBackupFlow.Failure("invalid");
+ }
+ byte[] content = request("GET", API + "/" + id + "?alt=media", null, null, DriveBackupFlow.MAX_BYTES);
+ DriveBackupFlow.File after = file(metadata(id));
+ if (!selected.version.equals(after.version) || content.length != size) {
+ throw new DriveBackupFlow.Failure("changed");
+ }
+ return new DriveBackupFlow.Blob(after, content);
+ }
+ @Override public DriveBackupFlow.File create(byte[] content) throws IOException {
+ // Pre-generated ID is durable before POST: an uncertain result can be reconciled without a duplicate.
+ String pending = preferences.getString("pending_create", "");
+ if (!pending.isEmpty()) {
+ try {
+ DriveBackupFlow.Blob previous = read(pending);
+ if (!java.util.Arrays.equals(previous.bytes, content)) {
+ throw new DriveBackupFlow.Failure("uncertain");
+ }
+ preferences.edit().remove("pending_create").commit();
+ return previous.file;
+ } catch (DriveBackupFlow.Failure error) {
+ if (!"missing".equals(error.code)) {
+ throw error;
+ }
+ }
+ }
+ try {
+ if (pending.isEmpty()) {
+ JSONObject ids = json("GET", API + "/generateIds?count=1&space=drive&type=files", null, null);
+ pending = ids.getJSONArray("ids").getString(0);
+ }
+ id(pending);
+ if (!preferences.edit().putString("pending_create", pending).commit()) {
+ throw new DriveBackupFlow.Failure("error");
+ }
+ JSONObject metadata = new JSONObject().put("id", pending).put("name", DriveBackupFlow.NAME)
+ .put("mimeType", "application/octet-stream")
+ .put("properties", new JSONObject().put("waoziBackup", DriveBackupFlow.MARKER));
+ String boundary = "waozi_entity_v3_boundary";
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ body.write(("--" + boundary + "\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
+ + metadata.toString() + "\r\n--" + boundary
+ + "\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8));
+ body.write(content);
+ body.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
+ DriveBackupFlow.File created = file(json("POST", UPLOAD + "?uploadType=multipart&fields=" + encode(FIELDS),
+ "multipart/related; boundary=" + boundary, body.toByteArray()));
+ preferences.edit().remove("pending_create").commit();
+ return created;
+ } catch (JSONException error) {
+ throw new DriveBackupFlow.Failure("invalid");
+ }
+ }
+ @Override public DriveBackupFlow.File replace(String id, String version, byte[] content) throws IOException {
+ // Recheck immediately before mutation. Drive v3 does not document atomic compare-and-swap.
+ if (!file(metadata(id)).version.equals(version)) {
+ throw new DriveBackupFlow.Failure("changed");
+ }
+ return file(json("PATCH", UPLOAD + "/" + id + "?uploadType=media&fields=" + encode(FIELDS),
+ "application/octet-stream", content));
+ }
+}
diff --git a/android/gplay/proguard-rules.pro b/android/gplay/proguard-rules.pro
new file mode 100644
index 0000000..22f536d
--- /dev/null
+++ b/android/gplay/proguard-rules.pro
@@ -0,0 +1,4 @@
+# JNI finds this Play-only entrypoint by its public name.
+-keep class xyz.waozi.entity.DriveBackup {
+ public static java.lang.String call(android.app.Activity, java.lang.String);
+}
diff --git a/android/gplay/res/raw/waozi_drive_keep.xml b/android/gplay/res/raw/waozi_drive_keep.xml
new file mode 100644
index 0000000..7ae4699
--- /dev/null
+++ b/android/gplay/res/raw/waozi_drive_keep.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/android/gplay/res/values-cs/waozi_drive.xml b/android/gplay/res/values-cs/waozi_drive.xml
new file mode 100644
index 0000000..922f7b0
--- /dev/null
+++ b/android/gplay/res/values-cs/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Vyberte zálohu účtu
+ Vybrat z Google Drive
+ Vytvořit novou zálohu
+ Záloha na Drive se liší od tohoto zařízení. Ponechat ji, nebo nahradit šifrovanou zálohou tohoto zařízení? Pokud potřebujete obě, nejprve uložte místní kopii.
+ Nahradit zálohu na Drive
+ Ponechat zálohu na Drive
+ Bez připojení. Místní účet je v bezpečí. Zkuste to po připojení.
+ Znovu povolte přístup ke Google Drive. Ověřte vybraný účet Google.
+ Přístup k Drive byl odepřen nebo odvolán. Vyberte správný účet a znovu povolte přístup.
+ Drive je zaneprázdněn nebo byl dosažen limit požadavků. Zkuste to později.
+ Google Drive je plný. Uvolněte místo a zkuste to znovu.
+ Záloha chybí nebo patří jinému účtu Google. Vyberte ji znovu.
+ Záloha na Drive se změnila. Před nahrazením ji znovu otevřete a zkontrolujte.
+ Toto není podporovaná šifrovaná záloha Waozi. Soubor zůstal beze změny.
+ Google Drive pro tuto aplikaci ještě není nastaven. Místní zálohy můžete používat dál.
+ Služby Google Play nejsou dostupné. Použijte místní zálohu.
+ Operaci na Drive nelze dokončit. Místní účet je v bezpečí.
+ Výsledek nahrávání je nejistý. Nevytvářejte další kopii. Před dalším pokusem vyberte stávající zálohu.
+ Nalezeno více záloh. Vyberte soubor; nová kopie nebyla vytvořena.
+ Záloha uložena na Google Drive.
+
diff --git a/android/gplay/res/values-de/waozi_drive.xml b/android/gplay/res/values-de/waozi_drive.xml
new file mode 100644
index 0000000..534ec4b
--- /dev/null
+++ b/android/gplay/res/values-de/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Kontosicherung auswählen
+ Aus Google Drive auswählen
+ Neue Sicherung erstellen
+ Die Drive-Sicherung unterscheidet sich von diesem Gerät. Behalten oder durch dessen verschlüsselte Sicherung ersetzen? Speichere zuerst eine lokale Kopie, wenn du beide brauchst.
+ Drive-Sicherung ersetzen
+ Drive-Sicherung behalten
+ Keine Verbindung. Dein lokales Konto ist sicher. Versuche es wieder, wenn du online bist.
+ Erlaube den Zugriff auf Google Drive erneut. Prüfe das ausgewählte Google-Konto.
+ Drive-Zugriff verweigert oder widerrufen. Wähle das richtige Konto und erlaube den Zugriff erneut.
+ Drive ist ausgelastet oder das Anfragelimit wurde erreicht. Versuche es später erneut.
+ Google Drive ist voll. Gib Speicherplatz frei und versuche es erneut.
+ Die Sicherung fehlt oder gehört zu einem anderen Google-Konto. Wähle sie erneut aus.
+ Die Drive-Sicherung wurde geändert. Öffne und prüfe sie vor dem Ersetzen erneut.
+ Dies ist keine unterstützte verschlüsselte Waozi-Sicherung. Die Datei bleibt unverändert.
+ Google Drive ist für diese App noch nicht eingerichtet. Lokale Sicherungsdateien funktionieren weiterhin.
+ Google Play-Dienste sind nicht verfügbar. Nutze eine lokale Sicherungsdatei.
+ Der Drive-Vorgang konnte nicht abgeschlossen werden. Dein lokales Konto ist sicher.
+ Das Ergebnis des Uploads ist unklar. Erstelle keine weitere Kopie. Wähle vor einem erneuten Versuch die bestehende Sicherung.
+ Mehrere Sicherungen gefunden. Wähle die Datei aus; keine neue Kopie erstellt.
+ Sicherung in Google Drive gespeichert.
+
diff --git a/android/gplay/res/values-es/waozi_drive.xml b/android/gplay/res/values-es/waozi_drive.xml
new file mode 100644
index 0000000..74ee9a7
--- /dev/null
+++ b/android/gplay/res/values-es/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Elige tu copia de la cuenta
+ Elegir de Google Drive
+ Crear nueva copia
+ La copia de Drive difiere de este dispositivo. ¿Conservarla o reemplazarla con la copia cifrada de este dispositivo? Guarda primero una copia local si necesitas ambas.
+ Reemplazar copia de Drive
+ Conservar copia de Drive
+ Sin conexión. Tu cuenta local está segura. Inténtalo cuando tengas conexión.
+ Vuelve a autorizar Google Drive. Comprueba la cuenta de Google seleccionada.
+ Acceso a Drive denegado o revocado. Elige la cuenta correcta y autoriza de nuevo.
+ Drive está ocupado o se alcanzó el límite de solicitudes. Inténtalo más tarde.
+ Google Drive está lleno. Libera espacio y vuelve a intentarlo.
+ La copia no existe o pertenece a otra cuenta de Google. Elígela de nuevo.
+ La copia de Drive cambió. Ábrela y revísala antes de reemplazarla.
+ No es una copia cifrada de Waozi compatible. No se modificó.
+ Google Drive aún no está configurado para esta app. Puedes guardar y abrir copias locales.
+ Los servicios de Google Play no están disponibles. Usa una copia local.
+ No se pudo completar la operación de Drive. Tu cuenta local está segura.
+ El resultado de la subida es incierto. No crees otra copia. Elige la copia existente antes de reintentar.
+ Se encontraron varias copias. Elige el archivo; no se creó otra copia.
+ Copia guardada en Google Drive.
+
diff --git a/android/gplay/res/values-fr/waozi_drive.xml b/android/gplay/res/values-fr/waozi_drive.xml
new file mode 100644
index 0000000..bd2cfe6
--- /dev/null
+++ b/android/gplay/res/values-fr/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Choisir la sauvegarde du compte
+ Choisir dans Google Drive
+ Créer une sauvegarde
+ La sauvegarde Drive diffère de cet appareil. La conserver ou la remplacer par celle chiffrée de cet appareil ? Enregistrez une copie locale si vous voulez garder les deux.
+ Remplacer la sauvegarde Drive
+ Conserver la sauvegarde Drive
+ Aucune connexion. Votre compte local est intact. Réessayez en ligne.
+ Autorisez à nouveau Google Drive. Vérifiez le compte Google sélectionné.
+ Accès à Drive refusé ou révoqué. Choisissez le bon compte et autorisez à nouveau.
+ Drive est occupé ou sa limite de requêtes est atteinte. Réessayez plus tard.
+ Google Drive est plein. Libérez de la place et réessayez.
+ La sauvegarde manque ou appartient à un autre compte Google. Choisissez-la à nouveau.
+ La sauvegarde Drive a changé. Ouvrez-la et vérifiez-la avant de la remplacer.
+ Ce fichier ne contient pas une sauvegarde Waozi chiffrée compatible. Il reste inchangé.
+ Google Drive doit encore être configuré pour cette application. Vous pouvez utiliser les sauvegardes locales.
+ Les services Google Play sont indisponibles. Utilisez une sauvegarde locale.
+ Impossible de terminer cette opération Drive. Votre compte local est intact.
+ Le résultat du transfert est incertain. Ne créez pas de doublon. Choisissez la sauvegarde existante avant de réessayer.
+ Plusieurs sauvegardes existent. Choisissez le fichier ; aucune nouvelle copie créée.
+ Sauvegarde enregistrée dans Google Drive.
+
diff --git a/android/gplay/res/values-in/waozi_drive.xml b/android/gplay/res/values-in/waozi_drive.xml
new file mode 100644
index 0000000..70eb03e
--- /dev/null
+++ b/android/gplay/res/values-in/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Pilih cadangan akun
+ Pilih dari Google Drive
+ Buat cadangan baru
+ Cadangan Drive berbeda dari perangkat ini. Simpan atau ganti dengan cadangan terenkripsi perangkat ini? Simpan salinan lokal dahulu jika memerlukan keduanya.
+ Ganti cadangan Drive
+ Pertahankan cadangan Drive
+ Tidak ada koneksi. Akun lokal Anda aman. Coba lagi saat online.
+ Izinkan akses Google Drive lagi. Periksa akun Google yang dipilih.
+ Akses Drive ditolak atau dicabut. Pilih akun yang benar dan izinkan lagi.
+ Drive sibuk atau batas permintaan tercapai. Coba lagi nanti.
+ Google Drive penuh. Kosongkan ruang lalu coba lagi.
+ Cadangan tidak ada atau milik akun Google lain. Pilih lagi.
+ Cadangan Drive berubah. Buka dan periksa lagi sebelum menggantinya.
+ Ini bukan cadangan Waozi terenkripsi yang didukung. Berkas tidak diubah.
+ Google Drive belum disiapkan untuk aplikasi ini. Anda tetap dapat memakai cadangan lokal.
+ Layanan Google Play tidak tersedia. Gunakan cadangan lokal.
+ Operasi Drive tidak dapat diselesaikan. Akun lokal Anda aman.
+ Hasil unggahan belum pasti. Jangan buat salinan lain. Pilih cadangan yang ada sebelum mencoba lagi.
+ Ditemukan beberapa cadangan. Pilih berkas; tidak ada salinan baru yang dibuat.
+ Cadangan disimpan ke Google Drive.
+
diff --git a/android/gplay/res/values-it/waozi_drive.xml b/android/gplay/res/values-it/waozi_drive.xml
new file mode 100644
index 0000000..2b58a68
--- /dev/null
+++ b/android/gplay/res/values-it/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Scegli il backup del tuo account
+ Scegli da Google Drive
+ Crea nuovo backup
+ Il backup di Drive è diverso da questo dispositivo. Conservarlo o sostituirlo con il backup cifrato di questo dispositivo? Salva prima una copia locale se servono entrambi.
+ Sostituisci backup di Drive
+ Conserva backup di Drive
+ Nessuna connessione. Il tuo account locale è al sicuro. Riprova quando sei online.
+ Autorizza di nuovo Google Drive. Controlla l’account Google selezionato.
+ Accesso a Drive negato o revocato. Scegli l’account corretto e autorizza di nuovo.
+ Drive è occupato o è stato raggiunto il limite di richieste. Riprova più tardi.
+ Google Drive è pieno. Libera spazio e riprova.
+ Il backup manca o appartiene a un altro account Google. Sceglilo di nuovo.
+ Il backup di Drive è cambiato. Aprilo e controllalo prima di sostituirlo.
+ Questo non è un backup Waozi cifrato supportato. Non è stato modificato.
+ Google Drive non è ancora configurato per questa app. Puoi usare i backup locali.
+ I servizi Google Play non sono disponibili. Usa un backup locale.
+ Impossibile completare l’operazione su Drive. Il tuo account locale è al sicuro.
+ L’esito del caricamento è incerto. Non creare altre copie. Scegli il backup esistente prima di riprovare.
+ Trovati più backup. Scegli il file; non è stata creata un’altra copia.
+ Backup salvato su Google Drive.
+
diff --git a/android/gplay/res/values-ja/waozi_drive.xml b/android/gplay/res/values-ja/waozi_drive.xml
new file mode 100644
index 0000000..b4c49be
--- /dev/null
+++ b/android/gplay/res/values-ja/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ アカウントのバックアップを選択
+ Google Drive から選択
+ 新しいバックアップを作成
+ Drive のバックアップはこの端末と異なります。保持するか、この端末の暗号化バックアップで置き換えますか?両方必要な場合は先にローカルコピーを保存してください。
+ Drive のバックアップを置換
+ Drive のバックアップを保持
+ 接続できません。端末のアカウントは安全です。接続後に再試行してください。
+ Google Drive へのアクセスを再度許可してください。選択した Google アカウントを確認してください。
+ Drive へのアクセスが拒否または取り消されました。正しいアカウントを選び、再度許可してください。
+ Drive が混雑しているか、リクエスト上限に達しました。後で再試行してください。
+ Google Drive の空き容量がありません。容量を確保して再試行してください。
+ バックアップがないか、別の Google アカウントに属しています。再度選択してください。
+ Drive のバックアップが変更されました。置換前に再度開いて確認してください。
+ 対応する暗号化 Waozi バックアップではありません。ファイルは変更していません。
+ このアプリの Google Drive 設定は未完了です。ローカルバックアップは利用できます。
+ Google Play 開発者サービスが利用できません。ローカルバックアップを使ってください。
+ Drive の操作を完了できませんでした。端末のアカウントは安全です。
+ アップロード結果が不明です。別のコピーは作らず、既存のバックアップを選んでから再試行してください。
+ 複数のバックアップがあります。ファイルを選んでください。新しいコピーは作成していません。
+ Google Drive にバックアップを保存しました。
+
diff --git a/android/gplay/res/values-ko/waozi_drive.xml b/android/gplay/res/values-ko/waozi_drive.xml
new file mode 100644
index 0000000..9544ea6
--- /dev/null
+++ b/android/gplay/res/values-ko/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ 계정 백업 선택
+ Google Drive에서 선택
+ 새 백업 만들기
+ Drive 백업이 이 기기와 다릅니다. 유지하거나 이 기기의 암호화된 백업으로 바꿀까요? 둘 다 필요하면 먼저 로컬 사본을 저장하세요.
+ Drive 백업 바꾸기
+ Drive 백업 유지
+ 연결되지 않았습니다. 로컬 계정은 안전합니다. 연결 후 다시 시도하세요.
+ Google Drive 접근을 다시 허용하세요. 선택한 Google 계정을 확인하세요.
+ Drive 접근이 거부되거나 취소되었습니다. 올바른 계정을 선택하고 다시 허용하세요.
+ Drive가 바쁘거나 요청 한도에 도달했습니다. 나중에 다시 시도하세요.
+ Google Drive가 가득 찼습니다. 공간을 확보하고 다시 시도하세요.
+ 백업이 없거나 다른 Google 계정에 속합니다. 다시 선택하세요.
+ Drive 백업이 변경되었습니다. 바꾸기 전에 다시 열어 확인하세요.
+ 지원되는 암호화 Waozi 백업이 아닙니다. 파일을 변경하지 않았습니다.
+ 이 앱의 Google Drive 설정이 완료되지 않았습니다. 로컬 백업은 사용할 수 있습니다.
+ Google Play 서비스를 사용할 수 없습니다. 로컬 백업을 사용하세요.
+ Drive 작업을 완료하지 못했습니다. 로컬 계정은 안전합니다.
+ 업로드 결과가 불확실합니다. 다른 사본을 만들지 마세요. 기존 백업을 선택한 후 다시 시도하세요.
+ 백업이 여러 개 있습니다. 파일을 선택하세요. 새 사본은 만들지 않았습니다.
+ Google Drive에 백업을 저장했습니다.
+
diff --git a/android/gplay/res/values-pt/waozi_drive.xml b/android/gplay/res/values-pt/waozi_drive.xml
new file mode 100644
index 0000000..ae59d26
--- /dev/null
+++ b/android/gplay/res/values-pt/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Escolha a cópia da sua conta
+ Escolher no Google Drive
+ Criar nova cópia
+ A cópia no Drive é diferente deste dispositivo. Manter ou substituir pela cópia criptografada deste dispositivo? Salve uma cópia local antes se precisar das duas.
+ Substituir cópia do Drive
+ Manter cópia do Drive
+ Sem conexão. Sua conta local está segura. Tente quando estiver online.
+ Autorize o Google Drive novamente. Verifique a conta Google selecionada.
+ Acesso ao Drive negado ou revogado. Escolha a conta correta e autorize novamente.
+ O Drive está ocupado ou atingiu o limite de solicitações. Tente mais tarde.
+ O Google Drive está cheio. Libere espaço e tente novamente.
+ A cópia não existe ou pertence a outra conta Google. Escolha novamente.
+ A cópia no Drive mudou. Abra e confira antes de substituir.
+ Esta não é uma cópia criptografada compatível do Waozi. Ela não foi alterada.
+ O Google Drive ainda não foi configurado neste app. Você pode salvar e abrir cópias locais.
+ Os serviços do Google Play estão indisponíveis. Use uma cópia local.
+ Não foi possível concluir a operação no Drive. Sua conta local está segura.
+ O resultado do envio é incerto. Não crie outra cópia. Escolha a cópia existente antes de tentar novamente.
+ Foram encontradas várias cópias. Escolha o arquivo; nenhuma nova cópia foi criada.
+ Cópia salva no Google Drive.
+
diff --git a/android/gplay/res/values-ru/waozi_drive.xml b/android/gplay/res/values-ru/waozi_drive.xml
new file mode 100644
index 0000000..7c4bca2
--- /dev/null
+++ b/android/gplay/res/values-ru/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Выберите резервную копию аккаунта
+ Выбрать в Google Drive
+ Создать новую копию
+ Копия на Drive отличается от этого устройства. Оставить её или заменить зашифрованной копией с устройства? Сначала сохраните локальную копию, если нужны обе.
+ Заменить копию на Drive
+ Оставить копию на Drive
+ Нет соединения. Локальный аккаунт в безопасности. Повторите после подключения.
+ Снова разрешите доступ к Google Drive. Проверьте выбранный аккаунт Google.
+ Доступ к Drive запрещён или отозван. Выберите верный аккаунт и разрешите доступ снова.
+ Drive занят или достигнут предел запросов. Повторите позже.
+ Google Drive заполнен. Освободите место и повторите.
+ Копия отсутствует или принадлежит другому аккаунту Google. Выберите её снова.
+ Копия на Drive изменилась. Откройте и проверьте её перед заменой.
+ Это неподдерживаемая зашифрованная копия Waozi. Файл не изменён.
+ Google Drive ещё не настроен для этого приложения. Можно использовать локальные копии.
+ Сервисы Google Play недоступны. Используйте локальную копию.
+ Не удалось завершить операцию Drive. Локальный аккаунт в безопасности.
+ Результат загрузки неизвестен. Не создавайте другую копию. Выберите существующую перед повтором.
+ Найдено несколько копий. Выберите файл; новая копия не создана.
+ Копия сохранена в Google Drive.
+
diff --git a/android/gplay/res/values-zh/waozi_drive.xml b/android/gplay/res/values-zh/waozi_drive.xml
new file mode 100644
index 0000000..3346f68
--- /dev/null
+++ b/android/gplay/res/values-zh/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ 选择账户备份
+ 从 Google Drive 选择
+ 创建新备份
+ Drive 备份与此设备不同。保留还是用此设备的加密备份替换?如需两份,请先保存本地副本。
+ 替换 Drive 备份
+ 保留 Drive 备份
+ 无法连接。本地账户安全,请联网后重试。
+ 请重新授权 Google Drive,并检查所选 Google 账户。
+ Drive 访问被拒绝或已撤销。请选择正确账户并重新授权。
+ Drive 繁忙或已达请求上限,请稍后重试。
+ Google Drive 已满,请释放空间后重试。
+ 备份不存在或属于另一个 Google 账户,请重新选择。
+ Drive 备份已更改。替换前请重新打开并检查。
+ 这不是受支持的加密 Waozi 备份,文件未被修改。
+ 此应用尚未完成 Google Drive 设置。您仍可使用本地备份。
+ Google Play 服务不可用,请使用本地备份。
+ 无法完成 Drive 操作,本地账户安全。
+ 上传结果不确定。请勿创建另一份副本,重试前请选择现有备份。
+ 找到多个备份。请选择文件,未创建新副本。
+ 备份已保存到 Google Drive。
+
diff --git a/android/gplay/res/values/waozi_drive.xml b/android/gplay/res/values/waozi_drive.xml
new file mode 100644
index 0000000..efe4ec0
--- /dev/null
+++ b/android/gplay/res/values/waozi_drive.xml
@@ -0,0 +1,23 @@
+
+
+ Choose your account backup
+ Choose from Google Drive
+ Create new backup
+ The Drive backup differs from this device. Keep it, or replace it with this device’s encrypted backup? Save a local copy first if you need both.
+ Replace Drive backup
+ Keep Drive backup
+ No connection. Your local account is safe. Try again when online.
+ Authorize Google Drive access again. Check the selected Google account.
+ Drive access was denied or revoked. Choose the correct account and authorize again.
+ Drive is busy or its request limit was reached. Try again later.
+ Google Drive is full. Free some space and try again.
+ The backup is missing or belongs to another Google account. Choose it again.
+ The Drive backup changed. Open it again and review before replacing.
+ This is not a supported encrypted Waozi backup. It was left unchanged.
+ Google Drive setup is not complete for this app. You can still save and open local backup files.
+ Google Play services are unavailable. Use a local backup file.
+ Could not complete the Drive operation. Your local account is safe.
+ The upload result is uncertain. Do not create another copy. Choose the existing backup before trying again.
+ More than one backup was found. Choose the file to use; no new copy was created.
+ Backup saved to Google Drive.
+
diff --git a/android/gplayTest/java/xyz/waozi/entity/DriveBackupTest.java b/android/gplayTest/java/xyz/waozi/entity/DriveBackupTest.java
new file mode 100644
index 0000000..1e8f354
--- /dev/null
+++ b/android/gplayTest/java/xyz/waozi/entity/DriveBackupTest.java
@@ -0,0 +1,34 @@
+package xyz.waozi.entity;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.test.InstrumentationTestCase;
+import java.lang.reflect.Method;
+
+/** Moto-only smoke test: deliberately refuses any configured Google account flow. */
+public final class DriveBackupTest extends InstrumentationTestCase {
+ public void testUnconfiguredPlayBackupCancelsWithoutGoogle() throws Exception {
+ android.content.Context target = getInstrumentation().getTargetContext();
+ int key = target.getResources().getIdentifier("waozi_drive_picker_key", "string", target.getPackageName());
+ assertTrue("This test requires an unconfigured Play build", key != 0 && target.getString(key).isEmpty());
+ Intent launcher = target.getPackageManager().getLaunchIntentForPackage(target.getPackageName());
+ assertNotNull(launcher);
+ assertEquals(Intent.ACTION_MAIN, launcher.getAction());
+ assertTrue(launcher.hasCategory(Intent.CATEGORY_LAUNCHER));
+ launcher.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ Activity activity = getInstrumentation().startActivitySync(launcher);
+ try {
+ Class> adapter = activity.getClassLoader().loadClass("xyz.waozi.entity.DriveBackup");
+ Method call = adapter.getMethod("call", Activity.class, String.class);
+ assertEquals("yes", call.invoke(null, activity, "available"));
+ assertTrue(((String) call.invoke(null, activity, "bad-request")).contains("invalid"));
+ assertTrue(((String) call.invoke(null, activity, "restore")).contains("pending"));
+ getInstrumentation().waitForIdleSync();
+ call.invoke(null, activity, "cancel");
+ getInstrumentation().waitForIdleSync();
+ assertTrue(((String) call.invoke(null, activity, "poll")).contains("cancelled"));
+ } finally {
+ getInstrumentation().runOnMainSync(activity::finish);
+ }
+ }
+}
diff --git a/android/tests/DriveBackupFlowTest.java b/android/tests/DriveBackupFlowTest.java
new file mode 100644
index 0000000..6c6677d
--- /dev/null
+++ b/android/tests/DriveBackupFlowTest.java
@@ -0,0 +1,111 @@
+package xyz.waozi.entity;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+public final class DriveBackupFlowTest {
+ private static byte[] sealed(char c) {
+ return (DriveBackupFlow.PREFIX + repeat('a', 32) + "\nnonce=" + repeat('b', 24)
+ + "\nciphertext=" + repeat(c, 160) + "\n").getBytes(StandardCharsets.UTF_8);
+ }
+ private static String repeat(char c, int n) {
+ char[] chars = new char[n];
+ java.util.Arrays.fill(chars, c);
+ return new String(chars);
+ }
+ private static void check(boolean condition) {
+ if (!condition) {
+ throw new AssertionError();
+ }
+ }
+ private interface Job { void run() throws IOException; }
+ private static void fails(String code, Job job) throws IOException {
+ try {
+ job.run();
+ throw new AssertionError("Expected " + code);
+ } catch (DriveBackupFlow.Failure error) {
+ check(code.equals(error.code));
+ }
+ }
+ private static final class Fake implements DriveBackupFlow.Transport {
+ List files = new ArrayList<>();
+ DriveBackupFlow.Blob blob = new DriveBackupFlow.Blob(new DriveBackupFlow.File("id1", "renamed", "1"), sealed('a'));
+ int reads;
+ int creates;
+ int writes;
+ String failure;
+ @Override public List list() throws IOException {
+ if (failure != null) {
+ throw new DriveBackupFlow.Failure(failure);
+ }
+ return files;
+ }
+ @Override public DriveBackupFlow.Blob read(String id) throws IOException {
+ reads++;
+ if (failure != null) {
+ throw new DriveBackupFlow.Failure(failure);
+ }
+ check(id.equals(blob.file.id));
+ return blob;
+ }
+ @Override public DriveBackupFlow.File create(byte[] bytes) {
+ creates++;
+ check(java.util.Arrays.equals(bytes, sealed('b')));
+ return new DriveBackupFlow.File("id2", DriveBackupFlow.NAME, "1");
+ }
+ @Override public DriveBackupFlow.File replace(String id, String version, byte[] bytes) {
+ writes++;
+ check(reads > 0 && id.equals(blob.file.id) && version.equals(blob.file.version));
+ check(java.util.Arrays.equals(bytes, sealed('b')));
+ return new DriveBackupFlow.File(id, blob.file.name, "2");
+ }
+ }
+ public static void main(String[] args) throws IOException {
+ check(DriveBackupFlow.sealed(sealed('a')));
+ check(!DriveBackupFlow.sealed("plain-private-key".getBytes(StandardCharsets.UTF_8)));
+ check(!DriveBackupFlow.sealed(new byte[17664]));
+ check(!DriveBackupFlow.sealed(new String(sealed('a'), StandardCharsets.UTF_8).replace("v3", "v4").getBytes(StandardCharsets.UTF_8)));
+ check(!DriveBackupFlow.sealed(new String(sealed('a'), StandardCharsets.UTF_8).replace("salt=aa", "salt=zz").getBytes(StandardCharsets.UTF_8)));
+ check(!DriveBackupFlow.sealed(new String(sealed('a'), StandardCharsets.UTF_8).replace("passes=3", "passes=9").getBytes(StandardCharsets.UTF_8)));
+ check(!DriveBackupFlow.sealed((new String(sealed('a'), StandardCharsets.UTF_8) + "garbage").getBytes(StandardCharsets.UTF_8)));
+ Fake fake = new Fake();
+ DriveBackupFlow flow = new DriveBackupFlow(fake);
+ check(flow.candidates().isEmpty() && fake.creates == 0);
+ check(flow.create(sealed('b')).id.equals("id2") && fake.creates == 1);
+ fake.files.add(fake.blob.file);
+ fails("duplicate", () -> flow.create(sealed('b')));
+ fake.files.add(new DriveBackupFlow.File("id3", fake.blob.file.name, "3"));
+ check(flow.candidates().size() == 2 && fake.writes == 0);
+ fails("duplicate", () -> flow.create(sealed('b')));
+ check(fake.creates == 1);
+ DriveBackupFlow.Blob compared = flow.read("id1");
+ check(flow.replace(compared, sealed('a')).version.equals("1") && fake.writes == 0);
+ check(flow.replace(compared, sealed('b')).version.equals("2") && fake.writes == 1);
+ fake.blob = new DriveBackupFlow.Blob(new DriveBackupFlow.File("id1", "renamed again", "2"), sealed('a'));
+ fails("changed", () -> flow.replace(compared, sealed('b')));
+ check(fake.writes == 1);
+ // Bytes changed while version is unexpectedly unchanged: still no silent overwrite.
+ fake.blob = new DriveBackupFlow.Blob(compared.file, sealed('c'));
+ fails("changed", () -> flow.replace(compared, sealed('b')));
+ fake.blob = new DriveBackupFlow.Blob(compared.file, "unknown-envelope".getBytes(StandardCharsets.UTF_8));
+ fails("invalid", () -> flow.replace(compared, sealed('b')));
+ for (String code : new String[]{"offline", "missing", "unauthorized", "forbidden", "quota", "full", "uncertain"}) {
+ fake.failure = code;
+ fails(code, () -> flow.read("id1"));
+ fails(code, () -> flow.create(sealed('b')));
+ }
+ check(fake.writes == 1 && fake.creates == 1);
+ check(DriveBackupFlow.failure(401, "").equals("unauthorized"));
+ check(DriveBackupFlow.failure(403, "storageQuotaExceeded").equals("full"));
+ check(DriveBackupFlow.failure(403, "rateLimitExceeded").equals("quota"));
+ check(DriveBackupFlow.failure(403, "userRateLimitExceeded").equals("quota"));
+ check(DriveBackupFlow.failure(403, "revoked").equals("forbidden"));
+ check(DriveBackupFlow.failure(404, "").equals("missing"));
+ check(DriveBackupFlow.failure(412, "").equals("changed"));
+ check(DriveBackupFlow.failure(429, "").equals("quota"));
+ check(DriveBackupFlow.failure(503, "").equals("offline"));
+ System.out.println("Drive fake-transport tests passed: envelope bounds, duplicates, rename/ID, compare before replace, changed bytes/revision, failures.");
+ }
+}
diff --git a/android/tests/test_adapter.py b/android/tests/test_adapter.py
new file mode 100644
index 0000000..ad2d623
--- /dev/null
+++ b/android/tests/test_adapter.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+"""No Google account, SDK, network, or desktop required."""
+from pathlib import Path
+import subprocess
+import xml.etree.ElementTree as ET
+
+root = Path(__file__).resolve().parents[2]
+output = root / 'build/drive-test'
+output.mkdir(parents=True, exist_ok=True)
+source = root / 'android/gplay/java/xyz/waozi/entity'
+subprocess.run(['javac', '-d', str(output), str(source / 'DriveBackupFlow.java'),
+ str(root / 'android/tests/DriveBackupFlowTest.java')], check=True)
+subprocess.run(['java', '-ea', '-cp', str(output), 'xyz.waozi.entity.DriveBackupFlowTest'], check=True)
+# Enforce the edition boundary and the only permitted scope.
+for path in (root / 'android').rglob('*.java'):
+ if '/tests/' in str(path) or '/gplayTest/' in str(path):
+ continue
+ assert '/gplay/' in str(path), path
+activity = (source / 'DriveActivity.java').read_text()
+assert activity.count('https://www.googleapis.com/auth/') == 1
+assert 'https://www.googleapis.com/auth/drive.file' in activity
+assert 'addJavascriptInterface' not in activity
+assert 'setAllowFileAccess(false)' in activity
+rest = (source / 'DriveRest.java').read_text()
+assert 'setInstanceFollowRedirects(false)' in rest
+assert '"Authorization", "Bearer " + token' in rest
+assert '"pending_create"' in rest
+assert 'appDataFolder' not in rest
+assert 'private_key' not in rest
+print('Drive edition, Picker bridge, bounded REST and scope contracts passed.')
+
+translations = list((root / 'android/gplay/res').glob('values*/waozi_drive.xml'))
+assert len(translations) == 12
+base = {node.attrib['name'] for node in ET.parse(root / 'android/gplay/res/values/waozi_drive.xml').getroot()}
+for translation in translations:
+ assert {node.attrib['name'] for node in ET.parse(translation).getroot()} == base, translation
+assert activity.index('config("picker_key").isEmpty()') < activity.index('startActivityForResult(android.accounts.AccountManager')
+print('All 12 Drive locales complete; unconfigured builds stop before authorization.')
diff --git a/src/drive_backup.zi b/src/drive_backup.zi
new file mode 100644
index 0000000..8297cc1
--- /dev/null
+++ b/src/drive_backup.zi
@@ -0,0 +1,143 @@
+// Optional sealed-backup transport. Normal/F-Droid builds do not reference a
+// Google class, scope or Android adapter. The adapter receives sealed v3 only.
+#import "recovery"
+#import "daochi_client/keys"
+#import "std/text_buffer"
+#import "std/c_string"
+#import "std/byte_text_linux"
+Json :: #import "std/json_scan";
+#if #defined(ANDROID_BUILD) && #defined(GOOGLE_PLAY) {
+ #import "kryon/android_jni"
+}
+
+DriveBackupAvailable :: () -> bool {
+ output: [32]u8
+ return DriveAndroidCall("available", output[:]) == "yes"
+}
+
+// Only the existing sealed v3 bytes cross the Java boundary.
+DriveBackupStart :: (value: *Recovery, passphrase: string) -> bool {
+ sealed: [ACCOUNT_EXPORT_ENCRYPTED_TEXT_SIZE]u8
+ defer { SecureWipe(*sealed[0], sealed.count) }
+ if !RecoveryEncode(value, passphrase, sealed[:]) || !RecoverySealedParse(TextUntilNul(sealed[:])).valid { return false }
+ request: [17800]u8
+ prefix := "save\n"
+ text := TextUntilNul(sealed[:])
+ for byte, index: prefix { request[index] = byte }
+ for byte, index: text { request[prefix.count + index] = byte }
+ output: [128]u8
+ answer := DriveAndroidCall(TextView(request[:prefix.count + text.count]), output[:])
+ return Json.MatchLiteral(answer, Json.FieldAt(answer, 0, "status"), "\"pending\"")
+}
+
+DriveBackupCancel :: () {
+ output: [128]u8
+ unused DriveAndroidCall("cancel", output[:])
+}
+
+DriveImportStart :: () -> bool {
+ output: [128]u8
+ answer := DriveAndroidCall("restore", output[:])
+ return Json.MatchLiteral(answer, Json.FieldAt(answer, 0, "status"), "\"pending\"")
+}
+
+// false while authorization, Picker or a bounded REST request is in progress.
+DriveBackupPoll :: (status: []u8, content: []u8) -> bool {
+ output: [20000]u8
+ answer := DriveAndroidCall("poll", output[:])
+ if Json.ReadStringText(answer, Json.FieldAt(answer, 0, "status"), status) <= 0 {
+ unused CopyCString("error", status)
+ return true
+ }
+ pending := TextUntilNul(status) == "pending"
+ restored := TextUntilNul(status) == "restored"
+ if pending { return false }
+ if restored {
+ if Json.ReadStringText(answer, Json.FieldAt(answer, 0, "content"), content) <= 0 ||
+ !RecoverySealedParse(TextUntilNul(content)).valid {
+ unused CopyCString("invalid", status)
+ }
+ }
+ return true
+}
+
+DriveAndroidCall :: (request: string, output: []u8) -> string {
+ #if #defined(ANDROID_BUILD) && #defined(GOOGLE_PLAY) {
+ text: [17800]u8
+ if !CopyCString(request, text[:]) { return "" }
+ session: AndroidJniSession
+ if AndroidJniAttachCurrent(*session) == 0 { return "" }
+ defer { AndroidJniDetachCurrent(*session) }
+ env := session.env
+ // The activity's class loader finds the Play-only class, so apps need
+ // no bridge code: an edition without it simply answers "".
+ adapter := DriveAndroidClass(env, session.activity)
+ if adapter == null { return "" }
+ defer { env.functions.DeleteLocalRef(env, adapter) }
+ name_1: [8]u8
+ name_2: [80]u8
+ method := env.functions.GetStaticMethodID(env, adapter, DriveAndroidName("call", name_1[:]),
+ DriveAndroidName("(Landroid/app/Activity;Ljava/lang/String;)Ljava/lang/String;", name_2[:]))
+ if method == null { DriveAndroidClear(env); return "" }
+ arguments: [2]JniValue
+ arguments[0].reference = session.activity
+ arguments[1].reference = AndroidJniString(env, *text[0])
+ if arguments[1].reference == null { return "" }
+ defer { env.functions.DeleteLocalRef(env, arguments[1].reference) }
+ value := env.functions.CallStaticObjectMethodA(env, adapter, method, *arguments[0])
+ if DriveAndroidClear(env) || value == null { return "" }
+ defer { env.functions.DeleteLocalRef(env, value) }
+ bytes := env.functions.GetStringUTFChars(env, value, null)
+ if bytes == null { return "" }
+ defer { env.functions.ReleaseStringUTFChars(env, value, bytes) }
+ answer := TextFromCString(bytes)
+ if !CopyCString(answer, output) { return "" }
+ return TextView(output[:answer.count])
+ }
+ unused request
+ unused output
+ return ""
+}
+
+#if #defined(ANDROID_BUILD) && #defined(GOOGLE_PLAY) {
+ // A NUL-terminated copy for JNI names and signatures.
+ DriveAndroidName :: (text: string, output: []u8) -> *u8 {
+ if !CopyCString(text, output) { return null }
+ return *output[0]
+ }
+
+ DriveAndroidClear :: (env: *JniEnv) -> bool {
+ if env.functions.ExceptionCheck(env) == 0 { return false }
+ env.functions.ExceptionClear(env)
+ return true
+ }
+
+ // xyz.waozi.entity.DriveBackup through the activity's class loader, or null.
+ DriveAndroidClass :: (env: *JniEnv, activity: *void) -> *void {
+ activity_class := env.functions.GetObjectClass(env, activity)
+ if activity_class == null { return null }
+ defer { env.functions.DeleteLocalRef(env, activity_class) }
+ name_3: [24]u8
+ name_4: [40]u8
+ get_loader := env.functions.GetMethodID(env, activity_class, DriveAndroidName("getClassLoader", name_3[:]), DriveAndroidName("()Ljava/lang/ClassLoader;", name_4[:]))
+ if get_loader == null { DriveAndroidClear(env); return null }
+ loader := env.functions.CallObjectMethodA(env, activity, get_loader, null)
+ if DriveAndroidClear(env) || loader == null { return null }
+ defer { env.functions.DeleteLocalRef(env, loader) }
+ loader_class := env.functions.GetObjectClass(env, loader)
+ if loader_class == null { return null }
+ defer { env.functions.DeleteLocalRef(env, loader_class) }
+ name_5: [16]u8
+ name_6: [48]u8
+ load := env.functions.GetMethodID(env, loader_class, DriveAndroidName("loadClass", name_5[:]), DriveAndroidName("(Ljava/lang/String;)Ljava/lang/Class;", name_6[:]))
+ if load == null { DriveAndroidClear(env); return null }
+ arguments: [1]JniValue
+ name_7: [48]u8
+ arguments[0].reference = AndroidJniString(env, DriveAndroidName("xyz.waozi.entity.DriveBackup", name_7[:]))
+ if arguments[0].reference == null { return null }
+ defer { env.functions.DeleteLocalRef(env, arguments[0].reference) }
+ billing := env.functions.CallObjectMethodA(env, loader, load, *arguments[0])
+ if DriveAndroidClear(env) { return null }
+ return billing
+ }
+}
diff --git a/tests/drive_backup_test.zi b/tests/drive_backup_test.zi
new file mode 100644
index 0000000..63b9793
--- /dev/null
+++ b/tests/drive_backup_test.zi
@@ -0,0 +1,32 @@
+// Normal editions must not discover or invoke the Play adapter.
+#import "drive_backup"
+#import "management"
+#import "model"
+#import "std/c_string"
+
+#program_export
+main :: () -> s32 {
+ if DriveBackupAvailable() { return 1 }
+ if DriveImportStart() { return 2 }
+ state: Management
+ state.available = true
+ state.capabilities = 2047
+ encoded := ManagementEncode(state)
+ defer { EntityFree(encoded) }
+ decoded: Management
+ if !ManagementDecode(encoded, *decoded) || decoded.capabilities != 2047 { return 3 }
+ state.capabilities = 8191
+ all := ManagementEncode(state)
+ defer { EntityFree(all) }
+ if !ManagementDecode(all, *decoded) || decoded.capabilities != 8191 { return 4 }
+ if ManagementOperation("drive_import") != ACCOUNT_DRIVE || ManagementOperation("drive_backup") != ACCOUNT_DRIVE { return 5 }
+ request: ManagementRequest
+ request.sequence = 1
+ unused CopyCString("drive_import", request.operation[:])
+ text := ManagementRequestEncode(request)
+ defer { EntityFree(text) }
+ queue: ManagementQueue
+ if ManagementEnqueue(*queue, text, 2047) { return 6 }
+ if !ManagementEnqueue(*queue, text, ACCOUNT_DRIVE) { return 7 }
+ return 0
+}