Klottr v2.2.0. Flyttat info i Hittat till klottrets sida. Infosida. Två debugloggnivåer istället för 0. Använder POST istället för GET av integritetsskäl. Första versionen på Google Play, där den publicerades igår.

This commit is contained in:
2025-08-27 16:49:33 +02:00
parent cc498ac55f
commit e42ebef5ed
57 changed files with 521 additions and 146 deletions

View File

@@ -1,4 +1,7 @@
import java.time.Instant import java.time.Instant
import java.util.Properties
// import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties
plugins { plugins {
id("org.jetbrains.kotlin.plugin.compose") id("org.jetbrains.kotlin.plugin.compose")
@@ -7,6 +10,9 @@ plugins {
kotlin("kapt") kotlin("kapt")
} }
// === Läs local.properties utan java.util.Properties === // === Läs local.properties utan java.util.Properties ===
val localProps: Map<String, String> = run { val localProps: Map<String, String> = run {
val file = rootProject.file("local.properties") val file = rootProject.file("local.properties")
@@ -24,6 +30,10 @@ val localProps: Map<String, String> = run {
.toMap() .toMap()
} }
val klLogDebug = localProps["KLLOG_DEBUG"]?.toBoolean() ?: false
val klLogHttpDebug = localProps["KLLOG_HTTP_DEBUG"]?.toBoolean() ?: false
fun propOrEmpty(key: String) = localProps[key] ?: "" fun propOrEmpty(key: String) = localProps[key] ?: ""
// ====================================================== // ======================================================
@@ -36,8 +46,8 @@ android {
applicationId = "app.klottr" applicationId = "app.klottr"
minSdk = 26 minSdk = 26
targetSdk = 35 targetSdk = 35
versionCode = 8 versionCode = 9
versionName = "0.2.1" versionName = "0.2.2"
// Byggtid i UTC (ISO 8601) genereras vid build-konfiguration // Byggtid i UTC (ISO 8601) genereras vid build-konfiguration
val buildTimeUtc = Instant.now().toString() val buildTimeUtc = Instant.now().toString()
@@ -50,8 +60,11 @@ android {
buildConfigField("String", "SERVER_API_KEY", "\"${propOrEmpty("SERVER_API_KEY")}\"") buildConfigField("String", "SERVER_API_KEY", "\"${propOrEmpty("SERVER_API_KEY")}\"")
buildConfigField("String", "WEB_CLIENT_ID", "\"${propOrEmpty("WEB_CLIENT_ID")}\"") buildConfigField("String", "WEB_CLIENT_ID", "\"${propOrEmpty("WEB_CLIENT_ID")}\"")
// Skicka Maps‑nyckeln som manifest‑placeholder (används i AndroidManifest.xml) // Skicka Maps‑nyckeln som manifest‑placeholder (används i AndroidManifest.xml)
manifestPlaceholders["MAPS_API_KEY"] = propOrEmpty("MAPS_API_KEY") manifestPlaceholders["MAPS_API_KEY"] = propOrEmpty("MAPS_API_KEY")
buildConfigField("boolean", "KLLOG_DEBUG", klLogDebug.toString())
buildConfigField("boolean", "KLLOG_HTTP_DEBUG", klLogHttpDebug.toString())
} }
buildFeatures { buildFeatures {

BIN
app/release/app-release.aab Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -11,8 +11,8 @@
"type": "SINGLE", "type": "SINGLE",
"filters": [], "filters": [],
"attributes": [], "attributes": [],
"versionCode": 7, "versionCode": 8,
"versionName": "0.2.0", "versionName": "0.2.1",
"outputFile": "app-release.apk" "outputFile": "app-release.apk"
} }
], ],

View File

@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest package="app.klottr" <manifest xmlns:android="http://schemas.android.com/apk/res/android">
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Behörigheter --> <!-- Behörigheter -->
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
@@ -11,19 +10,19 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.Yorlik"> android:theme="@style/Theme.Klottr">
<meta-data <meta-data
android:name="com.google.android.geo.API_KEY" android:name="com.google.android.geo.API_KEY"
android:value="${MAPS_API_KEY}" /> android:value="${MAPS_API_KEY}" />
<activity <activity
android:name="app.klottr.MainActivity" android:name="app.klottr.MainActivity"
android:exported="true"> android:exported="true">

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

View File

