Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,26 @@ not a history write) but never adopts the ring's copy. That is the same ±90 s a
**Known limit, worth stating when a user asks:** a reading already exported to Health Connect stays
there. The export doesn't retain HC record ids, so there is nothing to delete against.

## A preference that holds the user's data must ride in the archive

**The backup archive is the only way data reaches a new phone**: `android:allowBackup` is off, so
nothing in SharedPreferences moves with Android's own backup. Room tables go through
`DataArchiveService`; preferences go through `ArchivedSettings`, an allowlist of files.

Drinks is why this exists. Its entries were archived, but its on/off switch was a preference that
defaults to off, so after a phone change every drinks surface hid itself and the history looked
lost, and the plan, start date and AUDIT-C result were gone. `DrinkPrefs.adoptRestoredHistory`
repairs phones already restored that way (entries present, Drinks never switched on there).

- **A new preference that holds what the user entered or chose about their data** (a switch that
decides whether data shows, a plan, a log kept as JSON) **goes on the `ArchivedSettings`
allowlist in the same change.** Device state stays off it: ring pairing, Health Connect grants
and watermarks, notification scheduling, algorithm and scoring versions.
- **The EPDS answers are deliberately not carried** (`postpartum`'s `epds` key; see postpartum
mode). The life stage is.
- `body_measurements` and `findings` are deliberately not in the archive either: Health Connect
re-imports the first, and the second is recomputed.

## Deleting an activity bucket needs the tombstone *and* the day's deficit (issue #70)

