From d4bf14d3dc2a34459765d768b730cce47dac12f1 Mon Sep 17 00:00:00 2001 From: Rob Lazzurs Date: Mon, 23 Nov 2026 00:03:42 +0000 Subject: [PATCH 1/8] Delete a removed tag's keys, and offer to erase its history Removing a tag only set is_removed, so the private key and shared secrets of every tag ever removed stayed in the database, with its location history. Nothing on the phone ever deleted either, short of uninstalling. Remove now clears content, accessory_json and alignment_plist. The row stays hidden, as before, so a tag removed by mistake still comes back with its history when imported again; the keys come back from the import. A new box in both Remove dialogs, unticked, deletes the row instead, and with it the location history, fetched-day records, last Bluetooth sighting, the user's name for it, its naming record, and its import once nothing refers to it. The database is vacuumed afterwards so the deleted bytes do not stay in free pages. Logout gains the same kind of box: erase every tag, key and history and the iCloud link before signing out. Settings gains "Erase all data", which does that behind a confirmation. If the erase fails the user stays signed in and is told. Settings, the Apple device identity and the iCloud peer on the Apple account are left alone, and the dialog says the last of those. No schema change. Nine new strings in all ten locales. Co-Authored-By: Claude Opus 5.5 --- .../repo/RemovingATagForgetsItsKeysTest.java | 307 ++++++++++++++++++ .../ui/AlsoEraseDialogLayoutTest.java | 79 +++++ .../ui/mydevices/RemovingAFileTagTest.java | 234 +++++++++++++ .../ErasingEverythingFromSettingsTest.java | 253 +++++++++++++++ .../opentagviewer/DeviceInfoActivity.java | 17 +- .../android/opentagviewer/MapsActivity.java | 9 +- .../opentagviewer/MyDevicesListActivity.java | 20 +- .../opentagviewer/SettingsActivity.java | 52 ++- .../db/repo/BeaconRepository.java | 69 +++- .../db/repo/LocalDataEraser.java | 20 ++ .../db/repo/ThisPhonesTagData.java | 52 +++ .../db/repo/UserDataRepository.java | 10 + .../db/room/dao/BeaconNamingRecordDao.java | 3 + .../opentagviewer/db/room/dao/ImportDao.java | 11 + .../db/room/dao/OwnedBeaconDao.java | 26 ++ .../opentagviewer/python/AppDependencies.java | 23 ++ app/src/main/res/layout/activity_settings.xml | 14 + app/src/main/res/layout/dialog_also_erase.xml | 26 ++ app/src/main/res/values-de/strings.xml | 9 + app/src/main/res/values-en/strings.xml | 9 + app/src/main/res/values-fr/strings.xml | 9 + app/src/main/res/values-ja/strings.xml | 9 + app/src/main/res/values-ko/strings.xml | 9 + app/src/main/res/values-nl/strings.xml | 9 + app/src/main/res/values-ru/strings.xml | 9 + app/src/main/res/values-zh-rCN/strings.xml | 9 + app/src/main/res/values-zh-rTW/strings.xml | 9 + app/src/main/res/values/strings.xml | 9 + 28 files changed, 1299 insertions(+), 16 deletions(-) create mode 100644 app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/RemovingATagForgetsItsKeysTest.java create mode 100644 app/src/androidTest/java/dev/wander/android/opentagviewer/ui/AlsoEraseDialogLayoutTest.java create mode 100644 app/src/androidTest/java/dev/wander/android/opentagviewer/ui/mydevices/RemovingAFileTagTest.java create mode 100644 app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/ErasingEverythingFromSettingsTest.java create mode 100644 app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocalDataEraser.java create mode 100644 app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java create mode 100644 app/src/main/res/layout/dialog_also_erase.xml 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..6ec6c2d3 --- /dev/null +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/RemovingATagForgetsItsKeysTest.java @@ -0,0 +1,307 @@ +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 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; + +/** + * 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\"}"; + + 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)); + } + + /** 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..03eaa540 --- /dev/null +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/ErasingEverythingFromSettingsTest.java @@ -0,0 +1,253 @@ +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")); + } + + /** 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..fd414c1b 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,13 +1157,21 @@ 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.removeDevice(device, eraseHistory.isChecked()); } this.endSelection(); }) @@ -1184,12 +1193,13 @@ private void explainAccountTagsCannotBeRemoved(final int howMany) { .show(); } - private void removeDevice(final BeaconInformation device) { + private void removeDevice(final BeaconInformation device, final boolean alsoErasingHistory) { final String beaconId = 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) + // Same call DeviceInfoActivity makes. Unless the history is being erased too, the row is + // hidden rather than deleted, so the location history survives a re-import; the keys are + // deleted either way. + var async = this.beaconRepo.removeBeacon(beaconId, alsoErasingHistory) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> this.refreshListOnItemRemoved(beaconId), 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..3a82eee9 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; @@ -100,6 +101,7 @@ import dev.wander.android.opentagviewer.util.android.WebLink; 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 +255,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 +1282,65 @@ 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. + */ + 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(); + + var async = 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(); + }) + .andThen(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..7011e1d2 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; @@ -1038,15 +1040,74 @@ public Observable> storeHistoryRecords(DailyHistor }).subscribeOn(Schedulers.io()); } - public Completable markBeaconAsRemoved(final String beaconId) { + /** + * Remove a tag the user imported from a file. Never called for an account tag, which the + * next account read would only write back - see {@code MyDevicesListActivity}. + * + *

Its keys go either way. Removing used to only hide the row, so the private key and + * shared secrets of every tag ever removed stayed in the database, readable by anybody who got + * at it, and could locate the tag until it was re-paired. Somebody removing a tag they sold or + * handed back expects them gone. + * + *

Its history goes only when asked. Hiding the row rather than deleting it is what + * lets a tag removed by mistake come back with its history by importing it again, and that is + * still the default. {@code alsoErasingHistory} deletes the row instead, which cascades to + * its location history, the record of which days were fetched, its last Bluetooth sighting + * and the user's name for it; and the import it came from, once no other tag refers to it. + * + *

Then the database is compacted, because a deleted row is otherwise still in the file's + * free pages, which is exactly where somebody reading the file would look. + */ + public Completable removeBeacon(final String beaconId, final boolean alsoErasingHistory) { return Completable.fromRunnable(() -> { + db.runInTransaction(() -> { + if (alsoErasingHistory) { + final Long importId = db.ownedBeaconDao().importIdOf(beaconId); + db.ownedBeaconDao().deleteById(beaconId); + db.beaconNamingRecordDao().deleteById(beaconId); + if (importId != null) { + db.importDao().deleteIfNothingRefersTo(importId); + } + } else { + db.beaconNamingRecordDao().setRemoved(beaconId); + db.ownedBeaconDao().removeAndForgetKeys(beaconId); + } + }); - db.beaconNamingRecordDao().setRemoved(beaconId); - db.ownedBeaconDao().setRemoved(beaconId); - + this.compactBestEffort(); }).subscribeOn(Schedulers.io()); } + /** + * Delete every tag, its keys and history, every import and every record about them. + * + *

Room's {@code clearAllTables} also checkpoints the write-ahead log and vacuums, so what + * was deleted does not linger in the file. It must not run on the main thread or inside a + * transaction, hence the scheduler. + */ + public Completable eraseEverything() { + return Completable.fromRunnable(db::clearAllTables).subscribeOn(Schedulers.io()); + } + + /** + * Rewrite the database file without the free pages a delete leaves behind, then fold the + * write-ahead log back in and truncate it. + * + *

Best effort: if another connection is busy it fails, and the data is still deleted as far + * as the app is concerned - only a forensic reading of the file could find it until the next + * compaction. Not worth failing the user's removal over. + */ + private void compactBestEffort() { + try { + final SupportSQLiteDatabase sqlite = db.getOpenHelper().getWritableDatabase(); + sqlite.execSQL("VACUUM"); + sqlite.query("PRAGMA wal_checkpoint(TRUNCATE)").close(); + } catch (RuntimeException e) { + Log.w(TAG, "Could not compact the database after removing a tag; the rows are gone" + + " but their bytes stay in the file until the next compaction", e); + } + } + public Observable> getInsertionHistoryItem(final String beaconId, final long startOfDayTimestampMS) { return Observable.fromCallable(() -> { DailyHistoryFetchRecord record = db.dailyHistoryFetchRecordDao().getIfExists(beaconId, startOfDayTimestampMS); diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocalDataEraser.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocalDataEraser.java new file mode 100644 index 00000000..828c18db --- /dev/null +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocalDataEraser.java @@ -0,0 +1,20 @@ +package dev.wander.android.opentagviewer.db.repo; + +import io.reactivex.rxjava3.core.Completable; + +/** + * Erases what this app keeps about the user's tags on this phone. + * + *

An interface so that Settings can be driven in a test without erasing the database the test + * runs against: the instrumented suite shares the real on-device database, and on somebody's own + * phone that holds their tags. See {@code AppDependencies#replaceDataEraser}. + */ +public interface LocalDataEraser { + /** + * Every tag and its keys, location history, imports and the records about them; the iCloud + * link's keys; and the last map position. Not the settings, not the Apple session (signing + * out is the caller's next step) and not the device identity, which would make the next + * sign-in register a second device on the account (AGENTS.md rule 11). + */ + Completable eraseEverything(); +} diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java new file mode 100644 index 00000000..fa2bc751 --- /dev/null +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java @@ -0,0 +1,52 @@ +package dev.wander.android.opentagviewer.db.repo; + +import android.content.Context; + +import dev.wander.android.opentagviewer.db.datastore.UserAuthDataStore; +import dev.wander.android.opentagviewer.db.datastore.UserCacheDataStore; +import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; +import dev.wander.android.opentagviewer.util.android.AppCryptographyUtil; +import io.reactivex.rxjava3.core.Completable; + +/** + * The real {@link LocalDataEraser}: the Room database, the iCloud link and the map position. + * + *

The iCloud link is forgotten first, so that nothing reading the account between the + * two steps can write account tags back into a database that has just been emptied. + * + *

Forgetting the link does not leave the keychain circle; nothing here can. The peer stays on + * the account, which the confirmation says. It is still the right thing for "erase all data": + * those are a circle member's private keys, the most sensitive thing this app holds, and keeping + * them after the user asked for everything to be erased would be the opposite of what they asked. + */ +public final class ThisPhonesTagData implements LocalDataEraser { + + private final BeaconRepository beacons; + private final KeychainMembershipRepository memberships; + private final UserDataRepository userData; + + public ThisPhonesTagData( + final BeaconRepository beacons, + final KeychainMembershipRepository memberships, + final UserDataRepository userData) { + this.beacons = beacons; + this.memberships = memberships; + this.userData = userData; + } + + public static ThisPhonesTagData of(final Context context) { + final Context app = context.getApplicationContext(); + return new ThisPhonesTagData( + new BeaconRepository(OpenTagViewerDatabase.getInstance(app)), + new KeychainMembershipRepository( + UserAuthDataStore.getInstance(app), new AppCryptographyUtil()), + new UserDataRepository(UserCacheDataStore.getInstance(app))); + } + + @Override + public Completable eraseEverything() { + return this.memberships.forget() + .andThen(this.userData.forgetLastCameraPosition()) + .andThen(this.beacons.eraseEverything()); + } +} diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/UserDataRepository.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/UserDataRepository.java index 72bf35f6..05ac8b7d 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/UserDataRepository.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/UserDataRepository.java @@ -13,6 +13,7 @@ import java.util.Optional; import dev.wander.android.opentagviewer.data.model.UserMapCameraPosition; +import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.schedulers.Schedulers; @@ -54,4 +55,13 @@ public Observable storeLastCameraPosition(final UserMapCa .map(_ignored -> currentPosition) .subscribeOn(Schedulers.io()); } + + /** Forget where the map was last pointed, which is roughly where the user's tags were. */ + public Completable forgetLastCameraPosition() { + return Completable.fromSingle(this.userCache.updateDataAsync(cache -> { + final MutablePreferences mutablePreferences = cache.toMutablePreferences(); + mutablePreferences.remove(MAP_CAMERA_ORIENTATION); + return Single.just(mutablePreferences); + })).subscribeOn(Schedulers.io()); + } } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/BeaconNamingRecordDao.java b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/BeaconNamingRecordDao.java index f67833aa..5cb2c1c8 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/BeaconNamingRecordDao.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/BeaconNamingRecordDao.java @@ -24,6 +24,9 @@ public interface BeaconNamingRecordDao { @Query("UPDATE BeaconNamingRecord SET is_removed = 1 WHERE id = :beaconId") void setRemoved(String beaconId); + @Query("DELETE FROM BeaconNamingRecord WHERE id = :beaconId") + int deleteById(String beaconId); + @Delete void delete(BeaconNamingRecord beaconNamingRecWithId); } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/ImportDao.java b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/ImportDao.java index 0fc0ac63..daf87dee 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/ImportDao.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/ImportDao.java @@ -39,4 +39,15 @@ public interface ImportDao { @Delete int delete(Import importDataWithId); + + /** + * Delete an import once no tag refers to it any more, removed or not. + * + *

An import row records who exported the bundle ({@code source_user}, an Apple ID) and + * when. Once its last tag has been erased it describes nothing, so it goes too. One that a + * hidden, removed tag still points at stays, because a re-import may bring that tag back. + */ + @Query("DELETE FROM Import WHERE id = :importId" + + " AND NOT EXISTS (SELECT 1 FROM OwnedBeacons WHERE import_id = :importId)") + int deleteIfNothingRefersTo(long importId); } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/OwnedBeaconDao.java b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/OwnedBeaconDao.java index e7ef6576..ea9b18b8 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/OwnedBeaconDao.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/OwnedBeaconDao.java @@ -103,6 +103,32 @@ void refreshFromImport(String beaconId, String content, String alignmentPlist, @Query("UPDATE OwnedBeacons SET is_removed = 1 WHERE id = :beaconId") void setRemoved(String beaconId); + /** + * Hide a tag the user removed, and forget its keys. + * + *

The row stays, so its location history stays with it (hidden, like the row) and comes + * back if the same tag is imported again. The three columns that hold key material do not: + * {@code content} is the exported plist with the private key and shared secrets, + * {@code accessory_json} is FindMy.py's state built from the same keys, and + * {@code alignment_plist} is where the key schedule had got to. Somebody who removes a tag + * they sold or gave back reasonably expects those to be gone. A re-import supplies all three + * again, through {@link #refreshFromImport}, whose {@code COALESCE}s fill a null in. + */ + @Query("UPDATE OwnedBeacons SET is_removed = 1, content = NULL, accessory_json = NULL," + + " alignment_plist = NULL WHERE id = :beaconId") + void removeAndForgetKeys(String beaconId); + + /** + * Delete a tag outright. Its location history, fetch records, last Bluetooth sighting and the + * user's name for it are children of this row and go with it ({@code ON DELETE CASCADE}). + */ + @Query("DELETE FROM OwnedBeacons WHERE id = :beaconId") + int deleteById(String beaconId); + + /** Which import a row came from, removed or not; null for an account tag or no such row. */ + @Query("SELECT import_id FROM OwnedBeacons WHERE id = :beaconId") + Long importIdOf(String beaconId); + /** * Persist the rolling-key alignment state (FindMy 0.9.x stateful FindMyAccessory) * after a successful fetch. Targeted UPDATE so we don't risk clobbering other diff --git a/app/src/main/java/dev/wander/android/opentagviewer/python/AppDependencies.java b/app/src/main/java/dev/wander/android/opentagviewer/python/AppDependencies.java index 4f34d8a2..1e97f71b 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/python/AppDependencies.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/python/AppDependencies.java @@ -22,6 +22,8 @@ import dev.wander.android.opentagviewer.ble.RoutingSoundTrigger; import dev.wander.android.opentagviewer.python.icloud.ICloudService; import dev.wander.android.opentagviewer.python.icloud.PythonICloudService; +import dev.wander.android.opentagviewer.db.repo.LocalDataEraser; +import dev.wander.android.opentagviewer.db.repo.ThisPhonesTagData; import dev.wander.android.opentagviewer.db.repo.model.UserSettings; import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; import dev.wander.android.opentagviewer.service.web.AnisetteServerTesterService; @@ -135,6 +137,17 @@ public interface AnisetteFactory { */ private static BundleBuilder bundleBuilder = new ChaquopyBundleBuilder(); + /** + * Erases the user's tags, keys and history from this phone, for Settings. + * + *

Here so a test can press the button without it doing the thing. The instrumented + * suite runs against the real on-device database, which on somebody's own phone holds their + * tags; a test of the erase button that really erased would wipe them. So a test checks the + * screen calls this, and {@code ErasingEverythingTest} checks what the real one deletes, + * against an in-memory database. + */ + private static Function dataEraserFactory = ThisPhonesTagData::of; + /** Builds the blocking history importer for the My Devices screen. */ private static Function historyImporterFactory = context -> new HistoryImporter(OpenTagViewerDatabase.getInstance( @@ -236,6 +249,15 @@ public static BundleBuilder bundleBuilder() { return bundleBuilder; } + public static LocalDataEraser dataEraser(final Context context) { + return dataEraserFactory.apply(context); + } + + @VisibleForTesting + public static void replaceDataEraser(final LocalDataEraser replacement) { + dataEraserFactory = context -> replacement; + } + public static HistoryArchiveImporter historyImporter(final Context context) { return historyImporterFactory.apply(context); } @@ -308,6 +330,7 @@ public static void reset() { accessorySoundTrigger = null; logRedactor = new ChaquopyLogRedactor(); bundleBuilder = new ChaquopyBundleBuilder(); + dataEraserFactory = ThisPhonesTagData::of; historyImporterFactory = context -> new HistoryImporter( OpenTagViewerDatabase.getInstance(context.getApplicationContext())); icloudFactory = AppDependencies::openRealICloud; diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml index d9c30adf..c1d2db27 100644 --- a/app/src/main/res/layout/activity_settings.xml +++ b/app/src/main/res/layout/activity_settings.xml @@ -25,6 +25,7 @@ + + + + diff --git a/app/src/main/res/layout/dialog_also_erase.xml b/app/src/main/res/layout/dialog_also_erase.xml new file mode 100644 index 00000000..b35f5b5c --- /dev/null +++ b/app/src/main/res/layout/dialog_also_erase.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index eb49e8a3..a81918d2 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -465,4 +465,13 @@ Wenn Apple die Anfrage lediglich abgelehnt hat, lohnt es sich, zu warten und es Tags App Eine Datei von Apple konnte nicht geladen werden + Auch den Standortverlauf löschen. Ein erneuter Import des Tags bringt ihn nicht zurück. + Auch deren Standortverlauf löschen. Ein erneuter Import der Tags bringt ihn nicht zurück. + Auch alle Tags auf diesem Telefon samt Schlüsseln und Standortverlauf sowie die iCloud-Verknüpfung löschen + Alle Daten löschen + Alle Tags samt Schlüsseln und Standortverlauf von diesem Telefon löschen und abmelden + Alle Daten löschen? + Alle Tags auf diesem Telefon werden gelöscht, samt Schlüsseln und Standortverlauf, ebenso die Importe, aus denen sie stammen, und die iCloud-Verknüpfung. Du wirst von deinem Apple-Konto abgemeldet. Deine Einstellungen bleiben erhalten.\n\nDas lässt sich nicht rückgängig machen. Ein aus einer Datei importierter Tag kommt nur zurück, wenn du diese Datei erneut importierst.\n\nDie App wird dadurch nicht aus deinem Apple-Konto entfernt. Das muss auf einem Apple-Gerät geschehen. + Löschen + Die Daten auf diesem Telefon konnten nicht gelöscht werden, daher bist du weiterhin angemeldet. Versuche es erneut. \ No newline at end of file diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml index 63cb61c7..8982d754 100644 --- a/app/src/main/res/values-en/strings.xml +++ b/app/src/main/res/values-en/strings.xml @@ -465,4 +465,13 @@ If Apple simply refused the request, waiting and trying again is worth doing fir Tags App Couldn\'t download a file from Apple + Also delete its location history. Importing the tag again will not bring it back. + Also delete their location history. Importing the tags again will not bring it back. + Also erase every tag on this phone, with its keys and location history, and the iCloud link + Erase all data + Delete every tag, its keys and location history from this phone, and log out + Erase all data? + Every tag on this phone is deleted, with its keys and location history, along with the imports they came from and the iCloud link. You are logged out of your Apple account. Your settings stay.\n\nThis cannot be undone. A tag imported from a file comes back only by importing that file again.\n\nThis does not remove the app from your Apple account. That has to be done on an Apple device. + Erase + Could not erase the data on this phone, so you are still logged in. Try again. \ No newline at end of file diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 5d05eec1..5639b7f8 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -465,4 +465,13 @@ Si Apple a simplement refusé la requête, il vaut mieux attendre et réessayer. Balises Application Impossible de télécharger un fichier d\'Apple + Supprimer aussi son historique de localisation. Importer à nouveau la balise ne le restaurera pas. + Supprimer aussi leur historique de localisation. Importer à nouveau les balises ne le restaurera pas. + Effacer aussi toutes les balises de ce téléphone, avec leurs clés et leur historique de localisation, ainsi que l’association iCloud + Effacer toutes les données + Supprimer toutes les balises, leurs clés et leur historique de localisation de ce téléphone, et se déconnecter + Effacer toutes les données ? + Toutes les balises de ce téléphone sont supprimées, avec leurs clés et leur historique de localisation, ainsi que les importations dont elles proviennent et l’association iCloud. Vous êtes déconnecté de votre compte Apple. Vos réglages sont conservés.\n\nCette action est irréversible. Une balise importée depuis un fichier ne revient qu’en important à nouveau ce fichier.\n\nCela ne retire pas l’application de votre compte Apple. Cela doit se faire sur un appareil Apple. + Effacer + Impossible d’effacer les données de ce téléphone, vous êtes donc toujours connecté. Réessayez. \ No newline at end of file diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 2fdc24d5..45f6d5e5 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -465,4 +465,13 @@ Appleが要求を拒否しただけなら、少し待ってからもう一度お タグ アプリ Apple からファイルをダウンロードできませんでした + 位置情報の履歴も削除する。タグを再度インポートしても元に戻りません。 + 位置情報の履歴も削除する。タグを再度インポートしても元に戻りません。 + このスマートフォン上のすべてのタグ(キーと位置情報の履歴を含む)と iCloud 連携も消去する + すべてのデータを消去 + このスマートフォンからすべてのタグ、キー、位置情報の履歴を削除してログアウトします + すべてのデータを消去しますか? + このスマートフォン上のすべてのタグが、キーと位置情報の履歴、インポート元のデータ、iCloud 連携とともに削除されます。Apple アカウントからログアウトします。設定はそのまま残ります。\n\nこの操作は取り消せません。ファイルからインポートしたタグは、そのファイルを再度インポートしない限り戻りません。\n\nこれによって Apple アカウントからこのアプリが削除されるわけではありません。削除は Apple デバイスで行う必要があります。 + 消去 + このスマートフォンのデータを消去できなかったため、ログインしたままです。もう一度お試しください。 \ No newline at end of file diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 40abf6ac..1c83a9fb 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -465,4 +465,13 @@ Apple이 요청을 거부한 것뿐이라면 잠시 기다렸다가 다시 시 태그 앱 Apple에서 파일을 다운로드하지 못했습니다 + 위치 기록도 삭제합니다. 태그를 다시 가져와도 복구되지 않습니다. + 위치 기록도 삭제합니다. 태그를 다시 가져와도 복구되지 않습니다. + 이 휴대폰의 모든 태그(키와 위치 기록 포함)와 iCloud 연결도 지웁니다 + 모든 데이터 지우기 + 이 휴대폰에서 모든 태그, 키, 위치 기록을 삭제하고 로그아웃합니다 + 모든 데이터를 지우시겠습니까? + 이 휴대폰의 모든 태그가 키, 위치 기록, 가져온 원본 데이터, iCloud 연결과 함께 삭제됩니다. Apple 계정에서 로그아웃됩니다. 설정은 유지됩니다.\n\n이 작업은 되돌릴 수 없습니다. 파일에서 가져온 태그는 그 파일을 다시 가져와야만 돌아옵니다.\n\n이 작업으로 Apple 계정에서 이 앱이 제거되지는 않습니다. 제거는 Apple 기기에서 해야 합니다. + 지우기 + 이 휴대폰의 데이터를 지우지 못해 로그인 상태가 유지됩니다. 다시 시도하세요. \ No newline at end of file diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 0798f801..bf955314 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -465,4 +465,13 @@ Als Apple het verzoek simpelweg weigerde, is even wachten en opnieuw proberen he Tags App Kon een bestand van Apple niet downloaden + Ook de locatiegeschiedenis verwijderen. Opnieuw importeren van de tag brengt die niet terug. + Ook hun locatiegeschiedenis verwijderen. Opnieuw importeren van de tags brengt die niet terug. + Ook alle tags op deze telefoon wissen, met hun sleutels en locatiegeschiedenis, en de iCloud-koppeling + Alle gegevens wissen + Alle tags met hun sleutels en locatiegeschiedenis van deze telefoon verwijderen en uitloggen + Alle gegevens wissen? + Alle tags op deze telefoon worden verwijderd, met hun sleutels en locatiegeschiedenis, samen met de imports waar ze vandaan kwamen en de iCloud-koppeling. Je wordt uitgelogd bij je Apple-account. Je instellingen blijven bewaard.\n\nDit kan niet ongedaan worden gemaakt. Een tag die uit een bestand is geïmporteerd, komt alleen terug door dat bestand opnieuw te importeren.\n\nDe app wordt hiermee niet uit je Apple-account verwijderd. Dat moet op een Apple-apparaat gebeuren. + Wissen + De gegevens op deze telefoon konden niet worden gewist, dus je bent nog ingelogd. Probeer het opnieuw. \ No newline at end of file diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 31bd60bc..3d9b7762 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -465,4 +465,13 @@ Метки Приложение Не удалось скачать файл от Apple + Также удалить её историю местоположений. Повторный импорт метки её не вернёт. + Также удалить их историю местоположений. Повторный импорт меток её не вернёт. + Также стереть все метки на этом телефоне вместе с их ключами и историей местоположений, а также привязку iCloud + Стереть все данные + Удалить с этого телефона все метки, их ключи и историю местоположений и выйти + Стереть все данные? + Все метки на этом телефоне будут удалены вместе с ключами и историей местоположений, а также импорты, из которых они получены, и привязка iCloud. Вы выйдете из учётной записи Apple. Настройки сохранятся.\n\nЭто нельзя отменить. Метка, импортированная из файла, вернётся только при повторном импорте этого файла.\n\nЭто не удаляет приложение из вашей учётной записи Apple. Это нужно сделать на устройстве Apple. + Стереть + Не удалось стереть данные на этом телефоне, поэтому вы по-прежнему в учётной записи. Попробуйте ещё раз. \ No newline at end of file diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 0718faf6..c0bb7b7d 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -465,4 +465,13 @@ 标签 应用 无法从 Apple 下载文件 + 同时删除其位置记录。再次导入该标签也无法恢复。 + 同时删除它们的位置记录。再次导入这些标签也无法恢复。 + 同时清除此手机上的所有标签(包括密钥和位置记录)以及 iCloud 关联 + 清除所有数据 + 从此手机删除所有标签及其密钥和位置记录,并退出登录 + 清除所有数据? + 此手机上的所有标签将被删除,连同其密钥、位置记录、导入来源以及 iCloud 关联。你将退出 Apple 账户。你的设置会保留。\n\n此操作无法撤销。从文件导入的标签只有再次导入该文件才能恢复。\n\n这不会将此应用从你的 Apple 账户中移除。移除需要在 Apple 设备上进行。 + 清除 + 无法清除此手机上的数据,因此你仍处于登录状态。请重试。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 63429f9e..690da6ce 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -465,4 +465,13 @@ 標籤 App 無法從 Apple 下載檔案 + 同時刪除其位置記錄。再次匯入該標籤也無法復原。 + 同時刪除它們的位置記錄。再次匯入這些標籤也無法復原。 + 同時清除此手機上的所有標籤(包括金鑰和位置記錄)以及 iCloud 連結 + 清除所有資料 + 從此手機刪除所有標籤及其金鑰和位置記錄,並登出 + 清除所有資料? + 此手機上的所有標籤將被刪除,連同其金鑰、位置記錄、匯入來源以及 iCloud 連結。你將登出 Apple 帳戶。你的設定會保留。\n\n此操作無法復原。從檔案匯入的標籤只有再次匯入該檔案才能恢復。\n\n這不會將此 App 從你的 Apple 帳戶中移除。移除需要在 Apple 裝置上進行。 + 清除 + 無法清除此手機上的資料,因此你仍處於登入狀態。請再試一次。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index eaf81bb7..aa1c0659 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -500,4 +500,13 @@ If Apple simply refused the request, waiting and trying again is worth doing fir Tags App Couldn\'t download a file from Apple + Also delete its location history. Importing the tag again will not bring it back. + Also delete their location history. Importing the tags again will not bring it back. + Also erase every tag on this phone, with its keys and location history, and the iCloud link + Erase all data + Delete every tag, its keys and location history from this phone, and log out + Erase all data? + Every tag on this phone is deleted, with its keys and location history, along with the imports they came from and the iCloud link. You are logged out of your Apple account. Your settings stay.\n\nThis cannot be undone. A tag imported from a file comes back only by importing that file again.\n\nThis does not remove the app from your Apple account. That has to be done on an Apple device. + Erase + Could not erase the data on this phone, so you are still logged in. Try again. From 7fdd288ec8d37e36f79618cae7c91fdf126399d4 Mon Sep 17 00:00:00 2001 From: Rob Lazzurs Date: Mon, 23 Nov 2026 00:35:30 +0000 Subject: [PATCH 2/8] Do not sign out when the erase fails RxDataStore.updateDataAsync starts its write as soon as it is called, so `.andThen(authRepository.clearUser())` cleared the session while the chain was being built, before the erase had run, and whether or not it then failed. The toast said the user was still signed in; they were not. ErasingEverythingFromSettingsTest.aFailedEraseDoesNotSignOut caught it on the emulator. clearUser is now deferred until the erase completes, and the three steps of ThisPhonesTagData are deferred one after another for the same reason. AGENTS.md rule 23 records the trap. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 19 +++++++++++++++++++ .../opentagviewer/SettingsActivity.java | 5 ++++- .../db/repo/ThisPhonesTagData.java | 12 +++++++++--- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 34ebedfa..862355b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -841,6 +841,25 @@ 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 was caught by `ErasingEverythingFromSettingsTest.aFailedEraseDoesNotSignOut`: Settings signed +the user out after telling them the erase had failed and they were still signed in. **Wrap any +DataStore-backed call that must wait for something before it in `Completable.defer(...)`** (or +`Single.defer`), and when the order matters, test the failure path, because the success path +cannot tell the two apart. + --- ## Building and testing 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 3a82eee9..6f0f9d0e 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java @@ -1340,7 +1340,10 @@ private void performLogout(final boolean alsoErasingEverything) { 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(); }) - .andThen(this.authRepository.clearUser()) + // Deferred, not passed directly: RxDataStore.updateDataAsync starts the write the + // moment clearUser() is called, before anything subscribes, so building this chain + // with clearUser() in it signed the user out even when the erase above failed. + .andThen(Completable.defer(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/ThisPhonesTagData.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java index fa2bc751..d8105b76 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java @@ -43,10 +43,16 @@ public static ThisPhonesTagData of(final Context context) { new UserDataRepository(UserCacheDataStore.getInstance(app))); } + /** + * Each step deferred until the one before it has finished. The DataStore writes start the + * moment their method is called (RxDataStore.updateDataAsync does not wait for a subscriber), + * so chaining the calls directly would start all of them at once, and start them even if + * nobody ever subscribed. + */ @Override public Completable eraseEverything() { - return this.memberships.forget() - .andThen(this.userData.forgetLastCameraPosition()) - .andThen(this.beacons.eraseEverything()); + return Completable.defer(this.memberships::forget) + .andThen(Completable.defer(this.userData::forgetLastCameraPosition)) + .andThen(Completable.defer(this.beacons::eraseEverything)); } } From 4c81ca4257c1f0641703d0b39496eadaa0165e83 Mon Sep 17 00:00:00 2001 From: Rob Lazzurs Date: Mon, 23 Nov 2026 13:49:08 +0000 Subject: [PATCH 3/8] Use RxFlows.onlyAfter for the erase-then-sign-out step #317 added RxFlows.onlyAfter for the same eager-DataStore trap this branch worked around with Completable.defer. Settings' sign-out and ThisPhonesTagData's three steps now use it, so there is one way to write "only after" rather than two. AGENTS.md rule 23 points at the helper instead of describing a second convention. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 14 +++++++++----- .../android/opentagviewer/SettingsActivity.java | 13 +++++++------ .../opentagviewer/db/repo/ThisPhonesTagData.java | 16 +++++++++------- 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 862355b5..7d0924bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -854,11 +854,15 @@ but `clearUser()` is evaluated while the chain is being built, so the session is `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 was caught by `ErasingEverythingFromSettingsTest.aFailedEraseDoesNotSignOut`: Settings signed -the user out after telling them the erase had failed and they were still signed in. **Wrap any -DataStore-backed call that must wait for something before it in `Completable.defer(...)`** (or -`Single.defer`), and when the order matters, test the failure path, because the success path -cannot tell the two apart. +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. --- 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 6f0f9d0e..30366318 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java @@ -99,6 +99,7 @@ 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; @@ -1334,16 +1335,16 @@ private void performLogout(final boolean alsoErasingEverything) { ? AppDependencies.dataEraser(this).eraseEverything() : Completable.complete(); - var async = erasing + 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(); - }) - // Deferred, not passed directly: RxDataStore.updateDataAsync starts the write the - // moment clearUser() is called, before anything subscribes, so building this chain - // with clearUser() in it signed the user out even when the erase above failed. - .andThen(Completable.defer(this.authRepository::clearUser)) + }); + + // 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/ThisPhonesTagData.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java index d8105b76..1c7d57fe 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java @@ -6,6 +6,7 @@ import dev.wander.android.opentagviewer.db.datastore.UserCacheDataStore; import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; import dev.wander.android.opentagviewer.util.android.AppCryptographyUtil; +import dev.wander.android.opentagviewer.util.rx.RxFlows; import io.reactivex.rxjava3.core.Completable; /** @@ -44,15 +45,16 @@ public static ThisPhonesTagData of(final Context context) { } /** - * Each step deferred until the one before it has finished. The DataStore writes start the - * moment their method is called (RxDataStore.updateDataAsync does not wait for a subscriber), - * so chaining the calls directly would start all of them at once, and start them even if - * nobody ever subscribed. + * Each step starts only once the one before it has finished, through + * {@link RxFlows#onlyAfter}. The DataStore writes start the moment their method is called, so + * chaining the calls directly would start all of them at once, and start them even if nobody + * ever subscribed. The first is deferred for the same reason. */ @Override public Completable eraseEverything() { - return Completable.defer(this.memberships::forget) - .andThen(Completable.defer(this.userData::forgetLastCameraPosition)) - .andThen(Completable.defer(this.beacons::eraseEverything)); + final Completable link = Completable.defer(this.memberships::forget); + final Completable mapPosition = + RxFlows.onlyAfter(link, this.userData::forgetLastCameraPosition); + return RxFlows.onlyAfter(mapPosition, this.beacons::eraseEverything); } } From 1b6e57991ea6f89012a6fef25817d7dc4356967c Mon Sep 17 00:00:00 2001 From: Rob Lazzurs Date: Mon, 23 Nov 2026 13:49:49 +0000 Subject: [PATCH 4/8] Write nothing back onto a tag removed while a fetch was running updateAccessoryJson had no is_removed filter, so a fetch or Bluetooth sighting that was already running when the user removed a tag landed afterwards and wrote the accessory JSON, the keys Remove had just deleted, back onto the hidden row. It now updates only listed rows. The same race after "also delete its location history" failed the other way: the tag has no row, so its reports failed LocationReport's foreign key, and the single insert took every other tag's reports from that fetch with it. Reports are now stored only for tags that still have a row. Co-Authored-By: Claude Opus 5.5 --- .../repo/RemovingATagForgetsItsKeysTest.java | 66 +++++++++++++++++++ .../db/repo/BeaconRepository.java | 7 ++ .../db/room/dao/OwnedBeaconDao.java | 17 ++++- 3 files changed, 89 insertions(+), 1 deletion(-) 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 index 6ec6c2d3..7f880cd9 100644 --- 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 @@ -19,6 +19,10 @@ 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; @@ -29,6 +33,7 @@ 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; /** * What removing a tag leaves behind on the phone. @@ -55,6 +60,9 @@ public class RemovingATagForgetsItsKeysTest { 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; @@ -288,6 +296,64 @@ public void anImportAHiddenTagStillPointsAtIsKept() { 1, this.historyRowsFor(ITS_SIBLING)); } + /** + * 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() { 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 7011e1d2..dc9958a1 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 @@ -949,8 +949,15 @@ public Observable>> storeToLocationCache( final long now = System.currentTimeMillis(); + // Only for tags that still have a row. A fetch that was running when the user erased a + // tag lands afterwards, and one report for a tag with no row fails the foreign key and + // with it the whole insert, every other tag's reports included. + final Set held = new HashSet<>(db.ownedBeaconDao() + .whichExist(new ArrayList<>(reportsForBeaconId.keySet()))); + // flat map them all: LocationReport[] allRecords = reportsForBeaconId.entrySet().stream() + .filter(kvp -> held.contains(kvp.getKey())) .flatMap(kvp -> kvp.getValue().stream().map(locationReport -> LocationReport.builder() .hashId(BeaconLocationReportHasher.getSha256HashFor(kvp.getKey(), locationReport)) .beaconId(kvp.getKey()) diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/OwnedBeaconDao.java b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/OwnedBeaconDao.java index ea9b18b8..8f5be785 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/OwnedBeaconDao.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/OwnedBeaconDao.java @@ -133,10 +133,25 @@ void refreshFromImport(String beaconId, String content, String alignmentPlist, * Persist the rolling-key alignment state (FindMy 0.9.x stateful FindMyAccessory) * after a successful fetch. Targeted UPDATE so we don't risk clobbering other * columns if the in-memory copy is stale. + * + *

Never onto a removed tag. A fetch or a Bluetooth sighting that was already running + * when the user removed the tag lands afterwards, and without {@code is_removed = 0} it wrote + * the keys {@link #removeAndForgetKeys} had just deleted straight back onto the hidden row. */ - @Query("UPDATE OwnedBeacons SET accessory_json = :accessoryJson WHERE id = :beaconId") + @Query("UPDATE OwnedBeacons SET accessory_json = :accessoryJson" + + " WHERE id = :beaconId AND is_removed = 0") void updateAccessoryJson(String beaconId, String accessoryJson); + /** + * Which of these tags still have a row, removed or not. + * + *

For a fetch landing after a tag was erased: its reports have nothing to belong to, and + * {@code LocationReport}'s foreign key would fail the whole insert, every other tag's reports + * included. + */ + @Query("SELECT id FROM OwnedBeacons WHERE id IN (:beaconIds)") + List whichExist(List beaconIds); + @Delete void delete(OwnedBeacon ownedBeaconWithId); From 01faa37482528172b41c33e422b89aea993df04d Mon Sep 17 00:00:00 2001 From: Rob Lazzurs Date: Mon, 23 Nov 2026 13:50:07 +0000 Subject: [PATCH 5/8] Keep an import that a naming record still points at deleteIfNothingRefersTo checked only OwnedBeacons. 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, and BeaconNamingRecord cascades on delete. Erasing the other tag from that zip deleted the import and the account tag's name with it. The import now stays while a naming record refers to it. Co-Authored-By: Claude Opus 5.5 --- .../repo/RemovingATagForgetsItsKeysTest.java | 22 +++++++++++++++++++ .../opentagviewer/db/room/dao/ImportDao.java | 10 +++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) 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 index 7f880cd9..71ffc331 100644 --- 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 @@ -34,6 +34,7 @@ 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. @@ -296,6 +297,27 @@ public void anImportAHiddenTagStillPointsAtIsKept() { 1, this.historyRowsFor(ITS_SIBLING)); } + /** + * 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 diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/ImportDao.java b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/ImportDao.java index daf87dee..8e18fd21 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/ImportDao.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/ImportDao.java @@ -41,13 +41,19 @@ public interface ImportDao { int delete(Import importDataWithId); /** - * Delete an import once no tag refers to it any more, removed or not. + * Delete an import once nothing refers to it any more, removed or not. * *

An import row records who exported the bundle ({@code source_user}, an Apple ID) and * when. Once its last tag has been erased it describes nothing, so it goes too. One that a * hidden, removed tag still points at stays, because a re-import may bring that tag back. + * + *

Naming records count too. A tag that later arrived from the Apple account has its + * {@code OwnedBeacons} row moved off the import, but when the account holds no naming record + * for it, the one from the zip stays, still pointing here. {@code BeaconNamingRecord} cascades + * on delete, so deleting the import would take that tag's name with it. */ @Query("DELETE FROM Import WHERE id = :importId" - + " AND NOT EXISTS (SELECT 1 FROM OwnedBeacons WHERE import_id = :importId)") + + " AND NOT EXISTS (SELECT 1 FROM OwnedBeacons WHERE import_id = :importId)" + + " AND NOT EXISTS (SELECT 1 FROM BeaconNamingRecord WHERE import_id = :importId)") int deleteIfNothingRefersTo(long importId); } From 0c1208e3a3e6baaadc40f1be9916082e25939b02 Mon Sep 17 00:00:00 2001 From: Rob Lazzurs Date: Mon, 23 Nov 2026 13:53:00 +0000 Subject: [PATCH 6/8] Restart the background scan after erasing everything NearbyScanService reads the tags once, when it starts, and keeps their keys for the life of the service, so after "Erase all data" it went on listening for the erased tags, and alerting on them, until the process died. The eraser now restarts it, if it is running, as its last step, so only once the erase has succeeded. The same step deletes the addresses derived from each tag's keys, which are cached on disk. The restarted scan would retire them too, but only with Bluetooth permission, and only if it was running. ThisPhonesTagData takes its steps rather than the repositories, so ThisPhonesTagDataTest can pin the order on the JVM: link, map position, database, then the scan, and nothing after a failure. Co-Authored-By: Claude Opus 5.5 --- .../db/repo/LocalDataEraser.java | 7 +- .../db/repo/ThisPhonesTagData.java | 69 +++++++++++----- .../opentagviewer/python/AppDependencies.java | 4 +- .../service/NearbyScanService.java | 31 +++++++ .../db/repo/ThisPhonesTagDataTest.java | 80 +++++++++++++++++++ 5 files changed, 167 insertions(+), 24 deletions(-) create mode 100644 app/src/test/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagDataTest.java diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocalDataEraser.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocalDataEraser.java index 828c18db..2ffd44e3 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocalDataEraser.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocalDataEraser.java @@ -12,9 +12,10 @@ public interface LocalDataEraser { /** * Every tag and its keys, location history, imports and the records about them; the iCloud - * link's keys; and the last map position. Not the settings, not the Apple session (signing - * out is the caller's next step) and not the device identity, which would make the next - * sign-in register a second device on the account (AGENTS.md rule 11). + * link's keys; the last map position; and the tags the background scan is listening for. + * Not the settings, not the Apple session (signing out is the caller's next step) and not the + * device identity, which would make the next sign-in register a second device on the account + * (AGENTS.md rule 11). */ Completable eraseEverything(); } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java index 1c7d57fe..896acb0f 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagData.java @@ -2,46 +2,73 @@ import android.content.Context; +import java.util.Set; + +import dev.wander.android.opentagviewer.ble.DerivedAddressStore; import dev.wander.android.opentagviewer.db.datastore.UserAuthDataStore; import dev.wander.android.opentagviewer.db.datastore.UserCacheDataStore; import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; +import dev.wander.android.opentagviewer.service.NearbyScanService; import dev.wander.android.opentagviewer.util.android.AppCryptographyUtil; import dev.wander.android.opentagviewer.util.rx.RxFlows; import io.reactivex.rxjava3.core.Completable; +import io.reactivex.rxjava3.functions.Action; +import io.reactivex.rxjava3.functions.Supplier; /** - * The real {@link LocalDataEraser}: the Room database, the iCloud link and the map position. + * The real {@link LocalDataEraser}: the iCloud link, the map position, the Room database, and what + * the background scan holds. * *

The iCloud link is forgotten first, so that nothing reading the account between the - * two steps can write account tags back into a database that has just been emptied. + * steps can write account tags back into a database that has just been emptied. The cost is that + * a failure after it leaves the link gone and the tags still there, which the error says. * *

Forgetting the link does not leave the keychain circle; nothing here can. The peer stays on * the account, which the confirmation says. It is still the right thing for "erase all data": * those are a circle member's private keys, the most sensitive thing this app holds, and keeping * them after the user asked for everything to be erased would be the opposite of what they asked. + * + *

The steps are passed in rather than the repositories, so that the order can be tested on the + * JVM: two of them are DataStore writes, which start when called (AGENTS.md rule 23). */ public final class ThisPhonesTagData implements LocalDataEraser { - private final BeaconRepository beacons; - private final KeychainMembershipRepository memberships; - private final UserDataRepository userData; + private final Supplier forgetTheICloudLink; + private final Supplier forgetTheMapPosition; + private final Supplier eraseTheDatabase; + private final Action forgetWhatTheScanHolds; public ThisPhonesTagData( - final BeaconRepository beacons, - final KeychainMembershipRepository memberships, - final UserDataRepository userData) { - this.beacons = beacons; - this.memberships = memberships; - this.userData = userData; + final Supplier forgetTheICloudLink, + final Supplier forgetTheMapPosition, + final Supplier eraseTheDatabase, + final Action forgetWhatTheScanHolds) { + this.forgetTheICloudLink = forgetTheICloudLink; + this.forgetTheMapPosition = forgetTheMapPosition; + this.eraseTheDatabase = eraseTheDatabase; + this.forgetWhatTheScanHolds = forgetWhatTheScanHolds; } public static ThisPhonesTagData of(final Context context) { final Context app = context.getApplicationContext(); + final BeaconRepository beacons = + new BeaconRepository(OpenTagViewerDatabase.getInstance(app)); + final KeychainMembershipRepository memberships = new KeychainMembershipRepository( + UserAuthDataStore.getInstance(app), new AppCryptographyUtil()); + final UserDataRepository userData = + new UserDataRepository(UserCacheDataStore.getInstance(app)); + return new ThisPhonesTagData( - new BeaconRepository(OpenTagViewerDatabase.getInstance(app)), - new KeychainMembershipRepository( - UserAuthDataStore.getInstance(app), new AppCryptographyUtil()), - new UserDataRepository(UserCacheDataStore.getInstance(app))); + memberships::forget, + userData::forgetLastCameraPosition, + beacons::eraseEverything, + () -> { + // The addresses derived from each tag's keys, kept on disk so they are not + // derived again. The running scan retires them too when it restarts, but only + // if it has Bluetooth permission, and it may not be running at all. + new DerivedAddressStore(app.getFilesDir()).forgetAllExcept(Set.of()); + NearbyScanService.restartIfRunning(app); + }); } /** @@ -49,12 +76,16 @@ public static ThisPhonesTagData of(final Context context) { * {@link RxFlows#onlyAfter}. The DataStore writes start the moment their method is called, so * chaining the calls directly would start all of them at once, and start them even if nobody * ever subscribed. The first is deferred for the same reason. + * + *

The background scan is restarted last, and only once the database is empty: it read the + * tags when it started and keeps their keys until it stops, so before this it went on + * listening for the erased tags, and alerting on them, until the process died. */ @Override public Completable eraseEverything() { - final Completable link = Completable.defer(this.memberships::forget); - final Completable mapPosition = - RxFlows.onlyAfter(link, this.userData::forgetLastCameraPosition); - return RxFlows.onlyAfter(mapPosition, this.beacons::eraseEverything); + final Completable link = Completable.defer(this.forgetTheICloudLink); + final Completable mapPosition = RxFlows.onlyAfter(link, this.forgetTheMapPosition); + final Completable database = RxFlows.onlyAfter(mapPosition, this.eraseTheDatabase); + return database.andThen(Completable.fromAction(this.forgetWhatTheScanHolds)); } } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/python/AppDependencies.java b/app/src/main/java/dev/wander/android/opentagviewer/python/AppDependencies.java index 1e97f71b..519a897d 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/python/AppDependencies.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/python/AppDependencies.java @@ -143,8 +143,8 @@ public interface AnisetteFactory { *

Here so a test can press the button without it doing the thing. The instrumented * suite runs against the real on-device database, which on somebody's own phone holds their * tags; a test of the erase button that really erased would wipe them. So a test checks the - * screen calls this, and {@code ErasingEverythingTest} checks what the real one deletes, - * against an in-memory database. + * screen calls this, {@code RemovingATagForgetsItsKeysTest} checks what the real one deletes, + * against an in-memory database, and {@code ThisPhonesTagDataTest} the order it does it in. */ private static Function dataEraserFactory = ThisPhonesTagData::of; diff --git a/app/src/main/java/dev/wander/android/opentagviewer/service/NearbyScanService.java b/app/src/main/java/dev/wander/android/opentagviewer/service/NearbyScanService.java index 2074d2f9..4aac1e9d 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/service/NearbyScanService.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/service/NearbyScanService.java @@ -251,6 +251,35 @@ public static void stop(final Context context) { context.getApplicationContext().stopService(intent); } + /** Whether an instance is alive in this process: set in onCreate, cleared in onDestroy. */ + private static volatile boolean running = false; + + /** + * Stops the service and starts it again, if it is running. Otherwise does nothing. + * + *

For after the tags have been erased. The scan reads the tags once, when it starts, + * and keeps their keys for the life of the service. Without a restart it went on listening for + * the erased tags, and alerting on them, until the process died. A fresh instance reads the + * now empty database, and retires the erased tags' derived addresses on the way. + * + *

A start the system refuses is logged, not thrown. The erase has already succeeded by + * then, and failing it would tell the user nothing was erased. The stop has still happened, + * so nothing is listening for the erased tags; the setting starts it again with the app. + */ + public static void restartIfRunning(final Context context) { + if (!running) { + return; + } + Log.i(TAG, "Restarting, so the scan forgets tags that are no longer stored"); + stop(context); + try { + start(context); + } catch (IllegalStateException e) { + // ForegroundServiceStartNotAllowedException is one, on Android 12 and later. + Log.w(TAG, "Stopped the scan but could not start it again", e); + } + } + @Nullable @Override public IBinder onBind(final Intent intent) { @@ -260,6 +289,7 @@ public IBinder onBind(final Intent intent) { @Override public void onCreate() { super.onCreate(); + running = true; this.beaconRepo = new BeaconRepository( OpenTagViewerDatabase.getInstance(this.getApplicationContext())); @@ -310,6 +340,7 @@ public void onDestroy() { // alarm would outlive the thing that started it. this.alarm.stop(); } + running = false; super.onDestroy(); } diff --git a/app/src/test/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagDataTest.java b/app/src/test/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagDataTest.java new file mode 100644 index 00000000..e2ed0549 --- /dev/null +++ b/app/src/test/java/dev/wander/android/opentagviewer/db/repo/ThisPhonesTagDataTest.java @@ -0,0 +1,80 @@ +package dev.wander.android.opentagviewer.db.repo; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import io.reactivex.rxjava3.core.Completable; +import io.reactivex.rxjava3.functions.Supplier; + +/** + * The order "erase all data" does things in, and that a failure stops it. + * + *

What each step deletes is pinned against an in-memory database by + * {@code RemovingATagForgetsItsKeysTest}. This is about the sequence, which is where the bugs were: + * two of the steps are DataStore writes, which start when called rather than when subscribed + * (AGENTS.md rule 23), and the background scan kept listening for erased tags until it was + * restarted. + */ +public class ThisPhonesTagDataTest { + + private final List steps = new ArrayList<>(); + + /** + * Stands in for each step. Like a DataStore write, it is recorded when called, not when + * subscribed, so a step started too early shows up in {@link #steps}. + */ + private Supplier step(final String name, final Set failing) { + return () -> { + this.steps.add(name); + return failing.contains(name) + ? Completable.error(new IllegalStateException(name + " failed")) + : Completable.complete(); + }; + } + + private ThisPhonesTagData eraser(final Set failing) { + return new ThisPhonesTagData( + this.step("link", failing), + this.step("map position", failing), + this.step("database", failing), + () -> this.steps.add("scan")); + } + + @Test + public void nothingIsErasedUntilSubscribed() { + final Completable unused = this.eraser(Set.of()).eraseEverything(); + + assertEquals(List.of(), this.steps); + } + + /** The link first, so no account read can refill an emptied database; the scan last. */ + @Test + public void erasesInOrderAndRestartsTheScanLast() { + this.eraser(Set.of()).eraseEverything().test().assertComplete(); + + assertEquals(List.of("link", "map position", "database", "scan"), this.steps); + } + + /** A failed erase must leave the scan alone: the tags it is listening for are still there. */ + @Test + public void aFailedEraseStopsThereAndLeavesTheScanAlone() { + this.eraser(Set.of("database")).eraseEverything() + .test().assertError(IllegalStateException.class); + + assertEquals(List.of("link", "map position", "database"), this.steps); + } + + /** And a failure at the start erases nothing at all. */ + @Test + public void aFailureForgettingTheLinkErasesNothingElse() { + this.eraser(Set.of("link")).eraseEverything() + .test().assertError(IllegalStateException.class); + + assertEquals(List.of("link"), this.steps); + } +} From 1c0fb8ab483c44c1a8308674160de8b66008fc7f Mon Sep 17 00:00:00 2001 From: Rob Lazzurs Date: Mon, 23 Nov 2026 13:53:26 +0000 Subject: [PATCH 7/8] Say the iCloud link may be gone when the erase fails The eraser forgets the iCloud link before it empties the database, so an account read in between cannot write account tags back. A failure after that step leaves the link gone and the tags still there, but the toast said nothing had been erased. It now says the tags are still there and the link may not be. The order stays as it is. Co-Authored-By: Claude Opus 5.5 --- .../settings/ErasingEverythingFromSettingsTest.java | 11 +++++++++++ .../android/opentagviewer/SettingsActivity.java | 3 ++- app/src/main/res/values-de/strings.xml | 2 +- app/src/main/res/values-en/strings.xml | 2 +- app/src/main/res/values-fr/strings.xml | 2 +- app/src/main/res/values-ja/strings.xml | 2 +- app/src/main/res/values-ko/strings.xml | 2 +- app/src/main/res/values-nl/strings.xml | 2 +- app/src/main/res/values-ru/strings.xml | 2 +- app/src/main/res/values-zh-rCN/strings.xml | 2 +- app/src/main/res/values-zh-rTW/strings.xml | 2 +- app/src/main/res/values/strings.xml | 2 +- 12 files changed, 23 insertions(+), 11 deletions(-) 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 index 03eaa540..9bc0fc6f 100644 --- 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 @@ -180,6 +180,17 @@ public void theConfirmationSaysTheAppStaysOnTheAppleAccount() { 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() { 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 30366318..488f81dc 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java @@ -1324,7 +1324,8 @@ private void performLogout() { * *

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. + * 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 diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index a81918d2..c8c5066d 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -473,5 +473,5 @@ Wenn Apple die Anfrage lediglich abgelehnt hat, lohnt es sich, zu warten und es Alle Daten löschen? Alle Tags auf diesem Telefon werden gelöscht, samt Schlüsseln und Standortverlauf, ebenso die Importe, aus denen sie stammen, und die iCloud-Verknüpfung. Du wirst von deinem Apple-Konto abgemeldet. Deine Einstellungen bleiben erhalten.\n\nDas lässt sich nicht rückgängig machen. Ein aus einer Datei importierter Tag kommt nur zurück, wenn du diese Datei erneut importierst.\n\nDie App wird dadurch nicht aus deinem Apple-Konto entfernt. Das muss auf einem Apple-Gerät geschehen. Löschen - Die Daten auf diesem Telefon konnten nicht gelöscht werden, daher bist du weiterhin angemeldet. Versuche es erneut. + Es konnte nicht alles auf diesem Telefon gelöscht werden, daher bist du weiterhin angemeldet. Deine Tags sind noch da, die iCloud-Verknüpfung ist aber möglicherweise schon gelöscht. Versuche es erneut. \ No newline at end of file diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml index 8982d754..58f40289 100644 --- a/app/src/main/res/values-en/strings.xml +++ b/app/src/main/res/values-en/strings.xml @@ -473,5 +473,5 @@ If Apple simply refused the request, waiting and trying again is worth doing fir Erase all data? Every tag on this phone is deleted, with its keys and location history, along with the imports they came from and the iCloud link. You are logged out of your Apple account. Your settings stay.\n\nThis cannot be undone. A tag imported from a file comes back only by importing that file again.\n\nThis does not remove the app from your Apple account. That has to be done on an Apple device. Erase - Could not erase the data on this phone, so you are still logged in. Try again. + Could not erase everything on this phone, so you are still logged in. Your tags are still here, but the iCloud link may already be gone. Try again. \ No newline at end of file diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 5639b7f8..67b7e983 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -473,5 +473,5 @@ Si Apple a simplement refusé la requête, il vaut mieux attendre et réessayer. Effacer toutes les données ? Toutes les balises de ce téléphone sont supprimées, avec leurs clés et leur historique de localisation, ainsi que les importations dont elles proviennent et l’association iCloud. Vous êtes déconnecté de votre compte Apple. Vos réglages sont conservés.\n\nCette action est irréversible. Une balise importée depuis un fichier ne revient qu’en important à nouveau ce fichier.\n\nCela ne retire pas l’application de votre compte Apple. Cela doit se faire sur un appareil Apple. Effacer - Impossible d’effacer les données de ce téléphone, vous êtes donc toujours connecté. Réessayez. + Impossible de tout effacer sur ce téléphone, vous êtes donc toujours connecté. Vos balises sont toujours là, mais l’association iCloud a peut-être déjà été supprimée. Réessayez. \ No newline at end of file diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 45f6d5e5..506aaf4a 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -473,5 +473,5 @@ Appleが要求を拒否しただけなら、少し待ってからもう一度お すべてのデータを消去しますか? このスマートフォン上のすべてのタグが、キーと位置情報の履歴、インポート元のデータ、iCloud 連携とともに削除されます。Apple アカウントからログアウトします。設定はそのまま残ります。\n\nこの操作は取り消せません。ファイルからインポートしたタグは、そのファイルを再度インポートしない限り戻りません。\n\nこれによって Apple アカウントからこのアプリが削除されるわけではありません。削除は Apple デバイスで行う必要があります。 消去 - このスマートフォンのデータを消去できなかったため、ログインしたままです。もう一度お試しください。 + このスマートフォン上のすべてを消去できなかったため、ログインしたままです。タグは残っていますが、iCloud 連携はすでに削除されている可能性があります。もう一度お試しください。 \ No newline at end of file diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 1c83a9fb..92af15d2 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -473,5 +473,5 @@ Apple이 요청을 거부한 것뿐이라면 잠시 기다렸다가 다시 시 모든 데이터를 지우시겠습니까? 이 휴대폰의 모든 태그가 키, 위치 기록, 가져온 원본 데이터, iCloud 연결과 함께 삭제됩니다. Apple 계정에서 로그아웃됩니다. 설정은 유지됩니다.\n\n이 작업은 되돌릴 수 없습니다. 파일에서 가져온 태그는 그 파일을 다시 가져와야만 돌아옵니다.\n\n이 작업으로 Apple 계정에서 이 앱이 제거되지는 않습니다. 제거는 Apple 기기에서 해야 합니다. 지우기 - 이 휴대폰의 데이터를 지우지 못해 로그인 상태가 유지됩니다. 다시 시도하세요. + 이 휴대폰의 모든 데이터를 지우지 못해 로그인 상태가 유지됩니다. 태그는 그대로 있지만 iCloud 연결은 이미 삭제되었을 수 있습니다. 다시 시도하세요. \ No newline at end of file diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index bf955314..40dc009a 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -473,5 +473,5 @@ Als Apple het verzoek simpelweg weigerde, is even wachten en opnieuw proberen he Alle gegevens wissen? Alle tags op deze telefoon worden verwijderd, met hun sleutels en locatiegeschiedenis, samen met de imports waar ze vandaan kwamen en de iCloud-koppeling. Je wordt uitgelogd bij je Apple-account. Je instellingen blijven bewaard.\n\nDit kan niet ongedaan worden gemaakt. Een tag die uit een bestand is geïmporteerd, komt alleen terug door dat bestand opnieuw te importeren.\n\nDe app wordt hiermee niet uit je Apple-account verwijderd. Dat moet op een Apple-apparaat gebeuren. Wissen - De gegevens op deze telefoon konden niet worden gewist, dus je bent nog ingelogd. Probeer het opnieuw. + Niet alles op deze telefoon kon worden gewist, dus je bent nog ingelogd. Je tags zijn er nog, maar de iCloud-koppeling is mogelijk al verwijderd. Probeer het opnieuw. \ No newline at end of file diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 3d9b7762..416333a1 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -473,5 +473,5 @@ Стереть все данные? Все метки на этом телефоне будут удалены вместе с ключами и историей местоположений, а также импорты, из которых они получены, и привязка iCloud. Вы выйдете из учётной записи Apple. Настройки сохранятся.\n\nЭто нельзя отменить. Метка, импортированная из файла, вернётся только при повторном импорте этого файла.\n\nЭто не удаляет приложение из вашей учётной записи Apple. Это нужно сделать на устройстве Apple. Стереть - Не удалось стереть данные на этом телефоне, поэтому вы по-прежнему в учётной записи. Попробуйте ещё раз. + Не удалось стереть всё на этом телефоне, поэтому вы по-прежнему в учётной записи. Ваши метки на месте, но привязка iCloud, возможно, уже удалена. Попробуйте ещё раз. \ No newline at end of file diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index c0bb7b7d..2a2cb5da 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -473,5 +473,5 @@ 清除所有数据? 此手机上的所有标签将被删除,连同其密钥、位置记录、导入来源以及 iCloud 关联。你将退出 Apple 账户。你的设置会保留。\n\n此操作无法撤销。从文件导入的标签只有再次导入该文件才能恢复。\n\n这不会将此应用从你的 Apple 账户中移除。移除需要在 Apple 设备上进行。 清除 - 无法清除此手机上的数据,因此你仍处于登录状态。请重试。 + 无法清除此手机上的全部数据,因此你仍处于登录状态。你的标签仍在,但 iCloud 关联可能已被移除。请重试。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 690da6ce..25d3fb9a 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -473,5 +473,5 @@ 清除所有資料? 此手機上的所有標籤將被刪除,連同其金鑰、位置記錄、匯入來源以及 iCloud 連結。你將登出 Apple 帳戶。你的設定會保留。\n\n此操作無法復原。從檔案匯入的標籤只有再次匯入該檔案才能恢復。\n\n這不會將此 App 從你的 Apple 帳戶中移除。移除需要在 Apple 裝置上進行。 清除 - 無法清除此手機上的資料,因此你仍處於登入狀態。請再試一次。 + 無法清除此手機上的全部資料,因此你仍處於登入狀態。你的標籤仍在,但 iCloud 連結可能已被移除。請再試一次。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index aa1c0659..747f34a5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -508,5 +508,5 @@ If Apple simply refused the request, waiting and trying again is worth doing fir Erase all data? Every tag on this phone is deleted, with its keys and location history, along with the imports they came from and the iCloud link. You are logged out of your Apple account. Your settings stay.\n\nThis cannot be undone. A tag imported from a file comes back only by importing that file again.\n\nThis does not remove the app from your Apple account. That has to be done on an Apple device. Erase - Could not erase the data on this phone, so you are still logged in. Try again. + Could not erase everything on this phone, so you are still logged in. Your tags are still here, but the iCloud link may already be gone. Try again. From d9cdf58e6021b7fcb39bded84f8d4ef7e6c71d87 Mon Sep 17 00:00:00 2001 From: Rob Lazzurs Date: Mon, 23 Nov 2026 13:54:27 +0000 Subject: [PATCH 8/8] Remove a multi-selection in one transaction and one compaction Multi-select Remove called removeBeacon once per tag, concurrently, and each call vacuumed: the whole file was rewritten once per tag, and a vacuum that found another call holding the database failed. The device list now calls removeBeacons, which removes every selected tag in one transaction and compacts once. removeBeacon delegates to it. Co-Authored-By: Claude Opus 5.5 --- .../repo/RemovingATagForgetsItsKeysTest.java | 38 +++++++++++++++++++ .../opentagviewer/MyDevicesListActivity.java | 23 ++++++----- .../db/repo/BeaconRepository.java | 32 +++++++++++----- 3 files changed, 74 insertions(+), 19 deletions(-) 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 index 71ffc331..69c73239 100644 --- 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 @@ -297,6 +297,44 @@ public void anImportAHiddenTagStillPointsAtIsKept() { 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 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 fd414c1b..faee26e1 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/MyDevicesListActivity.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/MyDevicesListActivity.java @@ -1170,9 +1170,7 @@ private void confirmRemoveSelection() { .setMessage(message) .setView(alsoErase) .setPositiveButton(R.string.confirm, (dialog, which) -> { - for (BeaconInformation device : removable) { - this.removeDevice(device, eraseHistory.isChecked()); - } + this.removeDevices(removable, eraseHistory.isChecked()); this.endSelection(); }) .setNegativeButton(R.string.cancel, null) @@ -1193,18 +1191,23 @@ private void explainAccountTagsCannotBeRemoved(final int howMany) { .show(); } - private void removeDevice(final BeaconInformation device, final boolean alsoErasingHistory) { - 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. Unless the history is being erased too, the row is - // hidden rather than deleted, so the location history survives a re-import; the keys are + // 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.removeBeacon(beaconId, alsoErasingHistory) + 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/db/repo/BeaconRepository.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java index dc9958a1..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 @@ -1066,18 +1066,32 @@ public Observable> storeHistoryRecords(DailyHistor * free pages, which is exactly where somebody reading the file would look. */ public Completable removeBeacon(final String beaconId, final boolean alsoErasingHistory) { + return this.removeBeacons(List.of(beaconId), alsoErasingHistory); + } + + /** + * {@link #removeBeacon} for several tags at once, as the device list's multi-select does. + * + *

One transaction and one compaction, rather than one of each per tag. A compaction + * rewrites the whole file, so removing ten tags one by one rewrote it ten times, and the calls + * ran concurrently, so each could find another holding the database and fail. + */ + public Completable removeBeacons( + final List beaconIds, final boolean alsoErasingHistory) { return Completable.fromRunnable(() -> { db.runInTransaction(() -> { - if (alsoErasingHistory) { - final Long importId = db.ownedBeaconDao().importIdOf(beaconId); - db.ownedBeaconDao().deleteById(beaconId); - db.beaconNamingRecordDao().deleteById(beaconId); - if (importId != null) { - db.importDao().deleteIfNothingRefersTo(importId); + for (final String beaconId : beaconIds) { + if (alsoErasingHistory) { + final Long importId = db.ownedBeaconDao().importIdOf(beaconId); + db.ownedBeaconDao().deleteById(beaconId); + db.beaconNamingRecordDao().deleteById(beaconId); + if (importId != null) { + db.importDao().deleteIfNothingRefersTo(importId); + } + } else { + db.beaconNamingRecordDao().setRemoved(beaconId); + db.ownedBeaconDao().removeAndForgetKeys(beaconId); } - } else { - db.beaconNamingRecordDao().setRemoved(beaconId); - db.ownedBeaconDao().removeAndForgetKeys(beaconId); } });