diff --git a/app/src/main/java/app/klottr/net/Fornsok.kt b/app/src/main/java/app/klottr/net/Fornsok.kt index 1d44419..78583e4 100644 --- a/app/src/main/java/app/klottr/net/Fornsok.kt +++ b/app/src/main/java/app/klottr/net/Fornsok.kt @@ -27,27 +27,8 @@ object Fornsok { lon: Double, radiusMeters: Int ): List = withContext(Dispatchers.IO) { - - val bbox = bboxWgs84(lat, lon, radiusMeters) - app.klottr.util.AppLog.d(TAG) - { "BBox W,S,E,N = ${fmt6(bbox.w)} ${fmt6(bbox.s)} ${fmt6(bbox.e)} ${fmt6(bbox.n)} (radie=${radiusMeters} m)" } - - val cqlBase = - """boundingBox=/WGS84 "${fmt8(bbox.w)} ${fmt8(bbox.s)} ${fmt8(bbox.e)} ${fmt8(bbox.n)}" AND geoDataExists="j" AND (serviceName="kmr_lamningar" OR serviceName="fmi")""" - app.klottr.util.AppLog.d(TAG) { "CQL = $cqlBase"} - - // Fas 1: presentation (snabb) - val fast = queryAndParse(cqlBase, usePresentation = true, maxPages = MAX_PAGES_FAST) - if (fast.isNotEmpty()) { - app.klottr.util.AppLog.d(TAG) { "FÄRDIGA FORNSÖK-OBJEKT (presentation): ${fast.size} st"} - return@withContext fast - } - - // Fas 2: fullt schema (utan recordSchema) - app.klottr.util.AppLog.d(TAG) { "Inga coords via presentation – provar fullt schema (utan recordSchema)."} - val full = queryAndParse(cqlBase, usePresentation = false, maxPages = MAX_PAGES_FALLBACK) - app.klottr.util.AppLog.d(TAG) { "FÄRDIGA FORNSÖK-OBJEKT (fullt schema): ${full.size} st"} - return@withContext full + // Delegerar till delad KMP-klient (FornsokShared) – ingen övrig beteendeförändring här. + return@withContext FornsokShared.getNearby(lat, lon, radiusMeters) } // För detaljrutan från Hittat: hämta titel + desc + coords för ett känt entityUri diff --git a/shared/src/commonMain/kotlin/app/klottr/net/FornsokShared.kt b/shared/src/commonMain/kotlin/app/klottr/net/FornsokShared.kt new file mode 100644 index 0000000..eec04c1 --- /dev/null +++ b/shared/src/commonMain/kotlin/app/klottr/net/FornsokShared.kt @@ -0,0 +1,459 @@ +package app.klottr.net + +import io.ktor.client.HttpClient +import io.ktor.client.call.body +import io.ktor.client.plugins.DefaultRequest +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.request.get +import io.ktor.client.request.parameter +import io.ktor.serialization.kotlinx.json.json +import kotlinx.serialization.json.* +import kotlinx.serialization.json.contentOrNull +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.round + +/** + * Fornsök – delad (KMP) klient med Ktor + kotlinx.serialization (JsonObject/JsonArray). + * Vi portar ENDAST getNearby() i detta steg. Övriga metoder i appens Fornsok.kt lämnas orörda. + * + * Målet: funktionsmässigt spegla din befintliga getNearby: + * - Bygger bbox i WGS84 + * - Försöker först "presentation"-schema (snabbt), sedan "fullt schema" + * - Skannar JSON efter koordinater robust (pres:itemPosition, pres:coordinates, gml, etc.) + * - Returnerar alltid en lista, kastar inte exception (emptyList vid fel) + */ + +object FornsokShared { + + // ==== Konstanter (speglar din Fornsok.kt) ==== + private const val TAG = "FornsokShared" + private const val BASE = "https://kulturarvsdata.se/ksamsok/api" + private const val HITS = 200 + private const val MAX_PAGES_FAST = 3 + private const val MAX_PAGES_FALLBACK = 3 + + // Ktor-klient (återanvänds) + private val client by lazy { + HttpClient(platformEngine()) { + install(ContentNegotiation) { + json(Json { + ignoreUnknownKeys = true + isLenient = true + }) + } + install(DefaultRequest) { + headers.append("User-Agent", "Klottr/0.3.0 (KMP)") + headers.append("Accept", "application/json") + } + } + } + + // ==== Publikt API ==== + + suspend fun getNearby( + lat: Double, + lon: Double, + radiusMeters: Int + ): List { + val bbox = bboxWgs84(lat, lon, radiusMeters) + + val cqlBase = + """boundingBox=/WGS84 "${fmt8(bbox.w)} ${fmt8(bbox.s)} ${fmt8(bbox.e)} ${fmt8(bbox.n)}" AND geoDataExists="j" AND (serviceName="kmr_lamningar" OR serviceName="fmi")""" + + // 1) presentation (snabb) + queryAndParse(cqlBase, usePresentation = true, maxPages = MAX_PAGES_FAST).let { if (it.isNotEmpty()) return it } + + // 2) fullt schema + return queryAndParse(cqlBase, usePresentation = false, maxPages = MAX_PAGES_FALLBACK) + } + + // ==== HTTP + parse ==== + + private suspend fun queryAndParse(cql: String, usePresentation: Boolean, maxPages: Int): List { + val out = LinkedHashMap() + var start = 1 + var page = 1 + var totalHitsFromServer = -1 + + while (page <= maxPages) { + val resp: JsonObject = client.get(BASE) { + parameter("version", "1.1") + parameter("method", "search") + parameter("hitsPerPage", HITS) + parameter("startRecord", start) + if (usePresentation) { + parameter("recordSchema", "presentation") + parameter( + "fields", + "pres:entityUri,pres:id,pres:itemPosition,pres:coordinates,pres:latitude,pres:longitude,pres:title,pres:itemLabel,pres:service,serviceName,pres:description" + ) + } + // Viktigt: ersätt inte blanktecken manuellt; Ktor URL-enkodar korrekt. + parameter("query", cql) + }.body() + + val result = resp["result"]?.jsonObject ?: break + if (totalHitsFromServer < 0) { + totalHitsFromServer = result["totalHits"]?.jsonPrimitive?.intOrNull ?: -1 + } + + // result.records.record kan vara array ELLER objekt + val recordsNode = result["records"] + val recordArr: List = when (recordsNode) { + is JsonObject -> { + val r = recordsNode["record"] + when (r) { + is JsonArray -> r.mapNotNull { it as? JsonObject } + is JsonObject -> listOf(r) + else -> emptyList() + } + } + else -> emptyList() + } + if (recordArr.isEmpty()) break + + var added = 0 + for (rec in recordArr) { + val svc = (findStringDeep(rec, "serviceName") + ?: findStringDeep(rec, "pres:service")) + ?.lowercase() + + val entityUri = findStringDeep(rec, "pres:entityUri") + ?: findStringDeep(rec, "entityUri") + ?: findStringDeep(rec, "item") + + val presId = findStringDeep(rec, "pres:id") + + val ll = if (usePresentation) { + extractLatLonPresentation(rec) ?: extractLatLonGeneric(rec) + } else { + extractLatLonGeneric(rec) + } ?: continue + val (latV, lonV) = ll + + val looksFornsok = when { + svc == "kmr_lamningar" || svc == "fmi" -> true + entityUri?.contains("/raa/fmi/", true) == true -> true + entityUri?.contains("/raa/fmis/", true) == true -> true + entityUri?.contains("/raa/lamning/", true) == true -> true + entityUri?.contains("/raa/fornsok", true) == true -> true + else -> false + } + if (!looksFornsok) continue + + val title = findStringDeep(rec, "pres:itemLabel") + ?: findStringDeep(rec, "pres:title") + ?: findStringDeep(rec, "title") + ?: findStringDeep(rec, "label") + ?: "Fornlämning" + val description = findStringDeep(rec, "pres:description") + + val id = when { + entityUri != null -> entityUri + presId != null -> "kmr:$presId" + else -> "${title}@${fmt6(latV)},${fmt6(lonV)}" + } + + if (!out.containsKey(id)) { + out[id] = FornsokItem( + id = id, + title = title, + lat = latV, + lon = lonV, + uri = entityUri, + serviceName = svc, + desc = description + ) + added++ + } + } + + // Fler sidor? + if (totalHitsFromServer > 0) { + val maxByHits = (totalHitsFromServer + HITS - 1) / HITS + if (page >= maxByHits) break + } + start += HITS + page++ + + if (out.size >= 150) break + } + + return out.values.toList() + } + + // ==== Lat/Lon extraktion (presentation/generisk) ==== + + /** Presentation-schema – vägar inkl. gml:coordinates.content och gml:pos/posList. */ + private fun extractLatLonPresentation(rec: JsonObject): Pair? { + // 1) pres:itemPosition = "POINT(lon lat)" + findStringDeep(rec, "pres:itemPosition")?.let { pos -> + parseWktPoint(pos)?.let { (lon, lat) -> return lat to lon } + } + // 2) pres:coordinates = [{lat:.., lon|lng:..}, ...] + findArrayDeep(rec, "pres:coordinates")?.firstOrNull()?.jsonObject?.let { c0 -> + val lat = numOrNull(c0["lat"]) ?: numOrNull(c0["latitude"]) + val lon = numOrNull(c0["lon"]) ?: numOrNull(c0["lng"]) ?: numOrNull(c0["longitude"]) + if (lat != null && lon != null) return lat to lon + } + // 3) pres:latitude/pres:longitude + val latStr = findStringDeep(rec, "pres:latitude") + val lonStr = findStringDeep(rec, "pres:longitude") + if (!latStr.isNullOrBlank() && !lonStr.isNullOrBlank()) { + val la = latStr.replace(",", ".").toDoubleOrNull() + val lo = lonStr.replace(",", ".").toDoubleOrNull() + if (la != null && lo != null) return la to lo + } + // 4) gml:coordinates → objekt med content: "lon, lat" + findObjectDeep(rec, "gml:coordinates")?.get("content")?.jsonPrimitive?.contentOrNull?.let { content -> + parseLonLat(content)?.let { (lon, lat) -> return lat to lon } + } + // 5) gml:pos/gml:posList + findStringDeep(rec, "gml:pos")?.let { parsePosOrPosList(it)?.let { p -> return p } } + findStringDeep(rec, "gml:posList")?.let { parsePosOrPosList(it)?.let { p -> return p } } + return null + } + + /** Generisk sökning efter lat/lon i godtycklig JSON-struktur. */ + private fun extractLatLonGeneric(node: JsonElement?): Pair? { + return scanForLatLon(node)?.takeIf { isValidLatLon(it.first, it.second) } + } + + /** Rekursiv sökning efter lat/lon (WKT, gml, {lat,lon}, arr[2], etc.). */ + private fun scanForLatLon(node: JsonElement?): Pair? { + when (node) { + is JsonObject -> { + for ((k, v) in node) { + // WKT POINT(lon lat) + if (v is JsonPrimitive && v.isString && v.content.contains("POINT", true)) { + parseWktPoint(v.content)?.let { (lon, lat) -> + if (isValidLatLon(lat, lon)) return lat to lon + } + } + + // "*coordinates*" + if (k.endsWith("coordinates", true)) { + when (v) { + is JsonPrimitive -> { + v.contentOrNull?.let { s -> + parseLonLat(s)?.let { (lon, lat) -> + if (isValidLatLon(lat, lon)) return lat to lon + } + } + } + is JsonObject -> { + v["content"]?.jsonPrimitive?.contentOrNull?.let { s -> + parseLonLat(s)?.let { (lon, lat) -> + if (isValidLatLon(lat, lon)) return lat to lon + } + } + } + is JsonArray -> { + // hanteras via rekursion nedan + } + else -> { /* ignore */ } + } + } + + // gml:pos / gml:posList + if (k.endsWith("pos", true) || k.endsWith("posList", true)) { + when (v) { + is JsonPrimitive -> v.contentOrNull?.let { parsePosOrPosList(it)?.let { p -> return p } } + is JsonObject -> v["content"]?.jsonPrimitive?.contentOrNull?.let { parsePosOrPosList(it)?.let { p -> return p } } + else -> { /* ignore */ } + } + } + + // Objekt med {lat, lon|long|lng|...} + if (v is JsonObject) { + val lat = numOrNull(v["lat"]) + ?: numOrNull(v["latitude"]) + ?: numOrNull(v["wgs84_pos:lat"]) + val lon = numOrNull(v["lon"]) + ?: numOrNull(v["lng"]) + ?: numOrNull(v["long"]) + ?: numOrNull(v["longitude"]) + ?: numOrNull(v["wgs84_pos:long"]) + if (lat != null && lon != null && isValidLatLon(lat, lon)) return lat to lon + } + + // Rekursion + scanForLatLon(v)?.let { return it } + } + } + + is JsonArray -> { + // [lon, lat] eller [lat, lon] + if (node.size >= 2) { + if (node.size % 2 == 0) { + val a0 = numOrNull(node.getOrNull(0)) + val a1 = numOrNull(node.getOrNull(1)) + if (a0 != null && a1 != null) { + if (isValidLatLon(a1, a0)) return a1 to a0 + if (isValidLatLon(a0, a1)) return a0 to a1 + } + } + for (el in node) { + scanForLatLon(el)?.let { return it } + } + } + } + + is JsonPrimitive -> { + // Top-level sträng som råkar vara WKT "POINT(lon lat)" + if (node.isString && node.content.contains("POINT", true)) { + parseWktPoint(node.content)?.let { (lon, lat) -> + if (isValidLatLon(lat, lon)) return lat to lon + } + } + } + + else -> { /* täcker null och övrigt */ } + } + return null + } + + + // ==== Utils (bbox, parse, sök) ==== + + private data class BBox(val w: Double, val s: Double, val e: Double, val n: Double) + + private fun bboxWgs84(lat: Double, lon: Double, rMeters: Int): BBox { + val r = rMeters.coerceAtLeast(1) + val dLat = r / 111_320.0 + val dLon = r / (111_320.0 * cos(lat * PI / 180.0)).coerceAtLeast(1e-6) + return BBox( + w = lon - dLon, + s = lat - dLat, + e = lon + dLon, + n = lat + dLat + ) + } + + // Rekursiv sökning efter strängfält med nyckeln [key] – uttömmande when (else täcker null/övrigt) + private fun findStringDeep(node: JsonElement?, key: String): String? { + return when (node) { + is JsonObject -> { + node[key]?.let { v -> + if (v is JsonPrimitive && v.isString) return v.content + } + for ((_, v) in node) { + val r = findStringDeep(v, key) + if (r != null) return r + } + null + } + is JsonArray -> { + for (v in node) { + val r = findStringDeep(v, key) + if (r != null) return r + } + null + } + else -> null // täcker null och andra JsonElement-typer + } + } + + // Rekursiv sökning efter objektfält – uttömmande when + private fun findObjectDeep(node: JsonElement?, key: String): JsonObject? { + return when (node) { + is JsonObject -> { + node[key]?.let { v -> if (v is JsonObject) return v } + for ((_, v) in node) { + val r = findObjectDeep(v, key) + if (r != null) return r + } + null + } + is JsonArray -> { + for (v in node) { + val r = findObjectDeep(v, key) + if (r != null) return r + } + null + } + else -> null + } + } + + // Rekursiv sökning efter arrayfält – uttömmande when + private fun findArrayDeep(node: JsonElement?, key: String): JsonArray? { + return when (node) { + is JsonObject -> { + node[key]?.let { v -> if (v is JsonArray) return v } + for ((_, v) in node) { + val r = findArrayDeep(v, key) + if (r != null) return r + } + null + } + is JsonArray -> { + for (v in node) { + val r = findArrayDeep(v, key) + if (r != null) return r + } + null + } + else -> null + } + } + + private fun parseWktPoint(s: String): Pair? { + val idx = s.indexOf("POINT", ignoreCase = true) + if (idx < 0) return null + val open = s.indexOf('(', idx) + val close = s.indexOf(')', open + 1) + if (open < 0 || close < 0) return null + val inner = s.substring(open + 1, close).trim() + val parts = inner.split(Regex("\\s+")) + if (parts.size >= 2) { + val lon = parts[0].replace(",", ".").toDoubleOrNull() + val lat = parts[1].replace(",", ".").toDoubleOrNull() + if (lon != null && lat != null) return Pair(lon, lat) + } + return null + } + + private fun parseLonLat(txt: String): Pair? { + val cleaned = txt.replace(";", ",").trim() + val parts = cleaned.split(",") + if (parts.size >= 2) { + val lon = parts[0].trim().replace(",", ".").toDoubleOrNull() + val lat = parts[1].trim().replace(",", ".").toDoubleOrNull() + if (lon != null && lat != null) return lon to lat + } + return null + } + + /** Tolkar gml:pos/gml:posList (första paret). Hanterar både "lon lat" och "lat lon". */ + private fun parsePosOrPosList(s: String): Pair? { + val parts = s.trim().split(Regex("\\s+")) + if (parts.size >= 2) { + val a = parts[0].replace(",", ".").toDoubleOrNull() + val b = parts[1].replace(",", ".").toDoubleOrNull() + if (a != null && b != null) { + if (isValidLatLon(b, a)) return b to a + if (isValidLatLon(a, b)) return a to b + } + } + return null + } + + private fun isValidLatLon(lat: Double, lon: Double): Boolean { + return lat in -90.0..90.0 && lon in -180.0..180.0 && !(abs(lat) < 1e-9 && abs(lon) < 1e-9) + } + + private fun numOrNull(el: JsonElement?): Double? { + val p = el?.jsonPrimitive ?: return null + return when { + p.isString -> p.content.replace(",", ".").toDoubleOrNull() + else -> p.doubleOrNull + } + } + + // Fasta decimaler behövs inte – men vi rundar till 6/8 för finare CQL/ID + private fun fmt6(d: Double): String = (round(d * 1e6) / 1e6).toString() + private fun fmt8(d: Double): String = (round(d * 1e8) / 1e8).toString() +}