feat(shared): add DM lookupByIdentifier/getDetailText and delegate Android DigitaltMuseum to shared Ktor client
refactor(app): switch image stream to ByteArray and delegate get_image.php to shared client chore(app): remove OkHttp dependency after DM migration to shared docs(shared): add thorough comments to DigitaltMuseumShared (no logic changes)
This commit is contained in:
@@ -95,8 +95,7 @@ dependencies {
|
||||
debugImplementation("androidx.compose.ui:ui-tooling")
|
||||
implementation("com.google.android.material:material:1.12.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.9.0")
|
||||
// --- Nätverk ---
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
|
||||
// Google Maps (Compose + Play Services)
|
||||
implementation("com.google.maps.android:maps-compose:4.4.1")
|
||||
implementation("com.google.android.gms:play-services-maps:18.2.0")
|
||||
|
||||
@@ -711,8 +711,9 @@ private fun KlottrApp(
|
||||
val img = detail.image
|
||||
if (img != null && img.id > 0 && ImageBitmapCache.get(img.id) == null) {
|
||||
withContext(Dispatchers.IO) {
|
||||
fetchImageStreamPost(img.id, detail.id, f.lat, f.lon)?.byteStream()?.use { ins ->
|
||||
BitmapFactory.decodeStream(ins)?.let { bmp ->
|
||||
fetchImageStreamPost(img.id, detail.id, f.lat, f.lon)?.let { bytes ->
|
||||
val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
if (bmp != null) {
|
||||
ImageBitmapCache.put(img.id, bmp)
|
||||
}
|
||||
}
|
||||
@@ -2161,16 +2162,15 @@ private fun KlotterDialog(
|
||||
// Bild: hämta via POST (GDPR-fix), tunga saker i IO — uppdatera UI på huvudtråden.
|
||||
val imgMeta = detail.image
|
||||
if (imgMeta != null && imgMeta.id > 0) {
|
||||
|
||||
// 1) Nätverk + bitmap-dekodning i IO
|
||||
val bmp = withContext(Dispatchers.IO) {
|
||||
fetchImageStreamPost(
|
||||
imageId = imgMeta.id,
|
||||
noteId = detail.id,
|
||||
lat = lat, // NOTISENS lat (servern kräver koordinat-bevis)
|
||||
lon = lon // NOTISENS lon
|
||||
)?.byteStream()?.use { ins ->
|
||||
BitmapFactory.decodeStream(ins)
|
||||
lat = lat,
|
||||
lon = lon
|
||||
)?.let { bytes ->
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,10 +5,7 @@ import android.net.Uri
|
||||
import app.klottr.BuildConfig
|
||||
import app.klottr.net.KlottrApiShared
|
||||
import app.klottr.util.Auth
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import java.io.File
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
|
||||
/**
|
||||
* Läser bas‑URL och API‑nyckel från BuildConfig (hålls i local.properties → buildConfigField).
|
||||
@@ -358,14 +355,14 @@ suspend fun setUsernameRemote(input: String): UsernameSetResp? {
|
||||
return sh
|
||||
}
|
||||
|
||||
/** Hämta bildström via delad KMP-klient (form-POST) och bygg ResponseBody */
|
||||
/** Hämta bildbytes via delad KMP-klient (form-POST) */
|
||||
suspend fun fetchImageStreamPost(
|
||||
imageId: Long,
|
||||
noteId: Long,
|
||||
lat: Double,
|
||||
lon: Double
|
||||
): ResponseBody? {
|
||||
val bytes = try {
|
||||
): ByteArray? {
|
||||
return try {
|
||||
KlottrApiShared.getImageStreamPost(
|
||||
baseUrl = ApiConfig.SERVER_API_BASE_URL,
|
||||
apiKey = ApiConfig.SERVER_API_KEY,
|
||||
@@ -378,8 +375,5 @@ suspend fun fetchImageStreamPost(
|
||||
} catch (t: Throwable) {
|
||||
app.klottr.util.AppLog.d { "get_image exception: ${t.message}" }
|
||||
null
|
||||
} ?: return null
|
||||
|
||||
// Okänd MIME → använd generisk
|
||||
return bytes.toResponseBody("application/octet-stream".toMediaTypeOrNull())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,50 +1,11 @@
|
||||
package app.klottr.net
|
||||
|
||||
import android.util.Log
|
||||
import app.klottr.BuildConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.math.max
|
||||
|
||||
object DigitaltMuseum {
|
||||
|
||||
// Bas-URL enligt dokumentationen
|
||||
private const val BASE_URL = "https://api.dimu.org/api/solr/select"
|
||||
|
||||
// Solr-fältnamn enligt dokumentationen
|
||||
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 faktiskt använder (kan utökas vid behov)
|
||||
private const val FL =
|
||||
"$FIELD_ID,$FIELD_TITLE,$FIELD_COORD,$FIELD_DEFAULT_MEDIA,$FIELD_UNIQUE_ID,$FIELD_OWNER"
|
||||
|
||||
|
||||
// Rimliga tidsgränser
|
||||
private val http by lazy {
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(6, TimeUnit.SECONDS)
|
||||
.readTimeout(8, TimeUnit.SECONDS)
|
||||
.writeTimeout(6, TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Hämtar närliggande DM-objekt via Solr geofilt.
|
||||
* Kräver att BuildConfig.DM_API_KEY och BuildConfig.DM_OWNERS är satta.
|
||||
*/
|
||||
|
||||
suspend fun getNearby(
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
@@ -59,8 +20,7 @@ object DigitaltMuseum {
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
|
||||
// Delegera till delad KMP-klient (inga övriga ändringar i filen nu)
|
||||
return@withContext DigitaltMuseumShared.getNearby(
|
||||
DigitaltMuseumShared.getNearby(
|
||||
apiKey = apiKey,
|
||||
owners = owners,
|
||||
lat = lat,
|
||||
@@ -72,395 +32,20 @@ object DigitaltMuseum {
|
||||
suspend fun lookupByIdentifier(identifierId: String): DigitaltMuseumItem? = withContext(Dispatchers.IO) {
|
||||
val apiKey = BuildConfig.DM_API_KEY.orEmpty().trim()
|
||||
if (apiKey.isBlank()) return@withContext null
|
||||
|
||||
val url = "https://api.dimu.org/api/solr/select".toHttpUrlOrNull()?.newBuilder()
|
||||
?.addQueryParameter("wt", "json")
|
||||
?.addQueryParameter("q", "identifier.id:\"$identifierId\"")
|
||||
?.addQueryParameter("fl", "$FIELD_ID,$FIELD_TITLE,$FIELD_COORD,$FIELD_DEFAULT_MEDIA,$FIELD_UNIQUE_ID,$FIELD_OWNER")
|
||||
?.addQueryParameter("rows", "1")
|
||||
?.addQueryParameter("api.key", apiKey)
|
||||
?.build() ?: return@withContext null
|
||||
|
||||
val req = Request.Builder().url(url).get().build()
|
||||
try {
|
||||
http.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return@withContext null
|
||||
val body = resp.body?.string().orEmpty()
|
||||
val root = JSONObject(body)
|
||||
val doc = root.optJSONObject("response")?.optJSONArray("docs")?.optJSONObject(0) ?: return@withContext null
|
||||
|
||||
val id = doc.optString(FIELD_ID).takeIf { it.isNotBlank() } ?: return@withContext null
|
||||
val title = doc.optString(FIELD_TITLE).ifBlank { "DigitaltMuseum" }
|
||||
val coordRaw = doc.optString(FIELD_COORD)
|
||||
val ll = parseLatLon(coordRaw) ?: return@withContext null
|
||||
|
||||
val mediaId = doc.optString(FIELD_DEFAULT_MEDIA).ifBlank { null }
|
||||
val thumbUrl = mediaId?.let { "https://mm.dimu.org/image/$it?dimension=400x400" }
|
||||
val uniqueId = doc.optString(FIELD_UNIQUE_ID).ifBlank { null }
|
||||
val pageUrl = uniqueId?.let { "https://digitaltmuseum.se/$it" }
|
||||
val owner = doc.optString(FIELD_OWNER).ifBlank { null }
|
||||
|
||||
DigitaltMuseumItem(
|
||||
id = id,
|
||||
title = title,
|
||||
lat = ll.first,
|
||||
lon = ll.second,
|
||||
url = thumbUrl,
|
||||
uniqueId = uniqueId,
|
||||
webUrl = pageUrl,
|
||||
owner = owner
|
||||
DigitaltMuseumShared.lookupByIdentifier(
|
||||
apiKey = apiKey,
|
||||
identifierId = identifierId
|
||||
)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private inline fun <T> List<T>.ifNotEmpty(block: (List<T>) -> Unit): List<T> {
|
||||
if (this.isNotEmpty()) block(this)
|
||||
return this
|
||||
}
|
||||
|
||||
private fun queryWithGeo(
|
||||
apiKey: String,
|
||||
owners: List<String>?, // kan vara null = alla owners
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
radiusMeters: Int,
|
||||
sfield: String,
|
||||
useBBox: Boolean
|
||||
): List<DigitaltMuseumItem> {
|
||||
val url = buildUrl(apiKey, owners, lat, lon, radiusMeters, sfield, useBBox) ?: return emptyList()
|
||||
Log.d("DigitaltMuseum", "DM URL=$url (sfield=$sfield, bbox=$useBBox)")
|
||||
val req = Request.Builder().url(url).get().build()
|
||||
return try {
|
||||
http.newCall(req).execute().use { resp ->
|
||||
val code = resp.code
|
||||
val body = resp.body?.string().orEmpty()
|
||||
if (!resp.isSuccessful) {
|
||||
Log.w("DigitaltMuseum", "DM HTTP $code (sfield=$sfield, bbox=$useBBox)")
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
val root = try { JSONObject(body) } catch (t: Throwable) {
|
||||
Log.w("DigitaltMuseum", "DM JSON parse misslyckades: ${t.message}")
|
||||
return emptyList()
|
||||
}
|
||||
val response = root.optJSONObject("response")
|
||||
val docsArr = response?.optJSONArray("docs")
|
||||
val numFound = response?.optInt("numFound") ?: -1
|
||||
val docsLen = docsArr?.length() ?: 0
|
||||
Log.d("DigitaltMuseum", "DM numFound=$numFound docsLen=$docsLen (sfield=$sfield, bbox=$useBBox)")
|
||||
|
||||
if (docsLen == 0) return emptyList()
|
||||
|
||||
val items = parseItemsFromDocs(docsArr!!)
|
||||
Log.d("DigitaltMuseum", "DM parsed=${items.size} (sfield=$sfield, bbox=$useBBox)")
|
||||
return items
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w("DigitaltMuseum", "DM queryWithGeo failed ($sfield, bbox=$useBBox): ${t.message}")
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseItemsFromDocs(docs: org.json.JSONArray): List<DigitaltMuseumItem> {
|
||||
val out = ArrayList<DigitaltMuseumItem>()
|
||||
for (i in 0 until docs.length()) {
|
||||
val doc = docs.optJSONObject(i) ?: continue
|
||||
|
||||
val idRaw = doc.optString(FIELD_ID)
|
||||
if (idRaw.isBlank()) continue
|
||||
val id = idRaw
|
||||
|
||||
val title = doc.optString(FIELD_TITLE).ifBlank { "Okänt objekt" }
|
||||
|
||||
val coordRaw = doc.optString(FIELD_COORD).trim()
|
||||
val latLon = parseLatLon(coordRaw) ?: continue
|
||||
val (lat, lon) = latLon
|
||||
|
||||
|
||||
val mediaId = doc.optString(FIELD_DEFAULT_MEDIA).ifBlank { null }
|
||||
val thumbUrl = mediaId?.let { "https://mm.dimu.org/image/$it?dimension=400x400" }
|
||||
|
||||
val uniqueId = doc.optString(FIELD_UNIQUE_ID).ifBlank { null }
|
||||
val pageUrl = uniqueId?.let { "https://digitaltmuseum.se/$it" }
|
||||
|
||||
val owner = doc.optString(FIELD_OWNER).ifBlank { null }
|
||||
|
||||
|
||||
out += DigitaltMuseumItem(
|
||||
id = id,
|
||||
title = title,
|
||||
lat = lat,
|
||||
lon = lon,
|
||||
url = thumbUrl,
|
||||
webUrl = pageUrl,
|
||||
owner = owner
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun buildUrl(
|
||||
apiKey: String,
|
||||
owners: List<String>?, // null = alla owners
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
radiusMeters: Int,
|
||||
sfield: String,
|
||||
useBBox: Boolean
|
||||
): HttpUrl? {
|
||||
val km = (radiusMeters / 1000.0).coerceAtLeast(0.1)
|
||||
val geoClause = if (useBBox) {
|
||||
"{!bbox sfield=$sfield pt=$lat,$lon d=$km}"
|
||||
} else {
|
||||
"{!geofilt sfield=$sfield pt=$lat,$lon d=$km}"
|
||||
}
|
||||
|
||||
return BASE_URL.toHttpUrlOrNull()?.newBuilder()
|
||||
?.addQueryParameter("wt", "json")
|
||||
?.addQueryParameter("fl", FL)
|
||||
?.addQueryParameter("q", "*:*")
|
||||
?.apply {
|
||||
val list = owners?.filter { it.isNotBlank() }.orEmpty()
|
||||
if (list.isNotEmpty()) {
|
||||
val ownersFq = list.joinToString(" OR ") { "identifier.owner:$it" }
|
||||
addQueryParameter("fq", "($ownersFq)")
|
||||
}
|
||||
}
|
||||
?.addQueryParameter("fq", geoClause)
|
||||
?.addQueryParameter("rows", "50")
|
||||
?.addQueryParameter("api.key", apiKey)
|
||||
?.build()
|
||||
}
|
||||
|
||||
private fun parseLatLon(raw: String): Pair<Double, Double>? {
|
||||
if (raw.isBlank()) return null
|
||||
// Stöd både "lat, lon" och "lat lon"
|
||||
val cleaned = raw.replace("\\s+".toRegex(), " ").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
|
||||
return lat to lon
|
||||
}
|
||||
|
||||
suspend fun getDetailText(uniqueId: String?, owner: String?, identifierId: String): String? = withContext(Dispatchers.IO) {
|
||||
val apiKey = BuildConfig.DM_API_KEY.orEmpty().trim()
|
||||
if (apiKey.isBlank()) return@withContext null
|
||||
|
||||
// 1) Via uniqueId (snabbast)
|
||||
if (!uniqueId.isNullOrBlank()) {
|
||||
extractFromSimpleJson(uniqueId, apiKey)?.let { if (it.isNotBlank()) return@withContext it }
|
||||
// Sverige först
|
||||
extractFromEse(uniqueId, apiKey)?.let { if (it.isNotBlank()) return@withContext it }
|
||||
// Norge sen
|
||||
extractFromAbm(uniqueId, apiKey)?.let { if (it.isNotBlank()) return@withContext it }
|
||||
}
|
||||
|
||||
// 2) Fallback: owner + identifier (om uniqueId saknades)
|
||||
if (!owner.isNullOrBlank()) {
|
||||
extractFromSimpleJsonByOwnerId(owner, identifierId, apiKey)?.let { if (it.isNotBlank()) return@withContext it }
|
||||
// Sverige först
|
||||
extractFromEseByOwnerId(owner, identifierId, apiKey)?.let { if (it.isNotBlank()) return@withContext it }
|
||||
// Norge sen
|
||||
extractFromAbmByOwnerId(owner, identifierId, apiKey)?.let { if (it.isNotBlank()) return@withContext it }
|
||||
}
|
||||
|
||||
null
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** Enklaste heuristik: försök hitta fält som heter description/history/etc. */
|
||||
private fun extractBestTextFromSimpleJson(json: String): String? {
|
||||
return try {
|
||||
val root = JSONObject(json)
|
||||
|
||||
fun optStringPath(obj: JSONObject, path: String): String? {
|
||||
var cur: Any? = obj
|
||||
val parts = path.split('.')
|
||||
for (p in parts) {
|
||||
if (cur !is JSONObject) return null
|
||||
cur = cur.opt(p)
|
||||
}
|
||||
return (cur as? String)?.trim()?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
// Prioritet: 1) history.description 2) description 3) motif.description 4) otherInformation
|
||||
val ordered = listOf(
|
||||
optStringPath(root, "history.description"),
|
||||
optStringPath(root, "description"),
|
||||
optStringPath(root, "motif.description"),
|
||||
optStringPath(root, "otherInformation")
|
||||
).filterNotNull()
|
||||
|
||||
// Returnera första icke-tomma (trimma och begränsa längden)
|
||||
ordered.firstOrNull()?.take(4000)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun extractFromSimpleJson(uniqueId: String, apiKey: String): String? {
|
||||
val url = "https://api.dimu.org/api/artifact".toHttpUrlOrNull()?.newBuilder()
|
||||
?.addQueryParameter("unique_id", uniqueId)
|
||||
?.addQueryParameter("mapping", "simple_json")
|
||||
?.addQueryParameter("api.key", apiKey)
|
||||
?.build() ?: return null
|
||||
|
||||
val req = Request.Builder().url(url).get().build()
|
||||
return try {
|
||||
http.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val body = resp.body?.string().orEmpty()
|
||||
if (body.isBlank()) return null
|
||||
extractBestTextFromSimpleJson(body)
|
||||
}
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
|
||||
private fun extractFromAbm(uniqueId: String, apiKey: String): String? {
|
||||
val url = "https://api.dimu.org/api/artifact".toHttpUrlOrNull()?.newBuilder()
|
||||
?.addQueryParameter("unique_id", uniqueId)
|
||||
?.addQueryParameter("mapping", "ABM")
|
||||
?.addQueryParameter("api.key", apiKey)
|
||||
?.build() ?: return null
|
||||
|
||||
val req = Request.Builder().url(url).get().build()
|
||||
return try {
|
||||
http.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val xml = resp.body?.string().orEmpty()
|
||||
if (xml.isBlank()) return null
|
||||
// Plocka vanliga beskrivningsfält i ABM (Norwegiana) – tar första icke-tomma.
|
||||
extractTextFromXml(
|
||||
xml,
|
||||
// typiska vägar/elementnamn vi ser i ABM/Norvegiana
|
||||
listOf(
|
||||
// dcterms:description eller dc:description
|
||||
Regex("<(?:dcterms:|dc:)?description[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?description>", RegexOption.IGNORE_CASE),
|
||||
// ev. “history” i ABM-varianter
|
||||
Regex("<(?:abm:)?history[^>]*>([\\s\\S]*?)</(?:abm:)?history>", RegexOption.IGNORE_CASE),
|
||||
// fallback: “note”/”beskrivelse”
|
||||
Regex("<(?:abm:)?beskrivelse[^>]*>([\\s\\S]*?)</(?:abm:)?beskrivelse>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:dcterms:|dc:)?subject[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?subject>", RegexOption.IGNORE_CASE)
|
||||
DigitaltMuseumShared.getDetailText(
|
||||
apiKey = apiKey,
|
||||
uniqueId = uniqueId,
|
||||
owner = owner,
|
||||
identifierId = identifierId
|
||||
)
|
||||
)
|
||||
}
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
private fun extractFromEse(uniqueId: String, apiKey: String): String? {
|
||||
val url = "https://api.dimu.org/api/artifact".toHttpUrlOrNull()?.newBuilder()
|
||||
?.addQueryParameter("unique_id", uniqueId)
|
||||
?.addQueryParameter("mapping", "ESE")
|
||||
?.addQueryParameter("api.key", apiKey)
|
||||
?.build() ?: return null
|
||||
|
||||
val req = Request.Builder().url(url).get().build()
|
||||
return try {
|
||||
http.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val xml = resp.body?.string().orEmpty()
|
||||
if (xml.isBlank()) return null
|
||||
// Europeana/ESE: dc:description är vanligast
|
||||
extractTextFromXml(
|
||||
xml,
|
||||
listOf(
|
||||
Regex("<(?:dcterms:|dc:)?description[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?description>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:dcterms:|dc:)?title[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?title>", RegexOption.IGNORE_CASE)
|
||||
)
|
||||
)
|
||||
}
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
|
||||
/** Enkelt XML-utdrag: hittar första matchande text, rensar HTML-taggar och trimmar. */
|
||||
private fun extractTextFromXml(xml: String, patterns: List<Regex>): String? {
|
||||
for (re in patterns) {
|
||||
val m = re.find(xml) ?: continue
|
||||
val raw = m.groupValues.getOrNull(1)?.trim() ?: continue
|
||||
val cleaned = raw
|
||||
.replace(Regex("<[^>]+>"), " ") // ta bort taggar
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
if (cleaned.isNotEmpty()) return cleaned.take(4000)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun extractFromSimpleJsonByOwnerId(owner: String, identifierId: String, apiKey: String): String? {
|
||||
val url = "https://api.dimu.org/api/artifact".toHttpUrlOrNull()?.newBuilder()
|
||||
?.addQueryParameter("owner", owner)
|
||||
?.addQueryParameter("identifier", identifierId)
|
||||
?.addQueryParameter("mapping", "simple_json")
|
||||
?.addQueryParameter("api.key", apiKey)
|
||||
?.build() ?: return null
|
||||
|
||||
val req = Request.Builder().url(url).get().build()
|
||||
return try {
|
||||
http.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val body = resp.body?.string().orEmpty()
|
||||
if (body.isBlank()) return null
|
||||
extractBestTextFromSimpleJson(body)
|
||||
}
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
|
||||
private fun extractFromAbmByOwnerId(owner: String, identifierId: String, apiKey: String): String? {
|
||||
val url = "https://api.dimu.org/api/artifact".toHttpUrlOrNull()?.newBuilder()
|
||||
?.addQueryParameter("owner", owner)
|
||||
?.addQueryParameter("identifier", identifierId)
|
||||
?.addQueryParameter("mapping", "ABM")
|
||||
?.addQueryParameter("api.key", apiKey)
|
||||
?.build() ?: return null
|
||||
|
||||
val req = Request.Builder().url(url).get().build()
|
||||
return try {
|
||||
http.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val xml = resp.body?.string().orEmpty()
|
||||
if (xml.isBlank()) return null
|
||||
extractTextFromXml(
|
||||
xml,
|
||||
listOf(
|
||||
Regex("<(?:dcterms:|dc:)?description[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?description>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:abm:)?history[^>]*>([\\s\\S]*?)</(?:abm:)?history>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:abm:)?beskrivelse[^>]*>([\\s\\S]*?)</(?:abm:)?beskrivelse>", RegexOption.IGNORE_CASE)
|
||||
)
|
||||
)
|
||||
}
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
|
||||
private fun extractFromEseByOwnerId(owner: String, identifierId: String, apiKey: String): String? {
|
||||
val url = "https://api.dimu.org/api/artifact".toHttpUrlOrNull()?.newBuilder()
|
||||
?.addQueryParameter("owner", owner)
|
||||
?.addQueryParameter("identifier", identifierId)
|
||||
?.addQueryParameter("mapping", "ESE")
|
||||
?.addQueryParameter("api.key", apiKey)
|
||||
?.build() ?: return null
|
||||
|
||||
val req = Request.Builder().url(url).get().build()
|
||||
return try {
|
||||
http.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val xml = resp.body?.string().orEmpty()
|
||||
if (xml.isBlank()) return null
|
||||
extractTextFromXml(
|
||||
xml,
|
||||
listOf(
|
||||
Regex("<(?:dcterms:|dc:)?description[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?description>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:dcterms:|dc:)?title[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?title>", RegexOption.IGNORE_CASE)
|
||||
)
|
||||
)
|
||||
}
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,16 +18,35 @@ 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.
|
||||
* Delad (KMP) klient för DigitaltMuseum byggd på Ktor.
|
||||
*
|
||||
* Översikt
|
||||
* --------
|
||||
* - Vi anropar två publika DM-endpoints:
|
||||
* 1) Solr-sök: https://api.dimu.org/api/solr/select
|
||||
* 2) Artifact-detalj: https://api.dimu.org/api/artifact
|
||||
*
|
||||
* Varför i shared?
|
||||
* ----------------
|
||||
* - För att återanvända exakt samma nätverkskod på Android och iOS.
|
||||
* - Vi använder Ktor med plattforms-motor via `platformEngine()` (OkHttp på Android, Darwin på iOS).
|
||||
*
|
||||
* Säkerhet/konfiguration
|
||||
* ----------------------
|
||||
* - API-nyckel (DM_API_KEY) injiceras från plattformen (t.ex. via BuildConfig i Android).
|
||||
* - Inga hemligheter hårdkodas här.
|
||||
*
|
||||
* Felhantering
|
||||
* ------------
|
||||
* - Alla nätverks- och parse-fel fångas lokalt; vi returnerar tomma listor eller null (ingen exception ut ur API:t).
|
||||
* - Det gör att appen förblir responsiv även vid DM-störningar.
|
||||
*/
|
||||
object DigitaltMuseumShared {
|
||||
|
||||
// Bas-URL enligt dokumentationen (Solr endpoint)
|
||||
// Bas-URL till Solr (sök-endpoint)
|
||||
private const val BASE_URL = "https://api.dimu.org/api/solr/select"
|
||||
|
||||
// Solr-fältnamn vi behöver
|
||||
// Solr-fältnamn som vi använder (håll i sync med FL nedan)
|
||||
private const val FIELD_ID = "identifier.id"
|
||||
private const val FIELD_TITLE = "artifact.ingress.title"
|
||||
private const val FIELD_COORD = "artifact.coordinate"
|
||||
@@ -35,17 +54,17 @@ object DigitaltMuseumShared {
|
||||
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
|
||||
// Begär endast fält vi behöver → mindre payload, snabbare svar
|
||||
private const val FL = "$FIELD_ID,$FIELD_TITLE,$FIELD_COORD,$FIELD_DEFAULT_MEDIA,$FIELD_UNIQUE_ID,$FIELD_OWNER"
|
||||
|
||||
// Ktor-klient (återanvänds)
|
||||
// Delad Ktor-klient. ContentNegotiation → JSON-hjälp. DefaultRequest → sätt en tydlig User-Agent.
|
||||
private val client by lazy {
|
||||
HttpClient(platformEngine()) {
|
||||
install(ContentNegotiation) {
|
||||
json(
|
||||
Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
ignoreUnknownKeys = true // Tålig mot okända fält som DM kan lägga till
|
||||
isLenient = true // Tillåt "snällare" JSON
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -56,17 +75,19 @@ object DigitaltMuseumShared {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
* Hämta närliggande DigitaltMuseum-objekt.
|
||||
*
|
||||
* Strategi (samma ordning som i appens nuvarande kod):
|
||||
* Strategi (matchar tidigare Android-implementation):
|
||||
* 1) owners + geofilt
|
||||
* 2) owners + bbox
|
||||
* 3) alla + geofilt
|
||||
* 4) alla + bbox
|
||||
* Första icke-tomma resultat returneras; annars tom lista.
|
||||
* Vi returnerar första icke-tomma listan. Om alla är tomma → tom lista.
|
||||
*
|
||||
* @param apiKey DM API-nyckel (måste injiceras av plattformen)
|
||||
* @param owners Lista med musei-ägare att filtrera på (kan vara tom/null = alla)
|
||||
* @param lat/lon Mittpunkt för sökningen
|
||||
* @param radiusMeters Radie i meter (översätts till km för Solr)
|
||||
*/
|
||||
suspend fun getNearby(
|
||||
apiKey: String,
|
||||
@@ -77,23 +98,30 @@ object DigitaltMuseumShared {
|
||||
): List<DigitaltMuseumItem> {
|
||||
if (apiKey.isBlank()) return emptyList()
|
||||
|
||||
// 1–2) med owners
|
||||
// Normalisera owners (klipp whitespace och släng tomma)
|
||||
val cleanOwners = owners?.map { it.trim() }?.filter { it.isNotEmpty() }.orEmpty()
|
||||
|
||||
// 1–2) med owners
|
||||
if (cleanOwners.isNotEmpty()) {
|
||||
// geofilt → cirkel
|
||||
queryWithGeo(apiKey, cleanOwners, lat, lon, radiusMeters, useBBox = false).let { if (it.isNotEmpty()) return it }
|
||||
// bbox → rektangel (kan ge annan träffbild nära kanter)
|
||||
queryWithGeo(apiKey, cleanOwners, lat, lon, radiusMeters, useBBox = true).let { if (it.isNotEmpty()) return it }
|
||||
}
|
||||
|
||||
// 3–4) utan owners
|
||||
// 3–4) utan owners (alla museer)
|
||||
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
|
||||
/**
|
||||
* En enda Solr-fråga med antingen geofilt (cirkel) eller bbox (rektangel).
|
||||
* Vi bygger ett "local params"-filter i `fq` och plockar sedan ut `response.docs`.
|
||||
*
|
||||
* @return Lista med tolkade objekt (kan vara tom vid 0 träffar eller fel).
|
||||
*/
|
||||
private suspend fun queryWithGeo(
|
||||
apiKey: String,
|
||||
owners: List<String>?,
|
||||
@@ -102,50 +130,64 @@ object DigitaltMuseumShared {
|
||||
radiusMeters: Int,
|
||||
useBBox: Boolean
|
||||
): List<DigitaltMuseumItem> = try {
|
||||
val km = (radiusMeters / 1000.0).coerceAtLeast(0.1)
|
||||
val km = (radiusMeters / 1000.0).coerceAtLeast(0.1) // Solr använder km; vi tvingar min 0.1 km för rimlighet
|
||||
|
||||
// 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}"
|
||||
|
||||
// Ägarfilter (OR-kedja). Ex: identifier.owner:SMVK OR identifier.owner:XYZ
|
||||
val ownersFq: String? = owners?.takeIf { it.isNotEmpty() }?.joinToString(" OR ") { "identifier.owner:$it" }
|
||||
|
||||
// GET mot Solr
|
||||
// HTTP GET mot Solr
|
||||
val resp: JsonObject = client.get(BASE_URL) {
|
||||
parameter("wt", "json")
|
||||
parameter("fl", FL)
|
||||
parameter("q", "*:*")
|
||||
parameter("wt", "json") // JSON-respons
|
||||
parameter("fl", FL) // endast fälten vi behöver
|
||||
parameter("q", "*:*") // "alla dokument" + fq-filter
|
||||
if (!ownersFq.isNullOrBlank()) {
|
||||
parameter("fq", "($ownersFq)")
|
||||
}
|
||||
parameter("fq", geoClause)
|
||||
parameter("rows", 50)
|
||||
parameter("rows", 50) // rimligt tak
|
||||
parameter("api.key", apiKey)
|
||||
}.body()
|
||||
|
||||
// Plocka docs-arrayen och tolka
|
||||
val response = resp["response"]?.jsonObject ?: return emptyList()
|
||||
val docs = response["docs"] as? JsonArray ?: return emptyList()
|
||||
parseItemsFromDocs(docs)
|
||||
} catch (_: Throwable) {
|
||||
// Vid nätverksfel/parsefel: fall tillbaka till tom lista
|
||||
emptyList()
|
||||
}
|
||||
|
||||
// Tolka docs-arrayen till vår modell
|
||||
/**
|
||||
* Tolka Solr-dokumenten till vår modell.
|
||||
* DM kan leverera fält som ren sträng eller som array; `stringOrNull` hanterar båda.
|
||||
*/
|
||||
private fun parseItemsFromDocs(docs: JsonArray): List<DigitaltMuseumItem> {
|
||||
val out = ArrayList<DigitaltMuseumItem>(docs.size)
|
||||
for (el in docs) {
|
||||
val doc = el as? JsonObject ?: continue
|
||||
|
||||
// Obligatoriskt ID (utan ID hoppar vi posten)
|
||||
val id = stringOrNull(doc, FIELD_ID) ?: continue
|
||||
|
||||
// Titel: använd fallback om tomt
|
||||
val title = stringOrNull(doc, FIELD_TITLE)?.takeIf { it.isNotBlank() } ?: "Okänt objekt"
|
||||
|
||||
// Koordinater behövs för att sätta ut markör
|
||||
val coordRaw = stringOrNull(doc, FIELD_COORD)?.trim().orEmpty()
|
||||
val latLon = parseLatLon(coordRaw) ?: continue
|
||||
val (lat, lon) = latLon
|
||||
|
||||
// Thumb-url från mediaId om tillgängligt
|
||||
val mediaId = stringOrNull(doc, FIELD_DEFAULT_MEDIA)
|
||||
val thumbUrl = mediaId?.let { "https://mm.dimu.org/image/$it?dimension=400x400" }
|
||||
|
||||
// Länk till publik sida om uniqueId finns
|
||||
val uniqueId = stringOrNull(doc, FIELD_UNIQUE_ID)
|
||||
val pageUrl = uniqueId?.let { "https://digitaltmuseum.se/$it" }
|
||||
|
||||
@@ -165,7 +207,10 @@ object DigitaltMuseumShared {
|
||||
return out
|
||||
}
|
||||
|
||||
// Hämta strängfält ur JsonObject med fallback för både string och array[0]
|
||||
/**
|
||||
* Läs ett fält som antingen kan vara en sträng eller en array där första elementet är sträng.
|
||||
* DM/solr kan serialisera fält båda sätten beroende på innehåll och datamodell.
|
||||
*/
|
||||
private fun stringOrNull(obj: JsonObject, key: String): String? {
|
||||
val v = obj[key] ?: return null
|
||||
return when (v) {
|
||||
@@ -175,7 +220,10 @@ object DigitaltMuseumShared {
|
||||
}
|
||||
}
|
||||
|
||||
// Stöd både "lat, lon" och "lat lon"
|
||||
/**
|
||||
* Parsar koordinater från text. Stödjer både "lat, lon" och "lat lon".
|
||||
* Returnerar null om texten är tom/ogiltig eller om lat/lon hamnar utanför rimliga gränser.
|
||||
*/
|
||||
private fun parseLatLon(raw: String): Pair<Double, Double>? {
|
||||
if (raw.isBlank()) return null
|
||||
val cleaned = raw.replace(Regex("\\s+"), " ").trim()
|
||||
@@ -189,7 +237,222 @@ object DigitaltMuseumShared {
|
||||
return lat to lon
|
||||
}
|
||||
|
||||
/**
|
||||
* Grundvalidering av lat/lon (rimliga gränser och inte exakt 0/0).
|
||||
* (0,0) uppstår ibland som default och är inte meningsfullt här.
|
||||
*/
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* Slå upp ett enskilt objekt via `identifier.id` och returnera första träffen.
|
||||
* Används när vi redan känner till DM:s interna "identifier.id".
|
||||
*/
|
||||
suspend fun lookupByIdentifier(
|
||||
apiKey: String,
|
||||
identifierId: String
|
||||
): DigitaltMuseumItem? = try {
|
||||
val resp: JsonObject = client.get(BASE_URL) {
|
||||
parameter("wt", "json")
|
||||
parameter("q", "identifier.id:\"$identifierId\"")
|
||||
parameter("fl", FL)
|
||||
parameter("rows", 1)
|
||||
parameter("api.key", apiKey)
|
||||
}.body()
|
||||
|
||||
val doc = resp["response"]?.jsonObject
|
||||
?.get("docs") as? JsonArray
|
||||
?: return null
|
||||
val first = doc.firstOrNull() as? JsonObject ?: return null
|
||||
|
||||
val id = stringOrNull(first, FIELD_ID) ?: return null
|
||||
val title = stringOrNull(first, FIELD_TITLE)?.takeIf { it.isNotBlank() } ?: "DigitaltMuseum"
|
||||
val coordRaw = stringOrNull(first, FIELD_COORD)?.trim().orEmpty()
|
||||
val latLon = parseLatLon(coordRaw) ?: return null
|
||||
val (lat, lon) = latLon
|
||||
|
||||
val mediaId = stringOrNull(first, FIELD_DEFAULT_MEDIA)
|
||||
val thumbUrl = mediaId?.let { "https://mm.dimu.org/image/$it?dimension=400x400" }
|
||||
|
||||
val uniqueId = stringOrNull(first, FIELD_UNIQUE_ID)
|
||||
val pageUrl = uniqueId?.let { "https://digitaltmuseum.se/$it" }
|
||||
|
||||
val owner = stringOrNull(first, FIELD_OWNER)
|
||||
|
||||
DigitaltMuseumItem(
|
||||
id = id,
|
||||
title = title,
|
||||
lat = lat,
|
||||
lon = lon,
|
||||
url = thumbUrl,
|
||||
uniqueId = uniqueId,
|
||||
webUrl = pageUrl,
|
||||
owner = owner
|
||||
)
|
||||
} catch (_: Throwable) { null }
|
||||
|
||||
/**
|
||||
* Försök extrahera en beskrivande text om ett DM-objekt.
|
||||
*
|
||||
* Ordning/prioritet:
|
||||
* 1) Om `uniqueId` finns: prova artifact/simple_json → artifact/ESE → artifact/ABM
|
||||
* 2) Fallback med owner + identifierId: samma mappningar i samma ordning.
|
||||
*
|
||||
* Vi returnerar första icke-tomma texten (max ~4000 tecken), annars null.
|
||||
*/
|
||||
suspend fun getDetailText(
|
||||
apiKey: String,
|
||||
uniqueId: String?,
|
||||
owner: String?,
|
||||
identifierId: String
|
||||
): String? {
|
||||
if (!uniqueId.isNullOrBlank()) {
|
||||
extractFromSimpleJson(uniqueId = uniqueId, apiKey = apiKey)?.let { if (it.isNotBlank()) return it }
|
||||
extractFromEse(uniqueId = uniqueId, apiKey = apiKey)?.let { if (it.isNotBlank()) return it }
|
||||
extractFromAbm(uniqueId = uniqueId, apiKey = apiKey)?.let { if (it.isNotBlank()) return it }
|
||||
}
|
||||
if (!owner.isNullOrBlank()) {
|
||||
extractFromSimpleJsonByOwnerId(owner = owner!!, identifierId = identifierId, apiKey = apiKey)?.let { if (it.isNotBlank()) return it }
|
||||
extractFromEseByOwnerId(owner = owner!!, identifierId = identifierId, apiKey = apiKey)?.let { if (it.isNotBlank()) return it }
|
||||
extractFromAbmByOwnerId(owner = owner!!, identifierId = identifierId, apiKey = apiKey)?.let { if (it.isNotBlank()) return it }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* ”Best effort”: plocka användbar text från simple_json-mappningen.
|
||||
* Sökvägar som ofta innehåller beskrivning: history.description → description → motif.description → otherInformation
|
||||
*/
|
||||
private fun extractBestTextFromSimpleJson(jsonText: String): String? = try {
|
||||
val root = Json.parseToJsonElement(jsonText).jsonObject
|
||||
|
||||
fun optStringPath(obj: JsonObject, path: String): String? {
|
||||
var cur: Any? = obj
|
||||
for (p in path.split('.')) {
|
||||
cur = when (cur) {
|
||||
is JsonObject -> cur[p]
|
||||
else -> return null
|
||||
}
|
||||
}
|
||||
val prim = (cur as? JsonPrimitive) ?: return null
|
||||
return prim.contentOrNull?.trim()?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
listOf(
|
||||
optStringPath(root, "history.description"),
|
||||
optStringPath(root, "description"),
|
||||
optStringPath(root, "motif.description"),
|
||||
optStringPath(root, "otherInformation")
|
||||
).firstOrNull { !it.isNullOrBlank() }?.trim()?.take(4000)
|
||||
} catch (_: Throwable) { null }
|
||||
|
||||
/**
|
||||
* Enkelt XML-utdrag: ta första match i `patterns`, ta bort HTML-taggar och komprimera whitespace.
|
||||
* Returnerar första icke-tomma texten (max ~4000 tecken) eller null.
|
||||
*/
|
||||
private fun extractTextFromXml(xml: String, patterns: List<Regex>): String? {
|
||||
for (re in patterns) {
|
||||
val m = re.find(xml) ?: continue
|
||||
val raw = m.groupValues.getOrNull(1)?.trim() ?: continue
|
||||
val cleaned = raw
|
||||
.replace(Regex("<[^>]+>"), " ") // skala bort taggar
|
||||
.replace(Regex("\\s+"), " ") // komprimera whitespace
|
||||
.trim()
|
||||
if (cleaned.isNotEmpty()) return cleaned.take(4000)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ---- Privata HTTP-hjälpare till getDetailText (artifact-endpointen) ----
|
||||
|
||||
// simple_json-varianten returnerar JSON där beskrivning ofta finns i history.description/description.
|
||||
private suspend fun extractFromSimpleJson(uniqueId: String, apiKey: String): String? = try {
|
||||
val jsonText: String = client.get("https://api.dimu.org/api/artifact") {
|
||||
parameter("unique_id", uniqueId)
|
||||
parameter("mapping", "simple_json")
|
||||
parameter("api.key", apiKey)
|
||||
}.body()
|
||||
extractBestTextFromSimpleJson(jsonText)
|
||||
} catch (_: Throwable) { null }
|
||||
|
||||
// ESE-mappningen (Europeana) ger XML; vi letar description/title.
|
||||
private suspend fun extractFromEse(uniqueId: String, apiKey: String): String? = try {
|
||||
val xml: String = client.get("https://api.dimu.org/api/artifact") {
|
||||
parameter("unique_id", uniqueId)
|
||||
parameter("mapping", "ESE")
|
||||
parameter("api.key", apiKey)
|
||||
}.body()
|
||||
extractTextFromXml(
|
||||
xml,
|
||||
listOf(
|
||||
Regex("<(?:dcterms:|dc:)?description[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?description>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:dcterms:|dc:)?title[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?title>", RegexOption.IGNORE_CASE)
|
||||
)
|
||||
)
|
||||
} catch (_: Throwable) { null }
|
||||
|
||||
// ABM (Norvegiana) ger XML; fler möjliga fält (history/beskrivelse/subject).
|
||||
private suspend fun extractFromAbm(uniqueId: String, apiKey: String): String? = try {
|
||||
val xml: String = client.get("https://api.dimu.org/api/artifact") {
|
||||
parameter("unique_id", uniqueId)
|
||||
parameter("mapping", "ABM")
|
||||
parameter("api.key", apiKey)
|
||||
}.body()
|
||||
extractTextFromXml(
|
||||
xml,
|
||||
listOf(
|
||||
Regex("<(?:dcterms:|dc:)?description[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?description>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:abm:)?history[^>]*>([\\s\\S]*?)</(?:abm:)?history>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:abm:)?beskrivelse[^>]*>([\\s\\S]*?)</(?:abm:)?beskrivelse>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:dcterms:|dc:)?subject[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?subject>", RegexOption.IGNORE_CASE)
|
||||
)
|
||||
)
|
||||
} catch (_: Throwable) { null }
|
||||
|
||||
// Fallback: slå upp via owner + identifierId (simple_json)
|
||||
private suspend fun extractFromSimpleJsonByOwnerId(owner: String, identifierId: String, apiKey: String): String? = try {
|
||||
val jsonText: String = client.get("https://api.dimu.org/api/artifact") {
|
||||
parameter("owner", owner)
|
||||
parameter("identifier", identifierId)
|
||||
parameter("mapping", "simple_json")
|
||||
parameter("api.key", apiKey)
|
||||
}.body()
|
||||
extractBestTextFromSimpleJson(jsonText)
|
||||
} catch (_: Throwable) { null }
|
||||
|
||||
// Fallback: owner + identifierId (ESE → XML)
|
||||
private suspend fun extractFromEseByOwnerId(owner: String, identifierId: String, apiKey: String): String? = try {
|
||||
val xml: String = client.get("https://api.dimu.org/api/artifact") {
|
||||
parameter("owner", owner)
|
||||
parameter("identifier", identifierId)
|
||||
parameter("mapping", "ESE")
|
||||
parameter("api.key", apiKey)
|
||||
}.body()
|
||||
extractTextFromXml(
|
||||
xml,
|
||||
listOf(
|
||||
Regex("<(?:dcterms:|dc:)?description[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?description>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:dcterms:|dc:)?title[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?title>", RegexOption.IGNORE_CASE)
|
||||
)
|
||||
)
|
||||
} catch (_: Throwable) { null }
|
||||
|
||||
// Fallback: owner + identifierId (ABM → XML)
|
||||
private suspend fun extractFromAbmByOwnerId(owner: String, identifierId: String, apiKey: String): String? = try {
|
||||
val xml: String = client.get("https://api.dimu.org/api/artifact") {
|
||||
parameter("owner", owner)
|
||||
parameter("identifier", identifierId)
|
||||
parameter("mapping", "ABM")
|
||||
parameter("api.key", apiKey)
|
||||
}.body()
|
||||
extractTextFromXml(
|
||||
xml,
|
||||
listOf(
|
||||
Regex("<(?:dcterms:|dc:)?description[^>]*>([\\s\\S]*?)</(?:dcterms:|dc:)?description>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:abm:)?history[^>]*>([\\s\\S]*?)</(?:abm:)?history>", RegexOption.IGNORE_CASE),
|
||||
Regex("<(?:abm:)?beskrivelse[^>]*>([\\s\\S]*?)</(?:abm:)?beskrivelse>", RegexOption.IGNORE_CASE)
|
||||
)
|
||||
)
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user