diff --git a/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/SyncNoticeNotifier.kt b/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/SyncNoticeNotifier.kt index 64130e9..30eb17f 100644 --- a/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/SyncNoticeNotifier.kt +++ b/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/SyncNoticeNotifier.kt @@ -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(). diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt index 92067e5..f92bbc2 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt @@ -1,6 +1,8 @@ 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 @@ -8,7 +10,9 @@ 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. * - * Rotation only ever touches files whose name matches [fileName]'s pattern, so + * 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 { @@ -26,23 +30,33 @@ object AutoBackupPolicy { private const val PREFIX = "agendula-backup-" private const val EXTENSION = ".zip" - private val STAMP = DateTimeFormatter.ofPattern("uuuu-MM-dd-HHmmss", Locale.ROOT) - private val NAME = Regex("""agendula-backup-(\d{4}-\d{2}-\d{2}-\d{6})\.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-143005.zip`: sortable, and readable in a file manager. */ - fun fileName(at: LocalDateTime): String = PREFIX + STAMP.format(at) + EXTENSION + /** `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): LocalDateTime? = - NAME.matchEntire(name)?.let { runCatching { LocalDateTime.parse(it.groupValues[1], STAMP) }.getOrNull() } + 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], oldest last. */ + /** The backups in [names] beyond the newest [keep], newest first. */ fun staleBackups(names: Collection, keep: Int): List = names.mapNotNull { name -> timestampOf(name)?.let { name to it } } .sortedByDescending { it.second } .drop(clampKeep(keep)) .map { it.first } + /** Backups a run never finished, e.g. because the process was killed mid-write. */ + fun abandonedPartials(names: Collection): List = + names.filter { it.endsWith(PARTIAL_SUFFIX) && timestampOf(it.removeSuffix(PARTIAL_SUFFIX)) != null } + fun clampInterval(minutes: Int): Int = minutes.coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) fun clampKeep(count: Int): Int = count.coerceIn(1, MAX_KEEP) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt index 74a06fd..bf75352 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt @@ -25,12 +25,26 @@ data class AutoBackupConfig( val active: Boolean get() = enabled && folderUri != null } -/** How the last automatic backup went; [lastRunMillis] 0 = never ran. */ +/** Why an automatic backup failed: the export's write failures, plus the two before any write. */ +enum class BackupFailure { + FOLDER_UNAVAILABLE, + FOLDER_NOT_WRITABLE, + CANNOT_CREATE_FILE, + LOST_ACCESS, + WRITE_FAILED, + READ_FAILED, + NO_LISTS, + ; + + companion object { + fun of(failure: ExportFailure): BackupFailure = valueOf(failure.name) + } +} + +/** How the last automatic backup went; [lastRunMillis] 0 = never ran, [failure] null = it worked. */ data class AutoBackupStatus( val lastRunMillis: Long = 0L, - val lastSuccess: Boolean = false, - val consecutiveFailures: Int = 0, - val failure: ExportFailure? = null, + val failure: BackupFailure? = null, ) /** The automatic backup's settings and last outcome, in the app's DataStore. */ @@ -51,9 +65,9 @@ class AutoBackupPrefs @Inject constructor( val status: Flow = dataStore.data.map { p -> AutoBackupStatus( lastRunMillis = p[LAST_RUN] ?: 0L, - lastSuccess = p[LAST_SUCCESS] ?: false, - consecutiveFailures = p[FAILURES] ?: 0, - failure = p[FAILURE_REASON]?.let { runCatching { ExportFailure.valueOf(it) }.getOrNull() }, + failure = p[FAILURE_REASON]?.let { + runCatching { BackupFailure.valueOf(it) }.getOrDefault(BackupFailure.WRITE_FAILED) + }, ) }.distinctUntilChanged() @@ -72,18 +86,16 @@ class AutoBackupPrefs @Inject constructor( suspend fun recordSuccess(atMillis: Long) = dataStore.edit { it[LAST_RUN] = atMillis - it[LAST_SUCCESS] = true it[FAILURES] = 0 it.remove(FAILURE_REASON) } /** Returns how many runs in a row have now failed. */ - suspend fun recordFailure(atMillis: Long, reason: ExportFailure): Int { + suspend fun recordFailure(atMillis: Long, reason: BackupFailure): Int { var failures = 0 dataStore.edit { failures = (it[FAILURES] ?: 0) + 1 it[LAST_RUN] = atMillis - it[LAST_SUCCESS] = false it[FAILURES] = failures it[FAILURE_REASON] = reason.name } @@ -96,7 +108,6 @@ class AutoBackupPrefs @Inject constructor( val INTERVAL = intPreferencesKey("auto_backup_interval_minutes") val KEEP = intPreferencesKey("auto_backup_keep") val LAST_RUN = longPreferencesKey("auto_backup_last_run") - val LAST_SUCCESS = booleanPreferencesKey("auto_backup_last_success") val FAILURES = intPreferencesKey("auto_backup_failures") val FAILURE_REASON = stringPreferencesKey("auto_backup_failure_reason") } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt index 122f73b..86b7540 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt @@ -27,6 +27,7 @@ import javax.inject.Singleton class AutoBackupScheduler @Inject constructor( @ApplicationContext private val context: Context, private val prefs: AutoBackupPrefs, + private val notifier: BackupNotifier, @ApplicationScope private val scope: CoroutineScope, ) { @@ -61,6 +62,7 @@ class AutoBackupScheduler @Inject constructor( if (intervalMinutes == null) { workManager.cancelUniqueWork(WORK_NAME) workManager.cancelUniqueWork(WORK_NAME_NOW) + notifier.cancelFailure() return } val minutes = intervalMinutes.toLong() diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt index 99eb540..1bf42ab 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt @@ -13,8 +13,11 @@ import de.jeanlucmakiola.agendula.data.export.ExportFailure 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 java.time.LocalDateTime +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.time.Instant import kotlin.coroutines.cancellation.CancellationException /** @@ -34,20 +37,23 @@ class AutoBackupWorker @AssistedInject constructor( private val notifier: BackupNotifier, ) : CoroutineWorker(context, params) { - override suspend fun doWork(): Result { + // The periodic run and "Back up now" are separate work chains; one at a time, + // or one run's rotation could delete what the other is still writing. + override suspend fun doWork(): Result = runLock.withLock { backUp() } + + private suspend fun backUp(): Result { val config = prefs.config.first() // Turned off since this was queued: nothing to do, and nothing to retry. val folder = config.folderUri?.takeIf { config.enabled } ?: return Result.success() val now = System.currentTimeMillis() return try { startupGate.awaitReady() - val documents = exporter.export() - // No lists means nothing worth keeping; writing an empty backup would - // rotate the real ones out of the folder. - if (documents.isNotEmpty()) { - val tree = folder.toUri() - writer.writeZipToTree(tree, AutoBackupPolicy.fileName(LocalDateTime.now()), documents) - writer.deleteFromTree(tree) { names -> AutoBackupPolicy.staleBackups(names, config.keepCount) } + val documents = readLists() + val tree = folder.toUri() + val fileName = AutoBackupPolicy.fileName(Instant.ofEpochMilli(now)) + writer.writeZipToTree(tree, fileName, AutoBackupPolicy.partialName(fileName), documents) + writer.deleteFromTree(tree) { names -> + AutoBackupPolicy.staleBackups(names, config.keepCount) + AutoBackupPolicy.abandonedPartials(names) } prefs.recordSuccess(now) notifier.cancelFailure() @@ -56,14 +62,37 @@ class AutoBackupWorker @AssistedInject constructor( throw cancelled } catch (error: Exception) { Log.w(TAG, "Automatic backup failed", error) - val reason = (error as? ExportFailedException)?.failure ?: ExportFailure.WRITE_FAILED + val reason = when (error) { + is BackupFailedException -> error.failure + is ExportFailedException -> BackupFailure.of(error.failure) + else -> BackupFailure.of(ExportFailure.WRITE_FAILED) + } if (prefs.recordFailure(now, reason) >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() 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 { + 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 + val runLock = Mutex() } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt index eb61bf2..d1d4b12 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt @@ -1,16 +1,12 @@ package de.jeanlucmakiola.agendula.data.backup -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.pm.PackageManager -import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat -import androidx.core.content.ContextCompat import dagger.Binds import dagger.Module import dagger.hilt.InstallIn @@ -20,6 +16,7 @@ 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 @@ -33,17 +30,10 @@ class BackupNotifier @Inject constructor( @ApplicationContext private val context: Context, ) : ChannelRefresher { - 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() - } - - // canPost() checks POST_NOTIFICATIONS before we ever call notify(). + // canPostNotifications() checks POST_NOTIFICATIONS before we ever call notify(). @SuppressLint("MissingPermission") fun postFailure() { - if (!canPost()) return + if (!context.canPostNotifications()) return ensureChannel() val notification = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt index 52de154..b3abfed 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt @@ -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 @@ -99,37 +100,80 @@ class ExportWriter @Inject constructor( /** * Writes every document into a new zip named [fileName] inside [treeUri]. - * A zip that could not be written completely is removed again, so a failed - * run never leaves a truncated file that looks like a backup. + * + * 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. A provider that cannot rename gets the zip written + * under [fileName] directly. An existing [fileName] is left as it is. */ - suspend fun writeZipToTree(treeUri: Uri, fileName: String, documents: List): ExportResult = - withContext(io) { - runCatching { - val tree = openWritableTree(treeUri) - val file = tree.createFile(MIME_ZIP, fileName) - ?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE) - try { - zipInto(file.uri, documents) - } catch (error: Exception) { - runCatching { file.delete() } - throw error + suspend fun writeZipToTree( + treeUri: Uri, + fileName: String, + partialName: String, + documents: List, + ): ExportResult = withContext(io) { + runCatching { + val tree = openWritableTree(treeUri) + if (fileName !in childDocuments(treeUri)) { + val partial = createAndZip(tree, MIME_PARTIAL, partialName, documents) + if (!runCatching { partial.renameTo(fileName) }.getOrDefault(false)) { + runCatching { partial.delete() } + createAndZip(tree, MIME_ZIP, fileName, documents) } - }.getOrElse { throw asExportFailure(it) } - ExportResult(documents.size, documents.map { it.fileName }) - } + } + }.getOrElse { throw asExportFailure(it) } + ExportResult(documents.size, documents.map { it.fileName }) + } /** * Deletes the files of [treeUri] that [select] picks from the folder's file * names. Best effort: a file that will not go is left and the rest still are. */ - suspend fun deleteFromTree(treeUri: Uri, select: (List) -> Collection): Int = + suspend fun deleteFromTree(treeUri: Uri, select: (Set) -> Collection): Int = withContext(io) { - val files = runCatching { DocumentFile.fromTreeUri(context, treeUri)?.listFiles() } - .getOrNull().orEmpty() - val doomed = select(files.mapNotNull { it.name }).toSet() - files.count { it.name in doomed && runCatching { it.delete() }.getOrDefault(false) } + val children = runCatching { childDocuments(treeUri) }.getOrDefault(emptyMap()) + select(children.keys).count { name -> + val uri = children[name] ?: return@count false + runCatching { DocumentsContract.deleteDocument(context.contentResolver, uri) }.getOrDefault(false) + } } + private fun createAndZip( + tree: DocumentFile, + mime: String, + name: String, + documents: List, + ): DocumentFile { + val file = tree.createFile(mime, name) ?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE) + try { + zipInto(file.uri, documents) + } catch (error: Exception) { + runCatching { file.delete() } + throw error + } + return file + } + + /** The folder's files by name, in one provider query rather than one per file. */ + private fun childDocuments(treeUri: Uri): Map { + 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) @@ -170,5 +214,8 @@ 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" } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/NotificationPermission.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/NotificationPermission.kt new file mode 100644 index 0000000..f0722a3 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/NotificationPermission.kt @@ -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() +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt index 081b2f9..2065694 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt @@ -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(). diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt index fb797ef..e1557ed 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt @@ -339,7 +339,7 @@ private fun openIntent(destination: ExportDestination): Intent? = runCatching { private fun Context.canHandle(intent: Intent): Boolean = packageManager.queryIntentActivities(intent, 0).isNotEmpty() -internal fun failureMessage(reason: ExportFailure): Int = when (reason) { +private 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 diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt index 6394b4d..99c65bd 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt @@ -4,6 +4,7 @@ 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 @@ -12,18 +13,28 @@ 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.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. */ @@ -32,11 +43,21 @@ 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, so off the main thread: the folder may be on an SD card + // or a cloud provider that is slow to answer. + private val folderName = prefs.config.map { it.folderUri }.distinctUntilChanged().map { uri -> + uri?.let { withContext(io) { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } } + } + val state: StateFlow = - combine(prefs.config, prefs.status, scheduler.runningNow) { config, status, running -> - AutoBackupUiState(config, status, running) + combine(prefs.config, prefs.status, scheduler.runningNow, 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. */ @@ -55,7 +76,9 @@ class AutoBackupViewModel @Inject constructor( viewModelScope.launch { val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION val resolver = context.contentResolver - if (runCatching { resolver.takePersistableUriPermission(tree, flags) }.isFailure) return@launch + 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) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt index 3b50ecc..f5ec319 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt @@ -10,23 +10,22 @@ 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.platform.LocalContext 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.documentfile.provider.DocumentFile 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.export.ExportFailure +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 @@ -35,8 +34,8 @@ 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.OptionRows 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 @@ -91,11 +90,13 @@ internal fun BackupScreen( }, position = if (config.active) Position.Top else Position.Alone, ) + if (state.folderRejected) { + GroupedHint(stringResource(R.string.backup_auto_folder_rejected), style = MaterialTheme.typography.bodySmall) + } if (config.active) { GroupedRow( title = stringResource(R.string.backup_auto_folder), - summary = rememberFolderName(config.folderUri) - ?: stringResource(R.string.backup_auto_folder_unset), + summary = state.folderName ?: stringResource(R.string.backup_auto_folder_unset), position = Position.Middle, onClick = { launchFolderPicker() }, ) @@ -185,15 +186,17 @@ private fun AmountPicker( FullScreenPicker(title = title, onDismiss = onDismiss) { GroupedHint(hint) Spacer(Modifier.height(8.dp)) - OptionRows( - options = presets, - selected = selected, - label = label, - onSelect = { - onSelect(it) - onDismiss() - }, - ) + 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)) @@ -228,12 +231,15 @@ private fun AmountPicker( /** "Every 6 hours" / "Every day" / "Every 2 weeks": the interval in its largest whole unit. */ @Composable -private fun backupIntervalLabel(minutes: Int): String = when { - minutes % MINUTES_PER_WEEK == 0 -> - pluralStringResource(R.plurals.backup_every_weeks, minutes / MINUTES_PER_WEEK, minutes / MINUTES_PER_WEEK) - minutes % MINUTES_PER_DAY == 0 -> - pluralStringResource(R.plurals.backup_every_days, minutes / MINUTES_PER_DAY, minutes / MINUTES_PER_DAY) - else -> pluralStringResource(R.plurals.backup_every_hours, minutes / 60, minutes / 60) +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 @@ -242,26 +248,35 @@ private fun backupKeepLabel(count: Int): String = pluralStringResource(R.plurals @Composable private fun backupStatusText(state: AutoBackupUiState): String { val status = state.status + // "5 minutes ago" has to move on while the screen stays open. + val now by produceState(System.currentTimeMillis()) { + while (true) { + delay(STATUS_TICK_MILLIS) + value = System.currentTimeMillis() + } + } + 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) - status.lastSuccess -> stringResource(R.string.backup_auto_status_ok, relativeTimeAgo(status.lastRunMillis)) + failure == null -> stringResource(R.string.backup_auto_status_ok, relativeTimeAgo(status.lastRunMillis, now)) else -> stringResource( R.string.backup_auto_status_failed, - relativeTimeAgo(status.lastRunMillis), - stringResource(failureMessage(status.failure ?: ExportFailure.WRITE_FAILED)), + relativeTimeAgo(status.lastRunMillis, now), + stringResource(backupFailureMessage(failure)), ) } } -/** The folder's display name, resolved from its tree Uri. */ -@Composable -private fun rememberFolderName(uri: String?): String? { - val context = LocalContext.current - return remember(uri) { - uri?.let { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } - } +private fun backupFailureMessage(failure: BackupFailure): Int = when (failure) { + BackupFailure.FOLDER_UNAVAILABLE -> R.string.export_failed_folder + BackupFailure.FOLDER_NOT_WRITABLE -> R.string.export_failed_read_only + BackupFailure.CANNOT_CREATE_FILE -> R.string.export_failed_create + BackupFailure.LOST_ACCESS -> R.string.export_failed_access + BackupFailure.WRITE_FAILED -> R.string.export_failed + BackupFailure.READ_FAILED -> R.string.backup_failed_read + BackupFailure.NO_LISTS -> R.string.backup_failed_no_lists } -private const val MINUTES_PER_DAY = 1_440 -private const val MINUTES_PER_WEEK = 10_080 +private const val STATUS_TICK_MILLIS = 60_000L + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 41a4ac6..cb57497 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -570,6 +570,7 @@ Saves all your lists as a dated zip in a folder you pick. Restore one with Import tasks. Folder Choose a folder + That folder can\'t be kept for backups in the background. Pick another one. Frequency Android may run a backup a little later than this to save battery. @@ -595,10 +596,12 @@ No backup yet Last backup %1$s Backup failed %1$s. %2$s + Your tasks could not be read + There were no lists to back up Automatic backup When automatic backups keep failing Automatic backup failed - Your tasks are not being backed up. Tap to check the backup folder. + Your tasks are not being backed up. Tap to see why. Import tasks diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt index 679b610..09d0f95 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt @@ -2,24 +2,28 @@ package de.jeanlucmakiola.agendula.data.backup import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.Test -import java.time.LocalDateTime +import java.time.Instant class AutoBackupPolicyTest { - private fun name(day: Int, hour: Int = 3) = AutoBackupPolicy.fileName(LocalDateTime.of(2026, 11, day, hour, 0, 5)) + 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)) @Test - fun `names a backup by its local time`() { - assertThat(AutoBackupPolicy.fileName(LocalDateTime.of(2026, 1, 2, 9, 4, 7))) - .isEqualTo("agendula-backup-2026-01-02-090407.zip") + 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(LocalDateTime.of(2026, 11, 17, 3, 0, 5)) + assertThat(AutoBackupPolicy.timestampOf(name(17))).isEqualTo(at(17)) assertThat(AutoBackupPolicy.timestampOf("agendula-tasks.zip")).isNull() - assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-11-17-030005 (1).zip")).isNull() - assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-13-40-030005.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 @@ -36,7 +40,7 @@ class AutoBackupPolicyTest { @Test fun `rotation leaves files that are not backups alone`() { - val names = listOf("notes.txt", "agendula-tasks.zip", name(1), name(2)) + val names = listOf("notes.txt", "agendula-tasks.zip", AutoBackupPolicy.partialName(name(3)), name(1), name(2)) assertThat(AutoBackupPolicy.staleBackups(names, keep = 1)).containsExactly(name(1)) } @@ -50,6 +54,12 @@ class AutoBackupPolicyTest { assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 7)).isEmpty() } + @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)