Move stores using SharedPrefs to :shared and use KvPrefs instead

This commit is contained in:
Olof Hedman
2025-09-20 20:26:06 +02:00
parent a73f475957
commit 61fa43ff2c
18 changed files with 223 additions and 265 deletions

View File

@@ -1013,7 +1013,6 @@ private fun KlottrAppShell(
}, },
addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime -> addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime ->
OutboxStore.addDoc( OutboxStore.addDoc(
context = context,
lat = la, lat = la,
lon = lo, lon = lo,
title = t, title = t,
@@ -1084,7 +1083,6 @@ private fun KlottrAppShell(
}, },
addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime -> addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime ->
OutboxStore.addDoc( OutboxStore.addDoc(
context = context,
lat = la, lat = la,
lon = lo, lon = lo,
title = t, title = t,

View File

@@ -38,7 +38,7 @@ class OutboxWorker(
override suspend fun doWork(): Result { override suspend fun doWork(): Result {
val ctx = applicationContext val ctx = applicationContext
val pending = OutboxStore.all(ctx) val pending = OutboxStore.all()
if (pending.isEmpty()) return Result.success() if (pending.isEmpty()) return Result.success()
val keep = mutableListOf<OutboxStore.PendingNote>() val keep = mutableListOf<OutboxStore.PendingNote>()
@@ -137,7 +137,7 @@ class OutboxWorker(
if (!ok) keep.add(p) if (!ok) keep.add(p)
} }
OutboxStore.replaceAll(ctx, keep) OutboxStore.replaceAll( keep)
return if (keep.isEmpty()) Result.success() else Result.retry() return if (keep.isEmpty()) Result.success() else Result.retry()
} }
} }

View File

@@ -1,126 +0,0 @@
package app.klottr.util
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
/**
* Enkel "utkorg" i SharedPreferences. Lagrar klotter som inte kunde postas
* för att skickas senare när nätet kommer tillbaka.
*/
object OutboxStore {
private const val PREFS = "klottr_outbox"
private const val KEY = "pending_json"
data class PendingNote(
val lat: Double,
val lon: Double,
val createdAt: Long,
// TEXT-variant (som tidigare)
val text: String? = null,
// DOC-variant (ny)
val title: String? = null,
val body: String? = null,
val radiusM: Int = 20,
// BILD (ny) – lagras som LOKAL fil i appens lagring
val imagePath: String? = null,
val imageMime: String? = null
)
private fun prefs(ctx: Context) =
ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
fun add(context: Context, lat: Double, lon: Double, text: String, createdAt: Long) {
val list = all(context).toMutableList()
list.add(
PendingNote(
lat = lat,
lon = lon,
createdAt = createdAt,
text = text
)
)
save(context, list)
}
fun addDoc(
context: Context,
lat: Double,
lon: Double,
title: String,
body: String,
createdAt: Long,
radiusM: Int,
imagePath: String?, // absolut sökväg till vår lokala kopia (om vald)
imageMime: String? // "image/jpeg" osv (om vald)
) {
val list = all(context).toMutableList()
list.add(
PendingNote(
lat = lat, lon = lon, createdAt = createdAt,
title = title, body = body, radiusM = radiusM,
imagePath = imagePath, imageMime = imageMime
)
)
save(context, list)
}
fun all(context: Context): List<PendingNote> {
val s = prefs(context).getString(KEY, "[]") ?: "[]"
val arr = JSONArray(s)
val out = ArrayList<PendingNote>(arr.length())
for (i in 0 until arr.length()) {
val o = arr.getJSONObject(i)
val lat = o.getDouble("lat")
val lon = o.getDouble("lon")
val createdAt = o.getLong("createdAt")
// text fanns alltid förr – men gör den valfri nu
val text = if (o.has("text")) o.optString("text", null).let { if (it.isNullOrEmpty()) null else it } else null
// nya fält (kan saknas i äldre JSON)
val title = if (o.has("title")) o.optString("title", null).let { if (it.isNullOrEmpty()) null else it } else null
val body = if (o.has("body")) o.optString("body", null).let { if (it.isNullOrEmpty()) null else it } else null
val radiusM = if (o.has("radiusM")) o.optInt("radiusM", 20) else 20
val imagePath = if (o.has("imagePath")) o.optString("imagePath", null).let { if (it.isNullOrEmpty()) null else it } else null
val imageMime = if (o.has("imageMime")) o.optString("imageMime", null).let { if (it.isNullOrEmpty()) null else it } else null
out.add(
PendingNote(
lat = lat, lon = lon, createdAt = createdAt,
text = text,
title = title, body = body, radiusM = radiusM,
imagePath = imagePath, imageMime = imageMime
)
)
}
return out
}
fun replaceAll(context: Context, items: List<PendingNote>) {
save(context, items)
}
private fun save(context: Context, items: List<PendingNote>) {
val arr = JSONArray()
for (p in items) {
val o = JSONObject()
o.put("lat", p.lat)
o.put("lon", p.lon)
o.put("createdAt", p.createdAt)
// skriv bara nycklar som har värden
p.text?.let { o.put("text", it) }
p.title?.let { o.put("title", it) }
p.body?.let { o.put("body", it) }
if (p.radiusM != 20) o.put("radiusM", p.radiusM)
p.imagePath?.let { o.put("imagePath", it) }
p.imageMime?.let { o.put("imageMime", it) }
arr.put(o)
}
prefs(context).edit().putString(KEY, arr.toString()).apply()
}
}

View File

@@ -1,57 +0,0 @@
package app.klottr.util
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
/**
* Beständig lista över de senaste träffarna ("Funnet klotter") över appstarter.
* Lagrar de senaste 200 med (text, lat, lon, timeMillis), nyast först.
*/
object RecentHitsStore {
private const val PREFS = "klottr_recent_hits"
private const val KEY = "hits_json"
private const val MAX = 200
private fun prefs(ctx: Context) = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
fun append(ctx: Context, entry: HitEntry) {
val arr = JSONArray(prefs(ctx).getString(KEY, "[]") ?: "[]")
// stoppa in först (nyast först)
val obj = JSONObject()
obj.put("text", entry.text)
obj.put("lat", entry.lat)
obj.put("lon", entry.lon)
obj.put("timeMillis", entry.timeMillis)
// ny lista: [obj] + befintligt, upp till MAX
val newArr = JSONArray()
newArr.put(obj)
for (i in 0 until arr.length()) {
if (i + 1 >= MAX) break
newArr.put(arr.getJSONObject(i))
}
prefs(ctx).edit().putString(KEY, newArr.toString()).apply()
}
fun list(ctx: Context): List<HitEntry> {
val s = prefs(ctx).getString(KEY, "[]") ?: "[]"
val arr = JSONArray(s)
val out = ArrayList<HitEntry>(arr.length())
for (i in 0 until arr.length()) {
val o = arr.getJSONObject(i)
out.add(
HitEntry(
text = o.optString("text"),
lat = o.optDouble("lat"),
lon = o.optDouble("lon"),
timeMillis = o.optLong("timeMillis")
)
)
}
return out
}
fun clear(ctx: Context) {
prefs(ctx).edit().remove(KEY).apply()
}
}

View File

@@ -1,33 +0,0 @@
package app.klottr.util
import android.content.Context
/**
* Lagrar vilka Note-ID:n som redan har visats som träff.
* Implementerat med SharedPreferences StringSet för enkelhet.
*/
object SeenHits {
private const val PREFS_NAME = "klottr_seen_hits"
private const val KEY_SET = "seen_ids"
private fun prefs(ctx: Context) =
ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
fun isSeen(ctx: Context, id: Long): Boolean {
val set = prefs(ctx).getStringSet(KEY_SET, emptySet()) ?: emptySet()
return set.contains(id.toString())
}
fun markSeen(ctx: Context, id: Long) {
val p = prefs(ctx)
val set = (p.getStringSet(KEY_SET, emptySet()) ?: emptySet()).toMutableSet()
if (set.add(id.toString())) {
p.edit().putStringSet(KEY_SET, set).apply()
}
}
/** För felsökning / återställning - rensa listan */
fun clear(ctx: Context) {
prefs(ctx).edit().remove(KEY_SET).apply()
}
}

View File

@@ -1,19 +0,0 @@
package app.klottr.util
import android.content.Context
import java.util.UUID
object UserId {
private const val PREFS = "klottr_prefs"
private const val KEY = "user_id"
/** Ett anonymt men stabilt ID per app-installation. */
fun get(context: Context): String {
val sp = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val existing = sp.getString(KEY, null)
if (existing != null) return existing
val fresh = UUID.randomUUID().toString()
sp.edit().putString(KEY, fresh).apply()
return fresh
}
}

View File

@@ -1,26 +0,0 @@
package app.klottr.util
import android.content.Context
object WikiHitIndex {
private const val PREFS = "klottr_wiki_hit_index"
private fun prefs(ctx: Context) = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
fun put(ctx: Context, timeMillis: Long, pageId: Long) {
prefs(ctx).edit().putLong(timeMillis.toString(), pageId).apply()
}
fun isWiki(ctx: Context, timeMillis: Long): Boolean {
return prefs(ctx).contains(timeMillis.toString())
}
fun getPageId(ctx: Context, timeMillis: Long): Long? {
val v = prefs(ctx).getLong(timeMillis.toString(), Long.MIN_VALUE)
return if (v == Long.MIN_VALUE) null else v
}
fun clear(ctx: Context) {
prefs(ctx).edit().clear().apply()
}
}

View File

@@ -55,6 +55,16 @@ actual object KvPrefs {
notifyChanged(key) notifyChanged(key)
} }
actual fun getLong(key: String, def: Long?): Long? =
if (p().contains(key)) p().getLong(key, 0L) else def
actual fun putLong(key: String, value: Long) {
p().edit().putLong(key, value).apply()
notifyChanged(key)
}
actual fun contains(key: String): Boolean = p().contains(key)
actual fun remove(key: String) { actual fun remove(key: String) {
p().edit().remove(key).apply() p().edit().remove(key).apply()
notifyChanged(key) notifyChanged(key)

View File

@@ -16,6 +16,10 @@ expect object KvPrefs {
fun getStringSet(key: String): Set<String> fun getStringSet(key: String): Set<String>
fun putStringSet(key: String, value: Set<String>) fun putStringSet(key: String, value: Set<String>)
fun getLong(key: String, def: Long?): Long?
fun putLong(key: String, value: Long)
fun contains(key: String): Boolean
fun remove(key: String) fun remove(key: String)
fun clearAll() fun clearAll()

View File

@@ -0,0 +1,70 @@
package app.klottr.util
import app.klottr.prefs.KvPrefs
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
/**
* Enkel "utkorg" i KvPrefs. Lagrar klotter som inte kunde postas
* för att skickas senare när nätet kommer tillbaka.
*/
object OutboxStore {
private const val KEY = "pending_json"
private val json = Json { ignoreUnknownKeys = true }
@Serializable
data class PendingNote(
val lat: Double,
val lon: Double,
val createdAt: Long,
// TEXT-variant (som tidigare)
val text: String? = null,
// DOC-variant (ny)
val title: String? = null,
val body: String? = null,
val radiusM: Int = 20,
// BILD (ny) – lagras som LOKAL fil i appens lagring
val imagePath: String? = null,
val imageMime: String? = null
)
fun add(lat: Double, lon: Double, text: String, createdAt: Long) {
val list = all().toMutableList()
list.add(PendingNote(lat = lat, lon = lon, createdAt = createdAt, text = text))
save(list)
}
fun addDoc(
lat: Double,
lon: Double,
title: String,
body: String,
createdAt: Long,
radiusM: Int,
imagePath: String?, // absolut sökväg till vår lokala kopia (om vald)
imageMime: String? // "image/jpeg" osv (om vald)
) {
val list = all().toMutableList()
list.add(
PendingNote(
lat = lat, lon = lon, createdAt = createdAt,
title = title, body = body, radiusM = radiusM,
imagePath = imagePath, imageMime = imageMime
)
)
save(list)
}
fun all(): List<PendingNote> =
json.decodeFromString(KvPrefs.getString(KEY, "[]")!!)
fun replaceAll(items: List<PendingNote>) {
save(items)
}
private fun save(items: List<PendingNote>) {
KvPrefs.putString(KEY, json.encodeToString(items))
}
}

View File

@@ -0,0 +1,44 @@
package app.klottr.util
import app.klottr.prefs.KvPrefs
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString
/**
* Beständig lista över de senaste träffarna ("Funnet klotter") över appstarter.
* Lagrar de senaste 200 med (text, lat, lon, timeMillis), nyast först.
*/
object RecentHitsStore {
private const val KEY = "hits_json" // keep the same key name
private const val MAX = 200
private val json = Json { ignoreUnknownKeys = true }
fun append(entry: HitEntry) {
val cur = decode().toMutableList()
cur.add(0, entry.toDto())
if (cur.size > MAX) cur.subList(MAX, cur.size).clear()
KvPrefs.putString(KEY, json.encodeToString(cur))
}
fun list(): List<HitEntry> =
decode().map { it.toModel() }
fun clear() = KvPrefs.remove(KEY)
private fun decode(): List<HitEntryDto> =
json.decodeFromString(KvPrefs.getString(KEY, "[]")!!)
@Serializable
private data class HitEntryDto(
val text: String,
val lat: Double,
val lon: Double,
val timeMillis: Long
)
// Map storage DTO <-> your domain model
private fun HitEntry.toDto() = HitEntryDto(text = text, lat = lat, lon = lon, timeMillis = timeMillis)
private fun HitEntryDto.toModel() = HitEntry(text = text, lat = lat, lon = lon, timeMillis = timeMillis)
}

View File

@@ -0,0 +1,29 @@
package app.klottr.util
import app.klottr.prefs.KvPrefs
/**
* Lagrar vilka Note-ID:n som redan har visats som träff.
* Implementerat med KvPrefs StringSet (fungerar på Android+iOS).
*/
object SeenHits {
private const val KEY_SET = "seen_ids"
fun isSeen(id: Long): Boolean {
if (!KvPrefs.contains(KEY_SET)) return false
return KvPrefs.getStringSet(KEY_SET).contains(id.toString())
}
fun markSeen(id: Long) {
val s = id.toString()
if (!KvPrefs.contains(KEY_SET)) {
KvPrefs.putStringSet(KEY_SET, setOf(s))
return
}
val set = KvPrefs.getStringSet(KEY_SET).toMutableSet()
if (set.add(s)) KvPrefs.putStringSet(KEY_SET, set)
}
/** För felsökning / återställning - rensa listan */
fun clear() = KvPrefs.remove(KEY_SET)
}

View File

@@ -0,0 +1,26 @@
package app.klottr.util
import app.klottr.prefs.KvPrefs
import kotlin.random.Random
object UserId {
private const val KEY = "user_id"
/** Ett anonymt men stabilt ID per app-installation (RFC4122 v4-format, multiplatform). */
fun get(): String {
if (KvPrefs.contains(KEY)) {
KvPrefs.getString(KEY, null)?.let { return it }
}
val fresh = randomUuidV4()
KvPrefs.putString(KEY, fresh)
return fresh
}
private fun randomUuidV4(): String {
val b = Random.nextBytes(16)
b[6] = ((b[6].toInt() and 0x0f) or 0x40).toByte() // version 4
b[8] = ((b[8].toInt() and 0x3f) or 0x80).toByte() // variant 10
val h = b.joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
return "${h.substring(0,8)}-${h.substring(8,12)}-${h.substring(12,16)}-${h.substring(16,20)}-${h.substring(20)}"
}
}

View File

@@ -0,0 +1,28 @@
package app.klottr.util
import app.klottr.prefs.KvPrefs
object WikiHitIndex {
// Track keys so we can clear later without platform-specific APIs.
private const val KEY_INDEX = "wiki_hit_index_keys"
private fun keyFor(timeMillis: Long) = "wiki_hit_$timeMillis"
fun put(timeMillis: Long, pageId: Long) {
val k = keyFor(timeMillis)
KvPrefs.putLong(k, pageId) // store Long as String (KvPrefs has no Long API)
val idx = KvPrefs.getStringSet(KEY_INDEX).toMutableSet()
if (idx.add(k)) KvPrefs.putStringSet(KEY_INDEX, idx)
}
fun isWiki(timeMillis: Long): Boolean =
KvPrefs.contains(keyFor(timeMillis))
fun getPageId(timeMillis: Long): Long? =
KvPrefs.getLong(keyFor(timeMillis),null)
fun clear() {
val idx = KvPrefs.getStringSet(KEY_INDEX)
idx.forEach { KvPrefs.remove(it) }
KvPrefs.remove(KEY_INDEX)
}
}

View File

@@ -47,6 +47,16 @@ actual object KvPrefs {
notifyChanged(key) notifyChanged(key)
} }
actual fun getLong(key: String, def: Long?): Long? =
if (contains(key)) d.integerForKey(key) else def
actual fun putLong(key: String, value: Long) {
d.setInteger(value, forKey = key)
notifyChanged(key)
}
actual fun contains(key: String): Boolean = d.objectForKey(key) != null
actual fun remove(key: String) { actual fun remove(key: String) {
d.removeObjectForKey(key) d.removeObjectForKey(key)
notifyChanged(key) notifyChanged(key)