Merge #77 into release/v1.4.0

This commit is contained in:
makiolaj committed 2026-11-18 19:43:22 +01:00
commit 43f13f682c
20 files changed
+1163 -32

No files matched your search

+6
View File
@@ -7,6 +7,12 @@ All notable changes to this project are documented here. The format follows
## [Unreleased]
### Added
- Automatic backup. Settings → Backup & restore can save all your lists as a
dated zip into a folder you pick, every few hours, days or weeks, and keeps
only the latest few (7 by default). Restore one with Import tasks. A
notification says so if backups keep failing (#77).
## [1.3.2] - 2026-11-13
### Added
@@ -1,20 +1,18 @@
package de.jeanlucmakiola.agendula.data.sync
import android.Manifest
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
import de.jeanlucmakiola.agendula.data.reminders.canPostNotifications
import de.jeanlucmakiola.agendula.R
import javax.inject.Inject
import javax.inject.Singleton
@@ -37,10 +35,7 @@ class SyncNoticeNotifier @Inject constructor(
) : ChannelRefresher {
fun canPost(): Boolean {
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
return context.canPostNotifications()
}
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
@@ -9,6 +9,7 @@ import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.android.HiltAndroidApp
import dagger.hilt.components.SingletonComponent
import de.jeanlucmakiola.agendula.data.backup.AutoBackupScheduler
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
import de.jeanlucmakiola.agendula.data.reminders.ReminderMaintenanceWorker
@@ -74,6 +75,7 @@ class AgendulaApp : Application(), Configuration.Provider {
if (started.get()) runCatching { entryPoint.taskNotifier().refreshChannel() }
}
startupGate.start()
entryPoint.autoBackupScheduler().start()
refreshNotificationChannels()
ProcessLifecycleOwner.get().lifecycle.addObserver(entryPoint.databaseCheckpoint())
scope.launch {
@@ -125,5 +127,6 @@ class AgendulaApp : Application(), Configuration.Provider {
fun taskWidgetUpdater(): TaskWidgetUpdater
fun reminderRefresher(): ReminderRefresher
fun providerSnapshotSource(): ProviderSnapshotSource
fun autoBackupScheduler(): AutoBackupScheduler
}
}
@@ -155,6 +155,7 @@ class MainActivity : ComponentActivity() {
const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
const val EXTRA_OCCURRENCE_START = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
private const val EXTRA_OPEN_ACCOUNTS = "de.jeanlucmakiola.agendula.extra.OPEN_ACCOUNTS"
private const val ACTION_OPEN_BACKUP = "de.jeanlucmakiola.agendula.action.OPEN_BACKUP"
/** The account a sign-in notification is about, on the intent it opens. */
const val EXTRA_SIGN_IN_ACCOUNT_ID = "de.jeanlucmakiola.agendula.extra.SIGN_IN_ACCOUNT_ID"
@@ -195,6 +196,11 @@ class MainActivity : ComponentActivity() {
.putExtra(EXTRA_OPEN_ACCOUNTS, true)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/** Opens Settings → Backup & restore, where a failing automatic backup is fixed. */
fun backupIntent(context: Context): Intent =
Intent(ACTION_OPEN_BACKUP, null, context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/**
* The launcher shortcut's, Quick Settings tile's and a widget's "New
* task". [listId] preset the list when it names exactly one, [dueToday]
@@ -245,6 +251,7 @@ class MainActivity : ComponentActivity() {
returnHome = true,
)
ACTION_TODAY -> return NavRequest.OpenSmart(SmartList.TODAY)
ACTION_OPEN_BACKUP -> return NavRequest.OpenBackup
ACTION_OPEN_SMART -> intent.getStringExtra(EXTRA_SMART_LIST)
?.let { name -> SmartList.entries.firstOrNull { it.name == name } }
?.let { return NavRequest.OpenSmart(it) }
@@ -0,0 +1,69 @@
package de.jeanlucmakiola.agendula.data.backup
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Locale
/**
* The rules of the automatic backup that need no Android: how a backup file is
* named, which ones rotation removes, and the bounds of the user's choices.
*
* Names carry UTC, so a time-zone change or the DST fall-back can never make a
* new backup sort before an older one and get rotated out. Rotation only ever
* touches files matching [fileName]'s pattern (or their [partialName]), so
* anything else the user keeps in the same folder is safe.
*/
object AutoBackupPolicy {
const val DEFAULT_INTERVAL_MINUTES = 1_440
const val MIN_INTERVAL_MINUTES = 60
const val MAX_INTERVAL_MINUTES = 999 * 10_080
/** Every 6 and 12 hours, daily, weekly. */
val INTERVAL_PRESETS = listOf(360, 720, 1_440, 10_080)
const val DEFAULT_KEEP = 7
const val MAX_KEEP = 999
val KEEP_PRESETS = listOf(3, 7, 14, 30)
private const val PREFIX = "agendula-backup-"
private const val EXTENSION = ".zip"
private const val PARTIAL_SUFFIX = ".partial"
private val STAMP = DateTimeFormatter.ofPattern("uuuu-MM-dd-HHmmss'Z'", Locale.ROOT)
private val NAME = Regex("""agendula-backup-(\d{4}-\d{2}-\d{2}-\d{6}Z)\.zip""")
/** `agendula-backup-2026-11-17-143005Z.zip`: sortable, and readable in a file manager. */
fun fileName(at: Instant): String = PREFIX + STAMP.format(at.atOffset(ZoneOffset.UTC)) + EXTENSION
/** The name a backup is written under until it is complete. */
fun partialName(fileName: String): String = fileName + PARTIAL_SUFFIX
/** When the backup named [name] was taken, or null when it is not one of ours. */
fun timestampOf(name: String): Instant? =
NAME.matchEntire(name)?.let { match ->
runCatching { LocalDateTime.parse(match.groupValues[1], STAMP).toInstant(ZoneOffset.UTC) }.getOrNull()
}
/**
* The backups in [names] beyond the newest [keep], newest first. [current],
* the backup just written, always ranks first, so one dated ahead by a
* skewed clock can never rotate it away.
*/
fun staleBackups(names: Collection<String>, keep: Int, current: String): List<String> =
names.filter { it != current }
.mapNotNull { name -> timestampOf(name)?.let { name to it } }
.sortedByDescending { it.second }
.map { it.first }
.drop(clampKeep(keep) - 1)
/** Backups a run never finished, e.g. because the process was killed mid-write. */
fun abandonedPartials(names: Collection<String>): List<String> =
names.filter { it.endsWith(PARTIAL_SUFFIX) && timestampOf(it.removeSuffix(PARTIAL_SUFFIX)) != null }
/** Whole hours, within bounds. */
fun clampInterval(minutes: Int): Int = (minutes / 60 * 60).coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES)
fun clampKeep(count: Int): Int = count.coerceIn(1, MAX_KEEP)
}
@@ -0,0 +1,140 @@
package de.jeanlucmakiola.agendula.data.backup
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import de.jeanlucmakiola.agendula.data.export.ExportFailure
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
/** What the automatic backup does: [folderUri] is a persisted SAF tree grant. */
data class AutoBackupConfig(
val enabled: Boolean = false,
val folderUri: String? = null,
val intervalMinutes: Int = AutoBackupPolicy.DEFAULT_INTERVAL_MINUTES,
val keepCount: Int = AutoBackupPolicy.DEFAULT_KEEP,
) {
/** Whether there is anything to schedule. */
val active: Boolean get() = enabled && folderUri != null
}
/**
* Why an automatic backup failed: the export's write failures ([export]), plus
* the two that happen before anything is written. [transient] ones are retried.
*/
enum class BackupFailure(val export: ExportFailure?, val transient: Boolean) {
FOLDER_UNAVAILABLE(ExportFailure.FOLDER_UNAVAILABLE, transient = true),
FOLDER_NOT_WRITABLE(ExportFailure.FOLDER_NOT_WRITABLE, transient = false),
CANNOT_CREATE_FILE(ExportFailure.CANNOT_CREATE_FILE, transient = true),
LOST_ACCESS(ExportFailure.LOST_ACCESS, transient = false),
WRITE_FAILED(ExportFailure.WRITE_FAILED, transient = true),
READ_FAILED(null, transient = true),
NO_LISTS(null, transient = false),
;
companion object {
fun of(failure: ExportFailure): BackupFailure = entries.firstOrNull { it.export == failure } ?: WRITE_FAILED
}
}
/**
* How the automatic backup has gone: [lastRunMillis] 0 = never ran, [failure]
* null = the last run worked, [lastSuccessMillis] 0 = none has yet.
*/
data class AutoBackupStatus(
val lastRunMillis: Long = 0L,
val failure: BackupFailure? = null,
val lastSuccessMillis: Long = 0L,
)
/** The automatic backup's settings and last outcome, in the app's DataStore. */
@Singleton
class AutoBackupPrefs @Inject constructor(
private val dataStore: DataStore<Preferences>,
) {
val config: Flow<AutoBackupConfig> = dataStore.data.map { p ->
AutoBackupConfig(
enabled = p[ENABLED] ?: false,
folderUri = p[FOLDER],
intervalMinutes = p[INTERVAL]?.let(AutoBackupPolicy::clampInterval)
?: AutoBackupPolicy.DEFAULT_INTERVAL_MINUTES,
keepCount = p[KEEP]?.let(AutoBackupPolicy::clampKeep) ?: AutoBackupPolicy.DEFAULT_KEEP,
)
}.distinctUntilChanged()
val status: Flow<AutoBackupStatus> = dataStore.data.map { p ->
AutoBackupStatus(
lastRunMillis = p[LAST_RUN] ?: 0L,
lastSuccessMillis = p[LAST_SUCCESS_AT] ?: 0L,
failure = p[FAILURE_REASON]?.let {
runCatching { BackupFailure.valueOf(it) }.getOrDefault(BackupFailure.WRITE_FAILED)
},
)
}.distinctUntilChanged()
/** A fresh start, on or off, also restarts the count towards the failure notification. */
suspend fun setEnabled(enabled: Boolean) = dataStore.edit {
it[ENABLED] = enabled
it.remove(FAILURES)
}
/** Points the backup at [uri] and turns it on; the caller has taken the grant. */
suspend fun setFolder(uri: String) = dataStore.edit {
it[FOLDER] = uri
it[ENABLED] = true
it.remove(FAILURES)
}
/** Forgets a folder this install holds no grant for, e.g. settings restored onto a new device. */
suspend fun forgetFolder(uri: String) = dataStore.edit {
if (it[FOLDER] != uri) return@edit
it.remove(FOLDER)
it[ENABLED] = false
listOf(LAST_RUN, LAST_SUCCESS_AT, FAILURES, FAILURE_REASON).forEach { key -> it.remove(key) }
}
suspend fun setIntervalMinutes(minutes: Int) =
dataStore.edit { it[INTERVAL] = AutoBackupPolicy.clampInterval(minutes) }
suspend fun setKeepCount(count: Int) = dataStore.edit { it[KEEP] = AutoBackupPolicy.clampKeep(count) }
suspend fun recordSuccess(atMillis: Long) = dataStore.edit {
it[LAST_RUN] = atMillis
it[LAST_SUCCESS_AT] = atMillis
it[FAILURES] = 0
it.remove(FAILURE_REASON)
}
/**
* Records a failed attempt. Only [final] attempts — no retry left — count
* towards the failure notification; returns how many runs in a row have failed.
*/
suspend fun recordFailure(atMillis: Long, reason: BackupFailure, final: Boolean): Int {
var failures = 0
dataStore.edit {
failures = (it[FAILURES] ?: 0) + if (final) 1 else 0
it[LAST_RUN] = atMillis
it[FAILURES] = failures
it[FAILURE_REASON] = reason.name
}
return failures
}
private companion object {
val ENABLED = booleanPreferencesKey("auto_backup_enabled")
val FOLDER = stringPreferencesKey("auto_backup_folder")
val INTERVAL = intPreferencesKey("auto_backup_interval_minutes")
val KEEP = intPreferencesKey("auto_backup_keep")
val LAST_RUN = longPreferencesKey("auto_backup_last_run")
val LAST_SUCCESS_AT = longPreferencesKey("auto_backup_last_success_at")
val FAILURES = intPreferencesKey("auto_backup_failures")
val FAILURE_REASON = stringPreferencesKey("auto_backup_failure_reason")
}
}
@@ -0,0 +1,121 @@
package de.jeanlucmakiola.agendula.data.backup
import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
/**
* Keeps WorkManager in step with [AutoBackupPrefs]: a unique periodic request
* while the backup is on and has a folder, nothing otherwise. Reactive, so every
* settings change (and every launch) reconciles without the caller having to.
* Turning the backup on, or pointing it at a new folder, also takes one backup
* at once — here rather than at the call site, so it is ordered after any
* cancellation an earlier "off" caused.
*/
@Singleton
class AutoBackupScheduler @Inject constructor(
@ApplicationContext private val context: Context,
private val prefs: AutoBackupPrefs,
private val notifier: BackupNotifier,
@ApplicationScope private val scope: CoroutineScope,
) {
private data class Plan(val folderUri: String, val intervalMinutes: Int)
/** Call once, first thing in `Application.onCreate`, so no settings change predates the collector. */
fun start() {
scope.launch {
runCatching { forgetUngrantedFolder() }
var previous: Plan? = null
var first = true
prefs.config
.map { config -> config.folderUri?.takeIf { config.active }?.let { Plan(it, config.intervalMinutes) } }
.distinctUntilChanged()
.collect { plan ->
runCatching {
apply(plan?.intervalMinutes)
if (!first && plan != null && plan.folderUri != previous?.folderUri) runNow()
}
previous = plan
first = false
}
}
}
/** One backup now. A newer request replaces a queued or running one, so it runs on the current settings. */
fun runNow() {
WorkManager.getInstance(context).enqueueUniqueWork(
WORK_NAME_NOW,
ExistingWorkPolicy.REPLACE,
OneTimeWorkRequestBuilder<AutoBackupWorker>()
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_MINUTES, TimeUnit.MINUTES)
.build(),
)
}
/**
* Whether a backup is running, or a [runNow] one is about to; a periodic one
* waiting for its time, or any run waiting out a retry, does not count.
*/
val running: Flow<Boolean> = WorkManager.getInstance(context).let { workManager ->
combine(
workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME_NOW),
workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME),
) { now, periodic ->
now.any { it.state == WorkInfo.State.RUNNING || (it.state == WorkInfo.State.ENQUEUED && it.runAttemptCount == 0) } ||
periodic.any { it.state == WorkInfo.State.RUNNING }
}.distinctUntilChanged()
}
/**
* Settings restored onto another device (Android's own backup) bring the
* folder along but not the grant to write to it; every run would fail.
*/
private suspend fun forgetUngrantedFolder() {
val folder = prefs.config.first().folderUri ?: return
val granted = context.contentResolver.persistedUriPermissions.any {
it.uri.toString() == folder && it.isWritePermission
}
if (!granted) prefs.forgetFolder(folder)
}
/** [intervalMinutes] null cancels. The first periodic run waits one interval. */
private fun apply(intervalMinutes: Int?) {
val workManager = WorkManager.getInstance(context)
if (intervalMinutes == null) {
workManager.cancelUniqueWork(WORK_NAME)
workManager.cancelUniqueWork(WORK_NAME_NOW)
notifier.cancelFailure()
return
}
val minutes = intervalMinutes.toLong()
val request = PeriodicWorkRequestBuilder<AutoBackupWorker>(minutes, TimeUnit.MINUTES)
.setInitialDelay(minutes, TimeUnit.MINUTES)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_MINUTES, TimeUnit.MINUTES)
.build()
workManager.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request)
}
private companion object {
const val WORK_NAME = "auto-backup"
const val WORK_NAME_NOW = "auto-backup-now"
const val BACKOFF_MINUTES = 10L
}
}
@@ -0,0 +1,102 @@
package de.jeanlucmakiola.agendula.data.backup
import android.content.Context
import android.util.Log
import androidx.core.net.toUri
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import de.jeanlucmakiola.agendula.data.export.ExportFailedException
import de.jeanlucmakiola.agendula.data.export.ExportWriter
import de.jeanlucmakiola.agendula.data.export.TaskExporter
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.domain.export.ExportDocument
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.time.Instant
import kotlin.coroutines.cancellation.CancellationException
/**
* One automatic backup: every list of the current store, as the export's zip,
* into a new dated file in the chosen folder, then rotation down to the kept
* count. A transient failure is retried a few times with backoff; every
* failure is recorded for the settings status line, and a run that has given
* up twice in a row raises a notification. A periodic request runs again next
* interval either way.
*/
@HiltWorker
class AutoBackupWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val prefs: AutoBackupPrefs,
private val startupGate: StartupGate,
private val exporter: TaskExporter,
private val writer: ExportWriter,
private val notifier: BackupNotifier,
) : CoroutineWorker(context, params) {
// One at a time across the periodic and "now" chains.
override suspend fun doWork(): Result = runLock.withLock { backUp() }
private suspend fun backUp(): Result {
val config = prefs.config.first()
val folder = config.folderUri?.takeIf { config.enabled } ?: return Result.success()
val now = System.currentTimeMillis()
return try {
startupGate.awaitReady()
val documents = readLists()
val tree = folder.toUri()
val stamp = Instant.ofEpochMilli(now)
val fileName = AutoBackupPolicy.fileName(stamp)
writer.writeZipToTree(tree, fileName, AutoBackupPolicy.partialName(fileName), documents) { names ->
AutoBackupPolicy.staleBackups(names, config.keepCount, fileName) + AutoBackupPolicy.abandonedPartials(names)
}
prefs.recordSuccess(now)
notifier.cancelFailure()
Result.success()
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
Log.w(TAG, "Automatic backup failed", error)
// The user moved the backup elsewhere mid-run; the old folder's failure is not theirs.
if (prefs.config.first().folderUri != folder) return Result.success()
val reason = when (error) {
is BackupFailedException -> error.failure
is ExportFailedException -> BackupFailure.of(error.failure)
else -> BackupFailure.WRITE_FAILED
}
val retry = reason.transient && runAttemptCount < MAX_RETRIES
val failures = prefs.recordFailure(now, reason, final = !retry)
if (!retry && failures >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure()
if (retry) Result.retry() else Result.failure()
}
}
/**
* No lists is a failure, not an empty backup: it is what an unreachable task
* app looks like, and an empty zip would rotate the real backups out.
*/
private suspend fun readLists(): List<ExportDocument> {
val documents = try {
exporter.export()
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
throw BackupFailedException(BackupFailure.READ_FAILED, error)
}
return documents.ifEmpty { throw BackupFailedException(BackupFailure.NO_LISTS) }
}
private class BackupFailedException(val failure: BackupFailure, cause: Throwable? = null) :
Exception(failure.name, cause)
private companion object {
const val TAG = "AutoBackupWorker"
const val FAILURE_NOTIFY_THRESHOLD = 2
const val MAX_RETRIES = 3
val runLock = Mutex()
}
}
@@ -0,0 +1,89 @@
package de.jeanlucmakiola.agendula.data.backup
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoSet
import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
import de.jeanlucmakiola.agendula.data.reminders.canPostNotifications
import javax.inject.Inject
import javax.inject.Singleton
/**
* Says so when automatic backups keep failing — a revoked folder grant or an
* unmounted SD card would otherwise go unnoticed until the backup is needed.
* Its own low-importance channel, so it can be silenced on its own.
*/
@Singleton
class BackupNotifier @Inject constructor(
@ApplicationContext private val context: Context,
) : ChannelRefresher {
// canPostNotifications() checks POST_NOTIFICATIONS before we ever call notify().
@SuppressLint("MissingPermission")
fun postFailure() {
if (!context.canPostNotifications()) return
ensureChannel()
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.backup_failed_title))
.setContentText(context.getString(R.string.backup_failed_text))
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setAutoCancel(true)
.setContentIntent(
PendingIntent.getActivity(
context,
NOTIFICATION_ID,
MainActivity.backupIntent(context),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
),
)
.build()
runCatching { NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification) }
}
fun cancelFailure() {
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
}
private fun ensureChannel() {
context.getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(
CHANNEL_ID,
context.getString(R.string.backup_channel_name),
NotificationManager.IMPORTANCE_LOW,
).apply { description = context.getString(R.string.backup_channel_description) },
)
}
/** Re-create the channel, if it exists, in the current language. */
override fun refreshChannel() {
val manager = context.getSystemService(NotificationManager::class.java)
if (manager.getNotificationChannel(CHANNEL_ID) != null) ensureChannel()
}
private companion object {
const val CHANNEL_ID = "auto_backup"
const val NOTIFICATION_ID = 5
}
}
@Module
@InstallIn(SingletonComponent::class)
abstract class BackupModule {
@Binds
@IntoSet
abstract fun bindBackupChannel(impl: BackupNotifier): ChannelRefresher
}
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.agendula.data.export
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import androidx.documentfile.provider.DocumentFile
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
@@ -72,9 +73,7 @@ class ExportWriter @Inject constructor(
suspend fun writeToTree(treeUri: Uri, documents: List<ExportDocument>): ExportResult =
withContext(io) {
runCatching {
val tree = DocumentFile.fromTreeUri(context, treeUri)
?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE)
if (!tree.canWrite()) throw ExportFailedException(ExportFailure.FOLDER_NOT_WRITABLE)
val tree = openWritableTree(treeUri)
val existing = tree.listFiles().associateBy { it.name }
documents.forEach { document ->
@@ -95,20 +94,128 @@ class ExportWriter @Inject constructor(
*/
suspend fun writeZip(target: Uri, documents: List<ExportDocument>): ExportResult =
withContext(io) {
runCatching {
context.contentResolver.openOutputStream(target, "wt")?.use { raw ->
ZipOutputStream(raw.buffered()).use { zip ->
documents.forEach { document ->
zip.putNextEntry(ZipEntry(document.fileName))
zip.write(document.content)
zip.closeEntry()
}
}
} ?: throw ExportFailedException(ExportFailure.WRITE_FAILED)
}.getOrElse { throw asExportFailure(it) }
runCatching { zipInto(target, documents) }.getOrElse { throw asExportFailure(it) }
ExportResult(documents.size, documents.map { it.fileName })
}
/**
* Writes every document into a new zip named [fileName] inside [treeUri],
* then deletes the files [prune] picks from the folder's names (best effort:
* a file that will not go is left, and the write still counts).
*
* Where the provider can rename, the zip is written under [partialName] and
* renamed once complete, so a run that fails — or a process killed mid-write
* — never leaves a truncated file under a finished name. Elsewhere it is
* written under [fileName] directly. An existing [fileName] is left as it is.
*/
suspend fun writeZipToTree(
treeUri: Uri,
fileName: String,
partialName: String,
documents: List<ExportDocument>,
prune: (Set<String>) -> Collection<String> = { emptyList() },
): ExportResult = withContext(io) {
val children = runCatching {
val tree = openWritableTree(treeUri)
val children = childDocuments(treeUri)
if (fileName !in children) writeViaPartial(tree, fileName, partialName, documents)
children - partialName
}.getOrElse { throw asExportFailure(it) }
prune(children.keys + fileName).forEach { name ->
val uri = children[name] ?: return@forEach
runCatching { DocumentsContract.deleteDocument(context.contentResolver, uri) }
}
ExportResult(documents.size, documents.map { it.fileName })
}
private fun writeViaPartial(
tree: DocumentFile,
fileName: String,
partialName: String,
documents: List<ExportDocument>,
) {
val partial = tree.createFile(MIME_PARTIAL, partialName)
if (partial == null || !partial.supportsRename()) {
partial?.let { runCatching { it.delete() } }
createAndZip(tree, MIME_ZIP, fileName, documents)
return
}
zipOrDelete(partial, documents)
if (!runCatching { partial.renameTo(fileName) }.getOrDefault(false)) {
runCatching { partial.delete() }
createAndZip(tree, MIME_ZIP, fileName, documents)
}
}
private fun DocumentFile.supportsRename(): Boolean = runCatching {
context.contentResolver.query(uri, arrayOf(DocumentsContract.Document.COLUMN_FLAGS), null, null, null)
?.use { cursor ->
cursor.moveToFirst() &&
cursor.getInt(0) and DocumentsContract.Document.FLAG_SUPPORTS_RENAME != 0
} ?: false
}.getOrDefault(false)
private fun createAndZip(
tree: DocumentFile,
mime: String,
name: String,
documents: List<ExportDocument>,
): DocumentFile {
val file = tree.createFile(mime, name) ?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE)
zipOrDelete(file, documents)
return file
}
private fun zipOrDelete(file: DocumentFile, documents: List<ExportDocument>) {
try {
zipInto(file.uri, documents)
} catch (error: Exception) {
runCatching { file.delete() }
throw error
}
}
/** The folder's files by name, in one provider query rather than one per file. */
private fun childDocuments(treeUri: Uri): Map<String, Uri> {
val children = DocumentsContract.buildChildDocumentsUriUsingTree(
treeUri,
DocumentsContract.getTreeDocumentId(treeUri),
)
val projection = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
)
return context.contentResolver.query(children, projection, null, null, null)?.use { cursor ->
buildMap {
while (cursor.moveToNext()) {
val name = cursor.getString(1) ?: continue
put(name, DocumentsContract.buildDocumentUriUsingTree(treeUri, cursor.getString(0)))
}
}
}.orEmpty()
}
private fun openWritableTree(treeUri: Uri): DocumentFile {
val tree = DocumentFile.fromTreeUri(context, treeUri)
?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE)
// An unmounted volume or a dead provider answers neither query.
if (!tree.exists()) throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE)
if (!tree.canWrite()) throw ExportFailedException(ExportFailure.FOLDER_NOT_WRITABLE)
return tree
}
private fun zipInto(target: Uri, documents: List<ExportDocument>) {
context.contentResolver.openOutputStream(target, "wt")?.use { raw ->
ZipOutputStream(raw.buffered()).use { zip ->
documents.forEach { document ->
zip.putNextEntry(ZipEntry(document.fileName))
zip.write(document.content)
zip.closeEntry()
}
}
} ?: throw ExportFailedException(ExportFailure.WRITE_FAILED)
}
private fun write(target: Uri, bytes: ByteArray) {
runCatching {
// "wt" truncates. Without it a shorter export leaves the tail of the
@@ -129,5 +236,9 @@ class ExportWriter @Inject constructor(
private companion object {
const val MIME_ICALENDAR = "text/calendar"
const val MIME_ZIP = "application/zip"
// Not a zip MIME type, so the provider keeps the suffix rather than adding ".zip".
const val MIME_PARTIAL = "application/octet-stream"
}
}
@@ -0,0 +1,16 @@
package de.jeanlucmakiola.agendula.data.reminders
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
/** Whether a notification posted now would show: the runtime permission (13+) and the app-wide switch. */
fun Context.canPostNotifications(): Boolean {
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
return granted && NotificationManagerCompat.from(this).areNotificationsEnabled()
}
@@ -1,6 +1,5 @@
package de.jeanlucmakiola.agendula.data.reminders
import android.Manifest
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationChannelGroup
@@ -8,14 +7,11 @@ import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.text.format.DateFormat
import android.util.TypedValue
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.R
@@ -62,10 +58,7 @@ class TaskNotifier @Inject constructor(
private val channelPrefs get() = context.getSharedPreferences(CHANNEL_PREFS, Context.MODE_PRIVATE)
fun canPost(): Boolean {
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
return context.canPostNotifications()
}
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
@@ -339,7 +339,7 @@ private fun openIntent(destination: ExportDestination): Intent? = runCatching {
private fun Context.canHandle(intent: Intent): Boolean =
packageManager.queryIntentActivities(intent, 0).isNotEmpty()
private fun failureMessage(reason: ExportFailure): Int = when (reason) {
internal fun failureMessage(reason: ExportFailure): Int = when (reason) {
ExportFailure.FOLDER_UNAVAILABLE -> R.string.export_failed_folder
ExportFailure.FOLDER_NOT_WRITABLE -> R.string.export_failed_read_only
ExportFailure.CANNOT_CREATE_FILE -> R.string.export_failed_create
@@ -76,6 +76,8 @@ fun AgendulaNavHost(
nav.navigate(Dest.TaskDetail.build(navRequest.taskId, navRequest.occurrenceStart))
NavRequest.OpenAccounts ->
nav.navigate(Dest.Settings.build(Dest.Settings.SECTION_ACCOUNTS)) { launchSingleTop = true }
NavRequest.OpenBackup ->
nav.navigate(Dest.Settings.build(Dest.Settings.SECTION_BACKUP)) { launchSingleTop = true }
is NavRequest.OpenAccount ->
nav.navigate(Dest.Settings.buildAccount(navRequest.accountId)) { launchSingleTop = true }
is NavRequest.NewTask ->
@@ -40,6 +40,7 @@ object Dest {
const val ARG_ACCOUNT = "account"
const val route = "settings?$ARG_SECTION={$ARG_SECTION}&$ARG_ACCOUNT={$ARG_ACCOUNT}"
const val SECTION_ACCOUNTS = "Accounts"
const val SECTION_BACKUP = "Backup"
val arguments = listOf(
navArgument(ARG_SECTION) { type = NavType.StringType; nullable = true; defaultValue = null },
@@ -22,6 +22,9 @@ sealed interface NavRequest {
/** Settings → Accounts, where a sync report's detail lives. */
data object OpenAccounts : NavRequest
/** Settings → Backup & restore, from a failed automatic backup. */
data object OpenBackup : NavRequest
/** One account's detail — where "sign in again" lives. */
data class OpenAccount(val accountId: Long) : NavRequest
@@ -0,0 +1,101 @@
package de.jeanlucmakiola.agendula.ui.settings
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.backup.AutoBackupConfig
import de.jeanlucmakiola.agendula.data.backup.AutoBackupPrefs
import de.jeanlucmakiola.agendula.data.backup.AutoBackupScheduler
import de.jeanlucmakiola.agendula.data.backup.AutoBackupStatus
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
data class AutoBackupUiState(
val config: AutoBackupConfig = AutoBackupConfig(),
val status: AutoBackupStatus = AutoBackupStatus(),
val running: Boolean = false,
/** The backup folder's display name; null while unknown or unreadable. */
val folderName: String? = null,
/** The last folder picked could not be kept for background writes. */
val folderRejected: Boolean = false,
)
/** The automatic-backup block of Backup & restore. Scheduling follows the prefs on its own. */
@HiltViewModel
class AutoBackupViewModel @Inject constructor(
@ApplicationContext private val context: Context,
private val prefs: AutoBackupPrefs,
private val scheduler: AutoBackupScheduler,
@IoDispatcher private val io: CoroutineDispatcher,
) : ViewModel() {
private val folderRejected = MutableStateFlow(false)
// A provider query: off the main thread, and not holding up the rest of the state.
private val folderName = prefs.config.map { it.folderUri }.distinctUntilChanged().map { uri ->
uri?.let { withContext(io) { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } }
}.onStart { emit(null) }
val state: StateFlow<AutoBackupUiState> =
combine(prefs.config, prefs.status, scheduler.running, folderName, folderRejected) {
config, status, running, name, rejected ->
AutoBackupUiState(config, status, running, name, rejected)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AutoBackupUiState())
/**
* Turning it on without a folder is the screen's to handle: it asks for one
* first. The scheduler takes the first backup once it is on.
*/
fun setEnabled(enabled: Boolean) {
if (!enabled) folderRejected.value = false
viewModelScope.launch { prefs.setEnabled(enabled) }
}
/**
* Keeps a persisted grant on [tree] so background runs can write to it, lets
* go of the previous folder's and turns the backup on; the scheduler takes a
* backup into the new folder right away.
*/
fun chooseFolder(tree: Uri) {
viewModelScope.launch {
val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
val resolver = context.contentResolver
val granted = runCatching { resolver.takePersistableUriPermission(tree, flags) }.isSuccess
folderRejected.value = !granted
if (!granted) return@launch
val previous = prefs.config.first().folderUri?.toUri()
prefs.setFolder(tree.toString())
if (previous != null && previous != tree) {
runCatching { resolver.releasePersistableUriPermission(previous, flags) }
}
}
}
fun setIntervalMinutes(minutes: Int) {
viewModelScope.launch { prefs.setIntervalMinutes(minutes) }
}
fun setKeepCount(count: Int) {
viewModelScope.launch { prefs.setKeepCount(count) }
}
fun backUpNow() = scheduler.runNow()
}
@@ -1,20 +1,64 @@
package de.jeanlucmakiola.agendula.ui.settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.data.backup.AutoBackupPolicy
import de.jeanlucmakiola.agendula.data.backup.BackupFailure
import de.jeanlucmakiola.agendula.ui.common.reminderUnitLabel
import de.jeanlucmakiola.agendula.ui.export.failureMessage
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.CustomAmountEditor
import de.jeanlucmakiola.floret.components.CustomExpandRow
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.floret.locale.relativeTimeAgo
import de.jeanlucmakiola.floret.reminders.ReminderUnit
import de.jeanlucmakiola.floret.reminders.decomposeReminderMinutes
/** Backup & restore: the way into export and import, as its own entry (after Calendula). */
/** Backup & restore: export, import and the automatic backup (after Calendula). */
@Composable
internal fun BackupScreen(
onOpenExport: () -> Unit,
onOpenImport: () -> Unit,
onBack: () -> Unit,
visible: Boolean,
viewModel: AutoBackupViewModel = hiltViewModel(),
) {
val state by viewModel.state.collectAsStateWithLifecycle()
val config = state.config
var picker by rememberSaveable { mutableStateOf<BackupPicker?>(null) }
val pickFolder = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocumentTree(),
) { uri -> uri?.let(viewModel::chooseFolder) }
val launchFolderPicker = { runCatching { pickFolder.launch(config.folderUri?.toUri()) } }
CollapsingScaffold(
title = stringResource(R.string.settings_section_backup),
onBack = onBack,
@@ -33,5 +77,210 @@ internal fun BackupScreen(
position = Position.Bottom,
onClick = onOpenImport,
)
Spacer(Modifier.height(16.dp))
GroupedSectionHeader(stringResource(R.string.backup_auto_header))
GroupedSwitchRow(
title = stringResource(R.string.backup_auto),
summary = stringResource(R.string.backup_auto_hint),
checked = config.active,
onCheckedChange = { on ->
// No folder yet: the pick turns it on.
if (on && config.folderUri == null) launchFolderPicker() else viewModel.setEnabled(on)
},
position = if (config.active) Position.Top else Position.Alone,
)
if (config.active) {
GroupedRow(
title = stringResource(R.string.backup_auto_folder),
summary = state.folderName ?: stringResource(R.string.backup_auto_folder_unset),
position = Position.Middle,
onClick = { launchFolderPicker() },
)
GroupedRow(
title = stringResource(R.string.backup_auto_interval),
summary = backupIntervalLabel(config.intervalMinutes),
position = Position.Middle,
onClick = { picker = BackupPicker.Interval },
)
GroupedRow(
title = stringResource(R.string.backup_auto_keep),
summary = backupKeepLabel(config.keepCount),
position = Position.Middle,
onClick = { picker = BackupPicker.Keep },
)
GroupedRow(
title = stringResource(R.string.backup_auto_now),
position = Position.Bottom,
dimmed = state.running,
trailing = if (state.running) ({ CircularProgressIndicator(Modifier.size(20.dp)) }) else null,
onClick = viewModel::backUpNow.takeUnless { state.running },
)
GroupedHint(backupStatusText(state), style = MaterialTheme.typography.bodySmall)
}
if (state.folderRejected) {
GroupedHint(stringResource(R.string.backup_auto_folder_rejected), style = MaterialTheme.typography.bodySmall)
}
Spacer(Modifier.height(24.dp))
}
when (picker) {
BackupPicker.Interval -> AmountPicker(
title = stringResource(R.string.backup_auto_interval),
hint = stringResource(R.string.backup_auto_interval_hint),
presets = AutoBackupPolicy.INTERVAL_PRESETS,
selected = config.intervalMinutes,
label = { backupIntervalLabel(it) },
units = INTERVAL_UNITS,
onSelect = viewModel::setIntervalMinutes,
onDismiss = { picker = null },
)
BackupPicker.Keep -> AmountPicker(
title = stringResource(R.string.backup_auto_keep),
hint = stringResource(R.string.backup_auto_keep_hint),
presets = AutoBackupPolicy.KEEP_PRESETS,
selected = config.keepCount,
label = { backupKeepLabel(it) },
units = emptyList(),
onSelect = viewModel::setKeepCount,
onDismiss = { picker = null },
)
null -> Unit
}
}
private enum class BackupPicker { Interval, Keep }
private val INTERVAL_UNITS = listOf(ReminderUnit.Hours, ReminderUnit.Days, ReminderUnit.Weeks)
/**
* Presets plus a custom amount, full-screen. [units] scale the custom amount
* (to minutes, for the interval); empty means a plain count.
*/
@Composable
private fun AmountPicker(
title: String,
hint: String,
presets: List<Int>,
selected: Int,
label: @Composable (Int) -> String,
units: List<ReminderUnit>,
onSelect: (Int) -> Unit,
onDismiss: () -> Unit,
) {
val customSelected = selected !in presets
val seed = remember(selected) {
if (units.isEmpty()) {
selected.takeIf { customSelected } to null
} else {
val amount = decomposeReminderMinutes(selected.takeIf { customSelected })
amount.amount to amount.unit.takeIf { it in units }
}
}
var expanded by rememberSaveable { mutableStateOf(false) }
var amountText by rememberSaveable { mutableStateOf(seed.first?.toString().orEmpty()) }
var unitIndex by rememberSaveable { mutableStateOf(seed.second?.let(units::indexOf) ?: 0) }
val value = amountText.toIntOrNull()?.takeIf { it in 1..999 }
?.let { amount -> amount * (units.getOrNull(unitIndex)?.minutesFactor ?: 1) }
FullScreenPicker(title = title, onDismiss = onDismiss) {
GroupedHint(hint)
Spacer(Modifier.height(8.dp))
presets.forEachIndexed { index, preset ->
GroupedRow(
title = label(preset),
position = positionOf(index, presets.size + 1),
checked = preset == selected,
onClick = {
onSelect(preset)
onDismiss()
},
)
}
CustomExpandRow(
title = if (customSelected) {
stringResource(R.string.reminder_custom_with_value, label(selected))
} else {
stringResource(R.string.reminder_custom)
},
position = Position.Bottom,
expanded = expanded,
onExpandedChange = { expanded = it },
checked = customSelected,
) {
CustomAmountEditor(
amountText = amountText,
onAmountChange = { amountText = it },
preview = value?.let { label(it) } ?: stringResource(R.string.reminder_custom_amount),
setLabel = stringResource(R.string.reminder_custom_set),
confirmEnabled = value != null,
onConfirm = {
value?.let {
onSelect(it)
onDismiss()
}
},
placeholder = "1",
unitLabels = units.map { stringResource(reminderUnitLabel(it)) },
selectedUnit = unitIndex,
onUnitChange = { unitIndex = it },
)
}
}
}
/** "Every 6 hours" / "Every day" / "Every 2 weeks": the interval in its largest whole unit. */
@Composable
private fun backupIntervalLabel(minutes: Int): String {
val (amount, unit) = decomposeReminderMinutes(minutes)
val count = amount ?: 1
return when (unit) {
ReminderUnit.Weeks -> pluralStringResource(R.plurals.backup_every_weeks, count, count)
ReminderUnit.Days -> pluralStringResource(R.plurals.backup_every_days, count, count)
ReminderUnit.Hours -> pluralStringResource(R.plurals.backup_every_hours, count, count)
ReminderUnit.Minutes -> pluralStringResource(R.plurals.backup_every_hours, count / 60, count / 60)
}
}
@Composable
private fun backupKeepLabel(count: Int): String = pluralStringResource(R.plurals.backup_keep_count, count, count)
@Composable
private fun backupStatusText(state: AutoBackupUiState): String {
val status = state.status
// Ticks so "5 minutes ago" moves on; never behind a run that just finished.
val tick by produceState(System.currentTimeMillis()) {
while (true) {
delay(STATUS_TICK_MILLIS)
value = System.currentTimeMillis()
}
}
val now = maxOf(tick, status.lastRunMillis, status.lastSuccessMillis)
val failure = status.failure
return when {
state.running -> stringResource(R.string.backup_auto_status_running)
status.lastRunMillis == 0L -> stringResource(R.string.backup_auto_status_never)
failure == null -> stringResource(R.string.backup_auto_status_ok, relativeTimeAgo(status.lastRunMillis, now))
status.lastSuccessMillis == 0L -> stringResource(
R.string.backup_auto_status_failed,
relativeTimeAgo(status.lastRunMillis, now),
stringResource(backupFailureMessage(failure)),
)
// After a run of failures, when the last good one was is what matters.
else -> stringResource(
R.string.backup_auto_status_failed_last_ok,
relativeTimeAgo(status.lastRunMillis, now),
stringResource(backupFailureMessage(failure)),
relativeTimeAgo(status.lastSuccessMillis, now),
)
}
}
private fun backupFailureMessage(failure: BackupFailure): Int = failure.export?.let(::failureMessage)
?: when (failure) {
BackupFailure.NO_LISTS -> R.string.backup_failed_no_lists
else -> R.string.backup_failed_read
}
private const val STATUS_TICK_MILLIS = 60_000L
+41 -1
View File
@@ -506,7 +506,7 @@
<string name="settings_section_storage">Storage</string>
<string name="settings_storage_subtitle">Where your tasks are kept</string>
<string name="settings_section_backup">Backup &amp; restore</string>
<string name="settings_backup_subtitle">Export and import</string>
<string name="settings_backup_subtitle">Export, import and automatic backup</string>
<string name="settings_task_store">Task store</string>
<string name="settings_task_store_hint">Each store keeps its own tasks. Switching does not move them across — copy them over first, or export them from Backup &amp; restore.</string>
<string name="settings_store_own">On this device</string>
@@ -564,6 +564,46 @@
<string name="export_failed_create">A file could not be created in the chosen folder</string>
<string name="export_failed_access">Access to the chosen location was lost</string>
<!-- Automatic backup -->
<string name="backup_auto_header">Automatic backup</string>
<string name="backup_auto">Back up automatically</string>
<string name="backup_auto_hint">Saves all your lists as a dated zip in a folder you pick. Restore one with Import tasks.</string>
<string name="backup_auto_folder">Folder</string>
<string name="backup_auto_folder_unset">Choose a folder</string>
<string name="backup_auto_folder_rejected">That folder can\'t be kept for backups in the background. Pick another one.</string>
<string name="backup_auto_interval">Frequency</string>
<string name="backup_auto_interval_hint">Android may run a backup a little later than this to save battery.</string>
<plurals name="backup_every_hours">
<item quantity="one">Every hour</item>
<item quantity="other">Every %1$d hours</item>
</plurals>
<plurals name="backup_every_days">
<item quantity="one">Every day</item>
<item quantity="other">Every %1$d days</item>
</plurals>
<plurals name="backup_every_weeks">
<item quantity="one">Every week</item>
<item quantity="other">Every %1$d weeks</item>
</plurals>
<string name="backup_auto_keep">Backups to keep</string>
<string name="backup_auto_keep_hint">Once a new backup is saved, older ones in the folder are deleted. Other files there are left alone.</string>
<plurals name="backup_keep_count">
<item quantity="one">Only the latest</item>
<item quantity="other">The latest %1$d</item>
</plurals>
<string name="backup_auto_now">Back up now</string>
<string name="backup_auto_status_running">Backing up…</string>
<string name="backup_auto_status_never">No backup yet</string>
<string name="backup_auto_status_ok">Last backup %1$s</string>
<string name="backup_auto_status_failed">Backup failed %1$s. %2$s</string>
<string name="backup_auto_status_failed_last_ok">Backup failed %1$s. %2$s. Last good backup %3$s</string>
<string name="backup_failed_read">Your tasks could not be read</string>
<string name="backup_failed_no_lists">There were no lists to back up</string>
<string name="backup_channel_name">Automatic backup</string>
<string name="backup_channel_description">When automatic backups keep failing</string>
<string name="backup_failed_title">Automatic backup failed</string>
<string name="backup_failed_text">Your tasks are not being backed up. Tap to see why.</string>
<!-- Import from .ics -->
<string name="import_title">Import tasks</string>
<string name="settings_import_hint">Bring in tasks from an iCalendar file</string>
@@ -0,0 +1,83 @@
package de.jeanlucmakiola.agendula.data.backup
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
import java.time.Instant
class AutoBackupPolicyTest {
private fun at(day: Int, hour: Int = 3): Instant =
Instant.parse("2026-11-%02dT%02d:00:05Z".format(day, hour))
private fun name(day: Int, hour: Int = 3) = AutoBackupPolicy.fileName(at(day, hour))
private fun stale(names: List<String>, keep: Int, current: String = names.max()) =
AutoBackupPolicy.staleBackups(names, keep, current)
@Test
fun `names a backup by its UTC time`() {
assertThat(AutoBackupPolicy.fileName(Instant.parse("2026-01-02T09:04:07Z")))
.isEqualTo("agendula-backup-2026-01-02-090407Z.zip")
}
@Test
fun `reads the time back out of its own names only`() {
assertThat(AutoBackupPolicy.timestampOf(name(17))).isEqualTo(at(17))
assertThat(AutoBackupPolicy.timestampOf("agendula-tasks.zip")).isNull()
assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-11-17-030005Z (1).zip")).isNull()
assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-13-40-030005Z.zip")).isNull()
assertThat(AutoBackupPolicy.timestampOf(AutoBackupPolicy.partialName(name(17)))).isNull()
}
@Test
fun `rotation drops everything beyond the newest kept`() {
val names = listOf(name(3), name(1), name(5), name(4), name(2))
assertThat(stale(names, keep = 3)).containsExactly(name(2), name(1)).inOrder()
}
@Test
fun `rotation orders by time within a day`() {
val names = listOf(name(1, hour = 23), name(1, hour = 9), name(1, hour = 10))
assertThat(stale(names, keep = 1)).containsExactly(name(1, hour = 10), name(1, hour = 9))
}
@Test
fun `rotation leaves files that are not backups alone`() {
val names = listOf("notes.txt", "agendula-tasks.zip", AutoBackupPolicy.partialName(name(3)), name(1), name(2))
assertThat(stale(names, keep = 1, current = name(2))).containsExactly(name(1))
}
@Test
fun `rotation keeps at least the newest backup`() {
assertThat(stale(listOf(name(1), name(2)), keep = 0)).containsExactly(name(1))
}
@Test
fun `nothing is stale while under the limit`() {
assertThat(stale(listOf(name(1), name(2)), keep = 7)).isEmpty()
}
@Test
fun `a backup dated in the future never outranks the one just written`() {
val future = "agendula-backup-2027-06-01-000000Z.zip"
assertThat(stale(listOf(future, name(5), name(4)), keep = 1, current = name(5)))
.containsExactly(future, name(4))
assertThat(stale(listOf(future, name(5), name(4)), keep = 2, current = name(5)))
.containsExactly(name(4))
}
@Test
fun `finds partial backups a killed run left behind`() {
val partial = AutoBackupPolicy.partialName(name(1))
assertThat(AutoBackupPolicy.abandonedPartials(listOf(partial, name(1), "notes.partial"))).containsExactly(partial)
}
@Test
fun `clamps the user's choices`() {
assertThat(AutoBackupPolicy.clampInterval(15)).isEqualTo(AutoBackupPolicy.MIN_INTERVAL_MINUTES)
assertThat(AutoBackupPolicy.clampInterval(1_440)).isEqualTo(1_440)
assertThat(AutoBackupPolicy.clampInterval(90)).isEqualTo(60)
assertThat(AutoBackupPolicy.clampKeep(0)).isEqualTo(1)
assertThat(AutoBackupPolicy.clampKeep(5_000)).isEqualTo(AutoBackupPolicy.MAX_KEEP)
}
}