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 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 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 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 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:
+ * 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 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 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 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 @@
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
+ *
+ */
+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