|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Eric Li <[email protected]> |
| 3 | + * |
| 4 | + * This program is free software; you can redistribute it and/or modify it under |
| 5 | + * the terms of the GNU General Public License as published by the Free Software |
| 6 | + * Foundation; either version 3 of the License, or (at your option) any later |
| 7 | + * version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, but WITHOUT ANY |
| 10 | + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A |
| 11 | + * PARTICULAR PURPOSE. See the GNU General Public License for more details. |
| 12 | + * |
| 13 | + * You should have received a copy of the GNU General Public License along with |
| 14 | + * this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.ichi2.anki.reviewreminders |
| 18 | + |
| 19 | +import android.content.Context |
| 20 | +import androidx.annotation.VisibleForTesting |
| 21 | +import androidx.core.content.edit |
| 22 | +import com.ichi2.anki.AnkiDroidApp |
| 23 | +import com.ichi2.anki.showError |
| 24 | +import com.ichi2.libanki.DeckId |
| 25 | +import kotlinx.serialization.SerializationException |
| 26 | +import kotlinx.serialization.json.Json |
| 27 | + |
| 28 | +/** |
| 29 | + * Manages the storage and retrieval of [ReviewReminder]s in SharedPreferences. |
| 30 | + * |
| 31 | + * [ReviewReminder]s can either be tied to a specific deck and trigger based on the number of cards |
| 32 | + * due in that deck, or they can be app-wide reminders that trigger based on the total number |
| 33 | + * of cards due across all decks. |
| 34 | + */ |
| 35 | +class ReviewRemindersDatabase( |
| 36 | + val context: Context, |
| 37 | +) { |
| 38 | + companion object { |
| 39 | + /** |
| 40 | + * Key in SharedPreferences for retrieving deck-specific reminders. |
| 41 | + * Should have deck ID appended to its end, ex. "review_reminders_deck_12345". |
| 42 | + * Its value is a HashMap<[ReviewReminderId], [ReviewReminder]> serialized as a JSON String. |
| 43 | + */ |
| 44 | + @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) |
| 45 | + const val DECK_SPECIFIC_KEY = "review_reminders_deck_" |
| 46 | + |
| 47 | + /** |
| 48 | + * Key in SharedPreferences for retrieving app-wide reminders. |
| 49 | + * Its value is a HashMap<[ReviewReminderId], [ReviewReminder]> serialized as a JSON String. |
| 50 | + */ |
| 51 | + @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) |
| 52 | + const val APP_WIDE_KEY = "review_reminders_app_wide" |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Decode an encoded HashMap<[ReviewReminderId], [ReviewReminder]> JSON string. |
| 57 | + * It is possible for Json.decodeFromString to throw [SerializationException]s if a serialization |
| 58 | + * error is encountered, or [IllegalArgumentException]s if the decoded object is not a HashMap<[ReviewReminderId], [ReviewReminder]>. |
| 59 | + * @see Json.decodeFromString |
| 60 | + */ |
| 61 | + private fun decodeJson(jsonString: String): HashMap<ReviewReminderId, ReviewReminder> = |
| 62 | + try { |
| 63 | + // If, during development, the review reminders storage schema (i.e. ReviewReminder) is modified, |
| 64 | + // this class will attempt to read review reminders stored in the old schema via the new schema, causing a SerializationException. |
| 65 | + // To delete all review reminder keys in SharedPreferences, uncomment the following line. |
| 66 | + // AnkiDroidApp.sharedPrefs().edit { AnkiDroidApp.sharedPrefs().all.keys.filter { it.startsWith("review_reminders_") }.forEach { remove(it) } } |
| 67 | + |
| 68 | + Json.decodeFromString<HashMap<ReviewReminderId, ReviewReminder>>(jsonString) |
| 69 | + } catch (e: SerializationException) { |
| 70 | + showError( |
| 71 | + context, |
| 72 | + "Something went wrong. A serialization error was encountered while retrieving review reminders.", |
| 73 | + ) |
| 74 | + hashMapOf() |
| 75 | + } catch (e: IllegalArgumentException) { |
| 76 | + showError( |
| 77 | + context, |
| 78 | + "Something went wrong. An unexpected data type was read while retrieving review reminders.", |
| 79 | + ) |
| 80 | + hashMapOf() |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Encode a Map<[ReviewReminderId], [ReviewReminder]> as a JSON string. |
| 85 | + * it is possible for Json.encodeToString to throw [SerializationException]s if a serialization |
| 86 | + * error is encountered. |
| 87 | + * @see Json.encodeToString |
| 88 | + */ |
| 89 | + private fun encodeJson(reminders: Map<ReviewReminderId, ReviewReminder>): String = |
| 90 | + try { |
| 91 | + Json.encodeToString(reminders) |
| 92 | + } catch (e: SerializationException) { |
| 93 | + showError( |
| 94 | + context, |
| 95 | + "Something went wrong. A serialization error was encountered while saving review reminders.", |
| 96 | + ) |
| 97 | + "{}" |
| 98 | + } |
| 99 | + |
| 100 | + /** |
| 101 | + * Get the [ReviewReminder]s for a specific key. |
| 102 | + */ |
| 103 | + private fun getRemindersForKey(key: String): HashMap<ReviewReminderId, ReviewReminder> { |
| 104 | + val jsonString = AnkiDroidApp.sharedPrefs().getString(key, null) ?: return hashMapOf() |
| 105 | + return decodeJson(jsonString) |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Get the [ReviewReminder]s for a specific deck. |
| 110 | + */ |
| 111 | + fun getRemindersForDeck(did: DeckId): HashMap<ReviewReminderId, ReviewReminder> = getRemindersForKey(DECK_SPECIFIC_KEY + did) |
| 112 | + |
| 113 | + /** |
| 114 | + * Get the app-wide [ReviewReminder]s. |
| 115 | + */ |
| 116 | + fun getAllAppWideReminders(): HashMap<ReviewReminderId, ReviewReminder> = getRemindersForKey(APP_WIDE_KEY) |
| 117 | + |
| 118 | + /** |
| 119 | + * Get all [ReviewReminder]s that are associated with a specific deck, grouped by deck ID. |
| 120 | + */ |
| 121 | + private fun getAllDeckSpecificRemindersGrouped(): Map<DeckId, HashMap<ReviewReminderId, ReviewReminder>> { |
| 122 | + return AnkiDroidApp |
| 123 | + .sharedPrefs() |
| 124 | + .all |
| 125 | + .filterKeys { it.startsWith(DECK_SPECIFIC_KEY) } |
| 126 | + .mapNotNull { (key, value) -> |
| 127 | + val did = key.removePrefix(DECK_SPECIFIC_KEY).toLongOrNull() ?: return@mapNotNull null |
| 128 | + val reminders = decodeJson(value.toString()) |
| 129 | + did to reminders |
| 130 | + }.toMap() |
| 131 | + } |
| 132 | + |
| 133 | + /** |
| 134 | + * Get all [ReviewReminder]s that are associated with a specific deck, all in a single flattened map. |
| 135 | + */ |
| 136 | + fun getAllDeckSpecificReminders(): HashMap<ReviewReminderId, ReviewReminder> = getAllDeckSpecificRemindersGrouped().flatten() |
| 137 | + |
| 138 | + /** |
| 139 | + * Edit the [ReviewReminder]s for a specific key. |
| 140 | + * @param key |
| 141 | + * @param reminderEditor A lambda that takes the current map and returns the updated map. |
| 142 | + */ |
| 143 | + private fun editRemindersForKey( |
| 144 | + key: String, |
| 145 | + reminderEditor: (HashMap<ReviewReminderId, ReviewReminder>) -> Map<ReviewReminderId, ReviewReminder>, |
| 146 | + ) { |
| 147 | + val existingReminders = getRemindersForKey(key) |
| 148 | + val updatedReminders = reminderEditor(existingReminders) |
| 149 | + AnkiDroidApp.sharedPrefs().edit { |
| 150 | + putString(key, encodeJson(updatedReminders)) |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Edit the [ReviewReminder]s for a specific deck. |
| 156 | + * @param did |
| 157 | + * @param reminderEditor A lambda that takes the current map and returns the updated map. |
| 158 | + */ |
| 159 | + fun editRemindersForDeck( |
| 160 | + did: DeckId, |
| 161 | + reminderEditor: (HashMap<ReviewReminderId, ReviewReminder>) -> Map<ReviewReminderId, ReviewReminder>, |
| 162 | + ) = editRemindersForKey(DECK_SPECIFIC_KEY + did, reminderEditor) |
| 163 | + |
| 164 | + /** |
| 165 | + * Edit the app-wide [ReviewReminder]s. |
| 166 | + * @param reminderEditor A lambda that takes the current map and returns the updated map. |
| 167 | + */ |
| 168 | + fun editAllAppWideReminders(reminderEditor: (HashMap<ReviewReminderId, ReviewReminder>) -> Map<ReviewReminderId, ReviewReminder>) = |
| 169 | + editRemindersForKey(APP_WIDE_KEY, reminderEditor) |
| 170 | + |
| 171 | + /** |
| 172 | + * Edit all [ReviewReminder]s that are associated with a specific deck by operating on a single mutable map. |
| 173 | + */ |
| 174 | + fun editAllDeckSpecificReminders(reminderEditor: (HashMap<ReviewReminderId, ReviewReminder>) -> Map<ReviewReminderId, ReviewReminder>) { |
| 175 | + val existingRemindersGrouped = getAllDeckSpecificRemindersGrouped() |
| 176 | + val existingRemindersFlattened = existingRemindersGrouped.flatten() |
| 177 | + |
| 178 | + val updatedRemindersFlattened = reminderEditor(existingRemindersFlattened) |
| 179 | + val updatedRemindersGrouped = updatedRemindersFlattened.groupByDeckId() |
| 180 | + |
| 181 | + val existingKeys = existingRemindersGrouped.keys.map { DECK_SPECIFIC_KEY + it } |
| 182 | + |
| 183 | + AnkiDroidApp.sharedPrefs().edit { |
| 184 | + // Clear existing review reminder keys in SharedPreferences |
| 185 | + existingKeys.forEach { remove(it) } |
| 186 | + // Add the updated ones back in |
| 187 | + updatedRemindersGrouped.forEach { (did, reminders) -> |
| 188 | + putString(DECK_SPECIFIC_KEY + did, encodeJson(reminders)) |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + /** |
| 194 | + * Utility function for flattening maps of [ReviewReminder]s grouped by deck ID into a single map. |
| 195 | + */ |
| 196 | + private fun Map<DeckId, HashMap<ReviewReminderId, ReviewReminder>>.flatten(): HashMap<ReviewReminderId, ReviewReminder> = |
| 197 | + hashMapOf<ReviewReminderId, ReviewReminder>().apply { |
| 198 | + this@flatten.forEach { (_, reminders) -> |
| 199 | + putAll(reminders) |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + /** |
| 204 | + * Utility function for grouping maps of [ReviewReminder]s by deck ID. |
| 205 | + */ |
| 206 | + private fun Map<ReviewReminderId, ReviewReminder>.groupByDeckId(): Map<DeckId, HashMap<ReviewReminderId, ReviewReminder>> = |
| 207 | + hashMapOf<DeckId, HashMap<ReviewReminderId, ReviewReminder>>().apply { |
| 208 | + this@groupByDeckId.forEach { (id, reminder) -> |
| 209 | + getOrPut(reminder.did) { hashMapOf() }[id] = reminder |
| 210 | + } |
| 211 | + } |
| 212 | +} |
0 commit comments