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