diff --git a/AGENTS.md b/AGENTS.md
index 34ebedfa..7d0924bc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -841,6 +841,29 @@ whole arrangement leans on two private details of it - `_evt_loop.run_until_comp
fetcher looking `fetch_raw_reports` up on the instance - and a fake keeps both names after a rename
(rule 3).
+### 23. A DataStore write starts when you call it, not when you subscribe
+
+`RxDataStore.updateDataAsync` runs `scope.async { … }.asSingle()`, and `async` starts at once. So
+every repository method built on it (`UserAuthRepository.clearUser`, `storeUserAuth`,
+`KeychainMembershipRepository.forget`, `UserDataRepository.forgetLastCameraPosition`, settings
+writes) has **already begun writing by the time it returns its Completable**. Subscribing only
+waits for it.
+
+That makes `a.andThen(repo.clearUser())` a trap. It reads as "clear the user once `a` succeeds",
+but `clearUser()` is evaluated while the chain is being built, so the session is cleared whether
+`a` succeeds, fails, or is never subscribed at all. Nothing fails and nothing logs. On the happy
+path it looks right, which is the only path anyone tries by hand.
+
+It bit twice, independently: `MapsActivity.offerLocalAnisetteUpgradeIfDue` signed the user out
+before the local Anisette choice was saved, and Settings signed the user out after telling them an
+erase had failed and they were still signed in (caught by
+`ErasingEverythingFromSettingsTest.aFailedEraseDoesNotSignOut`). **Use
+`RxFlows.onlyAfter(first, repo::clearUser)`**, which takes the second step as a supplier and only
+calls it once `first` completes, and wrap a chain's own first step in `Completable.defer(...)` if
+the chain is built before anything subscribes. When the order matters, test the failure path,
+because the success path cannot tell the two apart. `RxFlowsTest` shows how, with a stand-in that
+writes when called.
+
---
## Building and testing
diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/RemovingATagForgetsItsKeysTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/RemovingATagForgetsItsKeysTest.java
new file mode 100644
index 00000000..69c73239
--- /dev/null
+++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/RemovingATagForgetsItsKeysTest.java
@@ -0,0 +1,433 @@
+package dev.wander.android.opentagviewer.db.repo;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import android.database.Cursor;
+
+import androidx.room.Room;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import dev.wander.android.opentagviewer.data.model.BeaconLocationReport;
+
+import dev.wander.android.opentagviewer.db.repo.model.ImportData;
+import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase;
+import dev.wander.android.opentagviewer.db.room.entity.BeaconNamingRecord;
+import dev.wander.android.opentagviewer.db.room.entity.DailyHistoryFetchRecord;
+import dev.wander.android.opentagviewer.db.room.entity.Import;
+import dev.wander.android.opentagviewer.db.room.entity.LastBleSighting;
+import dev.wander.android.opentagviewer.db.room.entity.LocationReport;
+import dev.wander.android.opentagviewer.db.room.entity.OwnedBeacon;
+import dev.wander.android.opentagviewer.db.room.entity.UserBeaconOptions;
+import dev.wander.android.opentagviewer.python.FetchResult;
+import dev.wander.android.opentagviewer.python.icloud.AccessoryRecords;
+
+/**
+ * What removing a tag leaves behind on the phone.
+ *
+ *
It used to leave everything. Remove only set {@code is_removed}, so the private key
+ * and shared secrets of every tag ever removed stayed in the database, enough to locate the tag
+ * until it was paired again. Somebody removing a tag they sold or handed back expects them gone.
+ *
+ *
The history is a different question, and the answer is the user's: kept (hidden) by default,
+ * so a tag removed by mistake comes back whole when imported again, or deleted with the row when
+ * they tick the box. Both paths are pinned here, along with "erase all data".
+ *
+ *
An in-memory database, never the real one: {@link BeaconRepository#eraseEverything} on the
+ * on-device database would take a developer's own tags with it.
+ */
+@RunWith(AndroidJUnit4.class)
+public class RemovingATagForgetsItsKeysTest {
+
+ private static final String THE_TAG = "sold-tag";
+ private static final String ITS_SIBLING = "kept-tag";
+
+ private static final String A_PLIST = ""
+ + "privateKeybm90LWEtcmVhbC1rZXk=";
+ private static final String AN_ALIGNMENT = ""
+ + "lastIndexObserved1234";
+ private static final String ACCESSORY_JSON = "{\"type\":\"accessory\",\"master_key\":\"x\"}";
+ /** What a fetch hands back: the same keys, with the alignment moved on. */
+ private static final String ALIGNED_JSON =
+ "{\"type\":\"accessory\",\"master_key\":\"x\",\"alignment\":5678}";
+
+ private OpenTagViewerDatabase db;
+ private BeaconRepository repo;
+
+ @Before
+ public void openAnInMemoryDatabase() {
+ this.db = Room.inMemoryDatabaseBuilder(
+ getInstrumentation().getTargetContext(), OpenTagViewerDatabase.class)
+ .allowMainThreadQueries()
+ .build();
+ this.repo = new BeaconRepository(this.db, (plist, alignment) -> ACCESSORY_JSON);
+ }
+
+ @After
+ public void closeIt() {
+ this.db.close();
+ }
+
+ // ---- arranging ----------------------------------------------------------------------------
+
+ private static OwnedBeacon aTag(final String id) {
+ return OwnedBeacon.builder()
+ .id(id)
+ .content(A_PLIST)
+ .alignmentPlist(AN_ALIGNMENT)
+ .accessoryJson(ACCESSORY_JSON)
+ .version("0.0.2")
+ .isRemoved(false)
+ .fromAccount(false)
+ .build();
+ }
+
+ private static BeaconNamingRecord itsName(final String id) {
+ return BeaconNamingRecord.builder()
+ .id(id)
+ .version("0.0.2")
+ .isRemoved(false)
+ .content("name" + id + "")
+ .build();
+ }
+
+ /** One zip, holding the given tags, as the importer would store it. */
+ private void importAZipOf(final String... ids) {
+ final List beacons = new ArrayList<>();
+ final List names = new ArrayList<>();
+ for (final String id : ids) {
+ beacons.add(aTag(id));
+ names.add(itsName(id));
+ }
+ this.repo.addNewImport(new ImportData(
+ Import.builder()
+ .version("0.0.2")
+ .importedAt(2_000L)
+ .exportedAt(1_000L)
+ .sourceUser("someone@example.invalid")
+ .exportedVia("OpenTagViewer.cli:test")
+ .build(),
+ beacons,
+ names)).blockingFirst();
+ }
+
+ private void givenItHasHistory(final String id) {
+ this.db.locationReportDao().insertAll(LocationReport.builder()
+ .hashId("report-" + id)
+ .beaconId(id)
+ .publishedAt(1_000L)
+ .description("Wi-Fi")
+ .timestamp(1_000L)
+ .confidence(0)
+ .latitude(52.370216)
+ .longitude(4.895168)
+ .horizontalAccuracy(83)
+ .status(144)
+ .lastUpdate(1_000L)
+ .provenance(LocationReport.PROVENANCE_APPLE)
+ .build());
+ this.db.dailyHistoryFetchRecordDao().insertAll(DailyHistoryFetchRecord.builder()
+ .beaconId(id)
+ .dayStartTime(0L)
+ .lastUpdate(1_000L)
+ .build());
+ this.db.lastBleSightingDao().insert(LastBleSighting.builder()
+ .beaconId(id)
+ .heardAt(1_000L)
+ .batteryLevel("FULL")
+ .statusByte(0)
+ .build());
+ this.db.userBeaconOptionsDao().insertAll(UserBeaconOptions.builder()
+ .beaconId(id)
+ .lastUpdate(1_000L)
+ .uiName("My keys")
+ .uiEmoji("🔑")
+ .build());
+ }
+
+ // ---- looking ------------------------------------------------------------------------------
+
+ /** The row as it is on disk, removed or not - the DAO's getters hide removed rows. */
+ private String[] storedKeysOf(final String id) {
+ try (Cursor row = this.db.query(
+ "SELECT content, accessory_json, alignment_plist FROM OwnedBeacons WHERE id = ?",
+ new Object[] {id})) {
+ if (!row.moveToFirst()) {
+ return null;
+ }
+ return new String[] {row.getString(0), row.getString(1), row.getString(2)};
+ }
+ }
+
+ private int countWhere(final String table, final String column, final String value) {
+ try (Cursor c = this.db.query(
+ "SELECT COUNT(*) FROM " + table + " WHERE " + column + " = ?",
+ new Object[] {value})) {
+ c.moveToFirst();
+ return c.getInt(0);
+ }
+ }
+
+ private int count(final String table) {
+ try (Cursor c = this.db.query("SELECT COUNT(*) FROM " + table, new Object[0])) {
+ c.moveToFirst();
+ return c.getInt(0);
+ }
+ }
+
+ private int historyRowsFor(final String id) {
+ return countWhere("LocationReport", "beacon_id", id);
+ }
+
+ // ---- the behaviour ------------------------------------------------------------------------
+
+ /**
+ * The audit finding. Plain Remove deletes the key material, and keeps the history.
+ */
+ @Test
+ public void removingDeletesTheKeysAndKeepsTheHistoryHidden() {
+ this.importAZipOf(THE_TAG);
+ this.givenItHasHistory(THE_TAG);
+
+ this.repo.removeBeacon(THE_TAG, false).blockingAwait();
+
+ final String[] keys = this.storedKeysOf(THE_TAG);
+ assertNotNull("the row should stay, hidden, so its history has something to belong to",
+ keys);
+ assertNull("the exported plist (the private key) is still stored", keys[0]);
+ assertNull("FindMy.py's accessory state (the same keys) is still stored", keys[1]);
+ assertNull("the key alignment record is still stored", keys[2]);
+
+ assertNull("a removed tag must not be listed", this.db.ownedBeaconDao().getById(THE_TAG));
+ assertEquals("plain Remove should keep the history, as it always has",
+ 1, this.historyRowsFor(THE_TAG));
+ assertNotNull("plain Remove should keep the user's name for it",
+ this.db.userBeaconOptionsDao().getById(THE_TAG));
+ }
+
+ /**
+ * Keeping the history is only worth it if importing the tag again brings it back, keys and
+ * all. This is the behaviour plain Remove exists to preserve.
+ */
+ @Test
+ public void importingARemovedTagAgainBringsBackItsKeysAndItsHistory() {
+ this.importAZipOf(THE_TAG);
+ this.givenItHasHistory(THE_TAG);
+ this.repo.removeBeacon(THE_TAG, false).blockingAwait();
+
+ this.importAZipOf(THE_TAG);
+
+ final OwnedBeacon back = this.db.ownedBeaconDao().getById(THE_TAG);
+ assertNotNull("the re-imported tag should be listed again", back);
+ assertEquals(A_PLIST, back.content);
+ assertEquals(AN_ALIGNMENT, back.alignmentPlist);
+ assertEquals(ACCESSORY_JSON, back.accessoryJson);
+ assertEquals("its history should have come back with it", 1, this.historyRowsFor(THE_TAG));
+ }
+
+ /** Ticking the box deletes the row and everything that hangs off it. */
+ @Test
+ public void removingWithTheHistoryDeletesEverythingAboutTheTag() {
+ this.importAZipOf(THE_TAG);
+ this.givenItHasHistory(THE_TAG);
+
+ this.repo.removeBeacon(THE_TAG, true).blockingAwait();
+
+ assertNull("the row itself, keys included, should be gone", this.storedKeysOf(THE_TAG));
+ assertEquals("location history", 0, this.historyRowsFor(THE_TAG));
+ assertEquals("fetched-day records",
+ 0, this.countWhere("DailyHistoryFetchRecord", "beacon_id", THE_TAG));
+ assertEquals("last Bluetooth sighting",
+ 0, this.countWhere("LastBleSighting", "beacon_id", THE_TAG));
+ assertEquals("the user's name and emoji",
+ 0, this.countWhere("UserBeaconOptions", "beacon_id", THE_TAG));
+ assertEquals("the naming record from the export",
+ 0, this.countWhere("BeaconNamingRecord", "id", THE_TAG));
+ assertEquals("the import, which only held this tag, still records who exported it",
+ 0, this.count("Import"));
+ }
+
+ /**
+ * Erasing one tag of a zip leaves the rest of that zip alone, its import row included -
+ * deleting the import would cascade into the other tags.
+ */
+ @Test
+ public void erasingOneTagLeavesTheOthersFromTheSameZip() {
+ this.importAZipOf(THE_TAG, ITS_SIBLING);
+ this.givenItHasHistory(THE_TAG);
+ this.givenItHasHistory(ITS_SIBLING);
+
+ this.repo.removeBeacon(THE_TAG, true).blockingAwait();
+
+ assertNotNull("the other tag from the same zip was taken too",
+ this.db.ownedBeaconDao().getById(ITS_SIBLING));
+ assertEquals(1, this.historyRowsFor(ITS_SIBLING));
+ assertEquals("the import still has a tag, so it stays", 1, this.count("Import"));
+ assertFalse(this.db.beaconNamingRecordDao().getAll().isEmpty());
+ }
+
+ /**
+ * A removed tag still points at its import, so erasing its sibling must not delete that
+ * import: it would cascade into the hidden row, and the history plain Remove promised to keep.
+ */
+ @Test
+ public void anImportAHiddenTagStillPointsAtIsKept() {
+ this.importAZipOf(THE_TAG, ITS_SIBLING);
+ this.givenItHasHistory(ITS_SIBLING);
+ this.repo.removeBeacon(ITS_SIBLING, false).blockingAwait();
+
+ this.repo.removeBeacon(THE_TAG, true).blockingAwait();
+
+ assertEquals(1, this.count("Import"));
+ assertEquals("the hidden tag's history went with an import that should have stayed",
+ 1, this.historyRowsFor(ITS_SIBLING));
+ }
+
+ /**
+ * Multi-select removes several tags in one call, so the file is compacted once. It must do to
+ * each tag exactly what removing it alone does.
+ */
+ @Test
+ public void removingSeveralAtOnceForgetsEveryOnesKeys() {
+ this.importAZipOf(THE_TAG, ITS_SIBLING);
+ this.givenItHasHistory(THE_TAG);
+ this.givenItHasHistory(ITS_SIBLING);
+
+ this.repo.removeBeacons(List.of(THE_TAG, ITS_SIBLING), false).blockingAwait();
+
+ for (final String id : new String[] {THE_TAG, ITS_SIBLING}) {
+ final String[] keys = this.storedKeysOf(id);
+ assertNotNull(id + " should stay, hidden", keys);
+ assertNull(id + "'s plist is still stored", keys[0]);
+ assertNull(id + "'s accessory state is still stored", keys[1]);
+ assertNull(id + "'s alignment record is still stored", keys[2]);
+ assertEquals(id + "'s history should be kept", 1, this.historyRowsFor(id));
+ }
+ }
+
+ /** And with the box ticked, the import goes once the last of its tags has. */
+ @Test
+ public void erasingAWholeZipAtOnceDeletesItsImport() {
+ this.importAZipOf(THE_TAG, ITS_SIBLING);
+ this.givenItHasHistory(THE_TAG);
+ this.givenItHasHistory(ITS_SIBLING);
+
+ this.repo.removeBeacons(List.of(THE_TAG, ITS_SIBLING), true).blockingAwait();
+
+ assertNull(this.storedKeysOf(THE_TAG));
+ assertNull(this.storedKeysOf(ITS_SIBLING));
+ assertEquals(0, this.count("LocationReport"));
+ assertEquals(0, this.count("BeaconNamingRecord"));
+ assertEquals("the import outlived every tag it held", 0, this.count("Import"));
+ }
+
+ /**
+ * A tag from a zip that later arrived from the Apple account has its row moved off the import,
+ * but keeps the zip's naming record when the account holds none. Erasing the other tag from
+ * that zip must not delete the import, which would cascade into that naming record and take
+ * the account tag's name with it.
+ */
+ @Test
+ public void anImportANamingRecordStillPointsAtIsKept() {
+ this.importAZipOf(THE_TAG, ITS_SIBLING);
+ // (beaconId, ownedBeaconPlist, namingRecordPlist, keyAlignmentPlist): no naming record.
+ this.repo.refreshAccountBeacons(
+ List.of(new AccessoryRecords(ITS_SIBLING, A_PLIST, null, AN_ALIGNMENT)))
+ .blockingFirst();
+
+ this.repo.removeBeacon(THE_TAG, true).blockingAwait();
+
+ assertNotNull("the account tag lost the name it had from the zip",
+ this.db.beaconNamingRecordDao().getByBeaconId(ITS_SIBLING));
+ assertEquals("the import still has a naming record, so it stays", 1, this.count("Import"));
+ }
+
+ /**
+ * A fetch already running when the tag was removed. It lands afterwards carrying the
+ * tag's freshly aligned accessory JSON, which is the same keys Remove has just deleted. It must
+ * not write them back onto the hidden row; the tag still listed beside it is updated as usual.
+ */
+ @Test
+ public void aFetchThatLandsAfterRemovalDoesNotWriteTheKeysBack() {
+ this.importAZipOf(THE_TAG, ITS_SIBLING);
+ this.repo.removeBeacon(THE_TAG, false).blockingAwait();
+
+ this.repo.storeFetchResult(new FetchResult(
+ Map.of(THE_TAG, List.of(), ITS_SIBLING, List.of()),
+ Map.of(THE_TAG, ALIGNED_JSON, ITS_SIBLING, ALIGNED_JSON),
+ Set.of(), Set.of())).blockingFirst();
+
+ assertNull("a fetch that was in flight put the removed tag's keys back",
+ this.storedKeysOf(THE_TAG)[1]);
+ assertEquals("the tag that was not removed should still get its new alignment",
+ ALIGNED_JSON, this.storedKeysOf(ITS_SIBLING)[1]);
+ }
+
+ /**
+ * The same for a Bluetooth sighting, which reads the row before deriving and writes after,
+ * so a removal can land in between. {@code recordAccessorySighting} ends in this write.
+ */
+ @Test
+ public void aSightingThatLandsAfterRemovalDoesNotWriteTheKeysBack() {
+ this.importAZipOf(THE_TAG);
+ this.repo.removeBeacon(THE_TAG, false).blockingAwait();
+
+ this.db.ownedBeaconDao().updateAccessoryJson(THE_TAG, ALIGNED_JSON);
+
+ assertNull(this.storedKeysOf(THE_TAG)[1]);
+ }
+
+ /**
+ * A fetch that lands after its tag was erased has reports for a row that no longer exists.
+ * One such report fails {@code LocationReport}'s foreign key and with it the whole insert, so
+ * the other tags fetched alongside lost their reports too.
+ */
+ @Test
+ public void aFetchThatLandsAfterTheTagWasErasedStillStoresTheOthers() {
+ this.importAZipOf(THE_TAG, ITS_SIBLING);
+ this.repo.removeBeacon(THE_TAG, true).blockingAwait();
+
+ final List aReport = List.of(BeaconLocationReport.builder()
+ .timestamp(5_000L).publishedAt(5_000L).description("somewhere")
+ .latitude(52.370216).longitude(4.895168).build());
+ this.repo.storeFetchResult(new FetchResult(
+ Map.of(THE_TAG, aReport, ITS_SIBLING, aReport),
+ Map.of(), Set.of(), Set.of())).blockingFirst();
+
+ assertEquals("the erased tag's report should be dropped", 0, this.historyRowsFor(THE_TAG));
+ assertEquals("the other tag's report went down with the erased one's",
+ 1, this.historyRowsFor(ITS_SIBLING));
+ assertNull("the erased tag came back", this.storedKeysOf(THE_TAG));
+ }
+
+ /** Settings -> Erase all data, as far as the database goes. */
+ @Test
+ public void erasingEverythingEmptiesEveryTable() {
+ this.importAZipOf(THE_TAG, ITS_SIBLING);
+ this.givenItHasHistory(THE_TAG);
+ this.repo.removeBeacon(ITS_SIBLING, false).blockingAwait();
+
+ this.repo.eraseEverything().blockingAwait();
+
+ for (final String table : new String[] {"OwnedBeacons", "Import", "BeaconNamingRecord",
+ "LocationReport", "DailyHistoryFetchRecord", "LastBleSighting",
+ "UserBeaconOptions"}) {
+ assertEquals(table + " still has rows after erasing everything", 0, this.count(table));
+ }
+ assertTrue(this.repo.getAllBeacons().blockingFirst().isEmpty());
+ }
+}
diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/AlsoEraseDialogLayoutTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/AlsoEraseDialogLayoutTest.java
new file mode 100644
index 00000000..46cb4730
--- /dev/null
+++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/AlsoEraseDialogLayoutTest.java
@@ -0,0 +1,79 @@
+package dev.wander.android.opentagviewer.ui;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import android.content.Context;
+import android.content.res.Configuration;
+import android.view.ContextThemeWrapper;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.CheckBox;
+
+import androidx.core.graphics.ColorUtils;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.google.android.material.color.MaterialColors;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import dev.wander.android.opentagviewer.R;
+
+/**
+ * The "and erase this too" box that the Remove and Logout dialogs now carry, inflated the way
+ * they inflate it: inside a Material 3 alert dialog's theme, over the activities' own theme, in
+ * both modes.
+ *
+ * It is the only thing on screen standing between the user and an erase that cannot be undone,
+ * so it has to be there, unticked, and readable against the dialog it sits in.
+ */
+@RunWith(AndroidJUnit4.class)
+public class AlsoEraseDialogLayoutTest {
+
+ @Test
+ public void itInflatesUntickedAndLegibleInLightMode() {
+ this.check(Configuration.UI_MODE_NIGHT_NO);
+ }
+
+ /** Half of what breaks only breaks in one mode. */
+ @Test
+ public void itInflatesUntickedAndLegibleInDarkMode() {
+ this.check(Configuration.UI_MODE_NIGHT_YES);
+ }
+
+ private void check(final int nightMode) {
+ final Context target = getInstrumentation().getTargetContext();
+ final Configuration config = new Configuration(target.getResources().getConfiguration());
+ config.uiMode = nightMode | Configuration.UI_MODE_TYPE_NORMAL;
+ final Context activity = new ContextThemeWrapper(
+ target.createConfigurationContext(config),
+ R.style.Theme_OpenTagViewer_GenericGreyishActivity);
+ final Context dialog = new ContextThemeWrapper(activity,
+ com.google.android.material.R.style.ThemeOverlay_Material3_MaterialAlertDialog);
+
+ final View[] root = new View[1];
+ getInstrumentation().runOnMainSync(() -> {
+ root[0] = LayoutInflater.from(dialog).inflate(R.layout.dialog_also_erase, null);
+ ((CheckBox) root[0].findViewById(R.id.dialog_also_erase))
+ .setText(R.string.logout_also_erase_data);
+ root[0].measure(View.MeasureSpec.makeMeasureSpec(900, View.MeasureSpec.EXACTLY),
+ View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
+ });
+
+ final CheckBox box = root[0].findViewById(R.id.dialog_also_erase);
+ assertNotNull("the id both screens look up does not resolve", box);
+ assertFalse("erasing must be opted into, not out of", box.isChecked());
+ assertTrue("the box measured to nothing", box.getMeasuredHeight() > 0);
+
+ // An M3 alert dialog draws on colorSurfaceContainerHigh.
+ final int background = MaterialColors.getColor(dialog,
+ com.google.android.material.R.attr.colorSurfaceContainerHigh, "no dialog surface");
+ final double ratio = ColorUtils.calculateContrast(
+ box.getCurrentTextColor() | 0xFF000000, background | 0xFF000000);
+ assertTrue("the label is " + ratio + ":1 against the dialog, under the 4.5:1 AA needs",
+ ratio >= 4.5);
+ }
+}
diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/mydevices/RemovingAFileTagTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/mydevices/RemovingAFileTagTest.java
new file mode 100644
index 00000000..b84adf6b
--- /dev/null
+++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/mydevices/RemovingAFileTagTest.java
@@ -0,0 +1,234 @@
+package dev.wander.android.opentagviewer.ui.mydevices;
+
+import static androidx.test.espresso.Espresso.onView;
+import static androidx.test.espresso.action.ViewActions.click;
+import static androidx.test.espresso.action.ViewActions.longClick;
+import static androidx.test.espresso.assertion.ViewAssertions.matches;
+import static androidx.test.espresso.matcher.RootMatchers.isDialog;
+import static androidx.test.espresso.matcher.RootMatchers.isPlatformPopup;
+import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
+import static androidx.test.espresso.matcher.ViewMatchers.isNotChecked;
+import static androidx.test.espresso.matcher.ViewMatchers.withId;
+import static androidx.test.espresso.matcher.ViewMatchers.withText;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static org.hamcrest.Matchers.allOf;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+
+import android.content.Intent;
+import android.database.Cursor;
+
+import androidx.test.core.app.ActivityScenario;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.LargeTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import dev.wander.android.opentagviewer.DeviceInfoActivity;
+import dev.wander.android.opentagviewer.Eventually;
+import dev.wander.android.opentagviewer.MyDevicesListActivity;
+import dev.wander.android.opentagviewer.R;
+import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase;
+import dev.wander.android.opentagviewer.db.room.entity.BeaconNamingRecord;
+import dev.wander.android.opentagviewer.db.room.entity.Import;
+import dev.wander.android.opentagviewer.db.room.entity.LocationReport;
+import dev.wander.android.opentagviewer.db.room.entity.OwnedBeacon;
+
+/**
+ * Removing a tag imported from a file, from both screens that offer it: the keys always go, and
+ * the location history goes only when the box is ticked.
+ *
+ *
What the repository does with each answer is pinned by
+ * {@code RemovingATagForgetsItsKeysTest}. This checks the screens offer the choice, unticked, and
+ * pass on what was chosen.
+ *
+ *
Seeds the real on-device database, as {@link RemoveAccountTagTest} does and for the same
+ * reason, and deletes only its own rows by id, before and after.
+ */
+@LargeTest
+@RunWith(AndroidJUnit4.class)
+public class RemovingAFileTagTest {
+
+ private static final String THE_TAG = "test-removing-a-file-tag";
+ private static final String ITS_NAME = "Tag To Be Removed";
+ private static final String A_TEST_USER = "removingafiletagtest@example.invalid";
+
+ private static final String A_PLIST = ""
+ + ""
+ + "batteryLevel1"
+ + "model"
+ + "pairingDate2025-02-27T20:03:32Z"
+ + "privateKeykey"
+ + "databm90LWEtcmVhbC1rZXk="
+ + "productId21760"
+ + "stableIdentifier2001~#0~#A0"
+ + "systemVersion2.0.73"
+ + "vendorId76"
+ + "";
+
+ private OpenTagViewerDatabase db;
+ private ActivityScenario> scenario;
+
+ @Before
+ public void seedTheDatabase() {
+ this.db = OpenTagViewerDatabase.getInstance(getInstrumentation().getTargetContext());
+ this.removeEverythingThisTestWrites();
+
+ final long importId = this.db.importDao().insert(Import.builder()
+ .version("0.0.2")
+ .importedAt(1_700_000_000_000L)
+ .exportedAt(1_699_000_000_000L)
+ .sourceUser(A_TEST_USER)
+ .exportedVia("OpenTagViewer.wizard:test")
+ .build());
+
+ this.db.ownedBeaconDao().insertAll(OwnedBeacon.builder()
+ .id(THE_TAG)
+ .importId(importId)
+ .content(A_PLIST)
+ .version("0.0.2")
+ .fromAccount(false)
+ .isRemoved(false)
+ .build());
+
+ this.db.beaconNamingRecordDao().insertAll(BeaconNamingRecord.builder()
+ .id(THE_TAG)
+ .importId(importId)
+ .version("0.0.2")
+ .isRemoved(false)
+ .content(""
+ + "identifier" + THE_TAG + ""
+ + "name" + ITS_NAME + ""
+ + "")
+ .build());
+
+ this.db.locationReportDao().insertAll(LocationReport.builder()
+ .hashId("report-" + THE_TAG)
+ .beaconId(THE_TAG)
+ .publishedAt(1_000L)
+ .description("Wi-Fi")
+ .timestamp(1_000L)
+ .confidence(0)
+ .latitude(52.370216)
+ .longitude(4.895168)
+ .horizontalAccuracy(83)
+ .status(144)
+ .lastUpdate(1_000L)
+ .provenance(LocationReport.PROVENANCE_APPLE)
+ .build());
+ }
+
+ @After
+ public void putTheDatabaseBack() {
+ if (this.scenario != null) {
+ this.scenario.close();
+ }
+ this.removeEverythingThisTestWrites();
+ }
+
+ private void removeEverythingThisTestWrites() {
+ // By id, never `clearAllTables`: this is the real database. Deleting the row cascades to
+ // the history this test wrote.
+ this.db.ownedBeaconDao().delete(OwnedBeacon.builder().id(THE_TAG).build());
+ this.db.beaconNamingRecordDao().delete(BeaconNamingRecord.builder().id(THE_TAG).build());
+ for (final Import stale : this.db.importDao().getImportsFromUser(A_TEST_USER)) {
+ this.db.importDao().delete(stale);
+ }
+ }
+
+ /** Whether the row is still in the table at all, hidden or not. */
+ private boolean rowExists() {
+ try (Cursor c = this.db.query(
+ "SELECT COUNT(*) FROM OwnedBeacons WHERE id = ?", new Object[] {THE_TAG})) {
+ c.moveToFirst();
+ return c.getInt(0) > 0;
+ }
+ }
+
+ private String storedPlist() {
+ try (Cursor c = this.db.query(
+ "SELECT content FROM OwnedBeacons WHERE id = ?", new Object[] {THE_TAG})) {
+ return c.moveToFirst() ? c.getString(0) : null;
+ }
+ }
+
+ private int historyRows() {
+ return this.db.locationReportDao().getInTimeRange(THE_TAG, 0L, 10_000L).size();
+ }
+
+ private void openTheListAndChooseRemove() {
+ this.scenario = ActivityScenario.launch(MyDevicesListActivity.class);
+ Eventually.check(() -> onView(withText(ITS_NAME)).check(matches(isDisplayed())));
+
+ onView(withText(ITS_NAME)).perform(longClick());
+ Eventually.check(() -> onView(withId(R.id.selection_menu_button))
+ .check(matches(isDisplayed())));
+ onView(withId(R.id.selection_menu_button)).perform(click());
+ onView(withText(R.string.remove_devices)).inRoot(isPlatformPopup()).perform(click());
+
+ Eventually.check(() -> onView(withId(R.id.dialog_also_erase))
+ .inRoot(isDialog()).check(matches(isDisplayed())));
+ }
+
+ /** Offered, worded for one tag, and unticked. */
+ @Test
+ public void theDialogOffersToEraseTheHistoryUnticked() {
+ this.openTheListAndChooseRemove();
+
+ onView(withId(R.id.dialog_also_erase)).inRoot(isDialog()).check(matches(allOf(
+ isNotChecked(), withText(R.string.remove_tag_also_erase_history))));
+ }
+
+ /** Left unticked: the keys go, the history stays for a re-import to bring back. */
+ @Test
+ public void removingDeletesTheKeysAndKeepsTheHistory() {
+ this.openTheListAndChooseRemove();
+
+ onView(withText(R.string.confirm)).inRoot(isDialog()).perform(click());
+
+ Eventually.check(() -> assertNull("the tag should no longer be listed",
+ this.db.ownedBeaconDao().getById(THE_TAG)));
+ assertNull("its private key is still in the database", this.storedPlist());
+ assertEquals("its history should have been kept", 1, this.historyRows());
+ }
+
+ /** Ticked: the row goes, and its history with it. */
+ @Test
+ public void tickingTheBoxErasesTheHistoryToo() {
+ this.openTheListAndChooseRemove();
+
+ onView(withId(R.id.dialog_also_erase)).inRoot(isDialog()).perform(click());
+ onView(withText(R.string.confirm)).inRoot(isDialog()).perform(click());
+
+ Eventually.check(() -> assertFalse("the row is still there", this.rowExists()));
+ assertEquals("its history is still there", 0, this.historyRows());
+ }
+
+ /** The tag's own page offers the same choice and honours it. */
+ @Test
+ public void theTagPageErasesTheHistoryWhenTicked() {
+ final Intent intent = new Intent(
+ getInstrumentation().getTargetContext(), DeviceInfoActivity.class);
+ intent.putExtra("beaconId", THE_TAG);
+ this.scenario = ActivityScenario.launch(intent);
+
+ Eventually.check(() -> onView(withId(R.id.page_menu_button))
+ .check(matches(isDisplayed())));
+ onView(withId(R.id.page_menu_button)).perform(click());
+ onView(withText(R.string.remove_device)).inRoot(isPlatformPopup()).perform(click());
+
+ Eventually.check(() -> onView(withId(R.id.dialog_also_erase))
+ .inRoot(isDialog()).check(matches(isDisplayed())));
+ onView(withId(R.id.dialog_also_erase)).inRoot(isDialog()).perform(click());
+
+ // Confirming finishes the page, so the click may report the activity gone.
+ Eventually.perform("Confirm", () -> !this.rowExists(),
+ () -> onView(withText(R.string.confirm)).inRoot(isDialog()).perform(click()));
+
+ assertEquals("its history is still there", 0, this.historyRows());
+ }
+}
diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/ErasingEverythingFromSettingsTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/ErasingEverythingFromSettingsTest.java
new file mode 100644
index 00000000..9bc0fc6f
--- /dev/null
+++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/ErasingEverythingFromSettingsTest.java
@@ -0,0 +1,264 @@
+package dev.wander.android.opentagviewer.ui.settings;
+
+import static androidx.test.espresso.Espresso.onView;
+import static androidx.test.espresso.action.ViewActions.click;
+import static androidx.test.espresso.action.ViewActions.scrollTo;
+import static androidx.test.espresso.assertion.ViewAssertions.matches;
+import static androidx.test.espresso.matcher.RootMatchers.isDialog;
+import static androidx.test.espresso.matcher.ViewMatchers.isChecked;
+import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
+import static androidx.test.espresso.matcher.ViewMatchers.isNotChecked;
+import static androidx.test.espresso.matcher.ViewMatchers.withId;
+import static androidx.test.espresso.matcher.ViewMatchers.withText;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static org.hamcrest.Matchers.allOf;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.app.Activity;
+import android.app.Instrumentation.ActivityResult;
+import android.content.Context;
+
+import androidx.lifecycle.Lifecycle;
+import androidx.test.core.app.ActivityScenario;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.LargeTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import dev.wander.android.opentagviewer.DeviceStateGuard;
+import dev.wander.android.opentagviewer.Eventually;
+import dev.wander.android.opentagviewer.R;
+import dev.wander.android.opentagviewer.SettingsActivity;
+import dev.wander.android.opentagviewer.anisette.FakeAnisetteSource;
+import dev.wander.android.opentagviewer.db.datastore.UserAuthDataStore;
+import dev.wander.android.opentagviewer.db.repo.LocalDataEraser;
+import dev.wander.android.opentagviewer.db.repo.UserAuthRepository;
+import dev.wander.android.opentagviewer.python.AppDependencies;
+import dev.wander.android.opentagviewer.util.android.AppCryptographyUtil;
+import io.reactivex.rxjava3.core.Completable;
+
+/**
+ * Erasing the user's tags, keys and history from Settings: the "Erase all data" row, and the box
+ * in the Logout dialog.
+ *
+ *
The eraser is a fake, on purpose. This suite shares the real on-device database, and
+ * on somebody's own phone that holds their tags. What the real eraser deletes is pinned against an
+ * in-memory database by {@code RemovingATagForgetsItsKeysTest}; this checks the screen asks first,
+ * calls it only when told to, and does not sign anybody out when it fails.
+ *
+ *
Signing out here is real, so the stored session is captured first and put back afterwards.
+ */
+@LargeTest
+@RunWith(AndroidJUnit4.class)
+public class ErasingEverythingFromSettingsTest {
+
+ private final Context context = getInstrumentation().getTargetContext();
+ private final CountingEraser eraser = new CountingEraser();
+ private ActivityScenario scenario;
+ private DeviceStateGuard deviceState;
+
+ /** Counts calls, and fails when told to. Erases nothing. */
+ private static final class CountingEraser implements LocalDataEraser {
+ final AtomicInteger calls = new AtomicInteger();
+ volatile boolean fail;
+
+ @Override
+ public Completable eraseEverything() {
+ return Completable.fromAction(() -> {
+ this.calls.incrementAndGet();
+ if (this.fail) {
+ throw new IllegalStateException("the database is locked, say");
+ }
+ });
+ }
+ }
+
+ @Before
+ public void setUp() {
+ this.deviceState = DeviceStateGuard.capture(this.context);
+ // Or Settings loads Apple's real ADI library, which this is not about. See issue #135.
+ AppDependencies.replaceAnisette(settings -> FakeAnisetteSource.ready());
+ AppDependencies.replaceDataEraser(this.eraser);
+ }
+
+ @After
+ public void tearDown() {
+ if (this.scenario != null) {
+ this.scenario.close();
+ }
+ AppDependencies.reset();
+ this.deviceState.restore();
+ }
+
+ private UserAuthRepository auth() {
+ return new UserAuthRepository(
+ UserAuthDataStore.getInstance(this.context.getApplicationContext()),
+ new AppCryptographyUtil());
+ }
+
+ /** Invented; the name and address belong to nobody. */
+ private void givenSomebodyIsSignedIn() {
+ this.auth().storeUserAuth(("{\"account\":{\"info\":{"
+ + "\"account_name\":\"jamie.lang@example.com\","
+ + "\"first_name\":\"Jamie\","
+ + "\"last_name\":\"Lang\"}}}").getBytes(StandardCharsets.UTF_8))
+ .blockingAwait();
+ }
+
+ private boolean stillSignedIn() {
+ return this.auth().getUserAuth().blockingFirst().isPresent();
+ }
+
+ /** For a result, so that whether Settings asked the map to sign out can be read back. */
+ private void open() {
+ this.scenario = ActivityScenario.launchActivityForResult(SettingsActivity.class);
+ }
+
+ private void tapEraseAllData() {
+ Eventually.check(() -> onView(withId(R.id.settings_erase_all_data))
+ .perform(scrollTo()).check(matches(isDisplayed())));
+ onView(withId(R.id.settings_erase_all_data)).perform(click());
+ Eventually.check(() -> onView(withText(R.string.erase_all_data_confirm_title))
+ .inRoot(isDialog()).check(matches(isDisplayed())));
+ }
+
+ private void tapLogout() {
+ Eventually.check(() -> onView(withId(R.id.logout_button))
+ .perform(scrollTo()).check(matches(isDisplayed())));
+ onView(withId(R.id.logout_button)).perform(click());
+ Eventually.check(() -> onView(withId(R.id.dialog_also_erase))
+ .inRoot(isDialog()).check(matches(isDisplayed())));
+ }
+
+ /**
+ * The dialog's Logout button, by id: its title says "Logout" too. Confirming finishes the
+ * screen, so the click may report the activity gone - signed out is what says it worked.
+ */
+ private void confirmLogout() {
+ Eventually.perform("Logout", () -> !this.stillSignedIn(),
+ () -> onView(withId(android.R.id.button1)).inRoot(isDialog()).perform(click()));
+ }
+
+ private void assertSentToSignIn() {
+ final ActivityResult result = this.scenario.getResult();
+ assertEquals(Activity.RESULT_OK, result.getResultCode());
+ assertTrue("Settings signed out but did not send the map back to the sign-in screen",
+ result.getResultData().getBooleanExtra("requestSendToLogin", false));
+ }
+
+ /** The row is there, and tapping it only asks. */
+ @Test
+ public void eraseAllDataAsksBeforeErasingAnything() {
+ this.givenSomebodyIsSignedIn();
+ this.open();
+
+ this.tapEraseAllData();
+ onView(withText(R.string.erase_all_data_confirm_message))
+ .inRoot(isDialog()).check(matches(isDisplayed()));
+ onView(withText(R.string.cancel)).inRoot(isDialog()).perform(click());
+
+ assertEquals("cancelling erased anyway", 0, this.eraser.calls.get());
+ assertTrue("cancelling signed out anyway", this.stillSignedIn());
+ }
+
+ /**
+ * The confirmation says what survives and what does not, including that the app stays on the
+ * Apple account. That sentence is the sort somebody trims when shortening a dialog.
+ */
+ @Test
+ public void theConfirmationSaysTheAppStaysOnTheAppleAccount() {
+ final String message = this.context.getString(R.string.erase_all_data_confirm_message);
+ assertTrue(message, message.contains("Apple device"));
+ assertTrue(message, message.contains("cannot be undone"));
+ }
+
+ /**
+ * The failure message must not say nothing was erased. The iCloud link is forgotten before the
+ * tags, so a failure after it leaves the tags and not the link.
+ */
+ @Test
+ public void theFailureSaysTheICloudLinkMayBeGone() {
+ final String message = this.context.getString(R.string.error_erasing_data);
+ assertTrue(message, message.contains("iCloud link"));
+ assertTrue(message, message.contains("still logged in"));
+ }
+
+ /** Confirming erases, then signs out and sends the map to the sign-in screen. */
+ @Test
+ public void confirmingErasesAndSignsOut() {
+ this.givenSomebodyIsSignedIn();
+ this.open();
+
+ this.tapEraseAllData();
+ // Confirming finishes the screen, so the click may report the activity gone.
+ Eventually.perform("Erase", () -> this.eraser.calls.get() > 0,
+ () -> onView(withText(R.string.erase_all_data_confirm_button))
+ .inRoot(isDialog()).perform(click()));
+
+ Eventually.check(() -> assertEquals(1, this.eraser.calls.get()));
+ Eventually.check(() -> assertFalse("erased but still signed in", this.stillSignedIn()));
+ this.assertSentToSignIn();
+ }
+
+ /**
+ * A failed erase leaves the user signed in, on this screen, and says so. Signing out
+ * anyway would land them on the sign-in screen believing their tags were gone.
+ */
+ @Test
+ public void aFailedEraseDoesNotSignOut() {
+ this.eraser.fail = true;
+ this.givenSomebodyIsSignedIn();
+ this.open();
+
+ this.tapEraseAllData();
+ onView(withText(R.string.erase_all_data_confirm_button))
+ .inRoot(isDialog()).perform(click());
+
+ Eventually.check(() -> assertEquals(1, this.eraser.calls.get()));
+ assertTrue("the erase failed, so signing out would mislead", this.stillSignedIn());
+ assertEquals(Lifecycle.State.RESUMED, this.scenario.getState());
+ }
+
+ /**
+ * Logout still only logs out unless asked: tags imported from a file are the only copy
+ * anybody has, so the box starts unticked.
+ */
+ @Test
+ public void logoutLeavesTheDataAloneByDefault() {
+ this.givenSomebodyIsSignedIn();
+ this.open();
+
+ this.tapLogout();
+ onView(withId(R.id.dialog_also_erase)).inRoot(isDialog()).check(matches(allOf(
+ isNotChecked(), withText(R.string.logout_also_erase_data))));
+ this.confirmLogout();
+
+ Eventually.check(() -> assertFalse(this.stillSignedIn()));
+ assertEquals("logging out erased data nobody asked to erase", 0, this.eraser.calls.get());
+ this.assertSentToSignIn();
+ }
+
+ /** Ticking the box erases first. */
+ @Test
+ public void logoutWithTheBoxTickedErasesFirst() {
+ this.givenSomebodyIsSignedIn();
+ this.open();
+
+ this.tapLogout();
+ onView(withId(R.id.dialog_also_erase)).inRoot(isDialog()).perform(click());
+ onView(withId(R.id.dialog_also_erase)).inRoot(isDialog()).check(matches(isChecked()));
+ this.confirmLogout();
+
+ Eventually.check(() -> assertEquals(1, this.eraser.calls.get()));
+ Eventually.check(() -> assertFalse(this.stillSignedIn()));
+ this.assertSentToSignIn();
+ }
+}
diff --git a/app/src/main/java/dev/wander/android/opentagviewer/DeviceInfoActivity.java b/app/src/main/java/dev/wander/android/opentagviewer/DeviceInfoActivity.java
index 300fa80d..e8e7c6fe 100644
--- a/app/src/main/java/dev/wander/android/opentagviewer/DeviceInfoActivity.java
+++ b/app/src/main/java/dev/wander/android/opentagviewer/DeviceInfoActivity.java
@@ -21,6 +21,7 @@
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
+import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
@@ -1412,20 +1413,28 @@ private void onClickDeviceDelete() {
return;
}
+ // The tag's keys are deleted either way; see BeaconRepository#removeBeacon. Its history
+ // only when this is ticked, because keeping it is what lets a tag removed by mistake come
+ // back whole when it is imported again.
+ final View alsoErase = this.getLayoutInflater().inflate(R.layout.dialog_also_erase, null);
+ final CheckBox eraseHistory = alsoErase.findViewById(R.id.dialog_also_erase);
+ eraseHistory.setText(R.string.remove_tag_also_erase_history);
+
var dialog = new MaterialAlertDialogBuilder(this, com.google.android.material.R.style.ThemeOverlay_Material3_MaterialAlertDialog_Centered)
.setTitle(R.string.remove_device)
.setIcon(R.drawable.delete_24px)
.setMessage(R.string.are_you_sure_you_want_to_remove_this_device_once_removed_it_will_need_to_be_reimported_to_get_it_back)
+ .setView(alsoErase)
.setPositiveButton(R.string.confirm, (dialog1, which) -> {
- Log.d(TAG, "Clicked to confirm device deletion. Now proceeding to delete (actually hide) device...");
- this.handleDeviceRemoval();
+ Log.d(TAG, "Clicked to confirm device removal");
+ this.handleDeviceRemoval(eraseHistory.isChecked());
}).setNegativeButton(R.string.cancel, null)
.show();
}
- private void handleDeviceRemoval() {
+ private void handleDeviceRemoval(final boolean alsoErasingHistory) {
final String beaconId = this.beaconId;
- var async = this.beaconRepo.markBeaconAsRemoved(beaconId)
+ var async = this.beaconRepo.removeBeacon(beaconId, alsoErasingHistory)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(() -> {
Intent data = new Intent();
diff --git a/app/src/main/java/dev/wander/android/opentagviewer/MapsActivity.java b/app/src/main/java/dev/wander/android/opentagviewer/MapsActivity.java
index d47f5370..6cd5a27b 100644
--- a/app/src/main/java/dev/wander/android/opentagviewer/MapsActivity.java
+++ b/app/src/main/java/dev/wander/android/opentagviewer/MapsActivity.java
@@ -261,6 +261,9 @@ private float initialZoom() {
/** Whether the running ping started a sound that has a stop command (DULT). */
private boolean continuousPingLeftStoppableSound;
+ /** Set when Settings signed out, so leaving does not save the map position again. */
+ private boolean leavingForSignIn;
+
/**
* Stops still in flight, by beaconId. A new ping for the same tag cancels its pending stop,
* which would otherwise land after the new start and silence it.
@@ -666,7 +669,10 @@ protected void onPause() {
if (this.mapProvider != null) {
IMapProvider.CameraPosition pos = this.mapProvider.getCameraPosition();
- if (pos != null) {
+ // Not when leaving for the sign-in screen: that is a sign-out, possibly one that has
+ // just erased this position along with everything else, and writing it back here
+ // would undo that.
+ if (pos != null && !this.leavingForSignIn) {
var async = this.userDataRepository.storeLastCameraPosition(
UserMapCameraPosition.builder()
.zoom(pos.getZoom())
@@ -3366,6 +3372,7 @@ private void handleDeviceListChanged() {
}
private void handleSendToLogin() {
+ this.leavingForSignIn = true;
this.finish(); // finish current activity, send to login.
// Login will send back to instance of this if it succeeds.
Intent intent = new Intent(this, AppleLoginActivity.class);
diff --git a/app/src/main/java/dev/wander/android/opentagviewer/MyDevicesListActivity.java b/app/src/main/java/dev/wander/android/opentagviewer/MyDevicesListActivity.java
index 5dddf740..faee26e1 100644
--- a/app/src/main/java/dev/wander/android/opentagviewer/MyDevicesListActivity.java
+++ b/app/src/main/java/dev/wander/android/opentagviewer/MyDevicesListActivity.java
@@ -10,6 +10,7 @@
import android.util.Log;
import android.util.Pair;
import android.view.View;
+import android.widget.CheckBox;
import android.widget.PopupMenu;
import android.widget.Toast;
@@ -1156,14 +1157,20 @@ private void confirmRemoveSelection() {
: R.string.are_you_sure_you_want_to_remove_these_devices)
: this.getString(R.string.remove_devices_but_keep_account_ones, fromTheAccount);
+ // Keys go either way, history only when ticked - see BeaconRepository#removeBeacon.
+ final View alsoErase = this.getLayoutInflater().inflate(R.layout.dialog_also_erase, null);
+ final CheckBox eraseHistory = alsoErase.findViewById(R.id.dialog_also_erase);
+ eraseHistory.setText(removable.size() == 1
+ ? R.string.remove_tag_also_erase_history
+ : R.string.remove_tags_also_erase_history);
+
new MaterialAlertDialogBuilder(this, com.google.android.material.R.style.ThemeOverlay_Material3_MaterialAlertDialog_Centered)
.setTitle(removable.size() == 1 ? R.string.remove_device : R.string.remove_devices)
.setIcon(R.drawable.delete_24px)
.setMessage(message)
+ .setView(alsoErase)
.setPositiveButton(R.string.confirm, (dialog, which) -> {
- for (BeaconInformation device : removable) {
- this.removeDevice(device);
- }
+ this.removeDevices(removable, eraseHistory.isChecked());
this.endSelection();
})
.setNegativeButton(R.string.cancel, null)
@@ -1184,17 +1191,23 @@ private void explainAccountTagsCannotBeRemoved(final int howMany) {
.show();
}
- private void removeDevice(final BeaconInformation device) {
- final String beaconId = device.getBeaconId();
+ private void removeDevices(
+ final List devices, final boolean alsoErasingHistory) {
+ final List beaconIds = new ArrayList<>(devices.size());
+ for (final BeaconInformation device : devices) {
+ beaconIds.add(device.getBeaconId());
+ }
- // Same call DeviceInfoActivity makes: rows are hidden rather than deleted, so the
- // location history survives a re-import.
- var async = this.beaconRepo.markBeaconAsRemoved(beaconId)
+ // The batch form of what DeviceInfoActivity calls, so the database is compacted once
+ // rather than once per tag. Unless the history is being erased too, the rows are hidden
+ // rather than deleted, so the location history survives a re-import; the keys are
+ // deleted either way.
+ var async = this.beaconRepo.removeBeacons(beaconIds, alsoErasingHistory)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
- () -> this.refreshListOnItemRemoved(beaconId),
+ () -> beaconIds.forEach(this::refreshListOnItemRemoved),
error -> {
- Log.e(TAG, "Failure marking beacon as removed!", error);
+ Log.e(TAG, "Failed to remove " + beaconIds.size() + " tag(s)", error);
Toast.makeText(
this.getApplicationContext(),
R.string.error_occurred_while_removing_the_device,
diff --git a/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java b/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java
index ae4e5e65..488f81dc 100644
--- a/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java
+++ b/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java
@@ -26,6 +26,7 @@
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
+import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
@@ -98,8 +99,10 @@
import dev.wander.android.opentagviewer.util.android.PropertiesUtil;
import dev.wander.android.opentagviewer.util.android.SigningInfoUtil;
import dev.wander.android.opentagviewer.util.android.WebLink;
+import dev.wander.android.opentagviewer.util.rx.RxFlows;
import dev.wander.android.opentagviewer.util.validate.AnisetteUrlValidatorUtil;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
+import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
@@ -253,6 +256,7 @@ protected void onCreate(Bundle savedInstanceState) {
this.binding.setIsShowAppleDevicesEnabled(this.currentSettings.shouldShowAppleDevices());
this.binding.setIsScanInBackgroundEnabled(this.currentSettings.shouldScanInBackground());
this.binding.setOnClickAppleDevicesHelpLink(this::onClickAppleDevicesHelpLink);
+ this.binding.setOnClickEraseAllData(this::onClickEraseAllData);
this.binding.setIsSystemColorsSupported(DynamicColors.isDynamicColorAvailable());
this.binding.setIsSystemColorsEnabled(
this.currentSettings.getUseSystemColors() == Boolean.TRUE);
@@ -1279,20 +1283,69 @@ private void fillInUIAuthInfo(UserAuthData userAuthData) {
private void onClickLogout(View view) {
if (this.userAuthData == null) return;
+ // Logging out has only ever cleared the session, and still does by default: tags
+ // imported from a file are the only copy anybody has. Erasing them is offered rather
+ // than assumed, unticked.
+ final View alsoErase = this.getLayoutInflater().inflate(R.layout.dialog_also_erase, null);
+ final CheckBox eraseEverything = alsoErase.findViewById(R.id.dialog_also_erase);
+ eraseEverything.setText(R.string.logout_also_erase_data);
+
var dialog = new MaterialAlertDialogBuilder(this)
.setTitle(R.string.logout)
.setMessage(R.string.are_you_sure_you_want_to_logout)
+ .setView(alsoErase)
+ .setNegativeButton(R.string.cancel, null)
+ .setPositiveButton(R.string.logout, (dialog1, which) ->
+ this.performLogout(eraseEverything.isChecked()))
+ .show();
+ }
+
+ /**
+ * Settings -> Erase all data. The same as logging out with the box ticked, offered on its
+ * own because somebody looking to wipe the app looks for that, not inside Logout.
+ */
+ private void onClickEraseAllData() {
+ new MaterialAlertDialogBuilder(this, com.google.android.material.R.style.ThemeOverlay_Material3_MaterialAlertDialog_Centered)
+ .setTitle(R.string.erase_all_data_confirm_title)
+ .setIcon(R.drawable.delete_24px)
+ .setMessage(R.string.erase_all_data_confirm_message)
.setNegativeButton(R.string.cancel, null)
- .setPositiveButton(R.string.logout, (dialog1, which) -> this.performLogout())
+ .setPositiveButton(R.string.erase_all_data_confirm_button,
+ (dialog, which) -> this.performLogout(true))
.show();
}
private void performLogout() {
+ this.performLogout(false);
+ }
+
+ /**
+ * Sign out, and first erase the tags, keys and history when asked to.
+ *
+ * If the erase fails, the user stays signed in and is told. Signing out anyway
+ * would leave them believing their data was gone when it was not, and back at a sign-in
+ * screen with no way to tell. The message does not claim nothing was erased: the iCloud link
+ * goes first, on purpose (see {@code ThisPhonesTagData}), so it may already be gone.
+ */
+ private void performLogout(final boolean alsoErasingEverything) {
// Let go of the Apple session too, closing its HTTP session and sockets rather
// than leaving them to a finaliser that cannot do it. See issue #133.
PythonAppleService.forget();
- var async = this.authRepository.clearUser()
+ final Completable erasing = alsoErasingEverything
+ ? AppDependencies.dataEraser(this).eraseEverything()
+ : Completable.complete();
+
+ final Completable erasedOrToldWhyNot = erasing
+ .observeOn(AndroidSchedulers.mainThread())
+ .doOnError(error -> {
+ Log.e(TAG, "Failed to erase this phone's data, so not signing out", error);
+ Toast.makeText(this, R.string.error_erasing_data, Toast.LENGTH_LONG).show();
+ });
+
+ // RxFlows.onlyAfter and not andThen: clearUser() starts writing when it is called, so
+ // passed to andThen directly it signed the user out even when the erase above failed.
+ var async = RxFlows.onlyAfter(erasedOrToldWhyNot, this.authRepository::clearUser)
.subscribe(() -> {
// logout by sending back to login page
Intent data = new Intent();
diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java
index 81977929..688cd659 100644
--- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java
+++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java
@@ -2,6 +2,8 @@
import android.util.Log;
+import androidx.sqlite.db.SupportSQLiteDatabase;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -947,8 +949,15 @@ public Observable