diff --git a/app/src/main/java/app/klottr/net/DigitaltMuseum.kt b/app/src/main/java/app/klottr/net/DigitaltMuseum.kt index 6a0e1d4..3365013 100644 --- a/app/src/main/java/app/klottr/net/DigitaltMuseum.kt +++ b/app/src/main/java/app/klottr/net/DigitaltMuseum.kt @@ -53,31 +53,20 @@ object DigitaltMuseum { val apiKey = BuildConfig.DM_API_KEY.orEmpty().trim() if (apiKey.isBlank()) return@withContext emptyList() - val owners = BuildConfig.DM_OWNERS .orEmpty().trim() .split(',', ' ', ';') .map { it.trim() } .filter { it.isNotEmpty() } - Log.d("DigitaltMuseum", "DM keyLen=${BuildConfig.DM_API_KEY.length}, ownersCount=${owners.size}") - - - // Försök 1–3: med owners (om angivna) - if (owners.isNotEmpty()) { - queryWithGeo(apiKey, owners, lat, lon, radiusMeters, sfield = FIELD_COORD, useBBox = false) - .ifNotEmpty { return@withContext it } - queryWithGeo(apiKey, owners, lat, lon, radiusMeters, sfield = FIELD_COORD, useBBox = true) - .ifNotEmpty { return@withContext it } - } - - // Fallback 4–5: utan owners (alla) - queryWithGeo(apiKey, null, lat, lon, radiusMeters, sfield = FIELD_COORD, useBBox = false) - .ifNotEmpty { return@withContext it } - queryWithGeo(apiKey, null, lat, lon, radiusMeters, sfield = FIELD_COORD, useBBox = true) - .ifNotEmpty { return@withContext it } - - emptyList() + // Delegera till delad KMP-klient (inga övriga ändringar i filen nu) + return@withContext DigitaltMuseumShared.getNearby( + apiKey = apiKey, + owners = owners, + lat = lat, + lon = lon, + radiusMeters = radiusMeters + ) } suspend fun lookupByIdentifier(identifierId: String): DigitaltMuseumItem? = withContext(Dispatchers.IO) { diff --git a/shared/src/commonMain/kotlin/app/klottr/net/DigitaltMuseumShared.kt b/shared/src/commonMain/kotlin/app/klottr/net/DigitaltMuseumShared.kt new file mode 100644 index 0000000..e63b35f --- /dev/null +++ b/shared/src/commonMain/kotlin/app/klottr/net/DigitaltMuseumShared.kt @@ -0,0 +1,195 @@ +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.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlin.math.abs + +/** + * DigitaltMuseum – delad (KMP) klient med Ktor. + * Vi portar endast getNearby() i detta steg. Övriga metoder i appens DigitaltMuseum.kt + * lämnas orörda och kommer fungera parallellt. + */ +object DigitaltMuseumShared { + + // Bas-URL enligt dokumentationen (Solr endpoint) + private const val BASE_URL = "https://api.dimu.org/api/solr/select" + + // Solr-fältnamn vi behöver + private const val FIELD_ID = "identifier.id" + private const val FIELD_TITLE = "artifact.ingress.title" + private const val FIELD_COORD = "artifact.coordinate" + private const val FIELD_DEFAULT_MEDIA = "artifact.defaultMediaIdentifier" + private const val FIELD_UNIQUE_ID = "artifact.uniqueId" + private const val FIELD_OWNER = "identifier.owner" + + // Vi begär endast fält vi verkligen använder + private const val FL = "$FIELD_ID,$FIELD_TITLE,$FIELD_COORD,$FIELD_DEFAULT_MEDIA,$FIELD_UNIQUE_ID,$FIELD_OWNER" + + // 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)") + } + } + } + + /** + * Publik API för delad getNearby. + * - apiKey: DM API-nyckel (krävs av DigitaltMuseum) + * - owners: lista med owners eller null/empty för alla + * - radiusMeters: används i Solr geofilt/bbox (km) + * + * Strategi (samma ordning som i appens nuvarande kod): + * 1) owners + geofilt + * 2) owners + bbox + * 3) alla + geofilt + * 4) alla + bbox + * Första icke-tomma resultat returneras; annars tom lista. + */ + suspend fun getNearby( + apiKey: String, + owners: List?, + lat: Double, + lon: Double, + radiusMeters: Int + ): List { + if (apiKey.isBlank()) return emptyList() + + // 1–2) med owners + val cleanOwners = owners?.map { it.trim() }?.filter { it.isNotEmpty() }.orEmpty() + if (cleanOwners.isNotEmpty()) { + queryWithGeo(apiKey, cleanOwners, lat, lon, radiusMeters, useBBox = false).let { if (it.isNotEmpty()) return it } + queryWithGeo(apiKey, cleanOwners, lat, lon, radiusMeters, useBBox = true).let { if (it.isNotEmpty()) return it } + } + + // 3–4) utan owners + queryWithGeo(apiKey, null, lat, lon, radiusMeters, useBBox = false).let { if (it.isNotEmpty()) return it } + queryWithGeo(apiKey, null, lat, lon, radiusMeters, useBBox = true).let { if (it.isNotEmpty()) return it } + + return emptyList() + } + + // ----- Interna hjälpmetoder ----- + + // En fråga med geofilt eller bbox + private suspend fun queryWithGeo( + apiKey: String, + owners: List?, + lat: Double, + lon: Double, + radiusMeters: Int, + useBBox: Boolean + ): List = try { + val km = (radiusMeters / 1000.0).coerceAtLeast(0.1) + // Solr local params: + // geofilt: {!geofilt sfield=artifact.coordinate pt=lat,lon d=km} + // bbox: {!bbox sfield=artifact.coordinate pt=lat,lon d=km} + val geoClause = if (useBBox) "{!bbox sfield=$FIELD_COORD pt=$lat,$lon d=$km}" + else "{!geofilt sfield=$FIELD_COORD pt=$lat,$lon d=$km}" + + val ownersFq: String? = owners?.takeIf { it.isNotEmpty() }?.joinToString(" OR ") { "identifier.owner:$it" } + + // GET mot Solr + val resp: JsonObject = client.get(BASE_URL) { + parameter("wt", "json") + parameter("fl", FL) + parameter("q", "*:*") + if (!ownersFq.isNullOrBlank()) { + parameter("fq", "($ownersFq)") + } + parameter("fq", geoClause) + parameter("rows", 50) + parameter("api.key", apiKey) + }.body() + + val response = resp["response"]?.jsonObject ?: return emptyList() + val docs = response["docs"] as? JsonArray ?: return emptyList() + parseItemsFromDocs(docs) + } catch (_: Throwable) { + emptyList() + } + + // Tolka docs-arrayen till vår modell + private fun parseItemsFromDocs(docs: JsonArray): List { + val out = ArrayList(docs.size) + for (el in docs) { + val doc = el as? JsonObject ?: continue + + val id = stringOrNull(doc, FIELD_ID) ?: continue + val title = stringOrNull(doc, FIELD_TITLE)?.takeIf { it.isNotBlank() } ?: "Okänt objekt" + val coordRaw = stringOrNull(doc, FIELD_COORD)?.trim().orEmpty() + val latLon = parseLatLon(coordRaw) ?: continue + val (lat, lon) = latLon + + val mediaId = stringOrNull(doc, FIELD_DEFAULT_MEDIA) + val thumbUrl = mediaId?.let { "https://mm.dimu.org/image/$it?dimension=400x400" } + + val uniqueId = stringOrNull(doc, FIELD_UNIQUE_ID) + val pageUrl = uniqueId?.let { "https://digitaltmuseum.se/$it" } + + val owner = stringOrNull(doc, FIELD_OWNER) + + out += DigitaltMuseumItem( + id = id, + title = title, + lat = lat, + lon = lon, + url = thumbUrl, + uniqueId = uniqueId, + webUrl = pageUrl, + owner = owner + ) + } + return out + } + + // Hämta strängfält ur JsonObject med fallback för både string och array[0] + private fun stringOrNull(obj: JsonObject, key: String): String? { + val v = obj[key] ?: return null + return when (v) { + is JsonPrimitive -> v.contentOrNull + is JsonArray -> (v.firstOrNull() as? JsonPrimitive)?.contentOrNull + else -> null + } + } + + // Stöd både "lat, lon" och "lat lon" + private fun parseLatLon(raw: String): Pair? { + if (raw.isBlank()) return null + val cleaned = raw.replace(Regex("\\s+"), " ").trim() + val parts = cleaned.split(',', ' ') + .map { it.trim() } + .filter { it.isNotEmpty() } + if (parts.size < 2) return null + val lat = parts[0].toDoubleOrNull() ?: return null + val lon = parts[1].toDoubleOrNull() ?: return null + if (!isValidLatLon(lat, lon)) return null + return lat to lon + } + + 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) + } +}