diff --git a/CHANGELOG.md b/CHANGELOG.md index edf179a1c..87fd9dde5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,7 @@ Emojis for the following are chosen based on [gitmoji](https://gitmoji.dev/). ### ✨ New Features +- The "Regularly update data" switch is saved and defaults to off. When it is on, the app checks Scribe-Server for newer language data immediately and once during the second week of each month, then posts a local notification. It does not download the data ([#768](https://github.com/scribe-org/Scribe-Android/issues/768)). - Keyboard extensions that can be used in any app. - Annotation of words in the command bar including the genders of nouns and cases that follow prepositions ([#135](https://github.com/scribe-org/Scribe-Android/issues/135), [#136](https://github.com/scribe-org/Scribe-Android/issues/136), [#275](https://github.com/scribe-org/Scribe-Android/issues/275)). - The Scribe command UI can be displayed by pressing the Scribe Key ([#16](https://github.com/scribe-org/Scribe-Android/issues/16), [#89](https://github.com/scribe-org/Scribe-Android/issues/89), [#137](https://github.com/scribe-org/Scribe-Android/issues/137)). diff --git a/CHANGELOG_CONJUGATE.md b/CHANGELOG_CONJUGATE.md index 76df08686..62a922c2a 100644 --- a/CHANGELOG_CONJUGATE.md +++ b/CHANGELOG_CONJUGATE.md @@ -34,6 +34,7 @@ Emojis for the following are chosen based on [gitmoji](https://gitmoji.dev/). ### ✨ New Features +- The "Regularly update data" switch is saved and defaults to off. When it is on, the app checks Scribe-Server for newer verb data immediately and once during the second week of each month, then posts a local notification. It does not download the data ([#768](https://github.com/scribe-org/Scribe-Android/issues/768)). - A verb Conjugation tab was added to the application ([#563](https://github.com/scribe-org/Scribe-Android/issues/563)). - Users can search for verbs across languages ([#566](https://github.com/scribe-org/Scribe-Android/issues/566)). - A reactive conjugation selection UI was developed to easily copy desired conjugations ([#567](https://github.com/scribe-org/Scribe-Android/issues/567), [#570](https://github.com/scribe-org/Scribe-Android/issues/570)). diff --git a/app/build.gradle.kts b/app/build.gradle.kts index e7a05cee7..5dd4eaa00 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -337,6 +337,7 @@ dependencies { api("com.github.bumptech.glide:glide:4.16.0") ksp("com.github.bumptech.glide:ksp:4.16.0") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + implementation("androidx.work:work-runtime-ktx:2.11.2") implementation("com.charleskorn.kaml:kaml:0.57.0") implementation("org.jetbrains.kotlinx:kotlinx-collections-immutable:0.3.7") } diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 523e07311..8d958d2a5 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -7,3 +7,8 @@ -keep class be.scri.inputmethod.keyboard.** { *; } -keep class be.scri.inputmethod.latin.** { *; } -keep class be.scri.latin.** { *; } + +# WorkManager looks this class up by name. Keep the worker constructor. +-keep class be.scri.helpers.dataupdate.DataUpdateCheckWorker { + public (android.content.Context, androidx.work.WorkerParameters); +} diff --git a/app/src/conjugate/java/be/scri/activities/MainActivity.kt b/app/src/conjugate/java/be/scri/activities/MainActivity.kt index 61bfe1a3a..16597d872 100644 --- a/app/src/conjugate/java/be/scri/activities/MainActivity.kt +++ b/app/src/conjugate/java/be/scri/activities/MainActivity.kt @@ -6,6 +6,7 @@ package be.scri.activities +import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity @@ -24,6 +25,10 @@ import androidx.navigation.compose.rememberNavController import be.scri.ScribeApp import be.scri.helpers.PreferencesHelper import be.scri.helpers.PreferencesHelper.setLightDarkModePreference +import be.scri.helpers.dataupdate.DataUpdateNotifier +import be.scri.helpers.dataupdate.DataUpdateScheduler +import be.scri.helpers.dataupdate.DownloadNavEffect +import be.scri.helpers.dataupdate.DownloadNavEvents import be.scri.ui.common.bottombar.BottomBarScreen import be.scri.ui.theme.ScribeTheme @@ -32,12 +37,16 @@ import be.scri.ui.theme.ScribeTheme * Initializes theme settings, navigation, and sets up the main UI using Jetpack Compose. */ class MainActivity : ComponentActivity() { + private val downloadNavEvents = DownloadNavEvents() + /** * Initializes the app on launch. Sets the theme based on user preferences, sets up edge-to-edge * layout, and builds the UI using Compose. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + DataUpdateScheduler.ensureScheduled(this) + downloadNavEvents.publish(intent) AppCompatDelegate.setDefaultNightMode(PreferencesHelper.getUserDarkModePreference(this)) val isDark = PreferencesHelper.getUserDarkModePreference(this) == AppCompatDelegate.MODE_NIGHT_YES @@ -69,6 +78,11 @@ class MainActivity : ComponentActivity() { } val navController = rememberNavController() + DownloadNavEffect( + events = downloadNavEvents, + navController = navController, + route = DataUpdateNotifier.ROUTE_CONJUGATE, + ) val isHintChangedMap = remember { mutableStateMapOf() } @@ -121,6 +135,12 @@ class MainActivity : ComponentActivity() { } } + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + downloadNavEvents.publish(intent) + } + private fun applyNavigationBarStyle(isDark: Boolean) { enableEdgeToEdge( navigationBarStyle = diff --git a/app/src/keyboards/java/be/scri/activities/MainActivity.kt b/app/src/keyboards/java/be/scri/activities/MainActivity.kt index ba4c5c469..caf76ddcb 100644 --- a/app/src/keyboards/java/be/scri/activities/MainActivity.kt +++ b/app/src/keyboards/java/be/scri/activities/MainActivity.kt @@ -6,6 +6,7 @@ package be.scri.activities +import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity @@ -14,7 +15,6 @@ import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatDelegate import androidx.compose.foundation.pager.rememberPagerState -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -25,6 +25,10 @@ import androidx.navigation.compose.rememberNavController import be.scri.ScribeApp import be.scri.helpers.PreferencesHelper import be.scri.helpers.PreferencesHelper.setLightDarkModePreference +import be.scri.helpers.dataupdate.DataUpdateNotifier +import be.scri.helpers.dataupdate.DataUpdateScheduler +import be.scri.helpers.dataupdate.DownloadNavEffect +import be.scri.helpers.dataupdate.DownloadNavEvents import be.scri.ui.common.bottombar.BottomBarScreen import be.scri.ui.theme.ScribeTheme @@ -33,12 +37,16 @@ import be.scri.ui.theme.ScribeTheme * Initializes theme settings, navigation, and sets up the main UI using Jetpack Compose. */ class MainActivity : ComponentActivity() { + private val downloadNavEvents = DownloadNavEvents() + /** * Initializes the app on launch. Sets the theme based on user preferences, sets up edge-to-edge * layout, and builds the UI using Compose. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + DataUpdateScheduler.ensureScheduled(this) + downloadNavEvents.publish(intent) AppCompatDelegate.setDefaultNightMode(PreferencesHelper.getUserDarkModePreference(this)) val isDark = PreferencesHelper.getUserDarkModePreference(this) == AppCompatDelegate.MODE_NIGHT_YES @@ -71,13 +79,11 @@ class MainActivity : ComponentActivity() { } val navController = rememberNavController() - - val navigateTo = intent.getStringExtra("navigate_to") - LaunchedEffect(navigateTo) { - if (navigateTo == "download_data") { - navController.navigate("download_data") - } - } + DownloadNavEffect( + events = downloadNavEvents, + navController = navController, + route = DataUpdateNotifier.ROUTE_KEYBOARDS, + ) val isHintChangedMap = remember { mutableStateMapOf() } @@ -128,6 +134,12 @@ class MainActivity : ComponentActivity() { } } + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + downloadNavEvents.publish(intent) + } + private fun applyNavigationBarStyle(isDark: Boolean) { enableEdgeToEdge( navigationBarStyle = diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f12bc8b0b..fdb4def4d 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -3,6 +3,7 @@ android:installLocation="auto"> + = GIVE_UP_DAY) { + delayUntilNextSlot(now, slot) + } else { + Duration.ofHours(POSTPONE_HOURS) + } + + /** + * Same rule as [batterySaverDelay], using the slot saved for this install. + */ + fun batterySaverDelay( + context: Context, + now: LocalDateTime = LocalDateTime.now(), + ): Duration = batterySaverDelay(now, ensureSlot(context)) + + /** + * The next local date-time at which [slot] occurs strictly after [now]. + */ + fun nextOccurrence( + now: LocalDateTime, + slot: DataCheckSlot, + ): LocalDateTime { + val thisMonth = + now + .withDayOfMonth(slot.dayOfMonth) + .withHour(slot.minuteOfDay / MINUTES_PER_HOUR) + .withMinute(slot.minuteOfDay % MINUTES_PER_HOUR) + .withSecond(0) + .withNano(0) + return if (thisMonth.isAfter(now)) thisMonth else thisMonth.plusMonths(1) + } +} diff --git a/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateCheckRunner.kt b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateCheckRunner.kt new file mode 100644 index 000000000..2b93b80a6 --- /dev/null +++ b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateCheckRunner.kt @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import android.util.Log +import kotlinx.coroutines.CancellationException + +/** + * What the worker should tell WorkManager after one run. + */ +enum class DataUpdateRunOutcome { + /** Nothing more to do for this run. The next monthly check is queued when one is wanted. */ + DONE, + + /** Every check failed and attempts are left, so WorkManager should run it again with backoff. */ + RETRY, +} + +/** + * Which later run the worker should queue. + */ +enum class DataUpdateFollowUp { + /** The saved day of the second week, next time it comes round. */ + NEXT_SLOT, + + /** Twelve hours on, or next month's slot once past the 21st, because battery saver was on. */ + AFTER_BATTERY_SAVER, +} + +/** + * The decisions of one data-version check, kept free of Android classes so they can be unit tested. + * [DataUpdateCheckWorker] supplies the real implementations. + * + * - A run that finds the switch off does nothing. + * - A scheduled run waits out battery saver. A run from the switch does not, because the user just asked for it. + * - A run that cannot post notifications skips the network checks, since a result could never be shown. + * It queues nothing: opening the app queues the next check again through [DataUpdateScheduler.ensureScheduled]. + * - If every language check fails, the run is retried until [MAX_ATTEMPTS] runs have been made, + * then it gives up and falls through to the next monthly slot. + * Some languages failing is not a failed run: updates that were found are still reported. + */ +class DataUpdateCheckRunner( + private val isEnabled: () -> Boolean, + private val isBatterySaverOn: () -> Boolean, + private val canPostNotifications: () -> Boolean, + private val check: suspend () -> DataUpdateCheckResult, + private val notify: (List) -> Unit, + private val scheduleFollowUp: (DataUpdateFollowUp) -> Unit, +) { + /** + * Runs one check. [runAttemptCount] is WorkManager's zero-based count of earlier attempts. + */ + @Suppress("TooGenericExceptionCaught") + suspend fun run( + userInitiated: Boolean, + runAttemptCount: Int, + ): DataUpdateRunOutcome { + if (!isEnabled()) return DataUpdateRunOutcome.DONE + + if (!userInitiated && isBatterySaverOn()) { + scheduleFollowUp(DataUpdateFollowUp.AFTER_BATTERY_SAVER) + return DataUpdateRunOutcome.DONE + } + + if (!canPostNotifications()) { + Log.i(TAG, "Notifications are not allowed. Skipping the data check.") + return DataUpdateRunOutcome.DONE + } + + val result = + try { + check() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (e: Exception) { + Log.w(TAG, "Data update check failed", e) + null + } + + if (result == null || result.allFailed) { + if (runAttemptCount + 1 < MAX_ATTEMPTS) return DataUpdateRunOutcome.RETRY + Log.w(TAG, "Giving up after $MAX_ATTEMPTS attempts. Waiting for the next monthly check.") + } else if (result.languagesWithUpdates.isNotEmpty() && isEnabled()) { + try { + notify(result.languagesWithUpdates) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (e: Exception) { + Log.w(TAG, "Could not post the update notification", e) + } + } + + if (isEnabled()) scheduleFollowUp(DataUpdateFollowUp.NEXT_SLOT) + return DataUpdateRunOutcome.DONE + } + + companion object { + /** Total runs, including the first, before a failing check waits for the next monthly slot. */ + const val MAX_ATTEMPTS = 3 + + private const val TAG = "DataUpdateCheckRunner" + } +} diff --git a/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateCheckWorker.kt b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateCheckWorker.kt new file mode 100644 index 000000000..edc605102 --- /dev/null +++ b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateCheckWorker.kt @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import android.content.Context +import android.os.PowerManager +import androidx.core.app.NotificationManagerCompat +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import be.scri.data.remote.RetrofitClient +import be.scri.helpers.AppFlavor +import be.scri.helpers.FlavorProvider +import be.scri.helpers.PreferencesHelper + +/** + * Runs one data-version check through [DataUpdateCheckRunner], which holds the rules for + * battery saver, missing notification permission and the retry limit. + */ +class DataUpdateCheckWorker( + context: Context, + params: WorkerParameters, +) : CoroutineWorker(context, params) { + override suspend fun doWork(): Result { + val context = applicationContext + val outcome = + DataUpdateCheckRunner( + isEnabled = { PreferencesHelper.getRegularlyCheckForDataUpdates(context) }, + isBatterySaverOn = { isBatterySaverOn(context) }, + canPostNotifications = { NotificationManagerCompat.from(context).areNotificationsEnabled() }, + check = { buildChecker(context).check() }, + notify = { languages -> DataUpdateNotifier.show(context, languages) }, + scheduleFollowUp = { followUp -> + val delay = + when (followUp) { + DataUpdateFollowUp.NEXT_SLOT -> DataUpdateCalendar.delayUntilNextSlot(context) + DataUpdateFollowUp.AFTER_BATTERY_SAVER -> DataUpdateCalendar.batterySaverDelay(context) + } + DataUpdateScheduler.enqueueFollowUp(context, delay, userInitiated = false) + }, + ).run( + userInitiated = inputData.getBoolean(DataUpdateScheduler.KEY_USER_INITIATED, false), + runAttemptCount = runAttemptCount, + ) + return when (outcome) { + DataUpdateRunOutcome.DONE -> Result.success() + DataUpdateRunOutcome.RETRY -> Result.retry() + } + } + + private fun buildChecker(context: Context): DataUpdateChecker { + val conjugate = FlavorProvider.get() == AppFlavor.CONJUGATE + val prefsName = if (conjugate) CONJUGATE_DOWNLOAD_PREFS_NAME else DOWNLOAD_PREFS_NAME + val keyPrefix = if (conjugate) CONJUGATE_LAST_UPDATE_PREFIX else LAST_UPDATE_PREFIX + return DataUpdateChecker( + context.getSharedPreferences(prefsName, Context.MODE_PRIVATE), + RetrofitClient.apiService::getDataVersion, + keyPrefix, + ) + } + + private fun isBatterySaverOn(context: Context): Boolean { + val powerManager = context.getSystemService(PowerManager::class.java) + return powerManager?.isPowerSaveMode == true + } +} diff --git a/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateChecker.kt b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateChecker.kt new file mode 100644 index 000000000..987e622b5 --- /dev/null +++ b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateChecker.kt @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import android.content.SharedPreferences +import android.util.Log +import be.scri.data.model.DataVersionResponse +import kotlinx.coroutines.CancellationException + +/** + * Loads one language's data-version payload. Production code passes the Retrofit service. + */ +fun interface DataVersionSource { + /** + * Fetches the version map for [language], an ISO code such as `fr`. + */ + suspend fun getDataVersion(language: String): DataVersionResponse +} + +/** + * What one pass over the downloaded languages found. + * [checkedCount] counts the languages that were asked, and [failedCount] the ones that did not answer. + */ +data class DataUpdateCheckResult( + val languagesWithUpdates: List, + val checkedCount: Int, + val failedCount: Int, +) { + /** + * True when at least one language was asked and none of them answered. + * That means the check itself failed, as opposed to there being nothing new. + */ + val allFailed: Boolean + get() = checkedCount > 0 && failedCount == checkedCount +} + +/** + * Asks Scribe-Server which already-downloaded languages have a newer data pack. + * A language that fails to answer is skipped so one error does not hide the rest, + * but it is counted so the caller can tell "nothing new" apart from "every check failed". + */ +class DataUpdateChecker( + private val downloadPrefs: SharedPreferences, + private val source: DataVersionSource, + private val keyPrefix: String = LAST_UPDATE_PREFIX, +) { + /** + * Compares each downloaded language's saved timestamp with the server. + * [keyPrefix] is `last_update_` in Keyboards and `last_conjugate_update_` in Conjugate. + */ + @Suppress("TooGenericExceptionCaught") + suspend fun check(): DataUpdateCheckResult { + val updates = mutableListOf() + var checked = 0 + var failed = 0 + for (code in downloadedLanguageCodes()) { + val localUpdatedAt = downloadPrefs.getString("$keyPrefix$code", null) ?: continue + checked++ + try { + val response = source.getDataVersion(code) + if (DataVersionComparator.anyVersionNewer(localUpdatedAt, response.versions)) { + updates.add(code) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (e: Exception) { + failed++ + Log.w(TAG, "Version check failed for $code", e) + } + } + return DataUpdateCheckResult(updates, checked, failed) + } + + private fun downloadedLanguageCodes(): List = + downloadPrefs.all.keys + .asSequence() + .filter { it.startsWith(keyPrefix) } + .map { it.removePrefix(keyPrefix) } + .filter { it.isNotBlank() } + .distinct() + .toList() + + private companion object { + const val TAG = "DataUpdateChecker" + } +} + +/** SharedPreferences file where keyboard download timestamps are stored. */ +const val DOWNLOAD_PREFS_NAME = "scribe_prefs" + +/** Prefix for a keyboard language timestamp, followed by a lowercase ISO code. */ +const val LAST_UPDATE_PREFIX = "last_update_" + +/** SharedPreferences file where conjugate download timestamps are stored. */ +const val CONJUGATE_DOWNLOAD_PREFS_NAME = "scribe_conjugate_prefs" + +/** Prefix for a conjugate language timestamp, followed by a lowercase ISO code. */ +const val CONJUGATE_LAST_UPDATE_PREFIX = "last_conjugate_update_" diff --git a/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateNotifier.kt b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateNotifier.kt new file mode 100644 index 000000000..b047a9b9e --- /dev/null +++ b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateNotifier.kt @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.util.Log +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import be.scri.R +import be.scri.activities.MainActivity +import be.scri.helpers.AppFlavor +import be.scri.helpers.FlavorProvider + +/** + * Posts one local notification naming the languages that have newer data. + * The wording uses strings that already exist in Scribe-i18n. + */ +object DataUpdateNotifier { + const val EXTRA_NAVIGATE_TO = "navigate_to" + const val ROUTE_KEYBOARDS = "download_data" + const val ROUTE_CONJUGATE = "conjugate_download_data" + + private const val CHANNEL_ID = "scribe_data_updates" + private const val NOTIFICATION_ID = 1001 + private const val TAG = "DataUpdateNotifier" + + /** + * Shows a notification for [languageCodes]. Does nothing when the list is empty. + * A missing notification permission is ignored; the download screen still checks on open. + */ + fun show( + context: Context, + languageCodes: List, + ) { + if (languageCodes.isEmpty()) return + val manager = NotificationManagerCompat.from(context) + val channelName = context.getString(R.string.i18n_app_download_menu_ui_update_data) + val channel = + android.app.NotificationChannel( + CHANNEL_ID, + channelName, + android.app.NotificationManager.IMPORTANCE_DEFAULT, + ) + manager.createNotificationChannel(channel) + + val title = context.getString(R.string.i18n_app_download_menu_ui_update_data_check_new) + val updateLabel = context.getString(R.string.i18n_app_download_menu_ui_download_data_update) + val names = + languageCodes + .map { languageName(context, it) } + .sorted() + .joinToString(", ") + val notification = + NotificationCompat + .Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_stat_data_update) + .setContentTitle(title) + .setContentText("$updateLabel: $names") + .setStyle(NotificationCompat.BigTextStyle().bigText("$updateLabel: $names")) + .setAutoCancel(true) + .setContentIntent(contentIntent(context)) + .build() + try { + manager.notify(NOTIFICATION_ID, notification) + } catch (e: SecurityException) { + Log.w(TAG, "Notification permission is missing", e) + } + } + + private fun contentIntent(context: Context): PendingIntent { + val route = + if (FlavorProvider.get() == AppFlavor.CONJUGATE) { + ROUTE_CONJUGATE + } else { + ROUTE_KEYBOARDS + } + val intent = + Intent(context, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP + putExtra(EXTRA_NAVIGATE_TO, route) + } + return PendingIntent.getActivity( + context, + 0, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private fun languageName( + context: Context, + isoCode: String, + ): String { + val resId = + when (isoCode.lowercase()) { + "en" -> R.string.i18n_app__global_english + "fr" -> R.string.i18n_app__global_french + "de" -> R.string.i18n_app__global_german + "it" -> R.string.i18n_app__global_italian + "pt" -> R.string.i18n_app__global_portuguese + "ru" -> R.string.i18n_app__global_russian + "es" -> R.string.i18n_app__global_spanish + "sv" -> R.string.i18n_app__global_swedish + else -> 0 + } + return if (resId == 0) isoCode.uppercase() else context.getString(resId) + } +} diff --git a/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateScheduler.kt b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateScheduler.kt new file mode 100644 index 000000000..8894d4e46 --- /dev/null +++ b/app/src/main/java/be/scri/helpers/dataupdate/DataUpdateScheduler.kt @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import android.content.Context +import androidx.work.BackoffPolicy +import androidx.work.Constraints +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequest +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.workDataOf +import be.scri.helpers.PreferencesHelper +import java.time.Duration +import java.util.concurrent.TimeUnit + +/** + * Owns the single background check named [WORK_NAME]. + * Turning the switch on replaces any pending run with an immediate check. + * That check appends the next monthly run when it finishes. + */ +object DataUpdateScheduler { + const val WORK_NAME = "scribe_data_update_check" + const val KEY_USER_INITIATED = "user_initiated" + + private const val RETRY_BACKOFF_MINUTES = 15L + + /** + * Saves [enabled] and either cancels the check or runs one now. + */ + fun onToggle( + context: Context, + enabled: Boolean, + ) { + PreferencesHelper.setRegularlyCheckForDataUpdates(context, enabled) + val workManager = WorkManager.getInstance(context) + if (!enabled) { + workManager.cancelUniqueWork(WORK_NAME) + return + } + DataUpdateCalendar.ensureSlot(context) + workManager.enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, request(Duration.ZERO, userInitiated = true)) + } + + /** + * If the switch is on and no check is waiting, queue the next monthly slot. + * Does not start a check just because the app was opened. + */ + fun ensureScheduled(context: Context) { + if (!PreferencesHelper.getRegularlyCheckForDataUpdates(context)) return + DataUpdateCalendar.ensureSlot(context) + WorkManager.getInstance(context).enqueueUniqueWork( + WORK_NAME, + ExistingWorkPolicy.KEEP, + request(DataUpdateCalendar.delayUntilNextSlot(context), userInitiated = false), + ) + } + + /** + * Adds the next run after the one that is currently executing. + * Append is required here: replace would cancel the running check. + */ + fun enqueueFollowUp( + context: Context, + delay: Duration, + userInitiated: Boolean, + ) { + WorkManager.getInstance(context).enqueueUniqueWork( + WORK_NAME, + ExistingWorkPolicy.APPEND_OR_REPLACE, + request(delay, userInitiated), + ) + } + + private fun request( + delay: Duration, + userInitiated: Boolean, + ): OneTimeWorkRequest = + OneTimeWorkRequestBuilder() + .setConstraints( + Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build(), + ).setInitialDelay(delay) + .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, RETRY_BACKOFF_MINUTES, TimeUnit.MINUTES) + .setInputData(workDataOf(KEY_USER_INITIATED to userInitiated)) + .build() +} diff --git a/app/src/main/java/be/scri/helpers/dataupdate/DataVersionComparator.kt b/app/src/main/java/be/scri/helpers/dataupdate/DataVersionComparator.kt new file mode 100644 index 000000000..741fa5757 --- /dev/null +++ b/app/src/main/java/be/scri/helpers/dataupdate/DataVersionComparator.kt @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import java.time.LocalDate +import java.time.format.DateTimeParseException + +/** + * Compares the saved language-data timestamp with dates from `data-version/{lang}`. + * A value that cannot be parsed is not treated as an update. + */ +object DataVersionComparator { + private const val DATE_LENGTH = 10 + + /** + * Returns true when [serverUpdatedAt] is a later calendar day than [localUpdatedAt]. + * Both values are compared on their first ten characters (`yyyy-MM-dd`). + */ + fun isUpdateAvailable( + localUpdatedAt: String, + serverUpdatedAt: String?, + ): Boolean { + val localDate = parseDate(localUpdatedAt) ?: return false + val serverDate = parseDate(serverUpdatedAt) ?: return false + return serverDate.isAfter(localDate) + } + + /** + * Returns true when any entry in [serverVersions] is newer than [localUpdatedAt]. + */ + fun anyVersionNewer( + localUpdatedAt: String, + serverVersions: Map, + ): Boolean = serverVersions.values.any { serverDate -> isUpdateAvailable(localUpdatedAt, serverDate) } + + private fun parseDate(value: String?): LocalDate? { + if (value.isNullOrBlank()) return null + return try { + LocalDate.parse(value.take(DATE_LENGTH)) + } catch (ignored: DateTimeParseException) { + null + } + } +} diff --git a/app/src/main/java/be/scri/helpers/dataupdate/DownloadNavEvents.kt b/app/src/main/java/be/scri/helpers/dataupdate/DownloadNavEvents.kt new file mode 100644 index 000000000..1fc1828db --- /dev/null +++ b/app/src/main/java/be/scri/helpers/dataupdate/DownloadNavEvents.kt @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import android.content.Intent +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.navigation.NavHostController + +/** + * One request to open the download screen, including a fresh id so a repeated tap navigates again. + */ +data class DownloadNavRequest( + val route: String, + val id: Long, +) + +/** + * Holds the latest `navigate_to` extra from a launch intent or a notification tap. + */ +class DownloadNavEvents { + var request by mutableStateOf(null) + private set + + /** + * Records [intent]'s navigate extra. An intent without the extra leaves the previous request alone. + */ + fun publish(intent: Intent) { + val route = intent.getStringExtra(DataUpdateNotifier.EXTRA_NAVIGATE_TO) ?: return + request = DownloadNavRequest(route, System.nanoTime()) + } +} + +/** + * Navigates to [route] when a matching request arrives, including one that was published before composition. + */ +@Composable +fun DownloadNavEffect( + events: DownloadNavEvents, + navController: NavHostController, + route: String, +) { + val request = events.request + LaunchedEffect(request?.id) { + if (request?.route == route) { + navController.navigate(route) { + launchSingleTop = true + } + } + } +} diff --git a/app/src/main/java/be/scri/ui/screens/download/ConjugateDataDownloadViewModel.kt b/app/src/main/java/be/scri/ui/screens/download/ConjugateDataDownloadViewModel.kt index c1e1999b8..11cd6fa7d 100644 --- a/app/src/main/java/be/scri/ui/screens/download/ConjugateDataDownloadViewModel.kt +++ b/app/src/main/java/be/scri/ui/screens/download/ConjugateDataDownloadViewModel.kt @@ -16,6 +16,9 @@ import be.scri.helpers.LanguageMappingConstants import be.scri.helpers.NetworkMonitor import be.scri.helpers.StringUtils import be.scri.helpers.data.ContractDataLoader +import be.scri.helpers.dataupdate.CONJUGATE_DOWNLOAD_PREFS_NAME +import be.scri.helpers.dataupdate.CONJUGATE_LAST_UPDATE_PREFIX +import be.scri.helpers.dataupdate.DataVersionComparator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.TimeoutCancellationException @@ -39,7 +42,8 @@ class ConjugateDataDownloadViewModel( val downloadStates = mutableStateMapOf() private val downloadSemaphore = kotlinx.coroutines.sync.Semaphore(1) private val downloadJobs = ConcurrentHashMap() - private val prefs = getApplication().getSharedPreferences("scribe_conjugate_prefs", Context.MODE_PRIVATE) + private val prefs = + getApplication().getSharedPreferences(CONJUGATE_DOWNLOAD_PREFS_NAME, Context.MODE_PRIVATE) private val _checkUpdateState = MutableStateFlow(CheckUpdateState.Idle) val checkUpdateState = _checkUpdateState.asStateFlow() @@ -64,7 +68,7 @@ class ConjugateDataDownloadViewModel( ).lowercase() // Check if a timestamp exists in SharedPreferences. - val savedTimestamp = prefs.getString("last_conjugate_update_$langCode", null) + val savedTimestamp = prefs.getString("$CONJUGATE_LAST_UPDATE_PREFIX$langCode", null) if (savedTimestamp != null) { downloadStates[key] = DownloadState.Completed @@ -88,12 +92,7 @@ class ConjugateDataDownloadViewModel( private fun isUpdateAvailable( localUpdatedAt: String, serverUpdatedAt: String?, - ): Boolean { - val localDate = LocalDate.parse(localUpdatedAt.take(10)) - val serverDate = LocalDate.parse(serverUpdatedAt.orEmpty().take(10)) - - return serverDate.isAfter(localDate) - } + ): Boolean = DataVersionComparator.isUpdateAvailable(localUpdatedAt, serverUpdatedAt) private fun isValidTimestamp(value: String?): Boolean = runCatching { LocalDate.parse(value.orEmpty().take(10)) }.isSuccess @@ -141,7 +140,7 @@ class ConjugateDataDownloadViewModel( key.replaceFirstChar { it.uppercase() }, ).lowercase() - val localLastUpdate = prefs.getString("last_conjugate_update_$langCode", "1970-01-01") ?: "1970-01-01" + val localLastUpdate = prefs.getString("$CONJUGATE_LAST_UPDATE_PREFIX$langCode", "1970-01-01") ?: "1970-01-01" // Store the job so we can cancel it later if needed. downloadJobs[key] = @@ -155,6 +154,11 @@ class ConjugateDataDownloadViewModel( } val serverLastUpdate = response.contract.updatedAt + // Comparator treats a bad timestamp as "not newer", which would skip the download. + if (!forceDownload && !isValidTimestamp(serverLastUpdate)) { + throw DateTimeParseException("Invalid timestamp", serverLastUpdate.orEmpty(), 0) + } + // Always download when forcing, or when update is available. val updateNeeded = forceDownload || isUpdateAvailable(localLastUpdate, serverLastUpdate) if (updateNeeded) { @@ -182,7 +186,7 @@ class ConjugateDataDownloadViewModel( // Save timestamp only if both database and contract saved successfully. if (updateNeeded && isValidTimestamp(serverLastUpdate)) { - prefs.edit().putString("last_conjugate_update_$langCode", serverLastUpdate).apply() + prefs.edit().putString("$CONJUGATE_LAST_UPDATE_PREFIX$langCode", serverLastUpdate).apply() } withContext(Dispatchers.Main) { @@ -276,7 +280,7 @@ class ConjugateDataDownloadViewModel( .getLanguageAlias(key.replaceFirstChar { it.uppercase() }) .lowercase() - val localLastUpdate = prefs.getString("last_conjugate_update_$langCode", "1970-01-01") ?: "1970-01-01" + val localLastUpdate = prefs.getString("$CONJUGATE_LAST_UPDATE_PREFIX$langCode", "1970-01-01") ?: "1970-01-01" try { val response = RetrofitClient.apiService.getDataVersion(langCode) diff --git a/app/src/main/java/be/scri/ui/screens/download/ConjugateDownloadDataScreen.kt b/app/src/main/java/be/scri/ui/screens/download/ConjugateDownloadDataScreen.kt index 46875a66b..1dee1f1fd 100644 --- a/app/src/main/java/be/scri/ui/screens/download/ConjugateDownloadDataScreen.kt +++ b/app/src/main/java/be/scri/ui/screens/download/ConjugateDownloadDataScreen.kt @@ -19,7 +19,6 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -34,7 +33,6 @@ import be.scri.R import be.scri.ui.common.ScribeBaseScreen import be.scri.ui.common.components.CircleClickableItemComp import be.scri.ui.common.components.LanguageItemComp -import be.scri.ui.common.components.SwitchableItemComp import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList @@ -48,7 +46,6 @@ fun ConjugateDownloadDataScreen( ) { val scrollState = rememberScrollState() val context = LocalContext.current - val regularlyUpdateData = remember { mutableStateOf(true) } val allLanguages: ImmutableList = remember { @@ -116,11 +113,7 @@ fun ConjugateDownloadDataScreen( modifier = Modifier.padding(vertical = 8.dp, horizontal = 12.dp), ) } - SwitchableItemComp( - title = stringResource(R.string.i18n_app_download_menu_ui_update_data_regular_update), - isChecked = regularlyUpdateData.value, - onCheckedChange = { regularlyUpdateData.value = it }, - ) + RegularDataCheckSwitch() } } } diff --git a/app/src/main/java/be/scri/ui/screens/download/DataDownloadScreen.kt b/app/src/main/java/be/scri/ui/screens/download/DataDownloadScreen.kt index 4fefe4eb8..a22b5e2a7 100644 --- a/app/src/main/java/be/scri/ui/screens/download/DataDownloadScreen.kt +++ b/app/src/main/java/be/scri/ui/screens/download/DataDownloadScreen.kt @@ -47,7 +47,6 @@ import be.scri.ui.common.appcomponents.ConfirmationDialog import be.scri.ui.common.appcomponents.InstallKeyboardButton import be.scri.ui.common.components.CircleClickableItemComp import be.scri.ui.common.components.LanguageItemComp -import be.scri.ui.common.components.SwitchableItemComp import be.scri.ui.screens.settings.SettingsUtil import be.scri.ui.screens.settings.SettingsViewModel import be.scri.ui.screens.settings.SettingsViewModelFactory @@ -79,7 +78,6 @@ fun DownloadDataScreen( ) { val currentInitializeStates by rememberUpdatedState(downloadActions.initializeStates) val scrollState = rememberScrollState() - val regularlyUpdateData = remember { mutableStateOf(true) } val selectedLanguage = remember { mutableStateOf(null) } val context = LocalContext.current val sharedPref = context.getSharedPreferences("app_preferences", Context.MODE_PRIVATE) @@ -169,11 +167,7 @@ fun DownloadDataScreen( modifier = Modifier.padding(vertical = 8.dp, horizontal = 12.dp), ) } - SwitchableItemComp( - title = stringResource(R.string.i18n_app_download_menu_ui_update_data_regular_update), - isChecked = regularlyUpdateData.value, - onCheckedChange = { regularlyUpdateData.value = it }, - ) + RegularDataCheckSwitch() } } } diff --git a/app/src/main/java/be/scri/ui/screens/download/DataDownloadViewModel.kt b/app/src/main/java/be/scri/ui/screens/download/DataDownloadViewModel.kt index 14b70e5e2..b97cd85c0 100644 --- a/app/src/main/java/be/scri/ui/screens/download/DataDownloadViewModel.kt +++ b/app/src/main/java/be/scri/ui/screens/download/DataDownloadViewModel.kt @@ -16,6 +16,9 @@ import be.scri.helpers.LanguageMappingConstants import be.scri.helpers.NetworkMonitor import be.scri.helpers.StringUtils import be.scri.helpers.data.ContractDataLoader +import be.scri.helpers.dataupdate.DOWNLOAD_PREFS_NAME +import be.scri.helpers.dataupdate.DataVersionComparator +import be.scri.helpers.dataupdate.LAST_UPDATE_PREFIX import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.TimeoutCancellationException @@ -39,7 +42,7 @@ class DataDownloadViewModel( val downloadStates = mutableStateMapOf() private val downloadSemaphore = kotlinx.coroutines.sync.Semaphore(1) private val downloadJobs = ConcurrentHashMap() - private val prefs = getApplication().getSharedPreferences("scribe_prefs", Context.MODE_PRIVATE) + private val prefs = getApplication().getSharedPreferences(DOWNLOAD_PREFS_NAME, Context.MODE_PRIVATE) private val _checkUpdateState = MutableStateFlow(CheckUpdateState.Idle) val checkUpdateState = _checkUpdateState.asStateFlow() @@ -64,7 +67,7 @@ class DataDownloadViewModel( ).lowercase() // Check if a timestamp exists in SharedPreferences. - val savedTimestamp = prefs.getString("last_update_$langCode", null) + val savedTimestamp = prefs.getString("$LAST_UPDATE_PREFIX$langCode", null) if (savedTimestamp != null) { downloadStates[key] = DownloadState.Completed @@ -88,12 +91,7 @@ class DataDownloadViewModel( private fun isUpdateAvailable( localUpdatedAt: String, serverUpdatedAt: String?, - ): Boolean { - val localDate = LocalDate.parse(localUpdatedAt.take(10)) - val serverDate = LocalDate.parse(serverUpdatedAt.orEmpty().take(10)) - - return serverDate.isAfter(localDate) - } + ): Boolean = DataVersionComparator.isUpdateAvailable(localUpdatedAt, serverUpdatedAt) private fun isValidTimestamp(value: String?): Boolean = runCatching { LocalDate.parse(value.orEmpty().take(10)) }.isSuccess @@ -141,7 +139,7 @@ class DataDownloadViewModel( key.replaceFirstChar { it.uppercase() }, ).lowercase() - val localLastUpdate = prefs.getString("last_update_$langCode", "1970-01-01") ?: "1970-01-01" + val localLastUpdate = prefs.getString("$LAST_UPDATE_PREFIX$langCode", "1970-01-01") ?: "1970-01-01" // Store the job so we can cancel it later if needed. downloadJobs[key] = @@ -155,6 +153,11 @@ class DataDownloadViewModel( } val serverLastUpdate = response.contract.updatedAt + // Comparator treats a bad timestamp as "not newer", which would skip the download. + if (!forceDownload && !isValidTimestamp(serverLastUpdate)) { + throw DateTimeParseException("Invalid timestamp", serverLastUpdate.orEmpty(), 0) + } + // Always download when forcing, or when update is available. val updateNeeded = forceDownload || isUpdateAvailable(localLastUpdate, serverLastUpdate) if (updateNeeded) { @@ -182,7 +185,7 @@ class DataDownloadViewModel( // Save timestamp only if both database and contract saved successfully. if (updateNeeded && isValidTimestamp(serverLastUpdate)) { - prefs.edit().putString("last_update_$langCode", serverLastUpdate).apply() + prefs.edit().putString("$LAST_UPDATE_PREFIX$langCode", serverLastUpdate).apply() } withContext(Dispatchers.Main) { @@ -276,7 +279,7 @@ class DataDownloadViewModel( .getLanguageAlias(key.replaceFirstChar { it.uppercase() }) .lowercase() - val localLastUpdate = prefs.getString("last_update_$langCode", "1970-01-01") ?: "1970-01-01" + val localLastUpdate = prefs.getString("$LAST_UPDATE_PREFIX$langCode", "1970-01-01") ?: "1970-01-01" try { val response = RetrofitClient.apiService.getDataVersion(langCode) diff --git a/app/src/main/java/be/scri/ui/screens/download/NotificationGatedToggle.kt b/app/src/main/java/be/scri/ui/screens/download/NotificationGatedToggle.kt new file mode 100644 index 000000000..5fc359613 --- /dev/null +++ b/app/src/main/java/be/scri/ui/screens/download/NotificationGatedToggle.kt @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.ui.screens.download + +/** + * Decides when the "Regularly update data" switch may actually turn on. + * Turning it on needs the notification permission on Android 13 and newer, because a check whose + * result can never be shown is pointless. The change is applied only once the permission is there, + * so a denial leaves the switch off and nothing is saved or scheduled. + * Turning it off never needs a permission. + */ +internal class NotificationGatedToggle( + private val needsPermission: () -> Boolean, + private val requestPermission: () -> Unit, + private val apply: (Boolean) -> Unit, +) { + /** The user flipped the switch to [checked]. */ + fun onUserToggle(checked: Boolean) { + if (checked && needsPermission()) { + requestPermission() + } else { + apply(checked) + } + } + + /** The system permission dialog was answered. A denial changes nothing. */ + fun onPermissionResult(granted: Boolean) { + if (granted) apply(true) + } +} diff --git a/app/src/main/java/be/scri/ui/screens/download/RegularDataCheckSwitch.kt b/app/src/main/java/be/scri/ui/screens/download/RegularDataCheckSwitch.kt new file mode 100644 index 000000000..1910a226d --- /dev/null +++ b/app/src/main/java/be/scri/ui/screens/download/RegularDataCheckSwitch.kt @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.ui.screens.download + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.util.Log +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.core.content.ContextCompat +import be.scri.R +import be.scri.helpers.PreferencesHelper +import be.scri.helpers.dataupdate.DataUpdateScheduler +import be.scri.ui.common.components.SwitchableItemComp + +/** + * The saved "Regularly update data" switch. + * The label stays on the existing i18n string. Turning it on checks now, then once each month. + * If the notification permission is denied on Android 13 and newer, the switch stays off. + */ +@Composable +fun RegularDataCheckSwitch(modifier: Modifier = Modifier) { + val context = LocalContext.current + var enabled by remember { + mutableStateOf(PreferencesHelper.getRegularlyCheckForDataUpdates(context)) + } + val toggleHolder = remember { ToggleHolder() } + val permissionLauncher = + rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + if (!granted) { + Log.i(TAG, "Notification permission denied. Data checks stay off.") + } + toggleHolder.toggle?.onPermissionResult(granted) + } + toggleHolder.toggle = + remember(context, permissionLauncher) { + NotificationGatedToggle( + needsPermission = { needsNotificationPermission(context) }, + requestPermission = { permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) }, + apply = { checked -> + enabled = checked + DataUpdateScheduler.onToggle(context, checked) + }, + ) + } + + SwitchableItemComp( + title = stringResource(R.string.i18n_app_download_menu_ui_update_data_regular_update), + isChecked = enabled, + onCheckedChange = { checked -> toggleHolder.toggle?.onUserToggle(checked) }, + modifier = modifier, + ) +} + +private fun needsNotificationPermission(context: Context): Boolean { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return false + val status = ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) + return status != PackageManager.PERMISSION_GRANTED +} + +/** Lets the permission callback reach the toggle that is created after the launcher. */ +private class ToggleHolder { + var toggle: NotificationGatedToggle? = null +} + +private const val TAG = "RegularDataCheckSwitch" diff --git a/app/src/main/res/drawable/ic_stat_data_update.xml b/app/src/main/res/drawable/ic_stat_data_update.xml new file mode 100644 index 000000000..d8be69b81 --- /dev/null +++ b/app/src/main/res/drawable/ic_stat_data_update.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCalendarTest.kt b/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCalendarTest.kt new file mode 100644 index 000000000..94843769e --- /dev/null +++ b/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCalendarTest.kt @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.time.Duration +import java.time.LocalDateTime +import kotlin.random.Random + +class DataUpdateCalendarTest { + @Test + fun newSlotStaysInsideTheSecondWeek() { + repeat(40) { seed -> + val slot = DataUpdateCalendar.newSlot(Random(seed)) + assertTrue(slot.dayOfMonth in DataUpdateCalendar.FIRST_DAY..DataUpdateCalendar.LAST_DAY) + assertTrue(slot.minuteOfDay in 0 until MINUTES_PER_DAY) + } + } + + @Test + fun futureSlotThisMonthIsKept() { + val now = LocalDateTime.of(2026, 2, 1, 0, 0) + val next = DataUpdateCalendar.nextOccurrence(now, DataCheckSlot(dayOfMonth = 8, minuteOfDay = 0)) + assertEquals(LocalDateTime.of(2026, 2, 8, 0, 0), next) + } + + @Test + fun pastSlotRollsToNextMonth() { + val now = LocalDateTime.of(2026, 5, 20, 8, 0) + val next = DataUpdateCalendar.nextOccurrence(now, DataCheckSlot(dayOfMonth = 9, minuteOfDay = 30)) + assertEquals(LocalDateTime.of(2026, 6, 9, 0, 30), next) + } + + @Test + fun decemberRollsIntoJanuary() { + val now = LocalDateTime.of(2026, 12, 14, 23, 59) + val next = DataUpdateCalendar.nextOccurrence(now, DataCheckSlot(dayOfMonth = 14, minuteOfDay = 23 * 60 + 50)) + assertEquals(LocalDateTime.of(2027, 1, 14, 23, 50), next) + } + + @Test + fun februaryUsesTheSameDayNextMonth() { + val now = LocalDateTime.of(2026, 2, 20, 12, 0) + val next = DataUpdateCalendar.nextOccurrence(now, DataCheckSlot(dayOfMonth = 10, minuteOfDay = 15 * 60)) + assertEquals(LocalDateTime.of(2026, 3, 10, 15, 0), next) + } + + @Test + fun delayUntilTheSlotIsNeverZeroOrNegative() { + val samples = + listOf( + LocalDateTime.of(2026, 5, 9, 0, 30), + LocalDateTime.of(2026, 5, 20, 8, 0), + LocalDateTime.of(2026, 12, 31, 23, 59), + ) + val slot = DataCheckSlot(dayOfMonth = 9, minuteOfDay = 30) + samples.forEach { now -> + val delay = DataUpdateCalendar.delayUntilNextSlot(now, slot) + assertFalse(delay.isNegative || delay.isZero) + } + } + + @Test + fun batterySaverBeforeThe21stWaitsTwelveHours() { + val now = LocalDateTime.of(2026, 5, 20, 23, 0) + val delay = DataUpdateCalendar.batterySaverDelay(now, DataCheckSlot(dayOfMonth = 8, minuteOfDay = 0)) + assertEquals(Duration.ofHours(DataUpdateCalendar.POSTPONE_HOURS), delay) + } + + @Test + fun batterySaverOnOrAfterThe21stUsesNextMonthsSlot() { + val now = LocalDateTime.of(2026, 5, 21, 0, 0) + val slot = DataCheckSlot(dayOfMonth = 10, minuteOfDay = 0) + val delay = DataUpdateCalendar.batterySaverDelay(now, slot) + val expected = Duration.between(now, LocalDateTime.of(2026, 6, 10, 0, 0)) + assertEquals(expected, delay) + } + + private companion object { + const val MINUTES_PER_DAY = 24 * 60 + } +} diff --git a/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCheckRunnerTest.kt b/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCheckRunnerTest.kt new file mode 100644 index 000000000..d5806e99f --- /dev/null +++ b/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCheckRunnerTest.kt @@ -0,0 +1,259 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import java.io.IOException + +class DataUpdateCheckRunnerTest { + private class Harness( + var enabled: Boolean = true, + var batterySaver: Boolean = false, + var canNotify: Boolean = true, + var onCheck: suspend () -> DataUpdateCheckResult = { ok(emptyList()) }, + var onNotify: (List) -> Unit = {}, + ) { + var checks = 0 + val notified = mutableListOf>() + var nextSlotScheduled = 0 + var batterySaverScheduled = 0 + + fun runner() = + DataUpdateCheckRunner( + isEnabled = { enabled }, + isBatterySaverOn = { batterySaver }, + canPostNotifications = { canNotify }, + check = { + checks++ + onCheck() + }, + notify = { + onNotify(it) + notified.add(it) + }, + scheduleFollowUp = { + when (it) { + DataUpdateFollowUp.NEXT_SLOT -> nextSlotScheduled++ + DataUpdateFollowUp.AFTER_BATTERY_SAVER -> batterySaverScheduled++ + } + }, + ) + } + + @Test + fun foundUpdatesAreNotifiedAndTheNextMonthIsQueued() = + runTest { + val h = Harness(onCheck = { ok(listOf("fr", "de")) }) + + val outcome = h.runner().run(userInitiated = false, runAttemptCount = 0) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(listOf(listOf("fr", "de")), h.notified) + assertEquals(1, h.nextSlotScheduled) + } + + @Test + fun nothingNewQueuesTheNextMonthWithoutANotification() = + runTest { + val h = Harness() + + val outcome = h.runner().run(userInitiated = false, runAttemptCount = 0) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(0, h.notified.size) + assertEquals(1, h.nextSlotScheduled) + } + + @Test + fun switchOffDoesNothing() = + runTest { + val h = Harness(enabled = false) + + val outcome = h.runner().run(userInitiated = true, runAttemptCount = 0) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(0, h.checks) + assertEquals(0, h.nextSlotScheduled) + } + + @Test + fun allLanguagesFailingRetriesInsteadOfReportingSuccess() = + runTest { + val h = Harness(onCheck = { DataUpdateCheckResult(emptyList(), checkedCount = 2, failedCount = 2) }) + + val outcome = h.runner().run(userInitiated = false, runAttemptCount = 0) + + assertEquals(DataUpdateRunOutcome.RETRY, outcome) + assertEquals(0, h.nextSlotScheduled) + assertEquals(0, h.notified.size) + } + + @Test + fun partialFailureStillNotifiesAndQueuesTheNextMonth() = + runTest { + val h = Harness(onCheck = { DataUpdateCheckResult(listOf("fr"), checkedCount = 3, failedCount = 1) }) + + val outcome = h.runner().run(userInitiated = false, runAttemptCount = 0) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(listOf(listOf("fr")), h.notified) + assertEquals(1, h.nextSlotScheduled) + } + + @Test + fun anUnexpectedExceptionIsHandledLikeAFailedCheck() = + runTest { + val h = Harness(onCheck = { throw IOException("boom") }) + + assertEquals(DataUpdateRunOutcome.RETRY, h.runner().run(userInitiated = true, runAttemptCount = 0)) + assertEquals(0, h.nextSlotScheduled) + } + + @Test + fun retriesStopAtTheCapAndFallThroughToTheNextMonth() = + runTest { + val h = Harness(onCheck = { DataUpdateCheckResult(emptyList(), checkedCount = 1, failedCount = 1) }) + val last = DataUpdateCheckRunner.MAX_ATTEMPTS - 1 + + assertEquals(DataUpdateRunOutcome.RETRY, h.runner().run(userInitiated = true, runAttemptCount = last - 1)) + assertEquals(0, h.nextSlotScheduled) + + assertEquals(DataUpdateRunOutcome.DONE, h.runner().run(userInitiated = true, runAttemptCount = last)) + assertEquals(1, h.nextSlotScheduled) + } + + @Test + fun theCapAppliesToScheduledRunsToo() = + runTest { + val h = Harness(onCheck = { throw IOException("offline") }) + + val outcome = + h.runner().run(userInitiated = false, runAttemptCount = DataUpdateCheckRunner.MAX_ATTEMPTS - 1) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(1, h.nextSlotScheduled) + } + + @Test + fun givingUpDoesNotQueueANextMonthIfTheSwitchWasTurnedOffMeanwhile() = + runTest { + val h = Harness() + h.onCheck = { + h.enabled = false + throw IOException("offline") + } + + val outcome = + h.runner().run(userInitiated = true, runAttemptCount = DataUpdateCheckRunner.MAX_ATTEMPTS - 1) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(0, h.nextSlotScheduled) + } + + @Test + fun noNotificationIsPostedIfTheSwitchWasTurnedOffMeanwhile() = + runTest { + val h = Harness() + h.onCheck = { + h.enabled = false + ok(listOf("fr")) + } + + h.runner().run(userInitiated = false, runAttemptCount = 0) + + assertEquals(0, h.notified.size) + assertEquals(0, h.nextSlotScheduled) + } + + @Test + fun scheduledRunWaitsOutBatterySaver() = + runTest { + val h = Harness(batterySaver = true) + + val outcome = h.runner().run(userInitiated = false, runAttemptCount = 0) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(0, h.checks) + assertEquals(1, h.batterySaverScheduled) + assertEquals(0, h.nextSlotScheduled) + } + + @Test + fun runFromTheSwitchIgnoresBatterySaver() = + runTest { + val h = Harness(batterySaver = true) + + h.runner().run(userInitiated = true, runAttemptCount = 0) + + assertEquals(1, h.checks) + assertEquals(0, h.batterySaverScheduled) + } + + @Test + fun withoutNotificationsTheNetworkIsNotUsed() = + runTest { + val h = Harness(canNotify = false) + + val outcome = h.runner().run(userInitiated = true, runAttemptCount = 0) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(0, h.checks) + assertEquals(0, h.nextSlotScheduled) + assertEquals(0, h.batterySaverScheduled) + } + + @Test + fun aFailingNotificationDoesNotRepeatTheCheckOrLoseTheNextMonth() = + runTest { + val h = + Harness( + onCheck = { ok(listOf("fr")) }, + onNotify = { throw IllegalStateException("channel") }, + ) + + val outcome = h.runner().run(userInitiated = false, runAttemptCount = 0) + + assertEquals(DataUpdateRunOutcome.DONE, outcome) + assertEquals(1, h.checks) + assertEquals(1, h.nextSlotScheduled) + } + + @Test + fun cancellationPropagatesAndSchedulesNothing() = + runTest { + val h = Harness(onCheck = { throw CancellationException("stopped") }) + + assertThrows(CancellationException::class.java) { + kotlinx.coroutines.runBlocking { h.runner().run(userInitiated = false, runAttemptCount = 0) } + } + assertEquals(0, h.nextSlotScheduled) + } + + @Test + fun cancellationWhilePostingTheNotificationPropagates() = + runTest { + val h = + Harness( + onCheck = { ok(listOf("fr")) }, + onNotify = { throw CancellationException("stopped") }, + ) + + assertThrows(CancellationException::class.java) { + kotlinx.coroutines.runBlocking { h.runner().run(userInitiated = false, runAttemptCount = 0) } + } + assertEquals(0, h.nextSlotScheduled) + } + + @Test + fun attemptCapIsThree() { + assertEquals(3, DataUpdateCheckRunner.MAX_ATTEMPTS) + } + + private companion object { + fun ok(updates: List) = DataUpdateCheckResult(updates, checkedCount = 2, failedCount = 0) + } +} diff --git a/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCheckerTest.kt b/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCheckerTest.kt new file mode 100644 index 000000000..f7f83e238 --- /dev/null +++ b/app/src/test/kotlin/be/scri/helpers/dataupdate/DataUpdateCheckerTest.kt @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import android.content.SharedPreferences +import be.scri.data.model.DataVersionResponse +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.io.IOException + +class DataUpdateCheckerTest { + @Test + fun onlyStoredLanguagesAreCheckedAndOneFailureDoesNotHideAnUpdate() = + runTest { + val prefs = + prefsWith( + mapOf( + "${LAST_UPDATE_PREFIX}fr" to "2024-01-01", + "${LAST_UPDATE_PREFIX}de" to "2024-06-01", + "${LAST_UPDATE_PREFIX}es" to "2024-01-01", + "${LAST_UPDATE_PREFIX}" to "2024-01-01", + "unrelated" to "ignore-me", + ), + ) + val requested = mutableListOf() + val source = + DataVersionSource { language -> + requested.add(language) + if (language == "es") throw IOException("offline") + val serverDate = if (language == "fr") "2025-01-01" else "2020-01-01" + DataVersionResponse(language, mapOf("verbs" to serverDate)) + } + + val result = DataUpdateChecker(prefs, source).check() + + assertEquals(listOf("fr"), result.languagesWithUpdates) + assertEquals(3, result.checkedCount) + assertEquals(1, result.failedCount) + assertFalse(result.allFailed) + assertEquals(setOf("fr", "de", "es"), requested.toSet()) + } + + @Test + fun nothingDownloadedMakesNoRequest() = + runTest { + val prefs = prefsWith(emptyMap()) + val source = + DataVersionSource { + error("no language should be requested") + } + + val result = DataUpdateChecker(prefs, source).check() + + assertTrue(result.languagesWithUpdates.isEmpty()) + assertEquals(0, result.checkedCount) + assertFalse(result.allFailed) + } + + @Test + fun conjugatePrefixDoesNotReadKeyboardTimestamps() = + runTest { + val prefs = + prefsWith( + mapOf( + "${LAST_UPDATE_PREFIX}fr" to "2020-01-01", + "${CONJUGATE_LAST_UPDATE_PREFIX}de" to "2020-01-01", + ), + ) + val requested = mutableListOf() + val source = + DataVersionSource { language -> + requested.add(language) + DataVersionResponse(language, mapOf("verbs" to "2025-01-01")) + } + + val result = DataUpdateChecker(prefs, source, CONJUGATE_LAST_UPDATE_PREFIX).check() + + assertEquals(listOf("de"), result.languagesWithUpdates) + assertEquals(listOf("de"), requested) + } + + @Test + fun everyLanguageFailingIsReportedAsAllFailedNotAsNoUpdates() = + runTest { + val prefs = + prefsWith( + mapOf( + "${LAST_UPDATE_PREFIX}fr" to "2024-01-01", + "${LAST_UPDATE_PREFIX}de" to "2024-01-01", + ), + ) + val source = DataVersionSource { throw IOException("offline") } + + val result = DataUpdateChecker(prefs, source).check() + + assertTrue(result.languagesWithUpdates.isEmpty()) + assertEquals(2, result.checkedCount) + assertEquals(2, result.failedCount) + assertTrue(result.allFailed) + } + + @Test + fun aLanguageWithoutASavedTimestampIsNotCounted() = + runTest { + val prefs = mockk() + every { prefs.all } returns mapOf("${LAST_UPDATE_PREFIX}fr" to "x") + every { prefs.getString("${LAST_UPDATE_PREFIX}fr", null) } returns null + val source = DataVersionSource { error("must not be asked") } + + val result = DataUpdateChecker(prefs, source).check() + + assertEquals(0, result.checkedCount) + assertFalse(result.allFailed) + } + + @Test + fun cancellationIsNotCountedAsAFailure() = + runTest { + val prefs = prefsWith(mapOf("${LAST_UPDATE_PREFIX}fr" to "2024-01-01")) + val source = DataVersionSource { throw CancellationException("stopped") } + + assertThrows(CancellationException::class.java) { + runBlocking { DataUpdateChecker(prefs, source).check() } + } + } + + private fun prefsWith(entries: Map): SharedPreferences { + val prefs = mockk() + every { prefs.all } returns entries + entries.forEach { (key, value) -> + every { prefs.getString(key, null) } returns value + } + return prefs + } +} diff --git a/app/src/test/kotlin/be/scri/helpers/dataupdate/DataVersionComparatorTest.kt b/app/src/test/kotlin/be/scri/helpers/dataupdate/DataVersionComparatorTest.kt new file mode 100644 index 000000000..079b9f2d1 --- /dev/null +++ b/app/src/test/kotlin/be/scri/helpers/dataupdate/DataVersionComparatorTest.kt @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class DataVersionComparatorTest { + @Test + fun newerDayIsAnUpdate() { + assertTrue(DataVersionComparator.isUpdateAvailable("2024-01-01", "2024-01-02")) + } + + @Test + fun sameDayIsNotAnUpdateEvenWhenTheClockTimeDiffers() { + assertFalse(DataVersionComparator.isUpdateAvailable("2024-01-01T01:00:00Z", "2024-01-01T23:59:59Z")) + } + + @Test + fun olderDayIsNotAnUpdate() { + assertFalse(DataVersionComparator.isUpdateAvailable("2024-06-01", "2024-01-01")) + } + + @Test + fun nullBlankAndUnparseableServerDatesAreNotUpdates() { + assertFalse(DataVersionComparator.isUpdateAvailable("2024-01-01", null)) + assertFalse(DataVersionComparator.isUpdateAvailable("2024-01-01", "")) + assertFalse(DataVersionComparator.isUpdateAvailable("2024-01-01", "not-a-date")) + assertFalse(DataVersionComparator.isUpdateAvailable("not-a-date", "2024-06-01")) + } + + @Test + fun oneNewerEntryInAMixedMapIsAnUpdate() { + val versions = + mapOf( + "nouns" to "2024-01-01", + "verbs" to null, + "emoji" to "yesterday", + "prepositions" to "2024-08-01", + ) + assertTrue(DataVersionComparator.anyVersionNewer("2024-02-01", versions)) + } + + @Test + fun mapWithNoNewerEntryIsNotAnUpdate() { + val versions = mapOf("nouns" to "2024-01-01", "verbs" to null) + assertFalse(DataVersionComparator.anyVersionNewer("2024-06-01", versions)) + } +} diff --git a/app/src/test/kotlin/be/scri/helpers/dataupdate/RegularDataCheckPreferenceTest.kt b/app/src/test/kotlin/be/scri/helpers/dataupdate/RegularDataCheckPreferenceTest.kt new file mode 100644 index 000000000..4e82a4806 --- /dev/null +++ b/app/src/test/kotlin/be/scri/helpers/dataupdate/RegularDataCheckPreferenceTest.kt @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.helpers.dataupdate + +import android.content.Context +import android.content.SharedPreferences +import be.scri.helpers.PreferencesHelper +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Test + +class RegularDataCheckPreferenceTest { + @Test + fun regularlyCheckForDataUpdatesDefaultsToFalse() { + val prefs = mockk() + val context = mockk() + every { context.getSharedPreferences(PreferencesHelper.SCRIBE_PREFS, Context.MODE_PRIVATE) } returns prefs + every { prefs.getBoolean("regularly_check_for_data_updates", false) } returns false + + assertFalse(PreferencesHelper.getRegularlyCheckForDataUpdates(context)) + + verify { prefs.getBoolean("regularly_check_for_data_updates", false) } + } +} diff --git a/app/src/test/kotlin/be/scri/ui/screens/download/NotificationGatedToggleTest.kt b/app/src/test/kotlin/be/scri/ui/screens/download/NotificationGatedToggleTest.kt new file mode 100644 index 000000000..305cff5e9 --- /dev/null +++ b/app/src/test/kotlin/be/scri/ui/screens/download/NotificationGatedToggleTest.kt @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package be.scri.ui.screens.download + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class NotificationGatedToggleTest { + private class Harness( + var permissionMissing: Boolean, + ) { + var permissionRequests = 0 + val applied = mutableListOf() + val toggle = + NotificationGatedToggle( + needsPermission = { permissionMissing }, + requestPermission = { permissionRequests++ }, + apply = { applied.add(it) }, + ) + } + + @Test + fun turningOnWithPermissionAppliesAtOnce() { + val h = Harness(permissionMissing = false) + + h.toggle.onUserToggle(true) + + assertEquals(listOf(true), h.applied) + assertEquals(0, h.permissionRequests) + } + + @Test + fun turningOnWithoutPermissionAsksAndAppliesNothingYet() { + val h = Harness(permissionMissing = true) + + h.toggle.onUserToggle(true) + + assertEquals(1, h.permissionRequests) + assertEquals(emptyList(), h.applied) + } + + @Test + fun grantedPermissionTurnsTheSwitchOn() { + val h = Harness(permissionMissing = true) + + h.toggle.onUserToggle(true) + h.toggle.onPermissionResult(granted = true) + + assertEquals(listOf(true), h.applied) + } + + @Test + fun deniedPermissionLeavesTheSwitchOffAndSchedulesNothing() { + val h = Harness(permissionMissing = true) + + h.toggle.onUserToggle(true) + h.toggle.onPermissionResult(granted = false) + + assertEquals(emptyList(), h.applied) + } + + @Test + fun turningOffNeverAsksForPermission() { + val h = Harness(permissionMissing = true) + + h.toggle.onUserToggle(false) + + assertEquals(listOf(false), h.applied) + assertEquals(0, h.permissionRequests) + } +}