feat(layers): show server-driven dynamic layers in Near & Home tabs (per-layer radii, cache keys, PHP bbox+Haversine, ETag restored)
This commit is contained in:
@@ -119,9 +119,14 @@ class OutboxWorker(
|
|||||||
try {
|
try {
|
||||||
// Hämta närliggande från servern för att få rätt id/koordinater
|
// Hämta närliggande från servern för att få rätt id/koordinater
|
||||||
val nearby = Geocache.getNearby(
|
val nearby = Geocache.getNearby(
|
||||||
lat = p.lat, lon = p.lon, radiusMeters = 120, ttlMs = 0L
|
lat = p.lat,
|
||||||
|
lon = p.lon,
|
||||||
|
ttlMs = 0L,
|
||||||
|
layers = mapOf("klotter" to 120) // 🔸 temporär placeholder
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Välj bästa kandidat: nära i både tid och rum
|
// Välj bästa kandidat: nära i både tid och rum
|
||||||
val match = nearby
|
val match = nearby
|
||||||
.filter { app.klottr.util.distanceMeters(p.lat, p.lon, it.a, it.o) <= 80.0 }
|
.filter { app.klottr.util.distanceMeters(p.lat, p.lon, it.a, it.o) <= 80.0 }
|
||||||
|
|||||||
@@ -324,6 +324,15 @@ fun KlottrAppShell(
|
|||||||
layerRanges = tmp
|
layerRanges = tmp
|
||||||
layers = res.items.sortedBy { it.sortOrder }
|
layers = res.items.sortedBy { it.sortOrder }
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// Läs sparade inställningar för dynamiska lager från SettingsStore
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
for (layer in layers) {
|
||||||
|
val slug = layer.slug
|
||||||
|
dynamicVisible[slug] = SettingsStore.getLayerVisible(slug)
|
||||||
|
dynamicRadius[slug] = SettingsStore.getLayerRadiusMeters(slug)
|
||||||
|
}
|
||||||
|
|
||||||
// Initiera dynamiska states för slugs som inte är “kända”
|
// Initiera dynamiska states för slugs som inte är “kända”
|
||||||
val known = setOf("klotter", "wikipedia", "digitaltmuseum", "fornsok")
|
val known = setOf("klotter", "wikipedia", "digitaltmuseum", "fornsok")
|
||||||
for (l in layers) {
|
for (l in layers) {
|
||||||
@@ -395,41 +404,89 @@ fun KlottrAppShell(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Löser bugg som gjorde att Klotter-fynd inte dök upp: Klotter: skanna nära klotter och markera i FoundStore så Hem-fliken uppdateras
|
// Signatur för alla lager (statiska + dynamiska) så LaunchedEffect triggar om vid ändring
|
||||||
LaunchedEffect(showKlotter, locationTick) {
|
val layersSignature by remember(
|
||||||
if (!showKlotter) return@LaunchedEffect
|
showKlotter, showWiki, wikiRadius,
|
||||||
|
showDm, dmRadius,
|
||||||
|
showFornsok, fornsokRadius,
|
||||||
|
dynamicVisible, dynamicRadius
|
||||||
|
) {
|
||||||
|
derivedStateOf {
|
||||||
|
val stat =
|
||||||
|
"K=${SettingsStore.getShowKlotter()}:" +
|
||||||
|
Config.DEFAULT_KLOTTER_RADIUS_M + "|" +
|
||||||
|
"W=${SettingsStore.getShowWikipedia()}:" +
|
||||||
|
SettingsStore.getWikiRadiusMeters() + "|" +
|
||||||
|
"DM=${SettingsStore.getShowDigitaltMuseum()}:" +
|
||||||
|
SettingsStore.getDigitaltMuseumRadiusMeters() + "|" +
|
||||||
|
"F=${SettingsStore.getShowFornsok()}:" +
|
||||||
|
SettingsStore.getFornsokRadiusMeters()
|
||||||
|
|
||||||
|
val dynV = dynamicVisible.toMap().entries.sortedBy { it.key }
|
||||||
|
.joinToString(",") { "${it.key}:${it.value}" }
|
||||||
|
val dynR = dynamicRadius.toMap().entries.sortedBy { it.key }
|
||||||
|
.joinToString(",") { "${it.key}:${it.value}" }
|
||||||
|
|
||||||
|
"$stat|DV=$dynV|DR=$dynR"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Skanna alla aktiva lager och markera nya fynd
|
||||||
|
LaunchedEffect(locationTick, layersSignature) {
|
||||||
val gp = LocationServiceProvider.get().current(highAccuracy = false) ?: return@LaunchedEffect
|
val gp = LocationServiceProvider.get().current(highAccuracy = false) ?: return@LaunchedEffect
|
||||||
lastKnownLat = gp.lat
|
lastKnownLat = gp.lat
|
||||||
lastKnownLon = gp.lon
|
lastKnownLon = gp.lon
|
||||||
|
|
||||||
// Hämta klotter inom standardradien (20 m)
|
// Bygg layers-mapp (alla aktiva lager med radier)
|
||||||
|
val layersMap = mutableMapOf<String, Int>()
|
||||||
|
|
||||||
|
if (SettingsStore.getShowKlotter()) layersMap["klotter"] = Config.DEFAULT_KLOTTER_RADIUS_M
|
||||||
|
if (SettingsStore.getShowWikipedia()) layersMap["wikipedia"] = SettingsStore.getWikiRadiusMeters()
|
||||||
|
if (SettingsStore.getShowDigitaltMuseum()) layersMap["digitaltmuseum"] = SettingsStore.getDigitaltMuseumRadiusMeters()
|
||||||
|
if (SettingsStore.getShowFornsok()) layersMap["fornsok"] = SettingsStore.getFornsokRadiusMeters()
|
||||||
|
|
||||||
|
for ((slug, visible) in dynamicVisible) {
|
||||||
|
if (visible) {
|
||||||
|
val r = dynamicRadius[slug] ?: layerRanges[slug]?.first ?: 50
|
||||||
|
layersMap[slug] = r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val nearby = withContext(Dispatchers.IO) {
|
val nearby = withContext(Dispatchers.IO) {
|
||||||
Geocache.getNearby(
|
Geocache.getNearby(
|
||||||
lat = gp.lat,
|
lat = gp.lat,
|
||||||
lon = gp.lon,
|
lon = gp.lon,
|
||||||
radiusMeters = Config.DEFAULT_KLOTTER_RADIUS_M,
|
ttlMs = 0L,
|
||||||
ttlMs = 0L
|
layers = layersMap
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Markera nya (ej tidigare kända) som "hittade"
|
val now = Clock.System.now().toEpochMilliseconds()
|
||||||
|
var anyNew = false
|
||||||
|
|
||||||
|
// Hämta alla redan kända fynd (alla lager)
|
||||||
val known = FoundStore.getAll()
|
val known = FoundStore.getAll()
|
||||||
.asSequence()
|
.asSequence()
|
||||||
.filter { it.layer == LAYER_KLOTTER }
|
.map { it.layer to it.id }
|
||||||
.map { it.id }
|
|
||||||
.toSet()
|
.toSet()
|
||||||
|
|
||||||
var anyNew = false
|
|
||||||
val now = Clock.System.now().toEpochMilliseconds()
|
|
||||||
|
|
||||||
for (n in nearby) {
|
for (n in nearby) {
|
||||||
val idStr = n.i.toString()
|
val idStr = n.i.toString()
|
||||||
if (idStr !in known) {
|
val layerSlug = n.t?.lowercase()?.let {
|
||||||
|
when {
|
||||||
|
it.contains("wikipedia") -> "wikipedia"
|
||||||
|
it.contains("fornsök") -> "fornsok"
|
||||||
|
it.contains("digitaltmuseum") -> "digitaltmuseum"
|
||||||
|
else -> "klotter"
|
||||||
|
}
|
||||||
|
} ?: "klotter"
|
||||||
|
|
||||||
|
if (known.none { it.first == layerSlug && it.second == idStr }) {
|
||||||
FoundStore.markFound(
|
FoundStore.markFound(
|
||||||
layer = LAYER_KLOTTER,
|
layer = layerSlug,
|
||||||
id = idStr,
|
id = idStr,
|
||||||
label = n.t ?: "Klotter",
|
label = n.t ?: "Fynd",
|
||||||
lat = n.a,
|
lat = n.a,
|
||||||
lon = n.o,
|
lon = n.o,
|
||||||
timeMillis = now
|
timeMillis = now
|
||||||
@@ -438,18 +495,15 @@ fun KlottrAppShell(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Uppdatera away-flaggor (fetstil i listan blir korrekt)
|
|
||||||
FoundStore.updateAwayFlags(gp.lat, gp.lon)
|
FoundStore.updateAwayFlags(gp.lat, gp.lon)
|
||||||
|
|
||||||
if (anyNew) {
|
if (anyNew) {
|
||||||
// Återställ ev. "tvinga tomt" och trigga omritning
|
|
||||||
forceEmptyFound = false
|
forceEmptyFound = false
|
||||||
FoundEvents.notifyFoundUpdated()
|
FoundEvents.notifyFoundUpdated()
|
||||||
refreshFound()
|
refreshFound()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
CenterAlignedTopAppBar(
|
CenterAlignedTopAppBar(
|
||||||
@@ -713,6 +767,11 @@ fun KlottrAppShell(
|
|||||||
} else {
|
} else {
|
||||||
dynamicVisible[layer.slug] = false
|
dynamicVisible[layer.slug] = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Spara till SettingsStore (permanent)
|
||||||
|
SettingsStore.setLayerVisible(layer.slug, enabled)
|
||||||
|
SettingsStore.setLayerRadiusMeters(layer.slug, newVal)
|
||||||
|
|
||||||
}
|
}
|
||||||
v to h
|
v to h
|
||||||
}
|
}
|
||||||
@@ -740,7 +799,7 @@ fun KlottrAppShell(
|
|||||||
var nearbySplit by rememberSaveable { mutableStateOf(0.5f) }
|
var nearbySplit by rememberSaveable { mutableStateOf(0.5f) }
|
||||||
|
|
||||||
// Trigga scanning när fliken blir aktiv (och när lager-inställningar ändras)
|
// Trigga scanning när fliken blir aktiv (och när lager-inställningar ändras)
|
||||||
LaunchedEffect(selectedTab, showKlotter, showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
|
LaunchedEffect(selectedTab, layersSignature) {
|
||||||
if (selectedTab != "nearby") return@LaunchedEffect
|
if (selectedTab != "nearby") return@LaunchedEffect
|
||||||
nearbyRefreshing = true // Visa den grafiska loading-effekten.
|
nearbyRefreshing = true // Visa den grafiska loading-effekten.
|
||||||
nearbyError = null
|
nearbyError = null
|
||||||
@@ -752,11 +811,30 @@ fun KlottrAppShell(
|
|||||||
lastKnownLat = gp.lat
|
lastKnownLat = gp.lat
|
||||||
lastKnownLon = gp.lon
|
lastKnownLon = gp.lon
|
||||||
|
|
||||||
|
// Bygg layers-mapp (slug -> radie) från användarens inställningar och dynamiska lager
|
||||||
|
val layersMap = mutableMapOf<String, Int>()
|
||||||
|
|
||||||
|
// Fasta lager
|
||||||
|
if (showKlotter) layersMap["klotter"] = Config.DEFAULT_KLOTTER_RADIUS_M
|
||||||
|
if (showWiki) layersMap["wikipedia"] = wikiRadius
|
||||||
|
if (showDm) layersMap["digitaltmuseum"] = dmRadius
|
||||||
|
if (showFornsok) layersMap["fornsok"] = fornsokRadius
|
||||||
|
|
||||||
|
// Dynamiska lager
|
||||||
|
for ((slug, visible) in dynamicVisible) {
|
||||||
|
if (visible) {
|
||||||
|
val r = dynamicRadius[slug] ?: layerRanges[slug]?.first ?: 50
|
||||||
|
layersMap[slug] = r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val klotterEnabledForBundle = layersMap.isNotEmpty()
|
||||||
|
|
||||||
|
|
||||||
val newBundle = withContext(Dispatchers.IO) {
|
val newBundle = withContext(Dispatchers.IO) {
|
||||||
getNearbyBundle(
|
getNearbyBundle(
|
||||||
lat = gp.lat,
|
lat = gp.lat,
|
||||||
lon = gp.lon,
|
lon = gp.lon,
|
||||||
showKlotter = showKlotter,
|
showKlotter = klotterEnabledForBundle,
|
||||||
showWiki = showWiki,
|
showWiki = showWiki,
|
||||||
showDm = showDm,
|
showDm = showDm,
|
||||||
showFornsok = showFornsok,
|
showFornsok = showFornsok,
|
||||||
@@ -770,7 +848,15 @@ fun KlottrAppShell(
|
|||||||
.filter { it.layer == FoundStore.LAYER_KLOTTER }
|
.filter { it.layer == FoundStore.LAYER_KLOTTER }
|
||||||
.associate { it.id to it.label }[id]
|
.associate { it.id to it.label }[id]
|
||||||
},
|
},
|
||||||
klotterFetcher = { la, lo -> Geocache.getNearby(lat = la, lon = lo, radiusMeters = 300, ttlMs = 0L) },
|
klotterFetcher = { la, lo ->
|
||||||
|
Geocache.getNearby(
|
||||||
|
lat = la,
|
||||||
|
lon = lo,
|
||||||
|
ttlMs = 0L,
|
||||||
|
layers = layersMap
|
||||||
|
)
|
||||||
|
},
|
||||||
|
// klotterFetcher = { la, lo -> Geocache.getNearby(lat = la, lon = lo, radiusMeters = 300, ttlMs = 0L) },
|
||||||
wikiFetcher = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) },
|
wikiFetcher = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) },
|
||||||
dmFetcher = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) },
|
dmFetcher = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) },
|
||||||
fornFetcher = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) }
|
fornFetcher = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) }
|
||||||
@@ -799,6 +885,24 @@ fun KlottrAppShell(
|
|||||||
onSplitChange = { value -> nearbySplit = value },
|
onSplitChange = { value -> nearbySplit = value },
|
||||||
handleHeight = 18.dp,
|
handleHeight = 18.dp,
|
||||||
top = {
|
top = {
|
||||||
|
// Bygg extra-anteckningar för kartan av samma datakälla som listan
|
||||||
|
// Filtrera till klotter-typen (KLOTTER) och mappa till NoteDTO
|
||||||
|
val extraNotesForMap: List<NoteDTO> = nearbyBundle
|
||||||
|
?.entries
|
||||||
|
.orEmpty()
|
||||||
|
.asSequence()
|
||||||
|
.filter { it.layer.equals("KLOTTER", ignoreCase = true) }
|
||||||
|
.map { e ->
|
||||||
|
NoteDTO(
|
||||||
|
i = (e.id?.toLongOrNull() ?: (e.label.hashCode().toLong() and 0x7FFF_FFFF)), // stabil fallback om id saknas/inte är Long
|
||||||
|
a = e.lat,
|
||||||
|
o = e.lon,
|
||||||
|
t = e.label,
|
||||||
|
c = e.updatedAtMs ?: 0L,
|
||||||
|
u = "" // ISO-sträng används inte av kartan; lämnas tom
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.toList()
|
||||||
Box(Modifier.fillMaxSize()) {
|
Box(Modifier.fillMaxSize()) {
|
||||||
MapContent(
|
MapContent(
|
||||||
onKlotterClick = { id, la, lo, label -> openKlotter = OpenKlotter(id, la, lo, label) },
|
onKlotterClick = { id, la, lo, label -> openKlotter = OpenKlotter(id, la, lo, label) },
|
||||||
@@ -841,6 +945,12 @@ fun KlottrAppShell(
|
|||||||
isKnownNote = { noteId ->
|
isKnownNote = { noteId ->
|
||||||
FoundStore.getAll().any { it.layer == LAYER_KLOTTER && it.id == noteId.toString() }
|
FoundStore.getAll().any { it.layer == LAYER_KLOTTER && it.id == noteId.toString() }
|
||||||
},
|
},
|
||||||
|
// 🔽🔽🔽 Mata in samma data som listan använder – här redan mappad till List<NoteDTO>
|
||||||
|
// OBS: extraNotesForMap innehåller ENDAST KLOTTER (filtrerat) från nearbyBundle.entries
|
||||||
|
extraKlotter = extraNotesForMap,
|
||||||
|
// Använd enbart dessa på kartan (ingen intern hämtning i MapContent)
|
||||||
|
onlyExtraKlotter = true,
|
||||||
|
|
||||||
satellite = satellite,
|
satellite = satellite,
|
||||||
night = night
|
night = night
|
||||||
)
|
)
|
||||||
@@ -1387,14 +1497,32 @@ fun KlottrAppShell(
|
|||||||
// Markera nyskapad notis som "hittad" och uppdatera UI direkt
|
// Markera nyskapad notis som "hittad" och uppdatera UI direkt
|
||||||
scope.launch(Dispatchers.IO) {
|
scope.launch(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
|
// Bygg layers-mapp med alla aktiva lager
|
||||||
|
val layersMap = mutableMapOf<String, Int>()
|
||||||
|
|
||||||
|
// Fasta lager
|
||||||
|
if (SettingsStore.getShowKlotter()) layersMap["klotter"] = Config.DEFAULT_KLOTTER_RADIUS_M
|
||||||
|
if (SettingsStore.getShowWikipedia()) layersMap["wikipedia"] = SettingsStore.getWikiRadiusMeters()
|
||||||
|
if (SettingsStore.getShowDigitaltMuseum()) layersMap["digitaltmuseum"] = SettingsStore.getDigitaltMuseumRadiusMeters()
|
||||||
|
if (SettingsStore.getShowFornsok()) layersMap["fornsok"] = SettingsStore.getFornsokRadiusMeters()
|
||||||
|
|
||||||
|
// Dynamiska lager
|
||||||
|
for ((slug, visible) in dynamicVisible) {
|
||||||
|
if (visible) {
|
||||||
|
val r = dynamicRadius[slug] ?: layerRanges[slug]?.first ?: 50
|
||||||
|
layersMap[slug] = r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hämta närliggande poster för alla aktiva lager
|
||||||
val nearby = Geocache.getNearby(
|
val nearby = Geocache.getNearby(
|
||||||
lat = selLat,
|
lat = selLat,
|
||||||
lon = selLon,
|
lon = selLon,
|
||||||
radiusMeters = 120,
|
ttlMs = 0L,
|
||||||
ttlMs = 0L
|
layers = layersMap
|
||||||
)
|
)
|
||||||
|
|
||||||
// Kandidater nära i både tid och rum (tighta gränser för att undvika felmatch)
|
// Leta efter match baserat på position och tid
|
||||||
val candidates = nearby.filter {
|
val candidates = nearby.filter {
|
||||||
app.klottr.util.distanceMeters(selLat, selLon, it.a, it.o) <= 40.0 &&
|
app.klottr.util.distanceMeters(selLat, selLon, it.a, it.o) <= 40.0 &&
|
||||||
kotlin.math.abs(it.c - created) <= 10_000
|
kotlin.math.abs(it.c - created) <= 10_000
|
||||||
@@ -1402,29 +1530,30 @@ fun KlottrAppShell(
|
|||||||
val match = candidates.minByOrNull { kotlin.math.abs(it.c - created) }
|
val match = candidates.minByOrNull { kotlin.math.abs(it.c - created) }
|
||||||
|
|
||||||
if (match != null) {
|
if (match != null) {
|
||||||
val labelTitle = titleText.ifBlank { match.t ?: "Klotter" } // Spara endast rubriken i “Senaste”
|
val labelTitle = titleText.ifBlank { match.t ?: "Fynd" }
|
||||||
|
|
||||||
|
// Hämta lager utifrån match (klotter, wiki, dm, fornsok, osv.)
|
||||||
|
val foundLayer = when {
|
||||||
|
match.t?.contains("Wikipedia", ignoreCase = true) == true -> "wikipedia"
|
||||||
|
match.t?.contains("Fornsök", ignoreCase = true) == true -> "fornsok"
|
||||||
|
match.t?.contains("DigitaltMuseum", ignoreCase = true) == true -> "digitaltmuseum"
|
||||||
|
else -> "klotter"
|
||||||
|
}
|
||||||
|
|
||||||
FoundStore.markFound(
|
FoundStore.markFound(
|
||||||
LAYER_KLOTTER,
|
foundLayer,
|
||||||
match.i.toString(),
|
match.i.toString(),
|
||||||
label = labelTitle,
|
label = labelTitle,
|
||||||
lat = match.a,
|
lat = match.a,
|
||||||
lon = match.o,
|
lon = match.o,
|
||||||
timeMillis = Clock.System.now().toEpochMilliseconds()
|
timeMillis = Clock.System.now().toEpochMilliseconds()
|
||||||
)
|
)
|
||||||
|
|
||||||
withContext(Dispatchers.Main) {
|
withContext(Dispatchers.Main) {
|
||||||
// TODO: OH: Nog renare om foundstore är ansvarig för att skicka FoundEvents.
|
|
||||||
FoundEvents.notifyFoundUpdated()
|
FoundEvents.notifyFoundUpdated()
|
||||||
}
|
}
|
||||||
// Tysta avisering för just detta klotter under 60s (slipper “pling” på eget klotter)
|
|
||||||
// TODO: OH: How to implement? Via foundstore?
|
|
||||||
// context.startService(
|
|
||||||
// Intent(context, LocationService::class.java)
|
|
||||||
// .setAction(LocationService.ACTION_SUPPRESS_NOTIFY)
|
|
||||||
// .putExtra("layer", LAYER_KLOTTER)
|
|
||||||
// .putExtra("id", match.i.toString())
|
|
||||||
// .putExtra("ttlMs", 60_000L) // Valfri – hur länge det ska vara tyst
|
|
||||||
// )
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (_: Throwable) { /* no-op */ }
|
} catch (_: Throwable) { /* no-op */ }
|
||||||
}
|
}
|
||||||
showWrite = false
|
showWrite = false
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ fun MapDialog(
|
|||||||
|
|
||||||
if (showKlotter) {
|
if (showKlotter) {
|
||||||
klotter = withContext(Dispatchers.IO) {
|
klotter = withContext(Dispatchers.IO) {
|
||||||
Geocache.getNearby(lat = lat, lon = lon, radiusMeters = 300, ttlMs = 0L)
|
Geocache.getNearby(lat = lat, lon = lon, ttlMs = 0L, layers = mapOf("klotter" to 20)) // 🔸 temporär placeholder
|
||||||
}
|
}
|
||||||
} else klotter = emptyList()
|
} else klotter = emptyList()
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package app.klottr.net
|
package app.klottr.net
|
||||||
|
|
||||||
import app.klottr.BuildKonfig
|
import app.klottr.BuildKonfig
|
||||||
|
import app.klottr.util.SettingsStore
|
||||||
import app.klottr.util.AuthShared
|
import app.klottr.util.AuthShared
|
||||||
import app.klottr.util.KLog
|
import app.klottr.util.KLog
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
@@ -45,10 +46,11 @@ object Geocache {
|
|||||||
suspend fun getNearby(
|
suspend fun getNearby(
|
||||||
lat: Double,
|
lat: Double,
|
||||||
lon: Double,
|
lon: Double,
|
||||||
radiusMeters: Int,
|
ttlMs: Long,
|
||||||
ttlMs: Long
|
layers: Map<String, Int>
|
||||||
): List<NoteDTO> = withContext(Dispatchers.IO) {
|
): List<NoteDTO> = withContext(Dispatchers.IO) {
|
||||||
val key = keyFor(lat, lon, radiusMeters)
|
// Cache-nyckel baserad på plats + alla lager (slug + radie)
|
||||||
|
val key = keyFor(lat, lon, layers)
|
||||||
val now = Clock.System.now().toEpochMilliseconds()
|
val now = Clock.System.now().toEpochMilliseconds()
|
||||||
|
|
||||||
// 1) Snabbträff i giltig cache
|
// 1) Snabbträff i giltig cache
|
||||||
@@ -64,9 +66,9 @@ object Geocache {
|
|||||||
val first = safeFetch(
|
val first = safeFetch(
|
||||||
lat = lat,
|
lat = lat,
|
||||||
lon = lon,
|
lon = lon,
|
||||||
radiusMeters = radiusMeters,
|
|
||||||
sinceMs = prev?.sinceMs ?: 0L,
|
sinceMs = prev?.sinceMs ?: 0L,
|
||||||
etag = prev?.etag
|
etag = prev?.etag,
|
||||||
|
layers = layers
|
||||||
)
|
)
|
||||||
if (first.code !in listOf(200, 304)) {
|
if (first.code !in listOf(200, 304)) {
|
||||||
KLog.d { "Geocache: first fetch failed code=${first.code} → fallback to cache size=${prev?.items?.size ?: 0}" }
|
KLog.d { "Geocache: first fetch failed code=${first.code} → fallback to cache size=${prev?.items?.size ?: 0}" }
|
||||||
@@ -102,11 +104,10 @@ object Geocache {
|
|||||||
val fresh = safeFetch(
|
val fresh = safeFetch(
|
||||||
lat = lat,
|
lat = lat,
|
||||||
lon = lon,
|
lon = lon,
|
||||||
radiusMeters = radiusMeters,
|
|
||||||
sinceMs = 0L,
|
sinceMs = 0L,
|
||||||
etag = null
|
etag = null,
|
||||||
|
layers = layers
|
||||||
)
|
)
|
||||||
|
|
||||||
val items = when (fresh.code) {
|
val items = when (fresh.code) {
|
||||||
200 -> fresh.items
|
200 -> fresh.items
|
||||||
304 -> prev?.items.orEmpty() // borde inte inträffa utan etag, men säkra ändå
|
304 -> prev?.items.orEmpty() // borde inte inträffa utan etag, men säkra ändå
|
||||||
@@ -130,41 +131,56 @@ object Geocache {
|
|||||||
}
|
}
|
||||||
return@withContext firstItems
|
return@withContext firstItems
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skyddad fetch som aldrig kastar – använder KlottrApiShared.nearby från KlottrApiShared.kt
|
// Skyddad fetch som aldrig kastar – använder KlottrApiShared.nearby från KlottrApiShared.kt
|
||||||
private suspend fun safeFetch(
|
private suspend fun safeFetch(
|
||||||
lat: Double,
|
lat: Double,
|
||||||
lon: Double,
|
lon: Double,
|
||||||
radiusMeters: Int,
|
|
||||||
sinceMs: Long,
|
sinceMs: Long,
|
||||||
etag: String?
|
etag: String?,
|
||||||
): NearbyResult = try {
|
layers: Map<String, Int>
|
||||||
//TODO: OH: Call Shared directly for now, until Api.kt is fully migrated.
|
): NearbyResult {
|
||||||
|
return try {
|
||||||
|
// Om inga aktiva lager finns → returnera tom lista direkt
|
||||||
|
if (layers.isEmpty()) {
|
||||||
|
return NearbyResult(code = 200, items = emptyList(), etag = etag)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skicka förfrågan till servern
|
||||||
KlottrApiShared.nearby(
|
KlottrApiShared.nearby(
|
||||||
baseUrl = BuildKonfig.SERVER_API_BASE_URL,
|
baseUrl = BuildKonfig.SERVER_API_BASE_URL,
|
||||||
apiKey = BuildKonfig.SERVER_API_KEY,
|
apiKey = BuildKonfig.SERVER_API_KEY,
|
||||||
bearerToken = AuthShared.idToken,
|
bearerToken = AuthShared.idToken,
|
||||||
lat = roundCoord(lat),
|
lat = roundCoord(lat),
|
||||||
lon = roundCoord(lon),
|
lon = roundCoord(lon),
|
||||||
radiusMeters = radiusMeters.coerceIn(50, 2000),
|
radiusMeters = 0, // används ej längre, men param krävs i KlottrApiShared
|
||||||
sinceMs = sinceMs,
|
sinceMs = sinceMs,
|
||||||
lastEtag = etag,
|
lastEtag = etag,
|
||||||
limit = 200
|
limit = 200,
|
||||||
|
layers = layers
|
||||||
)
|
)
|
||||||
} catch (_: Throwable) {
|
} catch (_: Throwable) {
|
||||||
KLog.d { "nearby.php exception → code=599 lat=$lat lon=$lon r=$radiusMeters since=$sinceMs" }
|
KLog.d { "nearby.php exception → code=599 lat=$lat lon=$lon since=$sinceMs" }
|
||||||
NearbyResult(code = 599, items = emptyList(), etag = etag)
|
NearbyResult(code = 599, items = emptyList(), etag = etag)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Samma avrundning som du redan använder i UI när du sparar
|
// Samma avrundning som du redan använder i UI när du sparar
|
||||||
private fun roundCoord(v: Double): Double = ((v * 1e6).roundToInt() / 1e6)
|
private fun roundCoord(v: Double): Double = ((v * 1e6).roundToInt() / 1e6)
|
||||||
|
|
||||||
// Bygg en nyckel av "ruta" (0.001 grad) + radius bucket (avrundad till närmaste 50 m)
|
|
||||||
// Heltalsbaserad (milligrader) för att undvika String.format (JVM-only).
|
// Heltalsbaserad (milligrader) för att undvika String.format (JVM-only).
|
||||||
private fun keyFor(lat: Double, lon: Double, radiusMeters: Int): String {
|
// Bygg cache-nyckel av plats + lager och deras radier
|
||||||
|
private fun keyFor(lat: Double, lon: Double, layers: Map<String, Int>): String {
|
||||||
val cellLatMilli = floor(lat * 1000.0).toInt()
|
val cellLatMilli = floor(lat * 1000.0).toInt()
|
||||||
val cellLonMilli = floor(lon * 1000.0).toInt()
|
val cellLonMilli = floor(lon * 1000.0).toInt()
|
||||||
val r = ((radiusMeters + 25) / 50) * 50 // 0..2000 i steg om 50
|
|
||||||
return "$cellLatMilli,$cellLonMilli|r=$r"
|
// Skapa en stabil sträng av alla lager: "klotter:20,wikipedia:100000,..."
|
||||||
|
val layersSig = layers.entries
|
||||||
|
.sortedBy { it.key }
|
||||||
|
.joinToString(",") { "${it.key}:${it.value}" }
|
||||||
|
|
||||||
|
return "$cellLatMilli,$cellLonMilli|layers=$layersSig"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -116,15 +116,37 @@ object KlottrApiShared {
|
|||||||
radiusMeters: Int,
|
radiusMeters: Int,
|
||||||
sinceMs: Long,
|
sinceMs: Long,
|
||||||
lastEtag: String?,
|
lastEtag: String?,
|
||||||
limit: Int = 200
|
limit: Int = 200,
|
||||||
|
layers: Map<String, Int>? = null // slug → radiusMeters
|
||||||
): NearbyResult {
|
): NearbyResult {
|
||||||
val url = ensureSlash(baseUrl) + "nearby.php"
|
val url = ensureSlash(baseUrl) + "nearby.php"
|
||||||
val body = NearbyBodyShared(lat = lat, lon = lon, radiusMeters = radiusMeters, since = sinceMs, limit = limit)
|
// Bygg JSON-body – nytt format med flera lager (slug → radie)
|
||||||
|
val bodyJson = buildJsonObject {
|
||||||
|
put("lat", lat)
|
||||||
|
put("lon", lon)
|
||||||
|
put("since", sinceMs)
|
||||||
|
put("limit", limit)
|
||||||
|
|
||||||
|
if (!layers.isNullOrEmpty()) {
|
||||||
|
val arr = buildJsonArray {
|
||||||
|
layers.forEach { (slug, r) ->
|
||||||
|
add(buildJsonObject {
|
||||||
|
put("slug", slug)
|
||||||
|
put("r", r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
put("layers", arr)
|
||||||
|
} else {
|
||||||
|
// Fallback – endast gemensam radie (för gamla serverversioner)
|
||||||
|
put("r", radiusMeters)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val resp = try {
|
val resp = try {
|
||||||
client.post(url) {
|
client.post(url) {
|
||||||
contentType(ContentType.Application.Json)
|
contentType(ContentType.Application.Json)
|
||||||
setBody(body)
|
setBody(bodyJson)
|
||||||
header("X-API-Key", apiKey)
|
header("X-API-Key", apiKey)
|
||||||
if (bearerToken != null) header(HttpHeaders.Authorization, "Bearer $bearerToken")
|
if (bearerToken != null) header(HttpHeaders.Authorization, "Bearer $bearerToken")
|
||||||
if (lastEtag != null) header(HttpHeaders.IfNoneMatch, lastEtag)
|
if (lastEtag != null) header(HttpHeaders.IfNoneMatch, lastEtag)
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ fun MapContent(
|
|||||||
|
|
||||||
if (showKlotter) {
|
if (showKlotter) {
|
||||||
klotter = withContext(Dispatchers.IO) {
|
klotter = withContext(Dispatchers.IO) {
|
||||||
Geocache.getNearby(lat = lat, lon = lon, radiusMeters = 300, ttlMs = 0L)
|
Geocache.getNearby(lat = lat, lon = lon, ttlMs = 0L, layers = mapOf("klotter" to 20)) // 🔸 temporär placeholder
|
||||||
}
|
}
|
||||||
} else klotter = emptyList()
|
} else klotter = emptyList()
|
||||||
|
|
||||||
|
|||||||
@@ -105,4 +105,24 @@ object SettingsStore {
|
|||||||
private fun <T> preferenceFlow(key: String, defaultValue: T): Flow<T> {
|
private fun <T> preferenceFlow(key: String, defaultValue: T): Flow<T> {
|
||||||
return MutableStateFlow(defaultValue)
|
return MutableStateFlow(defaultValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// Generiska dynamiska lager-inställningar
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
fun getLayerVisible(slug: String): Boolean {
|
||||||
|
return KvPrefs.getBoolean("layer_visible_$slug", false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setLayerVisible(slug: String, value: Boolean) {
|
||||||
|
KvPrefs.putBoolean("layer_visible_$slug", value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getLayerRadiusMeters(slug: String): Int {
|
||||||
|
return KvPrefs.getInt("layer_radius_$slug", 50)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setLayerRadiusMeters(slug: String, value: Int) {
|
||||||
|
KvPrefs.putInt("layer_radius_$slug", value)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user