@@ -12,7 +12,6 @@ import android.os.IBinder
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import app.klottr.R
import app.klottr.net.Geocache import app.klottr.net.Geocache
import app.klottr.net.NoteDTO import app.klottr.net.NoteDTO
import app.klottr.util.FoundStore import app.klottr.util.FoundStore
@@ -114,11 +113,11 @@ class LocationService : Service() {
if (!hasLocationPerms()) return if (!hasLocationPerms()) return
val req = LocationRequest.create().apply { val req = LocationRequest.create().apply {
LocationRequest.setInterval = 4_000L interval = 4_000L
LocationRequest.setFastestInterval = 2_000L fastestInterval = 2_000L
LocationRequest.setSmallestDisplacement = 3f smallestDisplacement = 3f
LocationRequest.setPriority = Priority.PRIORITY_HIGH_ACCURACY priority = Priority.PRIORITY_HIGH_ACCURACY
LocationRequest.setMaxWaitTime = 5_000L maxWaitTime = 5_000L
} }
callback = object : LocationCallback() { callback = object : LocationCallback() {

View File

@@ -28,13 +28,19 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.rememberTransformableState import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.*
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
@@ -69,6 +75,7 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.Dialog
@@ -79,12 +86,14 @@ import androidx.work.Constraints
import androidx.work.NetworkType import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager import androidx.work.WorkManager
import app.klottr.R
import app.klottr.data.AppDatabase import app.klottr.data.AppDatabase
import app.klottr.data.NoteRepository import app.klottr.data.NoteRepository
import app.klottr.net.Api import app.klottr.net.Api
import app.klottr.net.ApiConfig import app.klottr.net.ApiConfig
import app.klottr.net.DigitaltMuseum import app.klottr.net.DigitaltMuseum
import app.klottr.net.DigitaltMuseumItem import app.klottr.net.DigitaltMuseumItem
import app.klottr.net.fetchImageStreamPost
import app.klottr.net.Fornsok import app.klottr.net.Fornsok
import app.klottr.net.FornsokItem import app.klottr.net.FornsokItem
import app.klottr.net.Geocache import app.klottr.net.Geocache
@@ -93,7 +102,6 @@ import app.klottr.net.Wikipedia
import app.klottr.net.WikipediaPage import app.klottr.net.WikipediaPage
import app.klottr.net.createNoteDoc import app.klottr.net.createNoteDoc
import app.klottr.net.fetchNoteDetail import app.klottr.net.fetchNoteDetail
import app.klottr.net.imageUrl
import app.klottr.net.uploadImageFromUri import app.klottr.net.uploadImageFromUri
import app.klottr.theme.KlottrTheme import app.klottr.theme.KlottrTheme
import app.klottr.util.Auth import app.klottr.util.Auth
@@ -108,6 +116,9 @@ import app.klottr.BuildConfig
import app.klottr.util.FoundStore.LAYER_DM import app.klottr.util.FoundStore.LAYER_DM
import app.klottr.util.FoundStore.LAYER_KLOTTER import app.klottr.util.FoundStore.LAYER_KLOTTER
import app.klottr.util.FoundStore.LAYER_WIKI import app.klottr.util.FoundStore.LAYER_WIKI
import app.klottr.util.formatDistance
import app.klottr.util.formatRelativeOrTime
import app.klottr.util.formatCoords
import app.klottr.work.OutboxWorker import app.klottr.work.OutboxWorker
import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.common.api.ApiException import com.google.android.gms.common.api.ApiException
@@ -248,6 +259,65 @@ private data class DocumentDraft(
val imageUri: Uri? val imageUri: Uri?
) )
@Composable
fun AboutDialog(onDismiss: () -> Unit) {
val context = LocalContext.current
val pInfo = remember {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager.getPackageInfo(
context.packageName,
PackageManager.PackageInfoFlags.of(0)
)
} else {
@Suppress("DEPRECATION")
context.packageManager.getPackageInfo(context.packageName, 0)
}
}
val versionCode = remember(pInfo) { PackageInfoCompat.getLongVersionCode(pInfo) }
val configuration = LocalConfiguration.current
val dialogWidth = (configuration.screenWidthDp.dp * 0.9f) // 90 % av skärmen
AlertDialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false),
confirmButton = { TextButton(onClick = onDismiss) { Text("Stäng") } },
text = {
Box(
Modifier
.fillMaxWidth()
.widthIn(max = dialogWidth)
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.Start
) {
// logga centrerad
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(R.drawable.klottr_logo_v2_line),
contentDescription = null,
modifier = Modifier.height(48.dp)
)
}
Spacer(Modifier.height(40.dp)) // tomrad
Text("Version ${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE}) • build $versionCode")
Text("Byggd ${BuildConfig.BUILD_TIME_UTC}")
Spacer(Modifier.height(8.dp))
Text("Utvecklad av Fabian Norlin.")
Text("Mejlkontakt: utv@ointressant.se")
}
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
private fun KlottrApp( private fun KlottrApp(
@@ -312,6 +382,25 @@ private fun KlottrApp(
var forceEmptyFound by remember { mutableStateOf(false) } var forceEmptyFound by remember { mutableStateOf(false) }
fun refreshFound() { foundRefresh++ } fun refreshFound() { foundRefresh++ }
// Kickstarta avstånd direkt vid appstart
LaunchedEffect(Unit) {
val client = GmsLocationServices.getFusedLocationProviderClient(context)
val loc = try {
client.lastLocation.await()
?: client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
} catch (_: Exception) { null }
if (loc != null) {
// Spara som "senaste kända" och uppdatera away-flaggor
LastLocationStore.lastKnownLocation = loc
FoundStore.updateAwayFlags(context, loc.latitude, loc.longitude)
// Tvinga omritning så att avstånd visas utan scroll
locationTick++
}
}
// Direkt UI-uppdatering från LocationService // Direkt UI-uppdatering från LocationService
DisposableEffect(Unit) { DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_FOUND_UPDATED) val filter = IntentFilter(LocationService.ACTION_FOUND_UPDATED)
@@ -447,13 +536,18 @@ private fun KlottrApp(
} }
} }
var showAbout by remember { mutableStateOf(false) }
Scaffold( Scaffold(
topBar = { topBar = {
CenterAlignedTopAppBar( CenterAlignedTopAppBar(
title = { Text("Klottr v" + BuildConfig.VERSION_NAME) }, title = { Text("") },
actions = { actions = {
IconButton(onClick = { showAbout = true }) {
Icon(imageVector = Icons.Filled.Info, contentDescription = "Om")
}
IconButton(onClick = { showSettings = true }) { IconButton(onClick = { showSettings = true }) {
Icon(Icons.Filled.Settings, contentDescription = "Inställningar") Icon(imageVector = Icons.Filled.Settings, contentDescription = "Inställningar")
} }
} }
) )
@@ -507,6 +601,10 @@ private fun KlottrApp(
lastKnownLat = loc.latitude lastKnownLat = loc.latitude
lastKnownLon = loc.longitude lastKnownLon = loc.longitude
app.klottr.util.AppLog.d { "Närliggande-debug: toggles klotter=$showKlotter wiki=$showWiki dm=$showDm forn=$showFornsok"}
app.klottr.util.AppLog.d { "Närliggande-debug: loc=${lastKnownLat},${lastKnownLon}"}
// Re-arm: markera alla tidigare fynd som "borta" om vi nu står >200 m från dem // Re-arm: markera alla tidigare fynd som "borta" om vi nu står >200 m från dem
FoundStore.updateAwayFlags(context, loc.latitude, loc.longitude) FoundStore.updateAwayFlags(context, loc.latitude, loc.longitude)
@@ -545,7 +643,7 @@ private fun KlottrApp(
) )
} }
} else nearbyFornsok = emptyList() } else nearbyFornsok = emptyList()
app.klottr.util.AppLog.d { "Närliggande-debug: counts klotter=${nearbyKlotter.size} wiki=${nearbyWiki.size} dm=${nearbyDm.size} forn=${nearbyFornsok.size}"}
nearbyLoading = false nearbyLoading = false
} }
}) { Text("Närliggande") } }) { Text("Närliggande") }
@@ -581,13 +679,9 @@ private fun KlottrApp(
val img = detail.image val img = detail.image
if (img != null && img.id > 0 && ImageBitmapCache.get(img.id) == null) { if (img != null && img.id > 0 && ImageBitmapCache.get(img.id) == null) {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val url = imageUrl(img.id, detail.id, f.lat, f.lon) fetchImageStreamPost(img.id, detail.id, f.lat, f.lon)?.byteStream()?.use { ins ->
val resp = Api.svc.getImageStream(url) BitmapFactory.decodeStream(ins)?.let { bmp ->
if (resp.isSuccessful) { ImageBitmapCache.put(img.id, bmp)
resp.body()?.byteStream()?.use { ins ->
BitmapFactory.decodeStream(ins)?.let { bmp ->
ImageBitmapCache.put(img.id, bmp)
}
} }
} }
} }
@@ -618,10 +712,8 @@ 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)
// --- NYTT: hämta away/first/last för UI --- // --- Hämta away för UI ---
val away = FoundStore.isAway(context, f.layer, f.id) val away = FoundStore.isAway(context, f.layer, f.id)
val firstVis = FoundStore.getFirstVisitMillis(context, f.layer, f.id)
val lastVis = FoundStore.getLastVisitMillis(context, f.layer, f.id) ?: f.timeMillis
ListItem( ListItem(
headlineContent = { headlineContent = {
@@ -651,21 +743,16 @@ private fun KlottrApp(
// 2) Avstånd från senaste kända position // 2) Avstånd från senaste kända position
val my = LastLocationStore.lastKnownLocation val my = LastLocationStore.lastKnownLocation
val distM = my?.let { distanceMeters(it.latitude, it.longitude, f.lat, f.lon).roundToInt() } val distM = my?.let { distanceMeters(it.latitude, it.longitude, f.lat, f.lon).roundToInt() }
val distText = distM?.let { "$it\u00A0m" } ?: "-" // \u00A0 = hårt mellanslag val distText = distM?.let { formatDistance(it) } ?: "-"
// 3) Ev. koordinater (om toggeln är på) // 3) Ev. koordinater (om toggeln är på)
val coordPart = if (showCoords) " • (%.5f, %.5f)".format(f.lat, f.lon) else "" val coordPart = if (showCoords) " • " + formatCoords(f.lat, f.lon) else ""
// 4) Tider från FoundStore (för debug/insikt)
val firstVis = FoundStore.getFirstVisitMillis(context, f.layer, f.id)
val lastVis = FoundStore.getLastVisitMillis(context, f.layer, f.id) ?: f.timeMillis
val firstText = firstVis?.let { formatTime(it) } ?: "-"
val lastText = formatTime(lastVis)
// 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 raderana ritas om när platsen uppdateras.
val _tick = locationTick // ignoreras, men binder UI till ticks val _tick = locationTick // ignoreras, men binder UI till ticks
Text("Första: $firstText • Senaste: $lastText • $layerName • $distText$coordPart") Text("$layerName • $distText$coordPart")
}, },
modifier = if (clickable) Modifier.clickable { modifier = if (clickable) Modifier.clickable {
when (f.layer) { when (f.layer) {
@@ -719,7 +806,10 @@ private fun KlottrApp(
} }
} }
} }
// Om-appen
if (showAbout) {
AboutDialog { showAbout = false }
}
// Närliggande // Närliggande
if (showNearby) { if (showNearby) {
NearbyDialog( NearbyDialog(
@@ -1469,12 +1559,12 @@ private fun SettingsDialog(
// Snabbinställningar // Snabbinställningar
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Text("Visa endast nytt klotter", modifier = Modifier.weight(1f)) Text("Visa endast nya fynd", modifier = Modifier.weight(1f))
Switch(checked = onlyNew, onCheckedChange = onOnlyNewChanged) Switch(checked = onlyNew, onCheckedChange = onOnlyNewChanged)
} }
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Text("Skriv ut GPS-koordinater", modifier = Modifier.weight(1f)) Text("Visa GPS-koordinater", modifier = Modifier.weight(1f))
Switch(checked = showCoords, onCheckedChange = onShowCoordsChanged) Switch(checked = showCoords, onCheckedChange = onShowCoordsChanged)
} }
@@ -1670,6 +1760,21 @@ private fun KlotterDialog(
) { ) {
val context = LocalContext.current val context = LocalContext.current
val firstVisitText by remember(id) {
mutableStateOf(
FoundStore.getFirstVisitMillis(context, FoundStore.LAYER_KLOTTER, id)
?.let { formatRelativeOrTime(it) } ?: "-"
)
}
val lastVisitText by remember(id) {
mutableStateOf(
(FoundStore.getLastVisitMillis(context, FoundStore.LAYER_KLOTTER, id)
?: System.currentTimeMillis()).let { formatRelativeOrTime(it) }
)
}
var loading by remember { mutableStateOf(true) } var loading by remember { mutableStateOf(true) }
var text by remember { mutableStateOf(label) } var text by remember { mutableStateOf(label) }
var titleText by remember { mutableStateOf(label.ifBlank { "Okänt klotter" }) } var titleText by remember { mutableStateOf(label.ifBlank { "Okänt klotter" }) }
@@ -1677,6 +1782,34 @@ private fun KlotterDialog(
var showImageViewer by remember { mutableStateOf(false) } var showImageViewer by remember { mutableStateOf(false) }
var prefilledFromCache by remember { mutableStateOf(false) } var prefilledFromCache by remember { mutableStateOf(false) }
// Lager + avstånd (uppdateras när plats-tick sänds)
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates(context) }
var distanceText by remember { mutableStateOf("-") }
fun recalcDistance() {
val my = app.klottr.util.LastLocationStore.lastKnownLocation
val d = my?.let { distanceMeters(it.latitude, it.longitude, lat, lon).roundToInt() }
distanceText = d?.let { "$it\u00A0m" } ?: "-" // hårt mellanslag
}
// Räkna ut direkt vid öppning
LaunchedEffect(Unit) { recalcDistance() }
// Lyssna på plats-tick så avståndet uppdateras live
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { recalcDistance() }
}
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) {} }
}
// Snabb hydrering från cache om vi redan har detalj/bild // Snabb hydrering från cache om vi redan har detalj/bild
LaunchedEffect(id) { LaunchedEffect(id) {
val idL = id.toLongOrNull() val idL = id.toLongOrNull()
@@ -1702,7 +1835,7 @@ private fun KlotterDialog(
val baseLabel = label.trim() val baseLabel = label.trim()
val isKnown = baseLabel.isNotBlank() && baseLabel != "Okänt klotter" val isKnown = baseLabel.isNotBlank() && baseLabel != "Okänt klotter"
Log.d("Klottr", "KlotterDialog start id=$id isKnown=$isKnown label='${baseLabel.take(40)}'") app.klottr.util.AppLog.d { "KlotterDialog start id=$id isKnown=$isKnown label='${baseLabel.take(40)}'"}
// Hämta ev. färsk plats (fallback LastLocationStore) // Hämta ev. färsk plats (fallback LastLocationStore)
val my = LastLocationStore.lastKnownLocation val my = LastLocationStore.lastKnownLocation
@@ -1723,7 +1856,7 @@ private fun KlotterDialog(
// Försök hämta detalj/bild om posten är känd (Hittat) ELLER vi är inom radien // Försök hämta detalj/bild om posten är känd (Hittat) ELLER vi är inom radien
val canAttempt = isKnown || withinRadius val canAttempt = isKnown || withinRadius
Log.d("Klottr", "KlotterDialog canAttempt=$canAttempt withinRadius=$withinRadius") app.klottr.util.AppLog.d { "KlotterDialog canAttempt=$canAttempt withinRadius=$withinRadius"}
if (canAttempt) { if (canAttempt) {
// get_note.php ska få: Hittat => NOTISENS coords, annars besökarens (fallback notisens) // get_note.php ska få: Hittat => NOTISENS coords, annars besökarens (fallback notisens)
@@ -1735,7 +1868,7 @@ private fun KlotterDialog(
fetchNoteDetail(id.toLong(), reqLat, reqLon) fetchNoteDetail(id.toLong(), reqLat, reqLon)
} catch (_: Throwable) { null } } catch (_: Throwable) { null }
} }
Log.d("Klottr", "detail fetch id=$id ok=${detail != null}") app.klottr.util.AppLog.d { "detail fetch id=$id ok=${detail != null}"}
if (detail != null) { if (detail != null) {
// Sätt titel + brödtext från servern // Sätt titel + brödtext från servern
@@ -1747,35 +1880,29 @@ private fun KlotterDialog(
NoteDetailCache.put(detail.id, detail) NoteDetailCache.put(detail.id, detail)
} }
// Bild: bygg URL som innehåller NOTISENS koordinater (servern kräver koordinat-bevis) // Bild: hämta via POST (GDPR-fix), tunga saker i IO — uppdatera UI på huvudtråden.
val imgMeta = detail.image val imgMeta = detail.image
if (imgMeta != null && imgMeta.id > 0) { if (imgMeta != null && imgMeta.id > 0) {
val partial = imgMeta.url?.trim().orEmpty()
val fullUrl = if (partial.isNotEmpty()) { // 1) Nätverk + bitmap-dekodning i IO
val absolute = ApiConfig.SERVER_API_BASE_URL + partial val bmp = withContext(Dispatchers.IO) {
if (absolute.contains("lat=") && absolute.contains("lon=")) { fetchImageStreamPost(
absolute imageId = imgMeta.id,
} else { noteId = detail.id,
val sep = if (absolute.contains("?")) "&" else "?" lat = lat, // NOTISENS lat (servern kräver koordinat-bevis)
absolute + "${sep}lat=$lat&lon=$lon" // NOTISENS coords lon = lon // NOTISENS lon
)?.byteStream()?.use { ins ->
BitmapFactory.decodeStream(ins)
} }
} else {
imageUrl(imgMeta.id, detail.id, lat, lon) // NOTISENS coords
} }
val resp = withContext(Dispatchers.IO) { // 2) Tillbaka på huvudtråden: uppdatera UI-tillstånd här
runCatching { Api.svc.getImageStream(fullUrl) }.getOrNull() app.klottr.util.AppLog.d { "img POST ok=${bmp != null} id=${imgMeta.id} note=${detail.id}"}
}
Log.d("Klottr", "img GET code=${resp?.code()} url=$fullUrl")
val bmp = if (resp?.isSuccessful == true) {
resp.body()?.byteStream()?.use { BitmapFactory.decodeStream(it) }
} else null
if (bmp != null) { if (bmp != null) {
imgBitmap = bmp imgBitmap = bmp
// cachea för snabb öppning nästa gång if (imgMeta.id > 0) {
val imgId = imgMeta.id ImageBitmapCache.put(imgMeta.id, bmp)
if (imgId > 0) ImageBitmapCache.put(imgId, bmp) }
} }
} }
} else { } else {
@@ -1790,7 +1917,6 @@ private fun KlotterDialog(
titleText = "Okänt klotter" titleText = "Okänt klotter"
text = "Okänt klotter. Du måste vara inom ${Config.DEFAULT_KLOTTER_RADIUS_M}\u00A0m för att se texten." text = "Okänt klotter. Du måste vara inom ${Config.DEFAULT_KLOTTER_RADIUS_M}\u00A0m för att se texten."
} }
loading = false loading = false
} }
Dialog( Dialog(
@@ -1837,6 +1963,24 @@ private fun KlotterDialog(
// Brödtext alltid synlig (även under loading) // Brödtext alltid synlig (även under loading)
Text(text) Text(text)
HorizontalDivider()
// "Klotter • 37 m (ev. koordinater)"
val coordPart = if (showCoords) " • " + formatCoords(lat, lon) else ""
Text(
"Klotter • $distanceText bort$coordPart",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text("Först besökt: $firstVisitText", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text("Senast besökt: $lastVisitText", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
// Knappar på EN rad: Maps till vänster, Stäng till höger // Knappar på EN rad: Maps till vänster, Stäng till höger
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -1846,7 +1990,10 @@ private fun KlotterDialog(
onClick = { onClick = {
val labelEnc = Uri.encode(titleText.ifBlank { "Plats" }) val labelEnc = Uri.encode(titleText.ifBlank { "Plats" })
val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon($labelEnc)") val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon($labelEnc)")
val intent = Intent(Intent.ACTION_VIEW, uri).apply { Intent.setPackage = "com.google.android.apps.maps" } val intent = Intent(
Intent.ACTION_VIEW,
uri
).apply { setPackage("com.google.android.apps.maps") }
try { context.startActivity(intent) } catch (_: Exception) { try { context.startActivity(intent) } catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, uri)) context.startActivity(Intent(Intent.ACTION_VIEW, uri))
} }
@@ -1929,6 +2076,36 @@ private fun WikiArticleDialog(
var extract by remember { mutableStateOf("") } var extract by remember { mutableStateOf("") }
var thumb: Bitmap? by remember { mutableStateOf(null) } var thumb: Bitmap? by remember { mutableStateOf(null) }
// Avståndstext som uppdateras när platsen tickar
var wikiDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates(context) }
fun recalcWikiDistance() {
val my = app.klottr.util.LastLocationStore.lastKnownLocation
val d = if (lat != null && lon != null && my != null)
distanceMeters(my.latitude, my.longitude, lat, lon).roundToInt()
else null
wikiDistanceText = d?.let { "$it\u00A0m" } ?: "-"
}
// Beräkna direkt
LaunchedEffect(lat, lon) { recalcWikiDistance() }
// Lyssna på plats-tick för att uppdatera avståndet live
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { recalcWikiDistance() }
}
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) {} }
}
LaunchedEffect(pageId) { LaunchedEffect(pageId) {
loading = true loading = true
val detail = withContext(Dispatchers.IO) { Wikipedia.getExtract(pageId) } val detail = withContext(Dispatchers.IO) { Wikipedia.getExtract(pageId) }
@@ -1974,6 +2151,17 @@ private fun WikiArticleDialog(
) )
} }
Text(extract.ifBlank { "Ingen sammanfattning tillgänglig." }) Text(extract.ifBlank { "Ingen sammanfattning tillgänglig." })
HorizontalDivider()
val bottomCoordPart = if (showCoords) " • (%.5f, %.5f)".format(lat, lon) else ""
Text(
"Klotter • $wikiDistanceText bort$bottomCoordPart",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Button( Button(
onClick = { onClick = {
@@ -1986,9 +2174,10 @@ private fun WikiArticleDialog(
onClick = { onClick = {
if (lat != null && lon != null) { if (lat != null && lon != null) {
val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon(${Uri.encode(title.ifBlank { "Wikipedia-plats" })})") val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon(${Uri.encode(title.ifBlank { "Wikipedia-plats" })})")
val intent = Intent(Intent.ACTION_VIEW, uri).apply { val intent = Intent(
Intent.setPackage = "com.google.android.apps.maps" Intent.ACTION_VIEW,
} uri
).apply { setPackage("com.google.android.apps.maps") }
try { context.startActivity(intent) } catch (_: Exception) { try { context.startActivity(intent) } catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, uri)) context.startActivity(Intent(Intent.ACTION_VIEW, uri))
} }
@@ -2021,6 +2210,38 @@ private fun FornsokDialog(
val platLat = item.lat val platLat = item.lat
val platLon = item.lon val platLon = item.lon
// Avståndstext som uppdateras på plats-tick
var fornDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates(context) }
fun recalcFornDistance() {
val my = app.klottr.util.LastLocationStore.lastKnownLocation
val d = if (my != null)
distanceMeters(my.latitude, my.longitude, platLat, platLon).roundToInt()
else null
fornDistanceText = d?.let { "$it\u00A0m" } ?: "-"
}
// Beräkna direkt
LaunchedEffect(platLat, platLon) { recalcFornDistance() }
// Lyssna på plats-tick
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { recalcFornDistance() }
}
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) {} }
}
AlertDialog( AlertDialog(
onDismissRequest = onClose, onDismissRequest = onClose,
properties = DialogProperties(usePlatformDefaultWidth = false), properties = DialogProperties(usePlatformDefaultWidth = false),
@@ -2043,14 +2264,26 @@ private fun FornsokDialog(
verticalArrangement = Arrangement.spacedBy(12.dp) verticalArrangement = Arrangement.spacedBy(12.dp)
) { ) {
Text(desc.ifBlank { "Ingen sammanfattning tillgänglig." }) Text(desc.ifBlank { "Ingen sammanfattning tillgänglig." })
HorizontalDivider()
val coordPart = if (showCoords) " • " + formatCoords(platLat, platLon) else ""
Text(
"Fornsök • $fornDistanceText bort$coordPart",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Button( Button(
onClick = { onClick = {
val geoTitle = Uri.encode(title) val geoTitle = Uri.encode(title)
val geo = Uri.parse("geo:$platLat,$platLon?q=$platLat,$platLon($geoTitle)") val geo = Uri.parse("geo:$platLat,$platLon?q=$platLat,$platLon($geoTitle)")
val intent = Intent(Intent.ACTION_VIEW, geo).apply { val intent = Intent(
Intent.setPackage = "com.google.android.apps.maps" Intent.ACTION_VIEW,
} geo
).apply { setPackage("com.google.android.apps.maps") }
try { context.startActivity(intent) } catch (_: Exception) { try { context.startActivity(intent) } catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, geo)) context.startActivity(Intent(Intent.ACTION_VIEW, geo))
} }
@@ -2090,12 +2323,6 @@ fun hasBgLocationPerm(ctx: Context): Boolean {
) == PackageManager.PERMISSION_GRANTED ) == PackageManager.PERMISSION_GRANTED
} }
private fun formatTime(ms: Long): String {
val z = ZoneId.systemDefault()
val t = Instant.ofEpochMilli(ms).atZone(z)
return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(t)
}
private fun distanceMeters(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double { private fun distanceMeters(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double {
val R = 6371000.0 val R = 6371000.0
val dLat = Math.toRadians(bLat - aLat) val dLat = Math.toRadians(bLat - aLat)

View File

@@ -337,9 +337,8 @@ fun MapDialog(
private fun openInMaps(ctx: Context, lat: Double?, lon: Double?, title: String?) { private fun openInMaps(ctx: Context, lat: Double?, lon: Double?, title: String?) {
if (lat == null || lon == null) return if (lat == null || lon == null) return
val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon(${Uri.encode(title ?: "Plats")})") val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon(${Uri.encode(title ?: "Plats")})")
val intent = Intent(Intent.ACTION_VIEW, uri).apply { val intent =
Intent.setPackage = "com.google.android.apps.maps" Intent(Intent.ACTION_VIEW, uri).apply { setPackage("com.google.android.apps.maps") }
}
try { try {
ctx.startActivity(intent) ctx.startActivity(intent)
} catch (_: Exception) { } catch (_: Exception) {
@@ -351,9 +350,8 @@ private fun openWalkingDirections(ctx: Context, lat: Double?, lon: Double?, titl
if (lat == null || lon == null) return if (lat == null || lon == null) return
val label = Uri.encode(title ?: "Plats") val label = Uri.encode(title ?: "Plats")
val uri = Uri.parse("google.navigation?q=$lat,$lon($label)&mode=w") val uri = Uri.parse("google.navigation?q=$lat,$lon($label)&mode=w")
val intent = Intent(Intent.ACTION_VIEW, uri).apply { val intent =
Intent.setPackage = "com.google.android.apps.maps" Intent(Intent.ACTION_VIEW, uri).apply { setPackage("com.google.android.apps.maps") }
}
try { try {
ctx.startActivity(intent) ctx.startActivity(intent)
} catch (_: Exception) { } catch (_: Exception) {

View File

@@ -38,8 +38,8 @@ object ApiConfig {
if (u.endsWith("/")) u else "$u/" if (u.endsWith("/")) u else "$u/"
} }
// v0.1.1: helper för säkra bild-URL:er. Bygger API-URL till get_image.php (kräver aktuell lat/lon för närhetslås) // v0.1.1: helper för säkra bild-URL:er. Bygger API-URL till get_image.php (kräver aktuell lat/lon för närhetslås)
fun imageUrl(imageId: Long, noteId: Long, lat: Double, lon: Double): String = //fun imageUrl(imageId: Long, noteId: Long, lat: Double, lon: Double): String =
"${ApiConfig.SERVER_API_BASE_URL}get_image.php?id=$imageId&note=$noteId&lat=$lat&lon=$lon" // "${ApiConfig.SERVER_API_BASE_URL}get_image.php?id=$imageId&note=$noteId&lat=$lat&lon=$lon"
/** Kompakta fält enligt nearby.php (behållna som i v0.0.1) */ /** Kompakta fält enligt nearby.php (behållna som i v0.0.1) */
data class NoteDTO( data class NoteDTO(
@@ -70,7 +70,6 @@ data class UploadImageResp(
val height: Int? = null val height: Int? = null
) )
/** Ny body till create.php när vi skickar dokument (rubrik/brödtext/bild) */ /** Ny body till create.php när vi skickar dokument (rubrik/brödtext/bild) */
data class CreateDocBody( data class CreateDocBody(
val lat: Double, val lat: Double,
@@ -108,6 +107,14 @@ data class NoteDetailBody(
val lon: Double val lon: Double
) )
// Body till nearby.php (POST)
data class NearbyBody(
val lat: Double,
val lon: Double,
@Json(name = "r") val radiusMeters: Int,
val since: Long = 0,
val limit: Int = 200
)
/** Dina endpoints – samma namn/banor som i v0.0.1 */ /** Dina endpoints – samma namn/banor som i v0.0.1 */
interface KlottrApi { interface KlottrApi {
@@ -133,8 +140,16 @@ interface KlottrApi {
@POST("get_note.php") @POST("get_note.php")
suspend fun getNote(@Body body: NoteDetailBody): RResponse<NoteDetailDTO> suspend fun getNote(@Body body: NoteDetailBody): RResponse<NoteDetailDTO>
@GET /** Hämtar en bildström via POST (form-url-encoded) så PHP får fält i $_POST. */
suspend fun getImageStream(@Url url: String): RResponse<ResponseBody> @FormUrlEncoded
@POST("get_image.php")
@Streaming
suspend fun getImagePost(
@Field("id") id: Long,
@Field("note") noteId: Long,
@Field("lat") lat: Double,
@Field("lon") lon: Double
): RResponse<ResponseBody>
@POST("create.php") @POST("create.php")
suspend fun create( suspend fun create(
@@ -142,15 +157,13 @@ interface KlottrApi {
@Header("X-Idempotency-Key") idempotencyKey: String? = null @Header("X-Idempotency-Key") idempotencyKey: String? = null
): RResponse<Map<String, Any>> ): RResponse<Map<String, Any>>
@GET("nearby.php") /** Hämtar närliggande klotter (via POST-body i stället för GET). */
@POST("nearby.php")
suspend fun nearby( suspend fun nearby(
@Query("lat") lat: Double, @Body body: NearbyBody,
@Query("lon") lon: Double,
@Query("r") radiusMeters: Int,
@Query("since") sinceMs: Long = 0,
@Query("limit") limit: Int = 200,
@Header("If-None-Match") etag: String? = null @Header("If-None-Match") etag: String? = null
): RResponse<List<NoteDTO>> ): RResponse<List<NoteDTO>>
} }
/** Lägger API‑nyckel + ev. Google ID‑token (Bearer) på varje request. */ /** Lägger API‑nyckel + ev. Google ID‑token (Bearer) på varje request. */
@@ -185,10 +198,8 @@ object Api {
.readTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS)
.also { b -> .also { b ->
if (BuildConfig.DEBUG) { if (BuildConfig.KLLOG_HTTP_DEBUG) {
val log = HttpLoggingInterceptor() val log = HttpLoggingInterceptor()
// log.level = HttpLoggingInterceptor.Level.BASIC
// log.level = HttpLoggingInterceptor.Level.HEADERS
log.level = HttpLoggingInterceptor.Level.BODY log.level = HttpLoggingInterceptor.Level.BODY
b.addInterceptor(log) b.addInterceptor(log)
} }
@@ -228,22 +239,31 @@ suspend fun fetchNearby(
): NearbyResult { ): NearbyResult {
val resp = try { val resp = try {
Api.svc.nearby( Api.svc.nearby(
lat = lat, body = NearbyBody(
lon = lon, lat = lat,
radiusMeters = radiusMeters, lon = lon,
sinceMs = sinceMs, radiusMeters = radiusMeters,
limit = limit, since = sinceMs,
limit = limit
),
etag = lastEtag etag = lastEtag
) )
} catch (t: Throwable) { } catch (t: Throwable) {
// Nätfel – presentera som “inga nya” men kod 599 (icke‑standard) för att kunna skilja i logik
return NearbyResult(code = 599, items = emptyList(), etag = lastEtag) return NearbyResult(code = 599, items = emptyList(), etag = lastEtag)
} }
val code = resp.code()
val newEtag = resp.headers()["ETag"] ?: lastEtag val newEtag = resp.headers()["ETag"] ?: lastEtag
val body = if (resp.isSuccessful) resp.body().orEmpty() else emptyList() val body = if (resp.isSuccessful) resp.body().orEmpty() else emptyList()
// 🔧 Tydligare loggning vid felkoder – annars ser det bara ut som tom lista
if (!resp.isSuccessful) {
val err = resp.errorBody()?.string()
app.klottr.util.AppLog.d { "nearby.php FAIL code=$code url=${ApiConfig.SERVER_API_BASE_URL}nearby.php err=$err" }
}
return NearbyResult( return NearbyResult(
code = resp.code(), code = code,
items = body, items = body,
etag = newEtag etag = newEtag
) )
@@ -283,14 +303,14 @@ suspend fun uploadImageFromUri(
val lonPart = lon.toString().toRequestBody("text/plain".toMediaTypeOrNull()) val lonPart = lon.toString().toRequestBody("text/plain".toMediaTypeOrNull())
val resp = try { Api.svc.uploadImage(imgPart, latPart, lonPart) } catch (t: Throwable) { val resp = try { Api.svc.uploadImage(imgPart, latPart, lonPart) } catch (t: Throwable) {
Log.d("Klottr", "uploadImage exception: ${t.message}") app.klottr.util.AppLog.d { "uploadImage exception: ${t.message}"}
return null return null
} }
Log.d("Klottr", "uploadImage code=${resp.code()} body=${resp.body()}") app.klottr.util.AppLog.d { "uploadImage code=${resp.code()} body=${resp.body()}"}
if (!resp.isSuccessful) { if (!resp.isSuccessful) {
val err = resp.errorBody()?.string() val err = resp.errorBody()?.string()
Log.d("Klottr", "uploadImage FAIL code=${resp.code()} err=$err") app.klottr.util.AppLog.d { "uploadImage FAIL code=${resp.code()} err=$err"}
// Försök plocka ut {"error": "...", "max": "..."} om servern skickar det // Försök plocka ut {"error": "...", "max": "..."} om servern skickar det
Api.lastUploadError = extractApiErrorMessage(err) ?: "Uppladdningen misslyckades (kod ${resp.code()})." Api.lastUploadError = extractApiErrorMessage(err) ?: "Uppladdningen misslyckades (kod ${resp.code()})."
return null return null
@@ -349,14 +369,14 @@ suspend fun uploadImageFromFile(
val lonPart = lon.toString().toRequestBody("text/plain".toMediaTypeOrNull()) val lonPart = lon.toString().toRequestBody("text/plain".toMediaTypeOrNull())
val resp = try { Api.svc.uploadImage(imgPart, latPart, lonPart) } catch (t: Throwable) { val resp = try { Api.svc.uploadImage(imgPart, latPart, lonPart) } catch (t: Throwable) {
Log.d("Klottr", "uploadImage(file) exception: ${t.message}") app.klottr.util.AppLog.d { "uploadImage(file) exception: ${t.message}"}
return null return null
} }
Log.d("Klottr", "uploadImage(file) code=${resp.code()} body=${resp.body()}") app.klottr.util.AppLog.d { "uploadImage(file) code=${resp.code()} body=${resp.body()}"}
if (!resp.isSuccessful) { if (!resp.isSuccessful) {
val err = resp.errorBody()?.string() val err = resp.errorBody()?.string()
Log.d("Klottr", "uploadImage(file) FAIL code=${resp.code()} err=$err") app.klottr.util.AppLog.d { "uploadImage(file) FAIL code=${resp.code()} err=$err"}
return null return null
} }
@@ -445,29 +465,52 @@ suspend fun fetchNoteDetail(id: Long, lat: Double, lon: Double): NoteDetailDTO?
val body = NoteDetailBody(id = id, lat = lat, lon = lon) val body = NoteDetailBody(id = id, lat = lat, lon = lon)
return try { return try {
val resp = Api.svc.getNote(body) val resp = Api.svc.getNote(body)
Log.d("Klottr", "get_note code=${resp.code()} ok=${resp.isSuccessful}") app.klottr.util.AppLog.d { "get_note code=${resp.code()} ok=${resp.isSuccessful}"}
if (!resp.isSuccessful) { if (!resp.isSuccessful) {
val err = resp.errorBody()?.string() val err = resp.errorBody()?.string()
Log.d("Klottr", "get_note err=$err") app.klottr.util.AppLog.d { "get_note err=$err"}
null null
} else { } else {
resp.body() resp.body()
} }
} catch (t: Throwable) { } catch (t: Throwable) {
Log.d("Klottr", "get_note exception: ${t.message}") app.klottr.util.AppLog.d { "get_note exception: ${t.message}"}
null
}
}
/** Hjälpfunktion för att hämta en bildström via POST (form-POST till PHP). */
suspend fun fetchImageStreamPost(
imageId: Long,
noteId: Long,
lat: Double,
lon: Double
): ResponseBody? {
return try {
val resp = Api.svc.getImagePost(
id = imageId,
noteId = noteId,
lat = lat,
lon = lon
)
if (resp.isSuccessful) {
resp.body()
} else {
app.klottr.util.AppLog.d { "get_image FAIL code=${resp.code()} err=${resp.errorBody()?.string()}" }
null
}
} catch (t: Throwable) {
app.klottr.util.AppLog.d { "get_image exception: ${t.message}" }
null null
} }
} }
//suspend fun fetchNoteDetail(id: Long, lat: Double, lon: Double): NoteDetailDTO? { private data class ApiErr(
// val body = mapOf("id" to id, "lat" to lat, "lon" to lon) val error: String? = null,
// val resp = try { Api.svc.getNote(body) } catch (_: Throwable) { return null } val max: String? = null,
// if (!resp.isSuccessful) return null @Json(name = "max_bytes") val maxBytes: Long? = null
// return resp.body() )
//}
private data class ApiErr(val error: String? = null, val max: String? = null, @Json(name = "max_bytes") val maxBytes: Long? = null)
private fun extractApiErrorMessage(json: String?): String? { private fun extractApiErrorMessage(json: String?): String? {
if (json.isNullOrBlank()) return null if (json.isNullOrBlank()) return null

View File

@@ -39,26 +39,24 @@ object Fornsok {
): List<FornsokItem> = withContext(Dispatchers.IO) { ): List<FornsokItem> = withContext(Dispatchers.IO) {
val bbox = bboxWgs84(lat, lon, radiusMeters) val bbox = bboxWgs84(lat, lon, radiusMeters)
Log.d( app.klottr.util.AppLog.d(TAG)
TAG, { "BBox W,S,E,N = ${fmt6(bbox.w)} ${fmt6(bbox.s)} ${fmt6(bbox.e)} ${fmt6(bbox.n)} (radie=${radiusMeters} m)" }
"BBox W,S,E,N = ${fmt6(bbox.w)} ${fmt6(bbox.s)} ${fmt6(bbox.e)} ${fmt6(bbox.n)} (radie=${radiusMeters} m)"
)
val cqlBase = val cqlBase =
"""boundingBox=/WGS84 "${fmt8(bbox.w)} ${fmt8(bbox.s)} ${fmt8(bbox.e)} ${fmt8(bbox.n)}" AND geoDataExists="j" AND (serviceName="kmr_lamningar" OR serviceName="fmi")""" """boundingBox=/WGS84 "${fmt8(bbox.w)} ${fmt8(bbox.s)} ${fmt8(bbox.e)} ${fmt8(bbox.n)}" AND geoDataExists="j" AND (serviceName="kmr_lamningar" OR serviceName="fmi")"""
Log.d(TAG, "CQL = $cqlBase") app.klottr.util.AppLog.d(TAG) { "CQL = $cqlBase"}
// Fas 1: presentation (snabb) // Fas 1: presentation (snabb)
val fast = queryAndParse(cqlBase, usePresentation = true, maxPages = MAX_PAGES_FAST) val fast = queryAndParse(cqlBase, usePresentation = true, maxPages = MAX_PAGES_FAST)
if (fast.isNotEmpty()) { if (fast.isNotEmpty()) {
Log.d(TAG, "FÄRDIGA FORNSÖK-OBJEKT (presentation): ${fast.size} st") app.klottr.util.AppLog.d(TAG) { "FÄRDIGA FORNSÖK-OBJEKT (presentation): ${fast.size} st"}
return@withContext fast return@withContext fast
} }
// Fas 2: fullt schema (utan recordSchema) // Fas 2: fullt schema (utan recordSchema)
Log.d(TAG, "Inga coords via presentation – provar fullt schema (utan recordSchema).") app.klottr.util.AppLog.d(TAG) { "Inga coords via presentation – provar fullt schema (utan recordSchema)."}
val full = queryAndParse(cqlBase, usePresentation = false, maxPages = MAX_PAGES_FALLBACK) val full = queryAndParse(cqlBase, usePresentation = false, maxPages = MAX_PAGES_FALLBACK)
Log.d(TAG, "FÄRDIGA FORNSÖK-OBJEKT (fullt schema): ${full.size} st") app.klottr.util.AppLog.d(TAG) { "FÄRDIGA FORNSÖK-OBJEKT (fullt schema): ${full.size} st"}
return@withContext full return@withContext full
} }
@@ -66,7 +64,7 @@ object Fornsok {
suspend fun getByEntityUri(entityUri: String): FornsokItem? = withContext(Dispatchers.IO) { suspend fun getByEntityUri(entityUri: String): FornsokItem? = withContext(Dispatchers.IO) {
val cql = """entityUri="$entityUri"""" val cql = """entityUri="$entityUri""""
val url = buildUrl(cql, startRecord = 1, usePresentation = true) val url = buildUrl(cql, startRecord = 1, usePresentation = true)
Log.d(TAG, "Detalj: GET $url") app.klottr.util.AppLog.d(TAG) { "Detalj: GET $url"}
val root = httpGetJson(url) ?: return@withContext null val root = httpGetJson(url) ?: return@withContext null
val result = root.optJSONObject("result") ?: return@withContext null val result = root.optJSONObject("result") ?: return@withContext null
@@ -152,7 +150,7 @@ object Fornsok {
return try { return try {
val code = conn.responseCode val code = conn.responseCode
val ctype = conn.getHeaderField("Content-Type") val ctype = conn.getHeaderField("Content-Type")
Log.d(TAG, "HTTP $code Content-Type=$ctype") app.klottr.util.AppLog.d(TAG) { "HTTP $code Content-Type=$ctype"}
if (code !in 200..299) return null if (code !in 200..299) return null
val body = conn.inputStream.use { it.readBytes().toString(Charsets.UTF_8) } val body = conn.inputStream.use { it.readBytes().toString(Charsets.UTF_8) }
if (body.isBlank()) return null if (body.isBlank()) return null
@@ -172,13 +170,13 @@ object Fornsok {
while (page <= maxPages) { while (page <= maxPages) {
val url = buildUrl(cql, start, usePresentation) val url = buildUrl(cql, start, usePresentation)
Log.d(TAG, "Sida $page: GET $url") app.klottr.util.AppLog.d(TAG) { "Sida $page: GET $url"}
val root = httpGetJson(url) ?: break val root = httpGetJson(url) ?: break
val result = root.optJSONObject("result") ?: break val result = root.optJSONObject("result") ?: break
if (totalHitsFromServer < 0) { if (totalHitsFromServer < 0) {
totalHitsFromServer = result.optInt("totalHits", -1) totalHitsFromServer = result.optInt("totalHits", -1)
Log.d(TAG, "totalHits (server): $totalHitsFromServer") app.klottr.util.AppLog.d(TAG) { "totalHits (server): $totalHitsFromServer"}
} }
val recordsNode = result.opt("records") val recordsNode = result.opt("records")
@@ -195,7 +193,7 @@ object Fornsok {
} }
if (recordArr.length() == 0) { if (recordArr.length() == 0) {
Log.d(TAG, "Ingen records.record på denna sida.") app.klottr.util.AppLog.d(TAG) { "Ingen records.record på denna sida."}
break break
} }
@@ -273,11 +271,7 @@ object Fornsok {
added++ added++
} }
} }
app.klottr.util.AppLog.d(TAG) {"Sida: genomgång visited=$visited, nonKmrFmi=$nonKmrFmi, noCoords=$noCoords, tillagda=$added, ack=${out.size}" }
Log.d(
TAG,
"Sida: genomgång visited=$visited, nonKmrFmi=$nonKmrFmi, noCoords=$noCoords, tillagda=$added, ack=${out.size}"
)
// Fler sidor? // Fler sidor?
if (totalHitsFromServer > 0) { if (totalHitsFromServer > 0) {

View File

@@ -57,6 +57,9 @@ object Geocache {
sinceMs = prev?.sinceMs ?: 0L, sinceMs = prev?.sinceMs ?: 0L,
etag = prev?.etag etag = prev?.etag
) )
if (first.code !in listOf(200, 304)) {
app.klottr.util.AppLog.d {"Geocache: first fetch failed code=${first.code} → fallback to cache size=${prev?.items?.size ?: 0}"}
}
// Hantera 304/not-modified och nätfel (kod 599 i fetchNearby) // Hantera 304/not-modified och nätfel (kod 599 i fetchNearby)
val firstItems = when (first.code) { val firstItems = when (first.code) {
@@ -131,6 +134,7 @@ object Geocache {
limit = 200 limit = 200
) )
} catch (_: Throwable) { } catch (_: Throwable) {
app.klottr.util.AppLog.d { "nearby.php exception → code=599 lat=$lat lon=$lon r=$radiusMeters since=$sinceMs"}
NearbyResult(code = 599, items = emptyList(), etag = etag) NearbyResult(code = 599, items = emptyList(), etag = etag)
} }

View File

@@ -1,6 +1,7 @@
package app.klottr.net package app.klottr.net
import android.os.Build import android.os.Build
import app.klottr.BuildConfig
object NetHeaders { object NetHeaders {
val userAgent: String by lazy { val userAgent: String by lazy {

View File

@@ -0,0 +1,19 @@
package app.klottr.util
import android.util.Log
import app.klottr.BuildConfig
object AppLog {
inline fun d(tag: String = "Klottr", msg: () -> String) {
if (BuildConfig.KLLOG_DEBUG) Log.d(tag, msg())
}
inline fun i(tag: String = "Klottr", msg: () -> String) {
if (BuildConfig.KLLOG_DEBUG) Log.i(tag, msg())
}
inline fun w(tag: String = "Klottr", msg: () -> String) {
if (BuildConfig.KLLOG_DEBUG) Log.w(tag, msg())
}
inline fun e(tag: String = "Klottr", msg: () -> String, tr: Throwable? = null) {
if (BuildConfig.KLLOG_DEBUG) Log.e(tag, msg(), tr)
}
}

View File

@@ -0,0 +1,55 @@
package app.klottr.util
import java.util.*
import java.util.Locale
import kotlin.math.abs
fun formatRelativeOrTime(ms: Long): String {
val now = System.currentTimeMillis()
val calNow = Calendar.getInstance()
val calTime = Calendar.getInstance().apply { timeInMillis = ms }
val sameYear = calNow.get(Calendar.YEAR) == calTime.get(Calendar.YEAR)
val sameDay = sameYear &&
calNow.get(Calendar.DAY_OF_YEAR) == calTime.get(Calendar.DAY_OF_YEAR)
val yesterday = sameYear &&
calNow.get(Calendar.DAY_OF_YEAR) - calTime.get(Calendar.DAY_OF_YEAR) == 1
return when {
sameDay -> {
android.text.format.DateFormat.format("HH:mm", ms).toString()
}
yesterday -> {
"Igår " + android.text.format.DateFormat.format("HH:mm", ms).toString()
}
else -> {
val pattern = if (sameYear) "d MMM HH:mm" else "yyyy-MM-dd HH:mm"
android.text.format.DateFormat.format(pattern, ms).toString()
}
}
}
fun formatCoords(lat: Double, lon: Double): String {
val latDir = if (lat >= 0) "N" else "S"
val lonDir = if (lon >= 0) "E" else "W"
// format med punkt först (Locale.US → garanterar punkt)
val latStr = String.format(Locale.US, "%.5f", abs(lat))
val lonStr = String.format(Locale.US, "%.5f", abs(lon))
// byt punkt till komma för svenskt skrivsätt
val latComma = latStr.replace('.', ',')
val lonComma = lonStr.replace('.', ',')
return "$latComma° $latDir, $lonComma° $lonDir"
}
fun formatDistance(meters: Int): String = when {
meters < 1000 -> "$meters\u00A0m"
meters < 10_000 -> String.format(Locale("sv"), "%.1f\u00A0km", meters / 1000.0)
else -> "${meters / 10_000.0}\u00A0mil" // 1 mil = 10 km
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/splash_logo_background"/>
<foreground android:drawable="@mipmap/splash_logo_foreground"/>
</adaptive-icon>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/splash_logo_background"/>
<foreground android:drawable="@mipmap/splash_logo_foreground"/>
</adaptive-icon>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@@ -7,4 +7,5 @@
<color name="teal_700">#FF018786</color> <color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color> <color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color> <color name="white">#FFFFFFFF</color>
<color name="splash_bg">#FFFFFF</color>
</resources> </resources>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="splace_logo_background">#FFFFFF</color>
</resources>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="splash_logo_background">#FFFFFF</color>
</resources>

View File

@@ -1,5 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<!-- Ditt app-tema som också pekas ut i manifestet: android:theme="@style/Theme.Klottr" -->
<style name="Theme.Yorlik" parent="android:Theme.Material.Light.NoActionBar" /> <style name="Theme.Klottr" parent="android:Theme.Material.Light.NoActionBar">
<!-- Android 12+ (API 31): systemets inbyggda splash -->
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_logo</item>
<item name="android:windowSplashScreenBackground">@color/splash_bg</item>
</style>
</resources> </resources>

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB