feat(shared): add KMP DigitaltMuseum client and delegate Android getNearby
This commit is contained in:
@@ -53,31 +53,20 @@ object DigitaltMuseum {
|
|||||||
val apiKey = BuildConfig.DM_API_KEY.orEmpty().trim()
|
val apiKey = BuildConfig.DM_API_KEY.orEmpty().trim()
|
||||||
if (apiKey.isBlank()) return@withContext emptyList()
|
if (apiKey.isBlank()) return@withContext emptyList()
|
||||||
|
|
||||||
|
|
||||||
val owners = BuildConfig.DM_OWNERS
|
val owners = BuildConfig.DM_OWNERS
|
||||||
.orEmpty().trim()
|
.orEmpty().trim()
|
||||||
.split(',', ' ', ';')
|
.split(',', ' ', ';')
|
||||||
.map { it.trim() }
|
.map { it.trim() }
|
||||||
.filter { it.isNotEmpty() }
|
.filter { it.isNotEmpty() }
|
||||||
|
|
||||||
Log.d("DigitaltMuseum", "DM keyLen=${BuildConfig.DM_API_KEY.length}, ownersCount=${owners.size}")
|
// Delegera till delad KMP-klient (inga övriga ändringar i filen nu)
|
||||||
|
return@withContext DigitaltMuseumShared.getNearby(
|
||||||
|
apiKey = apiKey,
|
||||||
// Försök 1–3: med owners (om angivna)
|
owners = owners,
|
||||||
if (owners.isNotEmpty()) {
|
lat = lat,
|
||||||
queryWithGeo(apiKey, owners, lat, lon, radiusMeters, sfield = FIELD_COORD, useBBox = false)
|
lon = lon,
|
||||||
.ifNotEmpty { return@withContext it }
|
radiusMeters = radiusMeters
|
||||||
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()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun lookupByIdentifier(identifierId: String): DigitaltMuseumItem? = withContext(Dispatchers.IO) {
|
suspend fun lookupByIdentifier(identifierId: String): DigitaltMuseumItem? = withContext(Dispatchers.IO) {
|
||||||
|
|||||||
@@ -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<String>?,
|
||||||
|
lat: Double,
|
||||||
|
lon: Double,
|
||||||
|
radiusMeters: Int
|
||||||
|
): List<DigitaltMuseumItem> {
|
||||||
|
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<String>?,
|
||||||
|
lat: Double,
|
||||||
|
lon: Double,
|
||||||
|
radiusMeters: Int,
|
||||||
|
useBBox: Boolean
|
||||||
|
): List<DigitaltMuseumItem> = 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<DigitaltMuseumItem> {
|
||||||
|
val out = ArrayList<DigitaltMuseumItem>(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<Double, Double>? {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user