diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/PruningOldLocationHistoryTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/PruningOldLocationHistoryTest.java new file mode 100644 index 00000000..c020d285 --- /dev/null +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/PruningOldLocationHistoryTest.java @@ -0,0 +1,222 @@ +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.assertNotNull; + +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.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import dev.wander.android.opentagviewer.db.repo.model.UserSettings; +import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; +import dev.wander.android.opentagviewer.db.room.entity.DailyHistoryFetchRecord; +import dev.wander.android.opentagviewer.db.room.entity.LocationReport; +import dev.wander.android.opentagviewer.db.room.entity.OwnedBeacon; + +/** + * What {@link LocationHistoryRetention} deletes, against a real SQLite in memory. + * + *

On a device because the delete is a correlated subquery, and whether it keeps each tag's + * newest report is a claim about SQLite that only SQLite can answer. In memory so it never + * touches the phone's own history. + */ +@RunWith(AndroidJUnit4.class) +public class PruningOldLocationHistoryTest { + + private static final String A_TAG = "tag-a"; + private static final String ANOTHER_TAG = "tag-b"; + + private static final long NOW = 1_800_000_000_000L; + private static final long DAY = TimeUnit.DAYS.toMillis(1); + private static final int A_MONTH = 31; + private static final long CUTOFF = NOW - A_MONTH * DAY; + + private OpenTagViewerDatabase db; + private LocationHistoryRetention retention; + + @Before + public void openAnInMemoryDatabase() { + this.db = Room.inMemoryDatabaseBuilder( + getInstrumentation().getTargetContext(), OpenTagViewerDatabase.class) + .allowMainThreadQueries() + .build(); + this.db.ownedBeaconDao().insertAll(own(A_TAG), own(ANOTHER_TAG)); + this.retention = new LocationHistoryRetention(this.db, () -> NOW); + } + + @After + public void closeIt() { + this.db.close(); + } + + @Test + public void keepingEverythingDeletesNothing() { + this.db.locationReportDao().insertAll( + report(A_TAG, NOW - 1000 * DAY), + report(A_TAG, NOW - 400 * DAY), + report(A_TAG, NOW - DAY)); + + assertEquals(0, (int) this.retention.prune(UserSettings.HISTORY_RETENTION_FOREVER) + .blockingGet()); + assertEquals(3, this.everything(A_TAG).size()); + } + + @Test + public void reportsOlderThanThePeriodGoAndNewerOnesStay() { + this.db.locationReportDao().insertAll( + report(A_TAG, NOW - 90 * DAY), + report(A_TAG, NOW - 40 * DAY), + report(A_TAG, NOW - 10 * DAY), + report(A_TAG, NOW - DAY)); + + assertEquals(2, (int) this.retention.prune(A_MONTH).blockingGet()); + assertEquals(List.of(NOW - 10 * DAY, NOW - DAY), this.timestamps(A_TAG)); + } + + /** + * A tag not heard from for longer than the period keeps its last known position. Without + * that the map would show it as never located, which reads as the app having lost it. + */ + @Test + public void aTagKeepsItsNewestReportHoweverOld() { + this.db.locationReportDao().insertAll( + report(A_TAG, NOW - 300 * DAY), + report(A_TAG, NOW - 200 * DAY), + report(A_TAG, NOW - 100 * DAY)); + + assertEquals(2, (int) this.retention.prune(A_MONTH).blockingGet()); + assertEquals(List.of(NOW - 100 * DAY), this.timestamps(A_TAG)); + } + + @Test + public void aTagWithOneOldReportKeepsIt() { + this.db.locationReportDao().insertAll(report(A_TAG, NOW - 500 * DAY)); + + assertEquals(0, (int) this.retention.prune(A_MONTH).blockingGet()); + assertEquals(List.of(NOW - 500 * DAY), this.timestamps(A_TAG)); + } + + /** Each tag is judged on its own newest, not on the newest report of any tag. */ + @Test + public void eachTagKeepsItsOwnNewest() { + this.db.locationReportDao().insertAll( + report(A_TAG, NOW - 200 * DAY), + report(A_TAG, NOW - DAY), + report(ANOTHER_TAG, NOW - 300 * DAY), + report(ANOTHER_TAG, NOW - 250 * DAY)); + + assertEquals(2, (int) this.retention.prune(A_MONTH).blockingGet()); + assertEquals(List.of(NOW - DAY), this.timestamps(A_TAG)); + assertEquals(List.of(NOW - 250 * DAY), this.timestamps(ANOTHER_TAG)); + + final Map onTheMap = new HashMap<>(); + for (final LocationReport latest : this.db.locationReportDao().getLastForAllBeacons()) { + onTheMap.put(latest.beaconId, latest); + } + assertEquals("the map still has a position for both tags", 2, onTheMap.size()); + assertEquals(NOW - 250 * DAY, onTheMap.get(ANOTHER_TAG).timestamp); + } + + @Test + public void aReportExactlyAtTheCutoffIsKept() { + this.db.locationReportDao().insertAll( + report(A_TAG, CUTOFF - 1), + report(A_TAG, CUTOFF), + report(A_TAG, NOW)); + + assertEquals(1, (int) this.retention.prune(A_MONTH).blockingGet()); + assertEquals(List.of(CUTOFF, NOW), this.timestamps(A_TAG)); + } + + /** + * Local sightings and Google reports are history too, and go by the same rule. The newest is + * the newest of any provenance, because that is what the map draws. + */ + @Test + public void everyProvenanceIsPrunedTheSameWay() { + this.db.locationReportDao().insertAll( + report(A_TAG, NOW - 60 * DAY, LocationReport.PROVENANCE_LOCAL), + report(A_TAG, NOW - 50 * DAY, LocationReport.PROVENANCE_GOOGLE), + report(A_TAG, NOW - 2 * DAY, LocationReport.PROVENANCE_APPLE)); + + assertEquals(2, (int) this.retention.prune(A_MONTH).blockingGet()); + assertEquals(List.of(NOW - 2 * DAY), this.timestamps(A_TAG)); + } + + /** + * The per-day "already fetched" markers stay. They hold no position, and without one the + * History screen would ask Apple for that day again. + */ + @Test + public void theFetchedDayMarkersAreLeftAlone() { + this.db.locationReportDao().insertAll( + report(A_TAG, NOW - 60 * DAY), + report(A_TAG, NOW - DAY)); + this.db.dailyHistoryFetchRecordDao().insertAll(DailyHistoryFetchRecord.builder() + .beaconId(A_TAG) + .dayStartTime(NOW - 60 * DAY) + .lastUpdate(NOW - 60 * DAY) + .build()); + + this.retention.prune(A_MONTH).blockingGet(); + + assertNotNull(this.db.dailyHistoryFetchRecordDao().getIfExists(A_TAG, NOW - 60 * DAY)); + } + + /** Ascending, so a failure reads as the history it left behind. */ + private List timestamps(final String beaconId) { + final List out = new ArrayList<>(); + for (final LocationReport report : this.everything(beaconId)) { + out.add(report.timestamp); + } + return out; + } + + private List everything(final String beaconId) { + return this.db.locationReportDao().getInTimeRange(beaconId, Long.MIN_VALUE, Long.MAX_VALUE); + } + + private static OwnedBeacon own(final String id) { + return OwnedBeacon.builder() + .id(id) + .content("{}") + .accessoryJson("{\"type\":\"accessory\"}") + .version("0.0.2") + .fromAccount(false) + .isRemoved(false) + .build(); + } + + private static LocationReport report(final String beaconId, final long timestamp) { + return report(beaconId, timestamp, LocationReport.PROVENANCE_APPLE); + } + + private static LocationReport report( + final String beaconId, final long timestamp, final String provenance) { + return LocationReport.builder() + .hashId(beaconId + "-" + timestamp) + .beaconId(beaconId) + .publishedAt(timestamp) + .description("report at " + timestamp) + .timestamp(timestamp) + .confidence(1) + .latitude(1.0) + .longitude(-1.0) + .horizontalAccuracy(10L) + .status(0) + .lastUpdate(timestamp) + .provenance(provenance) + .build(); + } +} diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionSettingTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionSettingTest.java new file mode 100644 index 00000000..27672141 --- /dev/null +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionSettingTest.java @@ -0,0 +1,235 @@ +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.doesNotExist; +import static androidx.test.espresso.assertion.ViewAssertions.matches; +import static androidx.test.espresso.matcher.RootMatchers.isDialog; +import static androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA; +import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; +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 android.content.Context; + +import androidx.test.core.app.ActivityScenario; +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.List; +import java.util.concurrent.CopyOnWriteArrayList; + +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.UserSettingsDataStore; +import dev.wander.android.opentagviewer.db.repo.HistoryPruner; +import dev.wander.android.opentagviewer.db.repo.UserSettingsRepository; +import dev.wander.android.opentagviewer.db.repo.model.UserSettings; +import dev.wander.android.opentagviewer.python.AppDependencies; +import io.reactivex.rxjava3.core.Single; + +/** + * Settings -> Keep location history. + * + *

The pruner is a fake: the suite runs against the real on-device database, and on somebody's + * own phone a real one would delete their history. {@code PruningOldLocationHistoryTest} checks + * what the real one deletes. This checks that the screen asks before deleting, asks for the right + * period, and saves the period before the delete starts. + */ +@RunWith(AndroidJUnit4.class) +public class HistoryRetentionSettingTest { + + private final Context context = getInstrumentation().getTargetContext(); + private final RecordingPruner pruner = new RecordingPruner(); + private DeviceStateGuard deviceState; + private ActivityScenario scenario; + + @Before + public void setUp() { + this.deviceState = DeviceStateGuard.capture(this.context); + AppDependencies.replaceAnisette(settings -> FakeAnisetteSource.ready()); + AppDependencies.replaceHistoryPruner(this.pruner); + this.storePeriod(null); + } + + @After + public void tearDown() { + if (this.scenario != null) { + this.scenario.close(); + } + AppDependencies.reset(); + this.deviceState.restore(); + } + + @Test + public void nobodyHasChosenSoItKeepsEverything() { + this.open(); + this.seeSubtitle(R.string.history_retention_forever); + assertEquals(List.of(), this.pruner.asked); + } + + @Test + public void choosingAMonthAsksBeforeDeleting() { + this.open(); + this.choose(R.string.history_retention_1_month); + + Eventually.check(() -> onView(withText(R.string.history_retention_confirm_message)) + .inRoot(isDialog()).check(matches(isDisplayed()))); + } + + @Test + public void cancellingKeepsEverythingAndDeletesNothing() { + this.open(); + this.choose(R.string.history_retention_1_month); + Eventually.check(() -> onView(withText(R.string.history_retention_confirm_title)) + .inRoot(isDialog()).check(matches(isDisplayed()))); + onView(withText(R.string.cancel)).inRoot(isDialog()).perform(click()); + + Eventually.check(() -> onView(withText(R.string.history_retention_confirm_title)) + .check(doesNotExist())); + this.seeSubtitle(R.string.history_retention_forever); + assertEquals(UserSettings.HISTORY_RETENTION_FOREVER, this.storedPeriod()); + assertEquals(List.of(), this.pruner.asked); + } + + /** + * Confirming saves the month and then deletes. The fake reads the stored period when it is + * called, so a delete that started before the save landed would record "forever". + */ + @Test + public void confirmingSavesTheMonthThenDeletesOlderHistory() { + this.open(); + this.choose(R.string.history_retention_1_month); + Eventually.check(() -> onView(withText(R.string.history_retention_confirm_button)) + .inRoot(isDialog()).check(matches(isDisplayed()))); + onView(withText(R.string.history_retention_confirm_button)) + .inRoot(isDialog()).perform(click()); + + Eventually.check(() -> assertEquals(List.of(31), this.pruner.asked)); + assertEquals("the period was not saved before the delete started", + List.of(31), this.pruner.storedWhenAsked); + assertEquals(31, this.storedPeriod()); + this.seeSubtitle(R.string.history_retention_1_month); + } + + @Test + public void goingBackToForeverDoesNotAskOrDelete() { + this.storePeriod(31); + this.open(); + this.seeSubtitle(R.string.history_retention_1_month); + + this.choose(R.string.history_retention_forever); + + Eventually.check(() -> assertEquals( + UserSettings.HISTORY_RETENTION_FOREVER, this.storedPeriod())); + this.seeSubtitle(R.string.history_retention_forever); + onView(withText(R.string.history_retention_confirm_title)).check(doesNotExist()); + assertEquals(List.of(), this.pruner.asked); + } + + @Test + public void aLongerPeriodIsSavedWithoutAsking() { + this.storePeriod(31); + this.open(); + + this.choose(R.string.history_retention_1_year); + + Eventually.check(() -> assertEquals(366, this.storedPeriod())); + this.seeSubtitle(R.string.history_retention_1_year); + onView(withText(R.string.history_retention_confirm_title)).check(doesNotExist()); + assertEquals(List.of(), this.pruner.asked); + } + + @Test + public void aShorterPeriodAsksAgain() { + this.storePeriod(366); + this.open(); + + this.choose(R.string.history_retention_3_months); + + Eventually.check(() -> onView(withText(R.string.history_retention_confirm_title)) + .inRoot(isDialog()).check(matches(isDisplayed()))); + onView(withText(R.string.history_retention_confirm_button)) + .inRoot(isDialog()).perform(click()); + Eventually.check(() -> assertEquals(List.of(92), this.pruner.asked)); + } + + /** The period stays chosen when the delete fails, so the next start deletes instead. */ + @Test + public void aFailedDeleteKeepsTheNewPeriod() { + this.pruner.fail = true; + this.open(); + this.choose(R.string.history_retention_1_month); + Eventually.check(() -> onView(withText(R.string.history_retention_confirm_button)) + .inRoot(isDialog()).check(matches(isDisplayed()))); + onView(withText(R.string.history_retention_confirm_button)) + .inRoot(isDialog()).perform(click()); + + Eventually.check(() -> assertEquals(List.of(31), this.pruner.asked)); + assertEquals(31, this.storedPeriod()); + this.seeSubtitle(R.string.history_retention_1_month); + } + + private void open() { + this.scenario = ActivityScenario.launch(SettingsActivity.class); + } + + private void choose(final int label) { + onView(withId(R.id.settings_history_retention)).perform(scrollTo(), click()); + Eventually.check(() -> onView(withText(label)).inRoot(isDialog()) + .check(matches(isDisplayed()))); + onView(withText(label)).inRoot(isDialog()).perform(click()); + onView(withText(R.string.accept)).inRoot(isDialog()).perform(click()); + } + + private void seeSubtitle(final int label) { + Eventually.check(() -> onView(allOf(withId(R.id.textView5), + isDescendantOfA(withId(R.id.settings_history_retention)))) + .check(matches(withText(label)))); + } + + private UserSettingsRepository repository() { + return new UserSettingsRepository(UserSettingsDataStore.getInstance(this.context)); + } + + private int storedPeriod() { + return this.repository().getUserSettings().resolveHistoryRetentionDays(); + } + + /** Changes only the period, leaving the rest of whatever is stored as it was. */ + private void storePeriod(final Integer days) { + final UserSettings settings = this.repository().getUserSettings(); + settings.setHistoryRetentionDays(days); + this.repository().storeUserSettings(settings).blockingAwait(); + } + + /** Records each call, and the period stored at that moment. */ + private final class RecordingPruner implements HistoryPruner { + final List asked = new CopyOnWriteArrayList<>(); + final List storedWhenAsked = new CopyOnWriteArrayList<>(); + volatile boolean fail = false; + + @Override + public Single prune(final int retentionDays) { + return Single.fromCallable(() -> { + this.storedWhenAsked.add(storedPeriod()); + this.asked.add(retentionDays); + if (this.fail) { + throw new IllegalStateException("a delete that fails, on purpose"); + } + return 0; + }); + } + } +} diff --git a/app/src/main/java/dev/wander/android/opentagviewer/OpenAirTagApplication.java b/app/src/main/java/dev/wander/android/opentagviewer/OpenAirTagApplication.java index d43d3ac4..a6016af8 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/OpenAirTagApplication.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/OpenAirTagApplication.java @@ -14,6 +14,7 @@ import dev.wander.android.opentagviewer.anisette.AppleLibraryProbeService; import dev.wander.android.opentagviewer.anisette.MacAdiService; import dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore; +import dev.wander.android.opentagviewer.db.repo.LocationHistoryRetention; import dev.wander.android.opentagviewer.db.repo.UserSettingsRepository; import dev.wander.android.opentagviewer.db.repo.model.UserSettings; import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; @@ -57,6 +58,7 @@ public void onCreate() { this.setupTheme(); this.setupSystemColors(); this.resumeBackgroundScanIfEnabled(); + this.deleteHistoryOlderThanChosen(); } private boolean isTheAppleLibraryProbe() { @@ -116,6 +118,39 @@ private void resumeBackgroundScanIfEnabled() { }); } + /** + * Deletes location history older than the period chosen in Settings, if one was. + * + *

At start because that is the one moment every process passes through, the background + * scan's included. Off the main thread for the same reason as the scan above, and because the + * delete can take a while on a large history. + * + *

With the default, keep everything, this reads one setting and stops: it never + * opens the database, so nothing changes for anyone who has not chosen a period. Nor does it + * create a database that does not exist yet, since there is nothing in it to delete. + */ + private void deleteHistoryOlderThanChosen() { + Schedulers.io().scheduleDirect(() -> { + try { + final int days = new UserSettingsRepository(UserSettingsDataStore.getInstance(this)) + .getUserSettings() + .resolveHistoryRetentionDays(); + + if (days == UserSettings.HISTORY_RETENTION_FOREVER || this.isFirstRun()) { + return; + } + + final int deleted = LocationHistoryRetention.of(this).prune(days).blockingGet(); + Log.i(TAG, "Kept " + days + " days of location history; deleted " + + deleted + " older reports"); + } catch (final Exception e) { + // Tried again at the next start. Keeping history a little longer than asked is + // not worth interrupting anybody over. + Log.w(TAG, "Could not delete location history older than the chosen period", e); + } + }); + } + /** * Whether to colour activities from the user's wallpaper. * 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..3ec0e913 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java @@ -90,6 +90,7 @@ import dev.wander.android.opentagviewer.service.web.sidestore.AnisetteServerSuggestion; import dev.wander.android.opentagviewer.ui.compat.WindowPaddingUtil; import dev.wander.android.opentagviewer.ui.settings.AmapApiKeyDialog; +import dev.wander.android.opentagviewer.ui.settings.HistoryRetentionRow; import dev.wander.android.opentagviewer.ui.settings.SharedMainSettingsManager; import dev.wander.android.opentagviewer.ui.extensions.AppAutoCompleteTextView; import dev.wander.android.opentagviewer.update.UpdateSettingsRow; @@ -275,6 +276,11 @@ protected void onCreate(Bundle savedInstanceState) { this.setupLeftBehindSettings(); + this.historyRetentionRow = new HistoryRetentionRow(this, this.currentSettings, + this.settingsRepository, this.binding::setHistoryRetentionSubtitle); + this.binding.setOnClickHistoryRetention(this.historyRetentionRow::onClick); + this.historyRetentionRow.refresh(); + this.setupUserInfo(); var async = this.github.getSuggestedServers().subscribe(suggestedServers -> { @@ -484,6 +490,9 @@ private String getCurrentThemeUiString() { /** Settings -> App updates. */ private UpdateSettingsRow appUpdatesRow; + /** Settings -> Keep location history. */ + private HistoryRetentionRow historyRetentionRow; + /** * Say whether this app has already joined the account's keychain. * diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/datastore/UserSettingsDataStore.java b/app/src/main/java/dev/wander/android/opentagviewer/db/datastore/UserSettingsDataStore.java index 9e59de1f..56b450b6 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/datastore/UserSettingsDataStore.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/datastore/UserSettingsDataStore.java @@ -42,6 +42,13 @@ public final class UserSettingsDataStore { public static final Preferences.Key LEFT_BEHIND_SOUND_URI = PreferencesKeys.stringKey("left_behind_sound_uri"); + /** + * How many days of location history to keep. Absent or zero means keep everything, which is + * what every install did before this existed. + */ + public static final Preferences.Key HISTORY_RETENTION_DAYS = + PreferencesKeys.intKey("history_retention_days"); + public static RxDataStore getInstance(Context context) { if (PREFERENCES_DATA_STORE == null) { PREFERENCES_DATA_STORE = new RxPreferenceDataStoreBuilder(context, SETTINGS_FILE_NAME) diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/HistoryPruner.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/HistoryPruner.java new file mode 100644 index 00000000..e5263fb7 --- /dev/null +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/HistoryPruner.java @@ -0,0 +1,22 @@ +package dev.wander.android.opentagviewer.db.repo; + +import io.reactivex.rxjava3.core.Single; + +/** + * Deletes location history older than the period chosen in Settings. + * + *

An interface so the Settings test can choose a period without deleting anything from the + * real on-device database, which on somebody's own phone holds their history. What the real one + * deletes is tested against an in-memory database instead. See {@link LocationHistoryRetention}. + */ +public interface HistoryPruner { + + /** + * Deletes reports older than {@code retentionDays}, keeping each tag's newest. + * + * @param retentionDays one of {@code UserSettings.HISTORY_RETENTION_CHOICES_DAYS}; + * {@code HISTORY_RETENTION_FOREVER} deletes nothing + * @return how many reports were deleted + */ + Single prune(int retentionDays); +} diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocationHistoryRetention.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocationHistoryRetention.java new file mode 100644 index 00000000..3bed677a --- /dev/null +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocationHistoryRetention.java @@ -0,0 +1,83 @@ +package dev.wander.android.opentagviewer.db.repo; + +import android.content.Context; + +import androidx.annotation.NonNull; + +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; + +import dev.wander.android.opentagviewer.db.repo.model.UserSettings; +import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; +import io.reactivex.rxjava3.core.Single; +import io.reactivex.rxjava3.schedulers.Schedulers; + +/** + * Deletes location reports older than the period chosen in Settings, keeping each tag's newest. + * + *

Runs when the app starts and when a shorter period is chosen. Nothing else deletes history + * on a timer, because the app has no background work outside the optional scan. + * + *

Keeping everything opens nothing. With the default, {@link #prune} returns without + * touching the database, so an install that never chose a period behaves exactly as it did + * before this existed. + * + *

What is left alone: + *

+ */ +public final class LocationHistoryRetention implements HistoryPruner { + + /** Returned by {@link #cutoffFor} when nothing is to be deleted. */ + public static final long NO_CUTOFF = Long.MIN_VALUE; + + private final OpenTagViewerDatabase db; + private final LongSupplier clock; + + public LocationHistoryRetention( + @NonNull final OpenTagViewerDatabase db, @NonNull final LongSupplier clock) { + this.db = db; + this.clock = clock; + } + + public static LocationHistoryRetention of(@NonNull final Context context) { + return new LocationHistoryRetention( + OpenTagViewerDatabase.getInstance(context.getApplicationContext()), + System::currentTimeMillis); + } + + @Override + public Single prune(final int retentionDays) { + return Single.fromCallable(() -> { + final long cutoff = cutoffFor(retentionDays, this.clock.getAsLong()); + if (cutoff == NO_CUTOFF) { + return 0; + } + return this.db.locationReportDao().deleteOlderThanExceptNewest(cutoff); + }).subscribeOn(Schedulers.io()); + } + + /** + * The oldest report time to keep, in Unix milliseconds, or {@link #NO_CUTOFF}. + * + *

The period goes through {@link UserSettings#resolveHistoryRetentionDays()} first, so a + * value that is not one of the choices keeps at least as much as asked, never less. + */ + public static long cutoffFor(final int retentionDays, final long nowUnixMS) { + final int days = UserSettings.builder() + .historyRetentionDays(retentionDays) + .build() + .resolveHistoryRetentionDays(); + + if (days == UserSettings.HISTORY_RETENTION_FOREVER) { + return NO_CUTOFF; + } + return nowUnixMS - TimeUnit.DAYS.toMillis(days); + } +} diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/UserSettingsRepository.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/UserSettingsRepository.java index a8920e8f..a6dd6131 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/UserSettingsRepository.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/UserSettingsRepository.java @@ -6,6 +6,7 @@ import static dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore.ANISETTE_UPGRADE_OFFERED; import static dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore.ANISETTE_SERVER_URL; import static dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore.ENABLE_DEBUG_DATA; +import static dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore.HISTORY_RETENTION_DAYS; import static dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore.ICLOUD_OFFER_MADE; import static dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore.LANGUAGE; import static dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore.LEFT_BEHIND_AFTER_SECONDS; @@ -50,6 +51,7 @@ public UserSettings getUserSettings() { Boolean icloudOfferMade = settings.get(ICLOUD_OFFER_MADE); Integer leftBehindAfterSeconds = settings.get(LEFT_BEHIND_AFTER_SECONDS); String leftBehindSoundUri = settings.get(LEFT_BEHIND_SOUND_URI); + Integer historyRetentionDays = settings.get(HISTORY_RETENTION_DAYS); return UserSettings.builder() .anisetteServerUrl(anisetteServerUrl) @@ -67,6 +69,7 @@ public UserSettings getUserSettings() { .icloudOfferMade(icloudOfferMade) .leftBehindAfterSeconds(leftBehindAfterSeconds) .leftBehindSoundUri(leftBehindSoundUri) + .historyRetentionDays(historyRetentionDays) .build(); }).subscribeOn(Schedulers.io()) @@ -115,6 +118,12 @@ public Completable storeUserSettings(UserSettings userSettings) { mutablePreferences.set(LEFT_BEHIND_SOUND_URI, userSettings.getLeftBehindSoundUri() == null ? "" : userSettings.getLeftBehindSoundUri()); + // Zero rather than absent for "keep everything", for the same reason as above: an int + // key cannot hold null. resolveHistoryRetentionDays reads zero as keep everything. + mutablePreferences.set(HISTORY_RETENTION_DAYS, + userSettings.getHistoryRetentionDays() == null + ? UserSettings.HISTORY_RETENTION_FOREVER + : userSettings.getHistoryRetentionDays()); // An empty string means "not chosen", which is not the same as either mode - see // UserSettings.anisetteMode. Writing "local" here for somebody who never chose // would move an existing session onto a different machine identity. diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/model/UserSettings.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/model/UserSettings.java index 6dcc12d9..fbdae36c 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/model/UserSettings.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/model/UserSettings.java @@ -1,5 +1,7 @@ package dev.wander.android.opentagviewer.db.repo.model; +import java.util.List; + import lombok.Builder; import lombok.Data; @@ -160,6 +162,17 @@ public class UserSettings { */ private String leftBehindSoundUri; + /** + * How many days of location history to keep, or null/zero to keep all of it. + * + *

Null means keep everything, and that is the default on purpose. Until this + * existed the app never deleted a report, and somebody updating should not find their history + * shorter for a setting they never saw. Older reports are deleted only once somebody picks a + * period. See {@link #resolveHistoryRetentionDays()} and + * {@code db.repo.LocationHistoryRetention}, which does the deleting. + */ + private Integer historyRetentionDays; + /** * What a tag's silence has to outlast before it is worth a targeted check. * @@ -199,6 +212,23 @@ public class UserSettings { /** Beyond this the tag is somewhere else entirely and the alert has missed its moment. */ public static final int LEFT_BEHIND_AFTER_SECONDS_MAX = 300; + /** Keep every report. The default, and what a stored zero or a missing value means. */ + public static final int HISTORY_RETENTION_FOREVER = 0; + + /** + * The periods Settings offers, in days, longest first, after + * {@link #HISTORY_RETENTION_FOREVER}: a year, six months, three months and a month. + * + *

Each is the longest the named period can be on a calendar (366, 184, 92 and 31 days), so + * "a month" never keeps less than a month. + * + *

A month is the shortest on purpose. The History screen asks Apple for a day it + * has no record of fetching, and Apple only has the last week or so. Every period here is well + * past that, so a day this deletes is never one the History screen would go and fetch again. + */ + public static final List HISTORY_RETENTION_CHOICES_DAYS = + List.of(HISTORY_RETENTION_FOREVER, 366, 184, 92, 31); + public static final String ANISETTE_LOCAL = "local"; public static final String ANISETTE_REMOTE = "remote"; @@ -212,6 +242,33 @@ public int resolveLeftBehindAfterSeconds() { Math.min(LEFT_BEHIND_AFTER_SECONDS_MAX, this.leftBehindAfterSeconds)); } + /** + * The history period in days, or {@link #HISTORY_RETENTION_FOREVER}. + * + *

Always one of {@link #HISTORY_RETENTION_CHOICES_DAYS}. A stored value that is not one + * (a later version's choice, say, after a downgrade) rounds up to the next choice that keeps + * at least as much, and past the longest it keeps everything. An unexpected value should + * never delete more than somebody asked for. + */ + public int resolveHistoryRetentionDays() { + if (this.historyRetentionDays == null || this.historyRetentionDays <= 0) { + return HISTORY_RETENTION_FOREVER; + } + + int resolved = HISTORY_RETENTION_FOREVER; + for (final int choice : HISTORY_RETENTION_CHOICES_DAYS) { + if (choice != HISTORY_RETENTION_FOREVER && choice >= this.historyRetentionDays) { + resolved = choice; + } + } + return resolved; + } + + /** Whether location history is kept forever - see {@link #historyRetentionDays}. */ + public boolean keepsHistoryForever() { + return this.resolveHistoryRetentionDays() == HISTORY_RETENTION_FOREVER; + } + public boolean hasDarkThemeEnabled() { return this.useDarkTheme == Boolean.TRUE; } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/LocationReportDao.java b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/LocationReportDao.java index c462b1d5..0c6f931e 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/LocationReportDao.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/room/dao/LocationReportDao.java @@ -67,4 +67,22 @@ public interface LocationReportDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insertAll(LocationReport... locationReports); + + /** + * Deletes every report older than {@code cutoffUnixMS}, except each tag's newest. + * + *

The newest one stays however old it is, because it is not history: it is where + * the map draws the tag, what "last updated" says and where Navigate goes. A tag that has + * not been heard for longer than the retention period would otherwise turn into "No last + * location known", which reads as the app having lost it. The comparison is against that + * tag's own newest timestamp, so a row tied with it is kept too. + * + *

The subquery is answered from the {@code (beacon_id, timestamp)} index. + * + * @return how many reports were deleted + */ + @Query("DELETE FROM LocationReport WHERE timestamp < :cutoffUnixMS" + + " AND timestamp < (SELECT MAX(newest.timestamp) FROM LocationReport AS newest" + + " WHERE newest.beacon_id = LocationReport.beacon_id)") + int deleteOlderThanExceptNewest(long cutoffUnixMS); } 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..8f6ea04d 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 @@ -24,6 +24,8 @@ import dev.wander.android.opentagviewer.python.icloud.PythonICloudService; import dev.wander.android.opentagviewer.db.repo.model.UserSettings; import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; +import dev.wander.android.opentagviewer.db.repo.HistoryPruner; +import dev.wander.android.opentagviewer.db.repo.LocationHistoryRetention; import dev.wander.android.opentagviewer.service.web.AnisetteServerTesterService; import dev.wander.android.opentagviewer.util.android.AddressLookup; import dev.wander.android.opentagviewer.util.history.HistoryArchiveImporter; @@ -169,6 +171,27 @@ public static void replaceGeocoder( geocoderFactory = replacement; } + /** + * Deletes location history older than the period chosen in Settings. + * + *

Here so a test can choose a period without it deleting anything. The instrumented + * suite runs against the real on-device database, and on somebody's own phone that holds + * their history. So the Settings test checks the screen asks for the right period, and + * {@code PruningOldLocationHistoryTest} checks what the real one deletes, against an + * in-memory database. + */ + private static Function historyPrunerFactory = + LocationHistoryRetention::of; + + public static HistoryPruner historyPruner(final Context context) { + return historyPrunerFactory.apply(context); + } + + @VisibleForTesting + public static void replaceHistoryPruner(final HistoryPruner replacement) { + historyPrunerFactory = context -> replacement; + } + /** * Opens a conversation with iCloud on the signed-in account. * @@ -313,5 +336,6 @@ public static void reset() { icloudFactory = AppDependencies::openRealICloud; geocoderFactory = (context, locale) -> AddressLookup.through(new Geocoder(context, locale)); + historyPrunerFactory = LocationHistoryRetention::of; } } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionRow.java b/app/src/main/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionRow.java new file mode 100644 index 00000000..45689123 --- /dev/null +++ b/app/src/main/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionRow.java @@ -0,0 +1,174 @@ +package dev.wander.android.opentagviewer.ui.settings; + +import static dev.wander.android.opentagviewer.db.repo.model.UserSettings.HISTORY_RETENTION_CHOICES_DAYS; +import static dev.wander.android.opentagviewer.db.repo.model.UserSettings.HISTORY_RETENTION_FOREVER; + +import android.content.Context; +import android.util.Log; +import android.widget.AdapterView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.StringRes; +import androidx.appcompat.app.AlertDialog; + +import com.google.android.material.dialog.MaterialAlertDialogBuilder; + +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; + +import dev.wander.android.opentagviewer.R; +import dev.wander.android.opentagviewer.db.repo.UserSettingsRepository; +import dev.wander.android.opentagviewer.db.repo.model.UserSettings; +import dev.wander.android.opentagviewer.python.AppDependencies; +import dev.wander.android.opentagviewer.util.rx.RxFlows; +import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; +import io.reactivex.rxjava3.core.Completable; + +/** + * Settings -> Keep location history: forever (the default), or a year, six months, three months + * or a month. + * + *

Choosing a shorter period asks first, then saves it and deletes what is now too old. A + * longer one, or forever, is only saved: there is nothing new to delete. After that the app + * deletes older history each time it starts (see {@code OpenAirTagApplication}). + * + *

Shares the screen's {@link UserSettings} object rather than reading its own, because the + * screen saves the whole object when anything else changes, and a second copy would write the old + * period back. + */ +public final class HistoryRetentionRow { + private static final String TAG = HistoryRetentionRow.class.getSimpleName(); + + /** Labels for {@link UserSettings#HISTORY_RETENTION_CHOICES_DAYS}, in the same order. */ + private static final List LABELS = List.of( + R.string.history_retention_forever, + R.string.history_retention_1_year, + R.string.history_retention_6_months, + R.string.history_retention_3_months, + R.string.history_retention_1_month); + + private final Context context; + private final UserSettings settings; + private final UserSettingsRepository repository; + private final Consumer showSubtitle; + + public HistoryRetentionRow( + @NonNull final Context context, + @NonNull final UserSettings settings, + @NonNull final UserSettingsRepository repository, + @NonNull final Consumer showSubtitle) { + this.context = context; + this.settings = settings; + this.repository = repository; + this.showSubtitle = showSubtitle; + } + + public void refresh() { + this.showSubtitle.accept(this.context.getString( + labelFor(this.settings.resolveHistoryRetentionDays()))); + } + + public void onClick() { + final int current = this.settings.resolveHistoryRetentionDays(); + final CharSequence[] labels = new CharSequence[LABELS.size()]; + for (int i = 0; i < labels.length; i++) { + labels[i] = this.context.getString(LABELS.get(i)); + } + + new MaterialAlertDialogBuilder(this.context) + .setTitle(R.string.history_retention_title) + .setSingleChoiceItems(labels, HISTORY_RETENTION_CHOICES_DAYS.indexOf(current), null) + .setNegativeButton(R.string.cancel, null) + .setPositiveButton(R.string.accept, (dialog, which) -> { + final int checked = + ((AlertDialog) dialog).getListView().getCheckedItemPosition(); + if (checked != AdapterView.INVALID_POSITION) { + this.choose(current, HISTORY_RETENTION_CHOICES_DAYS.get(checked)); + } + }) + .show(); + } + + private void choose(final int current, final int chosen) { + if (chosen == current) { + return; + } + + if (!deletesMore(current, chosen)) { + this.apply(current, chosen, false); + return; + } + + new MaterialAlertDialogBuilder(this.context) + .setTitle(R.string.history_retention_confirm_title) + .setMessage(R.string.history_retention_confirm_message) + .setNegativeButton(R.string.cancel, null) + .setPositiveButton(R.string.history_retention_confirm_button, + (dialog, which) -> this.apply(current, chosen, true)) + .show(); + } + + /** + * Saves the period, then, only once that has worked, deletes what is older. + * + *

Saved first, through {@link RxFlows#onlyAfter}, because the save is a DataStore + * write and those start the moment they are called. Built as {@code store.andThen(prune)} + * the delete would be created while the chain was, and would run even when the save failed, + * leaving history deleted under a setting that still says forever. + */ + private void apply(final int previous, final int chosen, final boolean deleteNow) { + this.settings.setHistoryRetentionDays(chosen); + this.refresh(); + + final Context app = this.context.getApplicationContext(); + final AtomicBoolean saved = new AtomicBoolean(false); + final Completable save = this.repository.storeUserSettings(this.settings) + .doOnComplete(() -> saved.set(true)); + final Completable work = deleteNow + ? RxFlows.onlyAfter(save, () -> AppDependencies.historyPruner(app) + .prune(chosen) + .doOnSuccess(deleted -> Log.i(TAG, "Deleted " + deleted + + " reports older than " + chosen + " days")) + .ignoreElement()) + : save; + + // Not disposed when the screen goes: a delete already under way should finish, and + // nothing here touches more than the subtitle. + final var unused = work + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(() -> Log.i(TAG, "Keeping location history for " + + (chosen == HISTORY_RETENTION_FOREVER ? "ever" : chosen + " days")), + error -> { + Log.e(TAG, "Could not apply the history period " + chosen, error); + if (!saved.get()) { + // Nothing was deleted, and the old period still stands. + this.settings.setHistoryRetentionDays(previous); + this.refresh(); + Toast.makeText(app, R.string.error_updating_settings, + Toast.LENGTH_LONG).show(); + } else { + Toast.makeText(app, R.string.history_retention_delete_failed, + Toast.LENGTH_LONG).show(); + } + }); + } + + /** + * Whether going from {@code current} to {@code chosen} deletes anything that would have been + * kept, which is what needs asking first. + */ + static boolean deletesMore(final int current, final int chosen) { + if (chosen == HISTORY_RETENTION_FOREVER) { + return false; + } + return current == HISTORY_RETENTION_FOREVER || chosen < current; + } + + @StringRes + static int labelFor(final int days) { + final int index = HISTORY_RETENTION_CHOICES_DAYS.indexOf(days); + return LABELS.get(Math.max(index, 0)); + } +} diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml index d9c30adf..de839ece 100644 --- a/app/src/main/res/layout/activity_settings.xml +++ b/app/src/main/res/layout/activity_settings.xml @@ -22,6 +22,8 @@ + + @@ -424,6 +426,18 @@ tools:text="Default alarm sound" /> + + + Wie lange ein Tag nicht zu hören sein darf, bevor die App entscheidet, dass du ihn zurückgelassen hast. Ab der Hälfte dieser Zeit sucht sie mit voller Leistung, ein kürzerer Wert warnt also früher und kostet mehr Akku. Alarmton Standard-Alarmton + Standortverlauf behalten + Für immer + 1 Jahr + 6 Monate + 3 Monate + 1 Monat + Älteren Verlauf löschen? + Positionen, die älter als der gewählte Zeitraum sind, werden jetzt gelöscht und danach bei jedem Start der App. Das gilt auch für importierten Verlauf. Jeder Tag behält seine letzte bekannte Position. + +Das kann nicht rückgängig gemacht werden. Exportiere vorher den Verlauf, wenn du eine Kopie möchtest. + Löschen + Der ältere Verlauf konnte nicht gelöscht werden. Die App versucht es beim nächsten Start erneut. Apple-Konto erneut verbinden Diese App hat eine Verbindung zu deinem Apple-Konto gespeichert, kann sie aber nicht mehr lesen. Die dafür nötigen Schlüssel liegen im sicheren Speicher dieses Geräts und lassen sich nicht wiederherstellen – die Verbindung muss also neu hergestellt werden. diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml index 63cb61c7..a9530c98 100644 --- a/app/src/main/res/values-en/strings.xml +++ b/app/src/main/res/values-en/strings.xml @@ -347,6 +347,18 @@ You can set this up now, or any time later from Settings. How long a tag has to go unheard before the app decides you have left it behind. It listens at full power from halfway through that time, so a shorter wait warns you sooner and costs more battery. Alarm sound Default alarm sound + Keep location history + Forever + 1 year + 6 months + 3 months + 1 month + Delete older history? + Positions older than the period you chose are deleted now, and again each time the app starts. That includes history you imported. Each tag keeps its last known position. + +This cannot be undone. Export History first if you want a copy. + Delete + Could not delete the older history. The app will try again the next time it starts. Reconnect your Apple account This app has a connection to your Apple account saved, but can no longer read it. The keys it needs are kept in this device\'s secure storage, and they cannot be recovered — so the connection has to be made again. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 5d05eec1..8b584a3f 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -348,6 +348,18 @@ Vous pouvez configurer cela maintenant, ou à tout moment depuis les réglages.< Combien de temps un tag doit rester inaudible avant que l\'application décide que vous l\'avez oublié. Elle écoute à pleine puissance à partir de la moitié de ce délai, donc un délai plus court avertit plus tôt et consomme plus de batterie. Son de l\'alarme Son d\'alarme par défaut + Conserver l’historique de localisation + Indéfiniment + 1 an + 6 mois + 3 mois + 1 mois + Supprimer l’historique plus ancien ? + Les positions plus anciennes que la durée choisie sont supprimées maintenant, puis à chaque démarrage de l’application. Cela inclut l’historique que vous avez importé. Chaque balise garde sa dernière position connue. + +Cette action est irréversible. Exportez d’abord l’historique si vous voulez en garder une copie. + Supprimer + Impossible de supprimer l’historique plus ancien. L’application réessaiera au prochain démarrage. Reconnectez votre compte Apple Cette application a une connexion à votre compte Apple enregistrée, mais ne parvient plus à la lire. Les clés nécessaires sont conservées dans le stockage sécurisé de cet appareil et ne peuvent pas être récupérées : la connexion doit donc être refaite. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 2fdc24d5..14ad01c3 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -347,6 +347,18 @@ タグの信号が途絶えてから、置き忘れと判断するまでの時間です。その半分を過ぎると全力で探すため、短いほど早く知らせますが電池を多く使います。 アラーム音 既定のアラーム音 + 位置情報履歴の保存期間 + 無期限 + 1 年 + 6 か月 + 3 か月 + 1 か月 + 古い履歴を削除しますか? + 選択した期間より古い位置情報は、今すぐ削除され、以後はアプリを起動するたびに削除されます。インポートした履歴も対象です。各タグの最後の既知の位置は残ります。 + +この操作は元に戻せません。コピーが必要な場合は、先に履歴をエクスポートしてください。 + 削除 + 古い履歴を削除できませんでした。次回アプリを起動したときに再試行します。 Apple アカウントを接続し直してください このアプリには Apple アカウントとの接続が保存されていますが、読み取れなくなりました。必要な鍵はこの端末の安全な保管領域にあり、復元できません。そのため接続をやり直す必要があります。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 40abf6ac..66cc10fb 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -347,6 +347,18 @@ 태그 신호가 끊긴 뒤 물건을 두고 왔다고 판단하기까지의 시간입니다. 그 절반이 지나면 전력을 다해 찾으므로, 짧을수록 빨리 알리지만 배터리를 더 씁니다. 알람음 기본 알람음 + 위치 기록 보관 기간 + 계속 보관 + 1년 + 6개월 + 3개월 + 1개월 + 오래된 기록을 삭제할까요? + 선택한 기간보다 오래된 위치는 지금 삭제되고, 이후 앱을 시작할 때마다 다시 삭제됩니다. 가져온 기록도 포함됩니다. 각 태그의 마지막으로 알려진 위치는 유지됩니다. + +이 작업은 되돌릴 수 없습니다. 사본이 필요하면 먼저 기록을 내보내세요. + 삭제 + 오래된 기록을 삭제하지 못했습니다. 다음에 앱을 시작할 때 다시 시도합니다. Apple 계정을 다시 연결하세요 이 앱에 Apple 계정 연결이 저장되어 있지만 더 이상 읽을 수 없습니다. 필요한 키는 이 기기의 보안 저장소에 있으며 복구할 수 없으므로 연결을 다시 만들어야 합니다. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 0798f801..d6c2b58a 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -347,6 +347,18 @@ Je kunt dit nu instellen, of later altijd nog via Instellingen. Hoe lang een tag onhoorbaar moet blijven voordat de app besluit dat je hem hebt laten liggen. Vanaf de helft van die tijd luistert hij op vol vermogen, dus korter waarschuwt eerder en kost meer batterij. Alarmgeluid Standaard alarmgeluid + Locatiegeschiedenis bewaren + Voor altijd + 1 jaar + 6 maanden + 3 maanden + 1 maand + Oudere geschiedenis verwijderen? + Posities die ouder zijn dan de gekozen periode worden nu verwijderd, en daarna elke keer dat de app start. Dat geldt ook voor geïmporteerde geschiedenis. Elke tag houdt zijn laatst bekende positie. + +Dit kan niet ongedaan worden gemaakt. Exporteer eerst de geschiedenis als je een kopie wilt. + Verwijderen + De oudere geschiedenis kon niet worden verwijderd. De app probeert het opnieuw bij de volgende start. Verbind je Apple-account opnieuw Deze app heeft een verbinding met je Apple-account opgeslagen, maar kan die niet meer lezen. De benodigde sleutels staan in de beveiligde opslag van dit apparaat en zijn niet te herstellen — de verbinding moet dus opnieuw worden gemaakt. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 31bd60bc..d1383629 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -347,6 +347,18 @@ Сколько метка должна молчать, прежде чем приложение решит, что вы её забыли. С середины этого времени поиск идёт на полной мощности, поэтому меньшее значение предупреждает раньше и расходует больше заряда. Звук будильника Стандартный звук будильника + Хранить историю местоположений + Всегда + 1 год + 6 месяцев + 3 месяца + 1 месяц + Удалить старую историю? + Местоположения старше выбранного срока будут удалены сейчас и затем при каждом запуске приложения. Это касается и импортированной истории. Для каждой метки сохраняется её последнее известное местоположение. + +Это действие нельзя отменить. Если нужна копия, сначала экспортируйте историю. + Удалить + Не удалось удалить старую историю. Приложение попробует снова при следующем запуске. Подключите учётную запись Apple заново Приложение хранит подключение к вашей учётной записи Apple, но больше не может его прочитать. Нужные ключи находятся в защищённом хранилище этого устройства и не подлежат восстановлению — поэтому подключение придётся выполнить заново. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 0718faf6..4b033fc6 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -347,6 +347,18 @@ 标签失去信号多久后,应用才判定你把它落下了。超过一半时间后会全力搜索,所以时间越短提醒越早,也越耗电。 报警声 默认报警声 + 位置历史保留时间 + 永久 + 1 年 + 6 个月 + 3 个月 + 1 个月 + 删除较早的历史记录? + 早于所选时间的位置会立即删除,之后每次启动应用时也会删除,包括你导入的历史记录。每个标签会保留其最后已知位置。 + +此操作无法撤销。如需副本,请先导出历史记录。 + 删除 + 无法删除较早的历史记录。应用会在下次启动时重试。 请重新连接您的 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..a6e12b22 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -347,6 +347,18 @@ 標籤失去訊號多久後,應用程式才判定你把它落下了。超過一半時間後會全力搜尋,所以時間越短提醒越早,也越耗電。 警報聲 預設警報聲 + 位置紀錄保留時間 + 永久 + 1 年 + 6 個月 + 3 個月 + 1 個月 + 刪除較舊的歷史記錄? + 早於所選時間的位置會立即刪除,之後每次啟動 App 時也會刪除,包括你匯入的歷史記錄。每個標籤會保留其最後已知位置。 + +此操作無法復原。如需副本,請先匯出歷史記錄。 + 刪除 + 無法刪除較舊的歷史記錄。App 會在下次啟動時重試。 請重新連接你的 Apple 帳戶 本應用程式儲存了與你的 Apple 帳戶的連線,但已無法讀取。所需的金鑰保存在本裝置的安全儲存空間中,且無法復原,因此必須重新建立連線。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index eaf81bb7..a6374daf 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -381,6 +381,18 @@ You can set this up now, or any time later from Settings. How long a tag has to go unheard before the app decides you have left it behind. It listens at full power from halfway through that time, so a shorter wait warns you sooner and costs more battery. Alarm sound Default alarm sound + Keep location history + Forever + 1 year + 6 months + 3 months + 1 month + Delete older history? + Positions older than the period you chose are deleted now, and again each time the app starts. That includes history you imported. Each tag keeps its last known position. + +This cannot be undone. Export History first if you want a copy. + Delete + Could not delete the older history. The app will try again the next time it starts. Reconnect your Apple account This app has a connection to your Apple account saved, but can no longer read it. The keys it needs are kept in this device\'s secure storage, and they cannot be recovered — so the connection has to be made again. diff --git a/app/src/test/java/dev/wander/android/opentagviewer/db/repo/model/KeepingLocationHistoryTest.java b/app/src/test/java/dev/wander/android/opentagviewer/db/repo/model/KeepingLocationHistoryTest.java new file mode 100644 index 00000000..76855abc --- /dev/null +++ b/app/src/test/java/dev/wander/android/opentagviewer/db/repo/model/KeepingLocationHistoryTest.java @@ -0,0 +1,91 @@ +package dev.wander.android.opentagviewer.db.repo.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import static dev.wander.android.opentagviewer.db.repo.model.UserSettings.HISTORY_RETENTION_CHOICES_DAYS; +import static dev.wander.android.opentagviewer.db.repo.model.UserSettings.HISTORY_RETENTION_FOREVER; + +import org.junit.Test; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +import dev.wander.android.opentagviewer.db.repo.LocationHistoryRetention; + +/** + * How long location history is kept, and what that means for the cutoff. + * + *

The default has to be "keep everything": until this setting existed the app never deleted a + * report, so anyone updating must not lose history to a setting they never saw. + */ +public class KeepingLocationHistoryTest { + + private static final long NOW = 1_800_000_000_000L; + + @Test + public void nobodyHasChosenSoEverythingIsKept() { + final UserSettings settings = UserSettings.builder().build(); + assertEquals(HISTORY_RETENTION_FOREVER, settings.resolveHistoryRetentionDays()); + assertTrue(settings.keepsHistoryForever()); + } + + @Test + public void zeroAndNegativeMeanForever() { + assertEquals(HISTORY_RETENTION_FOREVER, resolve(0)); + assertEquals(HISTORY_RETENTION_FOREVER, resolve(-5)); + } + + @Test + public void everyChoiceResolvesToItself() { + for (final int choice : HISTORY_RETENTION_CHOICES_DAYS) { + assertEquals(choice, resolve(choice)); + } + } + + @Test + public void theChoicesAreForeverThenAYearDownToAMonth() { + assertEquals(HISTORY_RETENTION_FOREVER, (int) HISTORY_RETENTION_CHOICES_DAYS.get(0)); + // Each is the longest that period can be on a calendar, so "a month" never keeps less. + assertEquals(List.of(0, 366, 184, 92, 31), HISTORY_RETENTION_CHOICES_DAYS); + } + + /** A value from somewhere else (a later version, say) keeps at least what it asked for. */ + @Test + public void anUnknownPeriodRoundsUpToTheNextChoiceNeverDown() { + assertEquals(31, resolve(1)); + assertEquals(31, resolve(7)); + assertEquals(92, resolve(45)); + assertEquals(366, resolve(200)); + assertEquals(HISTORY_RETENTION_FOREVER, resolve(400)); + assertFalse(UserSettings.builder().historyRetentionDays(45).build().keepsHistoryForever()); + } + + @Test + public void foreverHasNoCutoff() { + assertEquals(LocationHistoryRetention.NO_CUTOFF, + LocationHistoryRetention.cutoffFor(HISTORY_RETENTION_FOREVER, NOW)); + assertEquals(LocationHistoryRetention.NO_CUTOFF, + LocationHistoryRetention.cutoffFor(-1, NOW)); + } + + @Test + public void aPeriodCutsOffThatManyWholeDaysAgo() { + assertEquals(NOW - TimeUnit.DAYS.toMillis(31), + LocationHistoryRetention.cutoffFor(31, NOW)); + assertEquals(NOW - TimeUnit.DAYS.toMillis(366), + LocationHistoryRetention.cutoffFor(366, NOW)); + } + + @Test + public void theCutoffUsesTheRoundedUpPeriod() { + assertEquals(NOW - TimeUnit.DAYS.toMillis(92), + LocationHistoryRetention.cutoffFor(45, NOW)); + } + + private static int resolve(final int days) { + return UserSettings.builder().historyRetentionDays(days).build() + .resolveHistoryRetentionDays(); + } +} diff --git a/app/src/test/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionRowTest.java b/app/src/test/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionRowTest.java new file mode 100644 index 00000000..738f286b --- /dev/null +++ b/app/src/test/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionRowTest.java @@ -0,0 +1,67 @@ +package dev.wander.android.opentagviewer.ui.settings; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import static dev.wander.android.opentagviewer.db.repo.model.UserSettings.HISTORY_RETENTION_CHOICES_DAYS; +import static dev.wander.android.opentagviewer.db.repo.model.UserSettings.HISTORY_RETENTION_FOREVER; + +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; + +import dev.wander.android.opentagviewer.R; + +/** + * Which changes to the history period ask before deleting, and the labels the row shows. + * + *

Only a change that deletes something somebody would otherwise have kept asks first. Asking + * on every change teaches people to press Delete without reading. + */ +public class HistoryRetentionRowTest { + + @Test + public void choosingAPeriodWhenEverythingIsKeptAsks() { + for (final int chosen : HISTORY_RETENTION_CHOICES_DAYS) { + if (chosen != HISTORY_RETENTION_FOREVER) { + assertTrue("forever -> " + chosen, + HistoryRetentionRow.deletesMore(HISTORY_RETENTION_FOREVER, chosen)); + } + } + } + + @Test + public void aShorterPeriodAsks() { + assertTrue(HistoryRetentionRow.deletesMore(366, 31)); + assertTrue(HistoryRetentionRow.deletesMore(92, 31)); + } + + @Test + public void aLongerPeriodOrForeverDoesNotAsk() { + assertFalse(HistoryRetentionRow.deletesMore(31, 366)); + assertFalse(HistoryRetentionRow.deletesMore(31, HISTORY_RETENTION_FOREVER)); + assertFalse(HistoryRetentionRow.deletesMore( + HISTORY_RETENTION_FOREVER, HISTORY_RETENTION_FOREVER)); + } + + @Test + public void everyChoiceHasItsOwnLabel() { + final Set labels = new HashSet<>(); + for (final int choice : HISTORY_RETENTION_CHOICES_DAYS) { + labels.add(HistoryRetentionRow.labelFor(choice)); + } + assertEquals(HISTORY_RETENTION_CHOICES_DAYS.size(), labels.size()); + } + + @Test + public void theLabelsLineUpWithThePeriods() { + assertEquals(R.string.history_retention_forever, + HistoryRetentionRow.labelFor(HISTORY_RETENTION_FOREVER)); + assertEquals(R.string.history_retention_1_year, HistoryRetentionRow.labelFor(366)); + assertEquals(R.string.history_retention_6_months, HistoryRetentionRow.labelFor(184)); + assertEquals(R.string.history_retention_3_months, HistoryRetentionRow.labelFor(92)); + assertEquals(R.string.history_retention_1_month, HistoryRetentionRow.labelFor(31)); + } +}