diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 8750e52..1e4707d 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -46,8 +46,8 @@ android { applicationId = "app.klottr" minSdk = 26 targetSdk = 35 - versionCode = 11 - versionName = "0.2.4.1" + versionCode = 12 + versionName = "0.2.5" // Byggtid i UTC (ISO 8601) genereras vid build-konfiguration val buildTimeUtc = Instant.now().toString() @@ -63,6 +63,12 @@ android { // Skicka Maps‑nyckeln som manifest‑placeholder (används i AndroidManifest.xml) manifestPlaceholders["MAPS_API_KEY"] = propOrEmpty("MAPS_API_KEY") + // Digitalt Museum + buildConfigField("String", "DM_API_KEY", "\"${propOrEmpty("DM_API_KEY")}\"") + buildConfigField("String", "DM_OWNERS", "\"${propOrEmpty("DM_OWNERS")}\"") + + + buildConfigField("boolean", "KLLOG_DEBUG", klLogDebug.toString()) buildConfigField("boolean", "KLLOG_HTTP_DEBUG", klLogHttpDebug.toString()) } diff --git a/app/release/app-release.aab b/app/release/app-release.aab deleted file mode 100644 index 29b9cf6..0000000 Binary files a/app/release/app-release.aab and /dev/null differ diff --git a/app/src/main/java/app/klottr/MainActivity.kt b/app/src/main/java/app/klottr/MainActivity.kt index c735003..02f0a57 100644 --- a/app/src/main/java/app/klottr/MainActivity.kt +++ b/app/src/main/java/app/klottr/MainActivity.kt @@ -63,6 +63,7 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -379,6 +380,9 @@ private fun KlottrApp( var openWiki by remember { mutableStateOf(null) } // Fornsok-detalj var openFornsok by remember { mutableStateOf(null) } + // DigitaltMuseum + var openDm by remember { mutableStateOf(null) } + // Hittat-refresh + “force tomt” efter rensning var foundRefresh by remember { mutableStateOf(0) } @@ -717,8 +721,12 @@ private fun KlottrApp( Text("Inga fynd ännu.") } else { LazyColumn(Modifier.fillMaxWidth().weight(1f)) { - items(foundList) { f -> - var displayLabel by remember(f.id, f.layer, f.label) { mutableStateOf(f.label) } + items( + items = foundList, + key = { f -> "${f.layer}:${f.id}" } // ⬅️ stabil nyckel per rad + ) { f -> + var displayLabel by rememberSaveable(f.layer, f.id) { mutableStateOf(f.label) } + LaunchedEffect(f.id, f.layer) { if (f.layer == FoundStore.LAYER_KLOTTER && (displayLabel.isBlank() || displayLabel == "Okänt klotter")) { val items = withContext(Dispatchers.IO) { @@ -730,7 +738,10 @@ private fun KlottrApp( } } } - val clickable = (f.layer == FoundStore.LAYER_WIKI) || (f.layer == LAYER_FORNSOK || f.layer == FoundStore.LAYER_KLOTTER) + val clickable = (f.layer == FoundStore.LAYER_WIKI) || + (f.layer == LAYER_FORNSOK) || + (f.layer == FoundStore.LAYER_KLOTTER) || + (f.layer == FoundStore.LAYER_DM) // --- Hämta away för UI --- val away = FoundStore.isAway(context, f.layer, f.id) @@ -769,7 +780,7 @@ private fun KlottrApp( // 3) Ev. koordinater (om toggeln är på) val coordPart = if (showCoords) " • " + formatCoords(f.lat, f.lon) else "" - // Ska bara läsas så att Compose vet att innehållet beror på det. Gör så att raderana ritas om när platsen uppdateras. + // Ska bara läsas så att Compose vet att innehållet beror på det. Gör så att raderna ritas om när platsen uppdateras. val _tick = locationTick // ignoreras, men binder UI till ticks Text("$layerName • $distText$coordPart") @@ -789,7 +800,7 @@ private fun KlottrApp( val pid = f.id.toLongOrNull() if (pid != null) openWiki = OpenWiki(pid, f.lat, f.lon) } - LAYER_FORNSOK -> { + LAYER_FORNSOK -> { // Hämta riktiga fält (desc/type/uri) nära fyndets position innan vi öppnar dialogen scope.launch { val enriched = withContext(Dispatchers.IO) { @@ -812,12 +823,33 @@ private fun KlottrApp( ) } } + FoundStore.LAYER_DM -> { + // Öppna EXAKT det klickade objektet (inte "något i närheten") + scope.launch { + val exact = withContext(Dispatchers.IO) { + try { + app.klottr.net.DigitaltMuseum.lookupByIdentifier(f.id) + } catch (_: Exception) { null } + } + openDm = exact ?: app.klottr.net.DigitaltMuseumItem( + id = f.id, + title = displayLabel.ifBlank { "DigitaltMuseum" }, + lat = f.lat, + lon = f.lon, + url = null, + uniqueId = null, + webUrl = null, + owner = null + ) + } + } } } else Modifier ) - Divider() + HorizontalDivider() } } + } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { @@ -847,6 +879,8 @@ private fun KlottrApp( onKlotterClick = { id, la, lo, label -> openKlotter = OpenKlotter(id, la, lo, label) }, onWikiClick = { pageId, wlat, wlon -> openWiki = OpenWiki(pageId, wlat, wlon) }, onFornsokClick = { item -> openFornsok = OpenFornsok(item) }, + onDmClick = { item -> openDm = item }, + onMarkedFound = { refreshFound() // ✅ FIX: använd redan fångat 'context' – inte LocalContext.current här @@ -953,6 +987,7 @@ private fun KlottrApp( ) } + // Fornsök-detalj val currentForn = openFornsok if (currentForn != null) { FornsokDialog( @@ -961,6 +996,16 @@ private fun KlottrApp( ) } + // DigitaltMuseum-detalj + val currentDm = openDm + if (currentDm != null) { + DmDialog( + item = currentDm, + onClose = { openDm = null } + ) + } + + // Skrivdialog (dokument) var isSavingDoc by remember { mutableStateOf(false) } if (showWrite) { @@ -1161,6 +1206,7 @@ private fun NearbyDialog( onKlotterClick: (String, Double, Double, String) -> Unit, onWikiClick: (Long, Double, Double) -> Unit, onFornsokClick: (FornsokItem) -> Unit, + onDmClick: (DigitaltMuseumItem) -> Unit, onMarkedFound: () -> Unit, onClose: () -> Unit ) { @@ -1215,7 +1261,8 @@ private fun NearbyDialog( lat = dmi.lat, lon = dmi.lon, distanceM = d, - insideRadiusM = dmRadius + insideRadiusM = dmRadius, + click = { onDmClick(dmi) } // ⬅️ öppnar DM-detalj, samma mönster som övriga lager ) ) } @@ -1709,7 +1756,7 @@ private fun SettingsDialog( val maxDialogHeight = (configuration.screenHeightDp.dp * 0.75f) val wikiOptions = listOf(20, 50, 100, 200, 500, 1000, 2000, 5000) - val dmOptions = listOf(20, 50, 100, 200, 500, 1000, 2000, 5000) + val dmOptions = listOf(50, 100, 200, 500, 1000, 2000, 5000) val fornsokOptions = listOf(50, 100, 200, 500, 1000, 2000, 5000) var wikiExpanded by remember { mutableStateOf(false) } @@ -1863,34 +1910,20 @@ private fun SettingsDialog( // DigitaltMuseum Row(verticalAlignment = Alignment.CenterVertically) { - Text("DigitaltMuseum (ej klart än)", modifier = Modifier.weight(1f)) - - // dmtmpav: NÄR API-NYCKELN FINNS — byt till raden nedan och ta bort den efterföljande raden - // Switch(checked = showDm, onCheckedChange = onShowDmChanged) // dmtmpav: ORIGINAL - Switch(checked = false, onCheckedChange = {}, enabled = false) // dmtmpav: TILLFÄLLIGT AVSTÄNGD + Text("DigitaltMuseum (testas nu)", modifier = Modifier.weight(1f)) + Switch(checked = showDm, onCheckedChange = onShowDmChanged) } - ExposedDropdownMenuBox( - // dmtmpav: NÄR API-NYCKELN FINNS — byt till: - // expanded = dmExpanded, onExpandedChange = { dmExpanded = !dmExpanded } // dmtmpav: ORIGINAL - expanded = false, onExpandedChange = {} // dmtmpav: TILLFÄLLIGT AVSTÄNGD - ) { + ExposedDropdownMenuBox(expanded = dmExpanded, onExpandedChange = { dmExpanded = !dmExpanded }) { OutlinedTextField( value = radiusLabel(dmRadius), onValueChange = {}, readOnly = true, label = { Text("DigitaltMuseum-radie") }, - // dmtmpav: NÄR API-NYCKELN FINNS — byt till: - // trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = dmExpanded) } // dmtmpav: ORIGINAL - trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = false) }, // dmtmpav: TILLFÄLLIGT - // dmtmpav: NÄR API-NYCKELN FINNS — byt till: - // enabled = showDm, // dmtmpav: ORIGINAL - enabled = false, // dmtmpav: TILLFÄLLIGT + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = dmExpanded) }, + enabled = showDm, modifier = Modifier.menuAnchor().fillMaxWidth() ) - - // dmtmpav: NÄR API-NYCKELN FINNS — avkommentera hela menyn nedan (och ta bort denna kommentar) - /* DropdownMenu(expanded = dmExpanded, onDismissRequest = { dmExpanded = false }) { dmOptions.forEach { m -> DropdownMenuItem( @@ -1900,13 +1933,9 @@ private fun SettingsDialog( ) } } - */ } - - - - Divider() + HorizontalDivider() Button( onClick = { askClear = true }, @@ -2567,6 +2596,182 @@ private fun FornsokDialog( ) } +@Composable +private fun DmDialog( + item: DigitaltMuseumItem, + onClose: () -> Unit +) { + val context = LocalContext.current + val configuration = LocalConfiguration.current + val dialogWidth = (configuration.screenWidthDp.dp * 0.98f) + var detailText by remember { mutableStateOf(null) } + + + var loading by remember { mutableStateOf(false) } + var thumb: Bitmap? by remember { mutableStateOf(null) } + + // Avstånd som tickar + var dmDistanceText by remember { mutableStateOf("-") } + val showCoords = remember { SettingsStore.getShowCoordinates(context) } + + fun recalcDmDistance() { + val my = LastLocationStore.lastKnownLocation + val d = if (my != null) distanceMeters(my.latitude, my.longitude, item.lat, item.lon).roundToInt() else null + dmDistanceText = d?.let { formatDistance(it) } ?: "-" + } + + LaunchedEffect(item.lat, item.lon) { recalcDmDistance() } + + DisposableEffect(Unit) { + val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK) + val receiver = object : BroadcastReceiver() { + override fun onReceive(ctx: Context?, intent: Intent?) { recalcDmDistance() } + } + if (Build.VERSION.SDK_INT >= 33) { + context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) + } else { + @Suppress("DEPRECATION") + context.registerReceiver(receiver, filter) + } + onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} } + } + + // Hämta miniatyr om vi har bild-URL + LaunchedEffect(item.id) { + // Bild (om finns) + if (!item.url.isNullOrBlank()) { + loading = true + thumb = withContext(Dispatchers.IO) { fetchBitmapFromUrl(item.url!!) } + loading = false + } else { + thumb = null + } + // Text (om uniqueId finns) + detailText = withContext(Dispatchers.IO) { + app.klottr.net.DigitaltMuseum.getDetailText( + uniqueId = item.uniqueId, + owner = item.owner, + identifierId = item.id + ) + } + } + + // Post-process: om text saknas eller är samma som titel, försök stycka titeln i meningar. + val originalTitle = item.title.ifBlank { "DigitaltMuseum" }.trim() + val bodyFromApi = detailText?.trim() + + fun splitSentences(s: String): Pair { + // Enkel men robust meningdelning: dela på . ! ? följt av mellanslag och stor bokstav/siffra + val regex = Regex("(?<=[.!?])\\s+(?=[A-ZÅÄÖ0-9])") + val parts = s.split(regex).map { it.trim() }.filter { it.isNotEmpty() } + return if (parts.size >= 2) { + val first = parts.first() + val rest = parts.drop(1).joinToString(" ").take(4000).trim().ifEmpty { null } + first to rest + } else s to null + } + + val (displayTitle, displayBody) = run { + val noBody = bodyFromApi.isNullOrBlank() + val sameAsTitle = !bodyFromApi.isNullOrBlank() && bodyFromApi.equals(originalTitle, ignoreCase = true) + if (noBody || sameAsTitle) { + val (t, rest) = splitSentences(originalTitle) + t to rest + } else { + originalTitle to bodyFromApi + } + } + + AlertDialog( + onDismissRequest = onClose, + properties = DialogProperties(usePlatformDefaultWidth = false), + title = { + Box(Modifier.fillMaxWidth().widthIn(max = dialogWidth)) { + Text(displayTitle) + } + }, + text = { + Box( + Modifier + .fillMaxWidth() + .widthIn(max = dialogWidth) + .heightIn(max = 520.dp) + ) { + if (loading) { + Text("Söker …") + } else { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + if (thumb != null) { + Image( + bitmap = thumb!!.asImageBitmap(), + contentDescription = null, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 120.dp) + .clip(RoundedCornerShape(8.dp)), + contentScale = ContentScale.Crop + ) + } + + displayBody?.let { Text(it) } + + + HorizontalDivider() + + val bottomCoordPart = if (showCoords) " • (%.5f, %.5f)".format(item.lat, item.lon) else "" + Text( + "DigitaltMuseum • $dmDistanceText$bottomCoordPart", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Button( + onClick = { + if (!item.url.isNullOrBlank()) { + val i = Intent(Intent.ACTION_VIEW, Uri.parse(item.url)) + try { context.startActivity(i) } catch (_: Exception) {} + } + }, + enabled = !item.url.isNullOrBlank() + ) { Text("Öppna bild") } + + Button( + onClick = { + val uri = Uri.parse("geo:${item.lat},${item.lon}?q=${item.lat},${item.lon}(${Uri.encode(item.title.ifBlank { "DigitaltMuseum" })})") + val i = Intent(Intent.ACTION_VIEW, uri).apply { + setPackage("com.google.android.apps.maps") + } + try { context.startActivity(i) } catch (_: Exception) { + context.startActivity(Intent(Intent.ACTION_VIEW, uri)) + } + } + ) { Text("Maps") } + + Button( + onClick = { + val u = item.webUrl + if (!u.isNullOrBlank()) { + val i = Intent(Intent.ACTION_VIEW, Uri.parse(u)) + try { context.startActivity(i) } catch (_: Exception) {} + } + }, + enabled = !item.webUrl.isNullOrBlank() + ) { Text("Läs mer") } + } + } + } + } + }, + confirmButton = { Button(onClick = onClose) { Text("Stäng") } } + ) +} + /* ---------- Hjälp ---------- */ @@ -2594,4 +2799,14 @@ private fun distanceMeters(aLat: Double, aLon: Double, bLat: Double, bLon: Doubl val aa = s1 * s1 + Math.cos(Math.toRadians(aLat)) * Math.cos(Math.toRadians(bLat)) * s2 * s2 val c = 2 * Math.atan2(Math.sqrt(aa), Math.sqrt(1 - aa)) return R * c -} \ No newline at end of file +} + +private fun fetchBitmapFromUrl(url: String): Bitmap? { + return try { + val conn = java.net.URL(url).openConnection() as java.net.HttpURLConnection + conn.connectTimeout = 6000 + conn.readTimeout = 8000 + conn.instanceFollowRedirects = true + conn.inputStream.use { stream -> BitmapFactory.decodeStream(stream) } + } catch (_: Exception) { null } +} diff --git a/app/src/main/java/app/klottr/MapDialog.kt b/app/src/main/java/app/klottr/MapDialog.kt index 4b7d544..a21814a 100644 --- a/app/src/main/java/app/klottr/MapDialog.kt +++ b/app/src/main/java/app/klottr/MapDialog.kt @@ -247,13 +247,21 @@ fun MapDialog( dm.forEach { dmi -> val d = if (lat != null && lon != null) distanceMeters(lat, lon, dmi.lat, dmi.lon).roundToInt() else Int.MAX_VALUE - MarkerInfoWindow( + + MarkerInfoWindow( state = MarkerState(position = LatLng(dmi.lat, dmi.lon)), - //onClick = { - // selLat = dmi.lat; selLon = dmi.lon; selTitle = dmi.title; selUri = dmi.uri - // false - //}, - //onInfoWindowClick = { dmi.uri?.let { onOpenUrl(dmi.title, it) } } + onClick = { + // Sätt samma state som för Wiki/Fornsök så knapparna nere till höger aktiveras + selLat = dmi.lat + selLon = dmi.lon + selTitle = dmi.title + selUri = dmi.webUrl ?: dmi.url // objektsidan om den finns, annars bild-URL + false // låt infowindow visas + }, + onInfoWindowClick = { + // Öppna “Läs mer” på samma sätt som Wiki/Fornsök + (dmi.webUrl ?: dmi.url)?.let { onOpenUrl(dmi.title, it) } + } ) { Card( colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), @@ -262,8 +270,14 @@ fun MapDialog( ) { Column(Modifier.padding(8.dp)) { Text("DigitaltMuseum", style = MaterialTheme.typography.labelMedium) - Text(dmi.title, style = MaterialTheme.typography.bodyMedium) - Text("Läs mer", style = MaterialTheme.typography.bodySmall) + Text(dmi.title, style = MaterialTheme.typography.bodyMedium) + Text( + "Läs mer", + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.clickable { + (dmi.webUrl ?: dmi.url)?.let { onOpenUrl(dmi.title, it) } + } + ) } } } diff --git a/app/src/main/java/app/klottr/net/DigitaltMuseum.kt b/app/src/main/java/app/klottr/net/DigitaltMuseum.kt index bb410a4..ab46398 100644 --- a/app/src/main/java/app/klottr/net/DigitaltMuseum.kt +++ b/app/src/main/java/app/klottr/net/DigitaltMuseum.kt @@ -1,36 +1,488 @@ 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 data class DigitaltMuseumItem( val id: String, val title: String, val lat: Double, val lon: Double, - val url: String? = null + val url: String? = null, // vi fyller med bildlänk från mm.dimu.org om möjligt + val uniqueId: String? = null, + val webUrl: String? = null, // publika objektsidan (digitaltmuseum.se/) + val owner: String? = null // identifier.owner (behövs för owner+identifier-uppslag) ) -/** - * DigitaltMuseum – platsnära sök. - * - * OBS: Officiella API:t kräver nyckel och dokumentation/endpoint. - * Den här stubben returnerar tom lista (säkert), så allt funkar utan krascher. - * När du vill koppla på “på riktigt”: - * - lägg in API-nyckel (t.ex. via BuildConfig eller resValue) - * - implementera HTTP-anrop och JSON-parsning här och returnera faktiska träffar - */ 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, radiusMeters: Int + ): List = withContext(Dispatchers.IO) { + 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() + } + + 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 List.ifNotEmpty(block: (List) -> Unit): List { + if (this.isNotEmpty()) block(this) + return this + } + + private fun queryWithGeo( + apiKey: String, + owners: List?, // kan vara null = alla owners + lat: Double, + lon: Double, + radiusMeters: Int, + sfield: String, + useBBox: Boolean ): List { + 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 { - // TODO: Implementera riktig anrop mot DigitaltMuseum API här. - emptyList() + 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", "getNearby failed: ${t.message}") + Log.w("DigitaltMuseum", "DM queryWithGeo failed ($sfield, bbox=$useBBox): ${t.message}") emptyList() } } + + private fun parseItemsFromDocs(docs: org.json.JSONArray): List { + val out = ArrayList() + 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?, // 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? { + 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]*?)", RegexOption.IGNORE_CASE), + // ev. “history” i ABM-varianter + Regex("<(?:abm:)?history[^>]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE), + // fallback: “note”/”beskrivelse” + Regex("<(?:abm:)?beskrivelse[^>]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE), + Regex("<(?:dcterms:|dc:)?subject[^>]*>([\\s\\S]*?)", 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]*?)", RegexOption.IGNORE_CASE), + Regex("<(?:dcterms:|dc:)?title[^>]*>([\\s\\S]*?)", 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): 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]*?)", RegexOption.IGNORE_CASE), + Regex("<(?:abm:)?history[^>]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE), + Regex("<(?:abm:)?beskrivelse[^>]*>([\\s\\S]*?)", 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]*?)", RegexOption.IGNORE_CASE), + Regex("<(?:dcterms:|dc:)?title[^>]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE) + ) + ) + } + } catch (_: Throwable) { null } + } }