feat(#38): backup envelope, problems and SAF I/O from floret core-backup

This commit is contained in:
makiolaj committed 2026-11-14 04:24:17 +01:00
1 parent a81a3641ce
commit 5ab92d65e2
16 files changed
+319 -130

No files matched your search

+2
View File
@@ -213,6 +213,8 @@ dependencies {
implementation("de.jeanlucmakiola.floret:core-locale")
implementation("de.jeanlucmakiola.floret:core-crash")
implementation("de.jeanlucmakiola.floret:core-prefs")
implementation("de.jeanlucmakiola.floret:core-backup")
implementation("de.jeanlucmakiola.floret:core-android")
implementation("de.jeanlucmakiola.floret:core-di")
implementation("de.jeanlucmakiola.floret:identity")
implementation("de.jeanlucmakiola.floret:components")
@@ -6,10 +6,12 @@ import androidx.documentfile.provider.DocumentFile
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.clockula.backup.BACKUP_FILE_NAME
import de.jeanlucmakiola.clockula.backup.BackupFiles
import de.jeanlucmakiola.clockula.data.backup.MAX_BACKUP_CHARS
import de.jeanlucmakiola.floret.android.readDocumentBytes
import de.jeanlucmakiola.floret.android.writeDocumentBytes
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.UUID
import javax.inject.Inject
@@ -37,9 +39,7 @@ class SafBackupFiles @Inject constructor(
?: throw IOException("could not create a temporary backup")
var keepTemporary = false
try {
val stream = context.contentResolver.openOutputStream(temporary.uri)
?: throw IOException("could not open an output stream for ${temporary.uri}")
stream.use { it.write(bytes) }
context.contentResolver.writeDocumentBytes(temporary.uri, bytes)
val existing = tree.findFile(BACKUP_FILE_NAME)
if (existing != null && !existing.delete()) throw IOException("could not remove the previous backup")
// Some SAF providers cannot rename. Once the old file has been
@@ -57,25 +57,11 @@ class SafBackupFiles @Inject constructor(
override suspend fun read(documentUri: String): Result<String> = withContext(io) {
runCatching {
val stream = context.contentResolver.openInputStream(documentUri.toUri())
?: throw IOException("could not open an input stream for $documentUri")
stream.use { input ->
val output = ByteArrayOutputStream()
val buffer = ByteArray(8192)
var total = 0
while (true) {
val count = input.read(buffer)
if (count < 0) break
total += count
if (total > MAX_BACKUP_BYTES) throw IOException("backup exceeds the 8 MiB limit")
output.write(buffer, 0, count)
}
output.toString(Charsets.UTF_8.name())
}
context.contentResolver.readDocumentBytes(documentUri.toUri(), MAX_BACKUP_BYTES).toString(Charsets.UTF_8)
}
}
private companion object {
const val MAX_BACKUP_BYTES = 8 * 1024 * 1024
const val MAX_BACKUP_BYTES = MAX_BACKUP_CHARS
}
}
@@ -25,29 +25,19 @@ import de.jeanlucmakiola.clockula.domain.widget.parseQuickTimerDuration
import de.jeanlucmakiola.floret.prefs.ThemeMode
import de.jeanlucmakiola.floret.prefs.toEnum
import kotlinx.serialization.SerializationException
import de.jeanlucmakiola.floret.backup.BackupDocument
import de.jeanlucmakiola.floret.backup.BackupFormat
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupResult
import de.jeanlucmakiola.floret.backup.invalidBackup
import de.jeanlucmakiola.floret.backup.readBackup
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import java.time.LocalDate
import java.time.format.DateTimeParseException
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Instant
/**
* Why a restore failed, in words a user can act on. The codec's own four, plus
* the two the caller meets around it: the file would not open, or the import
* itself failed after the file was valid.
*/
enum class BackupProblem { NOT_A_BACKUP, NEWER_VERSION, INVALID_DATA, TOO_LARGE, UNREADABLE, NOT_APPLIED }
/**
* The result of [BackupCodec.decode]: either a validated [BackupContent], or
* why not — [problem] for the user, [reason] the specific detail, in English,
* for tests and logs.
*/
sealed interface BackupResult {
data class Success(val content: BackupContent) : BackupResult
data class Failure(val problem: BackupProblem, val reason: String) : BackupResult
}
/**
* The JSON wire format ↔ [BackupContent]. Pure Kotlin — no Android import —
* so the round trip and every rejection path are JVM-unit-testable.
@@ -57,7 +47,13 @@ sealed interface BackupResult {
*/
object BackupCodec {
private const val MAX_DOCUMENT_CHARS = 8 * 1024 * 1024
/** The envelope (`format`, `version`, `exportedAt`) is floret's; the sections are [BackupBody]. */
private val format = BackupFormat(
name = BACKUP_FORMAT,
version = BACKUP_VERSION,
minVersion = BACKUP_MIN_VERSION,
maxChars = MAX_BACKUP_CHARS,
)
private const val MAX_ALARMS = 10_000
private const val MAX_TIMERS = 10_000
private const val MAX_WORLD_CLOCKS = 1_000
@@ -69,29 +65,32 @@ object BackupCodec {
prettyPrint = true
}
fun encode(content: BackupContent): String =
json.encodeToString(BackupDocument.serializer(), content.toDocument())
fun encode(content: BackupContent): String = format.encode(
BackupDocument(
version = BACKUP_VERSION,
exportedAtMillis = content.exportedAt.toEpochMilliseconds(),
body = json.encodeToJsonElement(BackupBody.serializer(), content.toBody()).jsonObject,
),
)
fun decode(text: String): BackupResult {
if (text.length > MAX_DOCUMENT_CHARS) {
return BackupResult.Failure(BackupProblem.TOO_LARGE, "backup exceeds the 8 MiB limit")
fun decode(text: String): BackupResult<BackupContent> {
val document = when (val decoded = format.decode(text)) {
is BackupResult.Failure -> return decoded
is BackupResult.Success -> decoded.value
}
val document = try {
json.decodeFromString(BackupDocument.serializer(), text)
val body = try {
json.decodeFromJsonElement(BackupBody.serializer(), document.body)
} catch (e: SerializationException) {
return BackupResult.Failure(BackupProblem.NOT_A_BACKUP, "not a valid backup file: ${e.message}")
} catch (e: IllegalArgumentException) {
return BackupResult.Failure(BackupProblem.NOT_A_BACKUP, "not a valid backup file: ${e.message}")
}
return document.toContent()
return body.toContent(document.exportedAtMillis)
}
// --- encode ---
private fun BackupContent.toDocument(): BackupDocument = BackupDocument(
format = BACKUP_FORMAT,
version = BACKUP_VERSION,
exportedAtMillis = exportedAt.toEpochMilliseconds(),
private fun BackupContent.toBody(): BackupBody = BackupBody(
alarms = alarms.map { it.toDto() },
timers = timers.map { it.toDto() },
worldClocks = worldClocks.map { it.toDto() },
@@ -195,38 +194,33 @@ object BackupCodec {
// --- decode + validate ---
private fun BackupDocument.toContent(): BackupResult {
if (format != BACKUP_FORMAT) {
return BackupResult.Failure(BackupProblem.NOT_A_BACKUP, "unknown format: '$format'")
}
if (version !in BACKUP_MIN_VERSION..BACKUP_VERSION) {
val problem = if (version > BACKUP_VERSION) BackupProblem.NEWER_VERSION else BackupProblem.INVALID_DATA
return BackupResult.Failure(problem, "unsupported backup version: $version")
}
/** Rejects the file as [BackupProblem.TOO_LARGE]; the [invalidBackup] counterpart. */
private class TooLargeException(val reason: String) : Exception(reason)
private fun tooLarge(reason: String): Nothing = throw TooLargeException(reason)
private fun BackupBody.toContent(exportedAtMillis: Long): BackupResult<BackupContent> = try {
readBackup { parse(exportedAtMillis) }
} catch (e: TooLargeException) {
BackupResult.Failure(BackupProblem.TOO_LARGE, e.reason)
}
private fun BackupBody.parse(exportedAtMillis: Long): BackupContent {
if (alarms.size > MAX_ALARMS || timers.size > MAX_TIMERS || worldClocks.size > MAX_WORLD_CLOCKS) {
return BackupResult.Failure(BackupProblem.TOO_LARGE, "backup contains too many records")
tooLarge("backup contains too many records")
}
val alarms = mutableListOf<BackupAlarm>()
for ((index, dto) in this.alarms.withIndex()) {
if (dto.hour !in 0..23 || dto.minute !in 0..59) {
return BackupResult.Failure(
BackupProblem.INVALID_DATA,
"alarms[$index]: hour/minute out of range (${dto.hour}:${dto.minute})",
)
invalidBackup("alarms[$index]: hour/minute out of range (${dto.hour}:${dto.minute})")
}
if (dto.label.length > MAX_LABEL_CHARS || (dto.ringtoneUri?.length ?: 0) > MAX_URI_CHARS) {
return BackupResult.Failure(
BackupProblem.TOO_LARGE,
"alarms[$index]: label or ringtone URI is too long",
)
tooLarge("alarms[$index]: label or ringtone URI is too long")
}
val repeatDays = RepeatDays.fromMask(dto.repeatDays)
val dates = dto.dates(repeatDays.isRepeating)
?: return BackupResult.Failure(
BackupProblem.INVALID_DATA,
"alarms[$index]: scheduled_date or pause is not a valid date range",
)
?: invalidBackup("alarms[$index]: scheduled_date or pause is not a valid date range")
alarms += BackupAlarm(
time = TimeOfDay(dto.hour, dto.minute),
label = dto.label,
@@ -250,13 +244,10 @@ object BackupCodec {
val timers = mutableListOf<BackupTimer>()
for ((index, dto) in this.timers.withIndex()) {
if (dto.durationMillis < 0) {
return BackupResult.Failure(BackupProblem.INVALID_DATA, "timers[$index]: negative duration")
invalidBackup("timers[$index]: negative duration")
}
if (dto.label.length > MAX_LABEL_CHARS || (dto.ringtoneUri?.length ?: 0) > MAX_URI_CHARS) {
return BackupResult.Failure(
BackupProblem.TOO_LARGE,
"timers[$index]: label or ringtone URI is too long",
)
tooLarge("timers[$index]: label or ringtone URI is too long")
}
timers += BackupTimer(
label = dto.label,
@@ -270,13 +261,10 @@ object BackupCodec {
val worldClocks = mutableListOf<BackupWorldClock>()
for ((index, dto) in this.worldClocks.withIndex()) {
if (!Zones.isValid(dto.zoneId)) {
return BackupResult.Failure(
BackupProblem.INVALID_DATA,
"worldClocks[$index]: not an IANA zone id: '${dto.zoneId}'",
)
invalidBackup("worldClocks[$index]: not an IANA zone id: '${dto.zoneId}'")
}
if ((dto.label?.length ?: 0) > MAX_LABEL_CHARS) {
return BackupResult.Failure(BackupProblem.TOO_LARGE, "worldClocks[$index]: label is too long")
tooLarge("worldClocks[$index]: label is too long")
}
worldClocks += BackupWorldClock(
zoneId = dto.zoneId,
@@ -290,7 +278,7 @@ object BackupCodec {
(settingsDto.timerRingtoneUri?.length ?: 0) > MAX_URI_CHARS ||
(settingsDto.timerPresets?.size ?: 0) > 1_000
) {
return BackupResult.Failure(BackupProblem.TOO_LARGE, "settings contain oversized values")
tooLarge("settings contain oversized values")
}
val settingsContent = BackupSettings(
themeMode = settingsDto.themeMode.toEnum(ThemeMode.SYSTEM),
@@ -324,14 +312,12 @@ object BackupCodec {
bedtime = settingsDto.bedtime?.toBedtime(),
)
return BackupResult.Success(
BackupContent(
exportedAt = Instant.fromEpochMilliseconds(exportedAtMillis),
alarms = alarms,
timers = timers,
worldClocks = worldClocks,
settings = settingsContent,
),
return BackupContent(
exportedAt = Instant.fromEpochMilliseconds(exportedAtMillis),
alarms = alarms,
timers = timers,
worldClocks = worldClocks,
settings = settingsContent,
)
}
@@ -12,12 +12,15 @@ const val BACKUP_VERSION: Int = 2
/** The oldest version this build still reads. v1 is v2 without the alarm dates. */
const val BACKUP_MIN_VERSION: Int = 1
/** The wire shape of `clockula-backup-v1.json`. See `docs/BACKUP.md`. */
/** The longest backup Clockula reads or writes: 8 MiB. */
const val MAX_BACKUP_CHARS: Int = 8 * 1024 * 1024
/**
* The sections of `clockula-backup-v1.json`, next to floret's envelope
* (`format`, `version`, `exportedAt`). See `docs/BACKUP.md`.
*/
@Serializable
data class BackupDocument(
val format: String,
val version: Int,
@SerialName("exportedAt") val exportedAtMillis: Long,
data class BackupBody(
val alarms: List<AlarmDto> = emptyList(),
val timers: List<TimerDto> = emptyList(),
val worldClocks: List<WorldClockDto> = emptyList(),
@@ -32,7 +32,7 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.clockula.R
import de.jeanlucmakiola.clockula.data.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.components.GroupedRow
@@ -1,6 +1,6 @@
package de.jeanlucmakiola.clockula.ui.settings
import de.jeanlucmakiola.clockula.data.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupProblem
/**
* A one-off result the screen shows as a snackbar and then forgets. A failure
@@ -6,8 +6,8 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.clockula.backup.BackupEngine
import de.jeanlucmakiola.clockula.backup.BackupFiles
import de.jeanlucmakiola.clockula.data.backup.BackupCodec
import de.jeanlucmakiola.clockula.data.backup.BackupProblem
import de.jeanlucmakiola.clockula.data.backup.BackupResult
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupResult
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.Flow
@@ -89,7 +89,7 @@ class BackupViewModel @Inject internal constructor(
private suspend fun applyImport(text: String): BackupEvent = when (val decoded = BackupCodec.decode(text)) {
is BackupResult.Success -> {
engine.import(decoded.content)
engine.import(decoded.value)
BackupEvent.ImportSucceeded
}
is BackupResult.Failure -> BackupEvent.ImportFailed(decoded.problem)
@@ -21,6 +21,8 @@ import de.jeanlucmakiola.clockula.domain.screensaver.ScreenSaverStyle
import de.jeanlucmakiola.clockula.domain.timer.TimerPresets
import de.jeanlucmakiola.clockula.domain.widget.QuickTimerWidgetSettings
import de.jeanlucmakiola.floret.prefs.ThemeMode
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupResult
import org.junit.jupiter.api.Test
import java.time.DayOfWeek
import java.time.LocalDate
@@ -168,7 +170,7 @@ class BackupCodecTest {
val decoded = BackupCodec.decode(json)
assertThat(decoded).isInstanceOf(BackupResult.Success::class.java)
val defaults = (decoded as BackupResult.Success).content.settings.defaults
val defaults = (decoded as BackupResult.Success).value.settings.defaults
// Timers vibrated by the alarm default then, which defaults to on.
assertThat(defaults).isEqualTo(ClockDefaults(snoozeMinutes = 7, timerVibrate = true))
}
@@ -202,27 +204,27 @@ class BackupCodecTest {
fun `a file from before the week start setting follows the locale`() {
val decoded = BackupCodec.decode(settingsOnly(""""default_vibrate": true"""))
assertThat((decoded as BackupResult.Success).content.settings.weekStart).isEqualTo(WeekStartPref.Auto)
assertThat((decoded as BackupResult.Success).value.settings.weekStart).isEqualTo(WeekStartPref.Auto)
}
@Test
fun `an unknown week start follows the locale rather than rejecting the file`() {
val decoded = BackupCodec.decode(settingsOnly(""""week_start": "FUNDAY""""))
assertThat((decoded as BackupResult.Success).content.settings.weekStart).isEqualTo(WeekStartPref.Auto)
assertThat((decoded as BackupResult.Success).value.settings.weekStart).isEqualTo(WeekStartPref.Auto)
}
@Test
fun `a null week start follows the locale rather than rejecting the file`() {
val decoded = BackupCodec.decode(settingsOnly(""""week_start": null"""))
assertThat((decoded as BackupResult.Success).content.settings.weekStart).isEqualTo(WeekStartPref.Auto)
assertThat((decoded as BackupResult.Success).value.settings.weekStart).isEqualTo(WeekStartPref.Auto)
}
private fun settingsOnly(settings: String): String =
"""{ "format": "clockula-backup", "version": 1, "exportedAt": 0, "settings": { $settings } }"""
private fun BackupResult.defaults(): ClockDefaults = (this as BackupResult.Success).content.settings.defaults
private fun BackupResult<BackupContent>.defaults(): ClockDefaults = (this as BackupResult.Success).value.settings.defaults
@Test
fun `the retired default timer duration is no longer written`() {
@@ -256,7 +258,7 @@ class BackupCodecTest {
"\"alarms\": [{\"hour\":7,\"minute\":0,\"repeat_days\":31}]",
)
val decoded = BackupCodec.decode(json) as BackupResult.Success
val alarm = decoded.content.alarms.single()
val alarm = decoded.value.alarms.single()
assertThat(alarm.scheduledDate).isNull()
assertThat(alarm.pause).isNull()
}
@@ -314,8 +316,8 @@ class BackupCodecTest {
alarmDocument("\"pause_start\":\"2026-10-26\",\"pause_end\":\"2026-10-28\""),
) as BackupResult.Success
assertThat(datedRepeating.content.alarms.single().scheduledDate).isNull()
assertThat(pausedOneShot.content.alarms.single().pause).isNull()
assertThat(datedRepeating.value.alarms.single().scheduledDate).isNull()
assertThat(pausedOneShot.value.alarms.single().pause).isNull()
}
@Test
@@ -411,14 +413,14 @@ class BackupCodecTest {
""".trimIndent()
val result = BackupCodec.decode(json)
assertThat(result).isInstanceOf(BackupResult.Success::class.java)
val content = (result as BackupResult.Success).content
val content = (result as BackupResult.Success).value
assertThat(content.alarms.single().dismissChallenge).isEqualTo(DismissChallenge.NONE)
}
@Test
fun `a file without the volume-button setting keeps the volume keys as they were`() {
val result = BackupCodec.decode(minimalDocument())
val defaults = (result as BackupResult.Success).content.settings.defaults
val defaults = (result as BackupResult.Success).value.settings.defaults
assertThat(defaults.volumeButtons).isEqualTo(VolumeButtonAction.CONTROL_VOLUME)
}
@@ -429,7 +431,7 @@ class BackupCodecTest {
"\"settings\": {\"volume_buttons_while_ringing\": \"SOME_FUTURE_ACTION\"}",
)
val result = BackupCodec.decode(json)
val defaults = (result as BackupResult.Success).content.settings.defaults
val defaults = (result as BackupResult.Success).value.settings.defaults
assertThat(defaults.volumeButtons).isEqualTo(VolumeButtonAction.CONTROL_VOLUME)
}
@@ -440,7 +442,7 @@ class BackupCodecTest {
"\"alarms\": [{\"hour\":7,\"minute\":0,\"snooze_minutes\":0," +
"\"snooze_limit\":-5,\"volume_ramp_seconds\":100000}]",
)
val alarm = (BackupCodec.decode(json) as BackupResult.Success).content.alarms.single()
val alarm = (BackupCodec.decode(json) as BackupResult.Success).value.alarms.single()
assertThat(alarm.snoozeMinutes).isEqualTo(1)
assertThat(alarm.snoozeLimit).isEqualTo(0)
assertThat(alarm.volumeRampSeconds).isEqualTo(60)
@@ -452,19 +454,19 @@ class BackupCodecTest {
"\"timers\": []",
"\"timers\": [{\"duration_millis\":0},{\"duration_millis\":${Long.MAX_VALUE}}]",
)
val timers = (BackupCodec.decode(json) as BackupResult.Success).content.timers
val timers = (BackupCodec.decode(json) as BackupResult.Success).value.timers
assertThat(timers.map { it.duration }).containsExactly(TimerPresets.MIN, TimerPresets.MAX).inOrder()
}
@Test
fun `a file without timer presets keeps the built-in ones`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.timerPresets).isEqualTo(TimerPresets.BUILT_IN)
}
@Test
fun `a file from before bedtime existed carries no bedtime, so restoring it keeps the current one`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.bedtime).isNull()
}
@@ -475,7 +477,7 @@ class BackupCodecTest {
"\"settings\": {\"bedtime\": {\"enabled\": true, \"bedtime_minutes\": 99999, " +
"\"wake_minutes\": -5, \"days\": 255, \"reminder_minutes\": 999}}",
)
val bedtime = (BackupCodec.decode(json) as BackupResult.Success).content.settings.bedtime!!
val bedtime = (BackupCodec.decode(json) as BackupResult.Success).value.settings.bedtime!!
assertThat(bedtime.enabled).isTrue()
assertThat(bedtime.bedtime).isEqualTo(TimeOfDay(23, 59))
assertThat(bedtime.wakeTime).isEqualTo(TimeOfDay(0, 0))
@@ -485,7 +487,7 @@ class BackupCodecTest {
@Test
fun `a file from before silence after keeps the ten minutes it was made with`() {
val defaults = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings.defaults
val defaults = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings.defaults
assertThat(defaults.alarmSilenceAfterMinutes).isEqualTo(10)
assertThat(defaults.timerSilenceAfterMinutes).isEqualTo(10)
}
@@ -499,7 +501,7 @@ class BackupCodecTest {
@Test
fun `a file from before show-seconds existed keeps it off`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.worldClockSeconds).isFalse()
}
@@ -510,7 +512,7 @@ class BackupCodecTest {
@Test
fun `a file from before the compact home clock keeps it off`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.compactHomeClock).isFalse()
}
@@ -521,7 +523,7 @@ class BackupCodecTest {
@Test
fun `a file from before the automatic local clock keeps it on`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.defaults.automaticLocalClock).isTrue()
}
@@ -532,7 +534,7 @@ class BackupCodecTest {
@Test
fun `a file from before the screen saver restores its defaults`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.screenSaver).isEqualTo(ScreenSaverSettings())
}
@@ -542,27 +544,27 @@ class BackupCodecTest {
"\"settings\": {}",
"\"settings\": {\"screen_saver_style\": \"HOLOGRAM\", \"screen_saver_night_mode\": true}",
)
val settings = (BackupCodec.decode(json) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(json) as BackupResult.Success).value.settings
assertThat(settings.screenSaver).isEqualTo(ScreenSaverSettings(ScreenSaverStyle.DIGITAL, nightMode = true))
}
@Test
fun `a file without the quick tile's duration keeps its default`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.quickTileDuration).isEqualTo(QuickTimerWidgetSettings.DEFAULT)
}
@Test
fun `a quick tile duration the tile cannot start falls back to its default`() {
val json = minimalDocument().replace("\"settings\": {}", "\"settings\": {\"quick_tile_duration_millis\": 7200000}")
val settings = (BackupCodec.decode(json) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(json) as BackupResult.Success).value.settings
assertThat(settings.quickTileDuration).isEqualTo(QuickTimerWidgetSettings.DEFAULT)
}
@Test
fun `an empty preset list is honoured as all removed`() {
val json = minimalDocument().replace("\"settings\": {}", "\"settings\": {\"timer_presets\": []}")
val settings = (BackupCodec.decode(json) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(json) as BackupResult.Success).value.settings
assertThat(settings.timerPresets).isEmpty()
}
@@ -0,0 +1,68 @@
package de.jeanlucmakiola.clockula.data.backup
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.clockula.domain.DismissChallenge
import de.jeanlucmakiola.clockula.domain.TimeOfDay
import de.jeanlucmakiola.clockula.domain.backup.BackupContent
import de.jeanlucmakiola.clockula.domain.timer.TimerPresets
import de.jeanlucmakiola.floret.backup.BackupResult
import de.jeanlucmakiola.floret.prefs.ThemeMode
import org.junit.jupiter.api.Test
import java.time.LocalDate
import kotlin.time.Duration.Companion.minutes
/**
* Backups written by earlier builds still restore (#38). The v2 file is what
* the codec wrote before it moved onto floret's envelope; the v1 file has the
* shape of the first release's backups, with the since-retired timer length.
*/
class BackupFixtureTest {
private fun fixture(name: String): String =
requireNotNull(javaClass.classLoader.getResource("backup/$name")) { name }.readText()
private fun decode(name: String): BackupContent =
(BackupCodec.decode(fixture(name)) as BackupResult.Success).value
@Test
fun `a version 2 backup still restores`() {
val content = decode("clockula-backup-v2.json")
assertThat(content.alarms).hasSize(3)
assertThat(content.alarms[1].scheduledDate).isEqualTo(LocalDate.of(2026, 12, 24))
assertThat(content.alarms[2].pause?.end).isEqualTo(LocalDate.of(2027, 1, 6))
assertThat(content.timers.single().duration).isEqualTo(5.minutes)
assertThat(content.worldClocks.single().zoneId).isEqualTo("Europe/Berlin")
assertThat(content.settings.themeMode).isEqualTo(ThemeMode.DARK)
assertThat(content.settings.bedtime?.reminderMinutes).isEqualTo(30)
}
@Test
fun `the written format is unchanged`() {
val text = fixture("clockula-backup-v2.json")
assertThat(BackupCodec.encode(decode("clockula-backup-v2.json"))).isEqualTo(text)
}
@Test
fun `a version 1 backup still restores with the defaults it predates`() {
val content = decode("clockula-backup-v1.json")
assertThat(content.alarms.map { it.time }).containsExactly(TimeOfDay(6, 45), TimeOfDay(9, 0)).inOrder()
assertThat(content.alarms.all { it.scheduledDate == null && it.pause == null }).isTrue()
assertThat(content.timers.single().label).isEqualTo("Tea")
assertThat(content.settings.themeMode).isEqualTo(ThemeMode.BLACK)
assertThat(content.settings.defaults.dismissChallenge).isEqualTo(DismissChallenge.MATH)
// No timer vibration of its own yet: the alarms' default carries over.
assertThat(content.settings.defaults.timerVibrate).isFalse()
assertThat(content.settings.timerPresets).isEqualTo(TimerPresets.BUILT_IN)
assertThat(content.settings.bedtime).isNull()
}
@Test
fun `a backup re-saved with a byte-order mark still restores`() {
val decoded = BackupCodec.decode("" + fixture("clockula-backup-v1.json"))
assertThat(decoded).isInstanceOf(BackupResult.Success::class.java)
}
}
@@ -3,7 +3,7 @@ package de.jeanlucmakiola.clockula.ui.settings
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.clockula.backup.BackupFiles
import de.jeanlucmakiola.clockula.data.backup.BackupCodec
import de.jeanlucmakiola.clockula.data.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.clockula.testing.MainDispatcherExtension
import de.jeanlucmakiola.clockula.testing.backupHarness
import kotlinx.coroutines.flow.first
@@ -0,0 +1,41 @@
{
"format": "clockula-backup",
"version": 1,
"exportedAt": 1690000000000,
"alarms": [
{
"hour": 6,
"minute": 45,
"label": "Work",
"repeat_days": 31,
"vibrate": true,
"snooze_minutes": 5
},
{
"hour": 9,
"minute": 0,
"enabled": false
}
],
"timers": [
{
"label": "Tea",
"duration_millis": 180000
}
],
"worldClocks": [
{
"zone_id": "Asia/Tokyo"
}
],
"settings": {
"theme_mode": "BLACK",
"dynamic_color": false,
"default_snooze_minutes": 8,
"default_snooze_limit": 2,
"default_vibrate": false,
"default_volume_ramp_seconds": 30,
"default_dismiss_challenge": "MATH",
"default_timer_duration_millis": 600000
}
}
@@ -0,0 +1,96 @@
{
"format": "clockula-backup",
"version": 2,
"exportedAt": 1700000000000,
"alarms": [
{
"hour": 7,
"minute": 30,
"label": "Gym",
"repeat_days": 31,
"skip_next_occurrence": true,
"ringtone_uri": "content://media/42",
"vibrate": false,
"snooze_minutes": 7,
"snooze_limit": 2,
"volume_ramp_seconds": 30,
"dismiss_challenge": "MATH"
},
{
"hour": 6,
"minute": 0,
"label": "Flight",
"scheduled_date": "2026-12-24"
},
{
"hour": 8,
"minute": 15,
"label": "Weekend",
"enabled": false,
"repeat_days": 31,
"skip_next_occurrence": true,
"ringtone_uri": "content://media/42",
"vibrate": false,
"snooze_minutes": 7,
"snooze_limit": 2,
"volume_ramp_seconds": 30,
"dismiss_challenge": "MATH",
"pause_start": "2026-12-20",
"pause_end": "2027-01-06"
}
],
"timers": [
{
"label": "Pasta",
"duration_millis": 300000,
"ringtone_uri": "content://media/7",
"sort_order": 3
}
],
"worldClocks": [
{
"zone_id": "Europe/Berlin",
"label": "Home",
"sort_order": 2
}
],
"settings": {
"theme_mode": "DARK",
"dynamic_color": false,
"default_snooze_minutes": 9,
"default_snooze_limit": 4,
"default_vibrate": false,
"default_volume_ramp_seconds": 20,
"default_alarm_ringtone_uri": "content://media/1",
"default_timer_ringtone_uri": "content://media/2",
"default_timer_vibrate": true,
"default_timer_volume_ramp_seconds": 10,
"default_dismiss_challenge": "HOLD",
"home_zone_id": "America/New_York",
"volume_buttons_while_ringing": "SNOOZE",
"default_alarm_silence_after_minutes": 25,
"default_timer_silence_after_minutes": 0,
"automatic_local_clock": false,
"world_clock_show_seconds": true,
"world_clock_compact_home": true,
"timer_presets": [
60000,
120000,
600000
],
"bedtime": {
"enabled": true,
"bedtime_minutes": 1395,
"wake_minutes": 405,
"days": 31,
"reminder_minutes": 30,
"grayscale": false,
"dark_theme": false,
"hide_always_on_display": true
},
"screen_saver_style": "ANALOG",
"screen_saver_night_mode": true,
"quick_tile_duration_millis": 180000,
"week_start": "SATURDAY"
}
}
+1 -1
View File
@@ -112,7 +112,7 @@ kit module: the kit's roadmap keeps schedulers app-local.
| `data/ringtones/` | the two ringtone seams, `RingtoneCatalog` (the bundled and device alarm sounds, titles, playability, a SAF grant) and `RingtonePreviewer`, plus their `System*` implementations, and `MediaLibrary`/`SystemMediaLibrary`, the picker's view of other apps' `MediaBrowserService` libraries |
| `data/time/` | `SystemWallClock`, `SystemElapsedRealtimeClock`, `SystemZoneProvider`, `AndroidBootIdProvider`, `RealTicker`, `AndroidClockChanges` (a receiver for `TIME_SET`/`TIMEZONE_CHANGED` registered only while collected), `AndroidHourFormat` |
| `data/di/` | `DataModule`, `DatabaseModule`, `RepositoryModule`, `TimeModule`, `RingtoneModule`, `ZoneModule` (M8; one `@Binds`, `ZoneNames → IcuZoneNames`), `BackupModule` (M10) |
| `data/backup/` | the backup's data-layer half (M10): `BackupDto`/`BackupCodec` (the pure JSON wire format, `ignoreUnknownKeys`, strict on known fields), `BackupDao` (one `@Transaction` replace-all over alarms/timers/world clocks; no schema or version change), `BackupRepository(+Impl)`, mapping through the existing `AlarmMapper`/`TimerMapper`/`WorldClockMapper`, never a second copy |
| `data/backup/` | the backup's data-layer half (M10): `BackupDto`/`BackupCodec` (the pure JSON wire format on floret `core-backup`'s `BackupFormat` envelope, `ignoreUnknownKeys`, strict on known fields), `BackupDao` (one `@Transaction` replace-all over alarms/timers/world clocks; no schema or version change), `BackupRepository(+Impl)`, mapping through the existing `AlarmMapper`/`TimerMapper`/`WorldClockMapper`, never a second copy |
| `alarm/` | `AlarmEngine` and the four seams it talks to (`AlarmScheduler`, `AlarmCapabilities`, `RingCoordinator`, `AlarmNotifier`), plus `AlarmIntents` |
| `alarm/android/` | the seams' Android implementations: AlarmManager, the capability reads, the service handle, the snoozed and upcoming notifications |
| `alarm/receiver/` | `AlarmFireReceiver`, `AlarmActionReceiver`, `SystemEventReceiver` |
+6 -1
View File
@@ -4,7 +4,9 @@
own data, written to (and read from) a user-chosen folder via SAF
(`docs/PLAN.md` §7). This file is the schema's source of truth; the codec
(`data/backup/BackupDto.kt`, `BackupCodec.kt`) implements exactly what is
written here.
written here. The envelope (`format`, `version`, `exportedAt`) and the
version and size rules are floret-kit's `core-backup` `BackupFormat`, shared
with Calendula's settings backup; the sections are Clockula's own.
## Top level
@@ -30,6 +32,9 @@ written here.
tomorrow's, or a paused one back on. The file name stays
`clockula-backup-v1.json` so an existing backup folder keeps working.
- `exportedAt`: epoch milliseconds, informational only (not re-imported).
A file without `version` or `exportedAt`, or with either not a plain
number, is rejected as damaged.
- A leading byte-order mark (an editor re-saving the file) is ignored.
## Parsing rules
+1 -1
View File
@@ -35,7 +35,7 @@ room = "2.8.3"
# package directly, so it is declared at the version that already resolves.
graphicsShapes = "1.0.1"
# M10 backup: a pure-Kotlin JSON codec so BackupCodecTest runs on the JVM.
kotlinxSerialization = "1.11.0"
kotlinxSerialization = "1.13.0"
# M10 widgets.
glance = "1.2.0"