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:
2025-09-07 10:43:41 +02:00
parent 327ee6594b
commit 56752ab1f4
5 changed files with 318 additions and 477 deletions

View File

@@ -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)
}
}

View File

@@ -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())
}
}

View File

@@ -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
)
}
} 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
DigitaltMuseumShared.lookupByIdentifier(
apiKey = apiKey,
identifierId = identifierId
)
}
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)
)
)
}
} 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 }
DigitaltMuseumShared.getDetailText(
apiKey = apiKey,
uniqueId = uniqueId,
owner = owner,
identifierId = identifierId
)
}
}