|
| 1 | +package dev.dettmer.simplenotes.storage |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import android.content.SharedPreferences |
| 5 | +import androidx.core.content.edit |
| 6 | +import com.google.gson.Gson |
| 7 | +import com.google.gson.JsonParser |
| 8 | +import com.google.gson.annotations.SerializedName |
| 9 | +import com.google.gson.reflect.TypeToken |
| 10 | +import dev.dettmer.simplenotes.models.Folder |
| 11 | +import dev.dettmer.simplenotes.utils.Constants |
| 12 | +import dev.dettmer.simplenotes.utils.Logger |
| 13 | +import java.io.File |
| 14 | +import kotlinx.coroutines.Dispatchers |
| 15 | +import kotlinx.coroutines.sync.Mutex |
| 16 | +import kotlinx.coroutines.sync.withLock |
| 17 | +import kotlinx.coroutines.withContext |
| 18 | + |
| 19 | +/** 🆕 v2.7.0 (Folders): Persistierte Ordner-Metadaten (lokal + serverseitig in folders.json). */ |
| 20 | +data class FolderMeta( |
| 21 | + @SerializedName("name") val name: String, |
| 22 | + @SerializedName("color") val color: String? = null, |
| 23 | + @SerializedName("updatedAt") val updatedAt: Long = 0L, |
| 24 | + @SerializedName("deleted") val deleted: Boolean = false |
| 25 | +) |
| 26 | + |
| 27 | +/** |
| 28 | + * Gson umgeht Kotlin-Null-Safety und kann das non-null `name`-Feld zur Laufzeit mit `null` |
| 29 | + * befüllen (fehlender/`null`-Key im JSON). Solche korrupten Einträge würden später bei |
| 30 | + * `name.lowercase()` einen NPE auslösen → hier defensiv verwerfen. |
| 31 | + */ |
| 32 | +internal fun List<FolderMeta>.sanitized(): List<FolderMeta> = filter { !it.name.isNullOrBlank() } |
| 33 | + |
| 34 | +/** |
| 35 | + * 🆕 v2.7.0 (Folders): Persistiert Ordner-Metadaten (Name, Farbe, Tombstones) in `filesDir/folders.json`. |
| 36 | + * |
| 37 | + * Altes Format `["A","B"]` wird beim Lesen auf `FolderMeta(name, updatedAt=0, deleted=false)` |
| 38 | + * abgebildet (Backward-Compat). Schreib-Operationen sind Mutex-geschützt und atomar (tmp-Rename). |
| 39 | + * Dirty-Flag in SharedPreferences signalisiert ausstehende Uploads an den `FolderSyncManager`. |
| 40 | + */ |
| 41 | +class FolderStore(private val context: Context) { |
| 42 | + private val mutex = Mutex() |
| 43 | + private val gson = Gson() |
| 44 | + private val file: File get() = File(context.filesDir, FILE_NAME) |
| 45 | + private val prefs: SharedPreferences by lazy { |
| 46 | + context.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE) |
| 47 | + } |
| 48 | + |
| 49 | + /** Alle Einträge inkl. Tombstones (für Sync-Merge). */ |
| 50 | + suspend fun loadMeta(): List<FolderMeta> = mutex.withLock { loadMetaUnsafe() } |
| 51 | + |
| 52 | + /** Komplette Liste schreiben (Sync-Merge-Ergebnis). Kein dirty-Flag. */ |
| 53 | + suspend fun replaceMeta(list: List<FolderMeta>) = mutex.withLock { |
| 54 | + writeMetaUnsafe(list) |
| 55 | + } |
| 56 | + |
| 57 | + /** Sichtbare Ordnernamen (nicht deleted), alphabetisch case-insensitiv. */ |
| 58 | + suspend fun load(): List<String> = mutex.withLock { |
| 59 | + loadMetaUnsafe().filter { !it.deleted }.map { it.name }.sortedBy { it.lowercase() } |
| 60 | + } |
| 61 | + |
| 62 | + /** Sichtbare Ordner als Folder(name, color), sortiert. */ |
| 63 | + suspend fun loadFolders(): List<Folder> = mutex.withLock { |
| 64 | + loadMetaUnsafe() |
| 65 | + .filter { !it.deleted } |
| 66 | + .map { Folder(it.name, it.color) } |
| 67 | + .sortedBy { it.name.lowercase() } |
| 68 | + } |
| 69 | + |
| 70 | + /** User-Anlage: Eintrag anlegen/re-aktivieren. Setzt dirty-Flag. */ |
| 71 | + suspend fun addFolder(name: String) { |
| 72 | + val trimmed = name.trim() |
| 73 | + if (trimmed.isEmpty()) return |
| 74 | + mutex.withLock { |
| 75 | + val current = loadMetaUnsafe().toMutableList() |
| 76 | + val idx = current.indexOfFirst { it.name.equals(trimmed, ignoreCase = true) } |
| 77 | + if (idx >= 0) { |
| 78 | + val existing = current[idx] |
| 79 | + if (!existing.deleted && existing.name == trimmed) return@withLock |
| 80 | + current[idx] = existing.copy(name = trimmed, deleted = false, updatedAt = now()) |
| 81 | + } else { |
| 82 | + current.add(FolderMeta(name = trimmed, updatedAt = now())) |
| 83 | + } |
| 84 | + writeMetaUnsafe(current.sortedBy { it.name.lowercase() }) |
| 85 | + markDirty() |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /** Discovery-Mirror: Registriert nur unbekannte Namen mit updatedAt=0. Kein dirty-Flag. */ |
| 90 | + suspend fun addFolders(names: Collection<String>) { |
| 91 | + if (names.isEmpty()) return |
| 92 | + mutex.withLock { |
| 93 | + val current = loadMetaUnsafe().toMutableList() |
| 94 | + var changed = false |
| 95 | + for (raw in names) { |
| 96 | + val t = raw.trim() |
| 97 | + if (t.isNotEmpty() && current.none { it.name.equals(t, ignoreCase = true) }) { |
| 98 | + current.add(FolderMeta(name = t, updatedAt = 0L)) |
| 99 | + changed = true |
| 100 | + } |
| 101 | + } |
| 102 | + if (changed) writeMetaUnsafe(current.sortedBy { it.name.lowercase() }) |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + /** Farbe setzen. Setzt dirty-Flag. */ |
| 107 | + suspend fun setColor(name: String, color: String?) = mutex.withLock { |
| 108 | + val current = loadMetaUnsafe().toMutableList() |
| 109 | + val idx = current.indexOfFirst { it.name.equals(name, ignoreCase = true) && !it.deleted } |
| 110 | + if (idx >= 0) { |
| 111 | + current[idx] = current[idx].copy(color = color, updatedAt = now()) |
| 112 | + writeMetaUnsafe(current) |
| 113 | + markDirty() |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + /** Tombstoned old → new mit Farbe übernehmen. Setzt dirty-Flag. */ |
| 118 | + suspend fun rename(old: String, new: String) { |
| 119 | + val trimmedNew = new.trim() |
| 120 | + if (trimmedNew.isEmpty()) return |
| 121 | + mutex.withLock { |
| 122 | + val current = loadMetaUnsafe().toMutableList() |
| 123 | + val oldIdx = current.indexOfFirst { it.name.equals(old, ignoreCase = true) } |
| 124 | + val oldColor = current.getOrNull(oldIdx)?.color |
| 125 | + if (oldIdx >= 0) { |
| 126 | + current[oldIdx] = current[oldIdx].copy(deleted = true, updatedAt = now()) |
| 127 | + } |
| 128 | + val newIdx = current.indexOfFirst { it.name.equals(trimmedNew, ignoreCase = true) } |
| 129 | + if (newIdx >= 0) { |
| 130 | + current[newIdx] = current[newIdx].copy(name = trimmedNew, color = oldColor, deleted = false, updatedAt = now()) |
| 131 | + } else { |
| 132 | + current.add(FolderMeta(name = trimmedNew, color = oldColor, updatedAt = now())) |
| 133 | + } |
| 134 | + writeMetaUnsafe(current.sortedBy { it.name.lowercase() }) |
| 135 | + markDirty() |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + /** Tombstone statt Hard-Remove. Setzt dirty-Flag. */ |
| 140 | + suspend fun deleteFolder(name: String) = mutex.withLock { |
| 141 | + val current = loadMetaUnsafe().toMutableList() |
| 142 | + val idx = current.indexOfFirst { it.name.equals(name, ignoreCase = true) && !it.deleted } |
| 143 | + if (idx >= 0) { |
| 144 | + current[idx] = current[idx].copy(deleted = true, updatedAt = now()) |
| 145 | + writeMetaUnsafe(current) |
| 146 | + markDirty() |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + /** Nur für Tests / „Alle Daten löschen". */ |
| 151 | + suspend fun clear() = mutex.withLock { |
| 152 | + try { if (file.exists()) file.delete() } catch (e: Exception) { |
| 153 | + Logger.w(TAG, "clear failed: ${e.message}") |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + private fun markDirty() { |
| 158 | + prefs.edit { putBoolean(Constants.KEY_FOLDERS_DIRTY, true) } |
| 159 | + } |
| 160 | + |
| 161 | + private fun now() = System.currentTimeMillis() |
| 162 | + |
| 163 | + // ── Helpers (Mutex-FREE — nur unter withLock aufrufen!) ─────────────── |
| 164 | + |
| 165 | + private suspend fun loadMetaUnsafe(): List<FolderMeta> = withContext(Dispatchers.IO) { |
| 166 | + if (!file.exists()) return@withContext emptyList() |
| 167 | + val raw = try { file.readText() } catch (e: Exception) { |
| 168 | + Logger.w(TAG, "read failed: ${e.message}"); return@withContext emptyList() |
| 169 | + } |
| 170 | + if (raw.isBlank()) return@withContext emptyList() |
| 171 | + try { |
| 172 | + val arr = JsonParser.parseString(raw).asJsonArray |
| 173 | + if (arr.size() == 0) return@withContext emptyList() |
| 174 | + return@withContext if (arr[0].isJsonObject) { |
| 175 | + // Neues Format: List<FolderMeta> |
| 176 | + val type = object : TypeToken<List<FolderMeta>>() {}.type |
| 177 | + (gson.fromJson<List<FolderMeta>>(raw, type) ?: emptyList()).sanitized() |
| 178 | + } else { |
| 179 | + // Altes Format: List<String> → Backward-Compat-Migration |
| 180 | + val type = object : TypeToken<List<String>>() {}.type |
| 181 | + val names = gson.fromJson<List<String>>(raw, type) ?: emptyList() |
| 182 | + names.map { FolderMeta(name = it, updatedAt = 0L) }.sanitized() |
| 183 | + } |
| 184 | + } catch (e: Exception) { |
| 185 | + Logger.w(TAG, "parse failed: ${e.message}") |
| 186 | + emptyList() |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + private suspend fun writeMetaUnsafe(list: List<FolderMeta>) = withContext(Dispatchers.IO) { |
| 191 | + try { |
| 192 | + val tmp = File(file.parentFile, "$FILE_NAME.tmp") |
| 193 | + tmp.writeText(gson.toJson(list)) |
| 194 | + if (file.exists()) file.delete() |
| 195 | + if (!tmp.renameTo(file)) { |
| 196 | + file.writeText(gson.toJson(list)) |
| 197 | + tmp.delete() |
| 198 | + } |
| 199 | + } catch (e: Exception) { |
| 200 | + Logger.w(TAG, "write failed: ${e.message}") |
| 201 | + } |
| 202 | + } |
| 203 | + |
| 204 | + companion object { |
| 205 | + private const val TAG = "FolderStore" |
| 206 | + const val FILE_NAME = "folders.json" |
| 207 | + } |
| 208 | +} |
0 commit comments