`ActivityBucketDeletion` is the tombstone rule applied to intraday step blocks, and it has one more
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/pulseloop/PulseLoopApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ class PulseLoopApplication : Application() {
appScope.launch { DataRepairs.runIfNeeded(this@PulseLoopApplication) }
appScope.launch { DataRepairs.repairSleepDurationsIfNeeded(this@PulseLoopApplication) }
appScope.launch { DataRepairs.repairLuckRingActivityIfNeeded(this@PulseLoopApplication) }
// Phones already restored from an archive without settings: drinks there, Drinks off.
appScope.launch {
runCatching { com.pulseloop.service.DrinkPrefs.adoptRestoredHistory(PulseLoopDatabase.getInstance(this@PulseLoopApplication)) }
}

// Home-screen widgets (iOS #44): publish the snapshot on every foreground/background
// edge (the iOS scene-phase triggers — catches goal/unit/profile edits that don't run
Expand Down
92 changes: 92 additions & 0 deletions app/src/main/java/com/pulseloop/data/ArchivedSettings.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.pulseloop.data

import android.content.Context
import android.content.SharedPreferences
import kotlinx.serialization.Serializable

/** One SharedPreferences value, typed so a restore writes it back as what it was. */
@Serializable
data class PrefValue(
val type: String,
val value: String? = null,
val set: List<String>? = null,
)

/**
* The user's own data and choices that live in SharedPreferences rather than Room, carried in the
* archive so a new phone gets them back.
*
* Drinks is the case that made this necessary: its entries were in the archive, but its on/off
* switch was a preference that defaults to off, so after moving phones every drinks surface hid
* itself and the restored history looked lost. The plan (weekly limit, dry days, standard-drink
* size), its start date and the AUDIT-C result were lost outright.
*
* An allowlist, not a sweep of every file: device state (ring pairing, Health Connect grants and
* watermarks, notification scheduling, algorithm and scoring versions) must stay with the phone it
* describes, and some data stays on the phone on purpose.
*/
object ArchivedSettings {

/** File name to the keys never carried. An empty set carries the whole file. */
private val FILES: Map<String, Set<String>> = mapOf(
// Drinks: on/off, tracked-since, the plan, the AUDIT-C result.
"drinks" to emptySet(),
// Life stage. The EPDS answers stay on the phone (AGENTS.md, postpartum mode).
"postpartum" to setOf("epds"),
// Breathing sessions the user did.
"mindful_sessions" to emptySet(),
// The phone-step calibration and its daily counts. The raw step counter is this phone's.
"step_calibration" to setOf("lastCounter"),
// Detected workouts and naps already answered, so they aren't asked again.
"activity_detection" to emptySet(),
// Rest Mode, while it lasts.
"rest_mode" to emptySet(),
)

fun export(context: Context): Map<String, Map<String, PrefValue>> =
FILES.mapValues { (file, skipped) ->
prefs(context, file).all.filterKeys { it !in skipped }.mapNotNull { (k, v) -> encode(v)?.let { k to it } }.toMap()
}.filterValues { it.isNotEmpty() }

/**
* Writes the archive's values back. Only files on the allowlist are touched, and each is
* replaced as a whole except the keys it never carries, so a restore can't mix two phones'
* plans together.
*/
fun restore(context: Context, settings: Map<String, Map<String, PrefValue>>) {
FILES.forEach { (file, skipped) ->
val values = settings[file] ?: return@forEach
val p = prefs(context, file)
val e = p.edit()
p.all.keys.filter { it !in skipped }.forEach { e.remove(it) }
values.filterKeys { it !in skipped }.forEach { (k, v) -> put(e, k, v) }
e.commit()
}
}

private fun prefs(context: Context, file: String): SharedPreferences =
context.applicationContext.getSharedPreferences(file, Context.MODE_PRIVATE)

private fun encode(v: Any?): PrefValue? = when (v) {
is Boolean -> PrefValue("boolean", v.toString())
is Int -> PrefValue("int", v.toString())
is Long -> PrefValue("long", v.toString())
is Float -> PrefValue("float", v.toString())
is String -> PrefValue("string", v)
is Set<*> -> PrefValue("set", set = v.filterIsInstance<String>())
else -> null
}

private fun put(e: SharedPreferences.Editor, k: String, v: PrefValue) {
runCatching {
when (v.type) {
"boolean" -> e.putBoolean(k, v.value!!.toBoolean())
"int" -> e.putInt(k, v.value!!.toInt())
"long" -> e.putLong(k, v.value!!.toLong())
"float" -> e.putFloat(k, v.value!!.toFloat())
"string" -> e.putString(k, v.value)
"set" -> e.putStringSet(k, v.set.orEmpty().toSet())
}
}
}
}
2 changes: 1 addition & 1 deletion app/src/main/java/com/pulseloop/data/AutoBackup.kt
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ object AutoBackup {
val name = PREFIX + SimpleDateFormat("yyyy-MM-dd-HHmm", Locale.US).format(Date()) + ".json"
val doc = DocumentsContract.createDocument(resolver, parent, "application/json", name)
?: return fail(ctx, "Couldn't create a file in the backup folder")
val text = DataArchiveService.exportJson(PulseLoopDatabase.getInstance(ctx))
val text = DataArchiveService.exportJson(PulseLoopDatabase.getInstance(ctx), ctx)
resolver.openOutputStream(doc, "w")?.use { it.write(text.toByteArray()) }
?: return fail(ctx, "Couldn't write to the backup folder")
prune(ctx, tree, parentId)
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchive.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ data class PulseArchive(
val accuracyPausedUnits: List<AccuracyPausedUnitDTO> = emptyList(),
val accuracyCheckDays: List<AccuracyCheckDayDTO> = emptyList(),
val accuracyCorrections: List<AccuracyCorrectionDTO> = emptyList(),
/**
* The user's data and choices kept in SharedPreferences ([ArchivedSettings]): the Drinks
* switch and plan, life stage, breathing sessions, step calibration. Empty in archives written
* before it existed, and a restore then leaves this phone's own values alone.
*/
val settings: Map<String, Map<String, PrefValue>> = emptyMap(),
)

@Serializable data class AccuracyCheckDTO(
Expand Down
16 changes: 12 additions & 4 deletions app/src/main/java/com/pulseloop/data/DataArchiveService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ object DataArchiveService {
private fun insertRaw(db: PulseLoopDatabase, table: String, cv: ContentValues): Long =
db.openHelper.writableDatabase.insert(table, SQLiteDatabase.CONFLICT_NONE, cv)

suspend fun exportArchive(db: PulseLoopDatabase): PulseArchive = withContext(Dispatchers.Default) {
/** [context] reads the preferences the archive carries ([ArchivedSettings]); null leaves them out. */
suspend fun exportArchive(db: PulseLoopDatabase, context: Context? = null): PulseArchive = withContext(Dispatchers.Default) {
val counts = mutableMapOf<String, Int>()

fun <T> collect(table: String, mapper: (Cursor) -> T): List<T> {
Expand Down Expand Up @@ -356,6 +357,7 @@ object DataArchiveService {
computedAt = c.long("computedAt"),
)
},
settings = context?.let { ArchivedSettings.export(it) } ?: emptyMap(),
accuracyCorrections = collect("accuracy_corrections") { c ->
AccuracyCorrectionDTO(
deviceKey = c.str("deviceKey"), metric = c.str("metric"), kind = c.str("kind"),
Expand Down Expand Up @@ -395,12 +397,12 @@ object DataArchiveService {
}

/** The whole archive as JSON, the same text a manual export writes. */
suspend fun exportJson(db: PulseLoopDatabase): String = withContext(Dispatchers.Default) {
json.encodeToString(PulseArchive.serializer(), exportArchive(db))
suspend fun exportJson(db: PulseLoopDatabase, context: Context? = null): String = withContext(Dispatchers.Default) {
json.encodeToString(PulseArchive.serializer(), exportArchive(db, context))
}

suspend fun exportToFile(context: Context, db: PulseLoopDatabase): Uri? = withContext(Dispatchers.Default) {
val archive = exportArchive(db)
val archive = exportArchive(db, context)
val jsonStr = json.encodeToString(PulseArchive.serializer(), archive)
val name = "pulseloop-export-${dateFmt.format(Date())}.json"
val file = java.io.File(context.cacheDir, name)
Expand Down Expand Up @@ -771,6 +773,12 @@ object DataArchiveService {
}
}

// After the database, so a failed restore leaves this phone's preferences as they were.
ArchivedSettings.restore(context, archive.settings)
// An archive written before settings were carried brings drinks without their switch.
com.pulseloop.service.DrinkPrefs.init(context)
com.pulseloop.service.DrinkPrefs.adoptRestoredHistory(db)

// Phase 6 (iOS DataArchiveService.refreshSharedStores parity): importing history must not
// trigger a surprise full re-export into Health Connect. If the export is enabled, stamp
// every group's watermark to now so only data logged AFTER the restore is exported. The
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/pulseloop/data/dao/Daos.kt
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,10 @@ interface DrinkDao {
@Query("SELECT * FROM drink_entries ORDER BY timestamp DESC LIMIT 1")
suspend fun latest(): DrinkEntryEntity?

/** The local start of the earliest evening with a drink; null when there are none. */
@Query("SELECT MIN(day) FROM drink_entries")
suspend fun earliestDay(): Long?

@Upsert
suspend fun upsert(entry: DrinkEntryEntity)

Expand Down
16 changes: 16 additions & 0 deletions app/src/main/java/com/pulseloop/service/DrinksRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ object DrinkPrefs {
e.apply()
}

/**
* Drinks history with Drinks never switched on here, which only a restore from an archive
* written before [com.pulseloop.data.ArchivedSettings] produces: the entries came back but the
* switch, a preference, did not, so every drinks surface hid them. Switches Drinks on with its
* start on the first evening logged, so those days count as tracked rather than unknown.
* Leaves a user who switched Drinks off alone: switching on is what sets [trackedSince], and
* switching off keeps it.
*/
suspend fun adoptRestoredHistory(db: com.pulseloop.data.PulseLoopDatabase, zone: ZoneId = ZoneId.systemDefault()) {
val p = p() ?: return
if (p.getBoolean("enabled", false) || p.getString("trackedSince", null) != null) return
val first = db.drinkDao().earliestDay() ?: return
val firstDay = java.time.Instant.ofEpochMilli(first).atZone(zone).toLocalDate()
p.edit().putBoolean("enabled", true).putString("trackedSince", firstDay.toString()).apply()
}

/** The first day drinks were tracked; days before it are unknown rather than dry. */
val trackedSince: LocalDate
get() = p()?.getString("trackedSince", null)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: LocalDate.now()
Expand Down
Loading