Location refactor compiles and seemingly works
Location updates now handled in a more compose friendly way via StateFlow Lots of small changed in MainActivity and DetailDialogShell to make them platform independent Add new platform apis for openUrl, openMap (AppNavigator) Add Platform independent OutboxScheduler Try to clean up event handling of FoundEvents and location updates (need more cleanup) New wrapper for handling App Context in shared (could be used to clean up integration further)
This commit is contained in:
@@ -160,6 +160,7 @@ kotlin {
|
||||
implementation("com.google.maps.android:maps-compose:6.10.0") // Sep 9, 2025
|
||||
// Google Sign-In
|
||||
implementation("com.google.android.gms:play-services-auth:21.4.0")
|
||||
implementation(libs.androidx.work.runtime.ktx)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
160
shared/src/androidMain/kotlin/app/klottr/OutboxWorker.kt
Normal file
160
shared/src/androidMain/kotlin/app/klottr/OutboxWorker.kt
Normal file
@@ -0,0 +1,160 @@
|
||||
package app.klottr.work
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import app.klottr.events.FoundEvents
|
||||
import app.klottr.net.Geocache
|
||||
import app.klottr.net.createNote
|
||||
import app.klottr.net.createNoteDoc
|
||||
import app.klottr.net.ImageHandle
|
||||
import app.klottr.net.ImageReader
|
||||
import app.klottr.net.uploadImage
|
||||
import app.klottr.util.FoundStore
|
||||
import app.klottr.util.OutboxStore
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* Försöker skicka allt som ligger i utkorgen (offline-klotter).
|
||||
* Körs när nät finns (OneTimeWork med NetworkType.CONNECTED).
|
||||
*/
|
||||
class OutboxWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
|
||||
private fun sha256Hex(s: String): String {
|
||||
val md = MessageDigest.getInstance("SHA-256")
|
||||
val bytes = md.digest(s.toByteArray(Charsets.UTF_8))
|
||||
val sb = StringBuilder(bytes.size * 2)
|
||||
for (b in bytes) {
|
||||
val i = b.toInt() and 0xff
|
||||
if (i < 16) sb.append('0')
|
||||
sb.append(i.toString(16))
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
val ctx = applicationContext
|
||||
// Ensure shared ImageReader has Android application context available.
|
||||
ImageReader.init(applicationContext)
|
||||
|
||||
val pending = OutboxStore.all()
|
||||
if (pending.isEmpty()) return Result.success()
|
||||
|
||||
val keep = mutableListOf<OutboxStore.PendingNote>()
|
||||
|
||||
for (p in pending) {
|
||||
val ok = try {
|
||||
// Stabil nyckel per pending-post (idempotens)
|
||||
val sig = buildString {
|
||||
append(p.createdAt).append(':')
|
||||
append(p.lat).append(':')
|
||||
append(p.lon).append(':')
|
||||
// säkerställ att vi skiljer på text- och doc-varianten i signaturen
|
||||
when {
|
||||
p.title != null || p.body != null -> {
|
||||
append(p.title ?: "")
|
||||
append('#')
|
||||
append(p.body ?: "")
|
||||
}
|
||||
else -> append(p.text ?: "")
|
||||
}
|
||||
}
|
||||
val reqId = "obx-" + sha256Hex(sig).take(48)
|
||||
|
||||
when {
|
||||
// DOC med ev. bild
|
||||
(p.title != null || p.body != null) -> {
|
||||
val imgId: Long? = if (p.imagePath != null && p.imageMime != null) {
|
||||
val f = File(p.imagePath)
|
||||
if (f.exists()) {
|
||||
val read = ImageReader.read(
|
||||
ImageHandle.FilePath(
|
||||
path = f.path,
|
||||
mimeHint = p.imageMime,
|
||||
displayName = f.name
|
||||
)
|
||||
)
|
||||
if (read != null) uploadImage(
|
||||
data = read.bytes,
|
||||
filename = read.filename,
|
||||
mime = read.mime,
|
||||
lat = p.lat,
|
||||
lon = p.lon
|
||||
) else null
|
||||
} else null
|
||||
} else null
|
||||
|
||||
createNoteDoc(
|
||||
lat = p.lat,
|
||||
lon = p.lon,
|
||||
title = p.title ?: "",
|
||||
body = p.body ?: (p.text ?: ""),
|
||||
imageId = imgId,
|
||||
radiusM = p.radiusM,
|
||||
createdAt = p.createdAt,
|
||||
clientRequestId = reqId
|
||||
)
|
||||
}
|
||||
|
||||
// TEXT-variant (som tidigare)
|
||||
else -> {
|
||||
createNote(
|
||||
lat = p.lat,
|
||||
lon = p.lon,
|
||||
text = p.text ?: "",
|
||||
createdAt = p.createdAt,
|
||||
clientRequestId = reqId
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
if (ok) {
|
||||
try {
|
||||
// Hämta närliggande från servern för att få rätt id/koordinater
|
||||
val nearby = Geocache.getNearby(
|
||||
lat = p.lat, lon = p.lon, radiusMeters = 120, ttlMs = 0L
|
||||
)
|
||||
|
||||
// Välj bästa kandidat: nära i både tid och rum
|
||||
val match = nearby
|
||||
.filter { app.klottr.util.distanceMeters(p.lat, p.lon, it.a, it.o) <= 80.0 }
|
||||
.minByOrNull { abs(it.c - p.createdAt) }
|
||||
|
||||
if (match != null) {
|
||||
// Sätt label på ett rimligt sätt (titel + ev. brödtext, annars fallback)
|
||||
val label = when {
|
||||
!p.title.isNullOrBlank() -> p.title!!.trim()
|
||||
else -> (match.t ?: "Klotter")
|
||||
}
|
||||
|
||||
// Markera som hittad i FoundStore
|
||||
FoundStore.markFound(
|
||||
FoundStore.LAYER_KLOTTER,
|
||||
match.i.toString(),
|
||||
label = label,
|
||||
lat = match.a,
|
||||
lon = match.o,
|
||||
timeMillis = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
// Pinga UI så “Senaste” uppdateras direkt
|
||||
FoundEvents.notifyFoundUpdated()
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
// Tyst fallback – Workern ska inte krascha pga visuell uppdatering
|
||||
}
|
||||
}
|
||||
if (!ok) keep.add(p)
|
||||
}
|
||||
|
||||
OutboxStore.replaceAll( keep)
|
||||
return if (keep.isEmpty()) Result.success() else Result.retry()
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ private class AndroidLocationService(
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
override suspend fun current(highAccuracy: Boolean, timeoutMillis: Long): GeoPoint? {
|
||||
if (!hasPermission()) return _location.value ?: LastLocationStore.lastKnown.value
|
||||
if (!hasPermission()) return _location.value ?: LastLocationStore.lastKnownLocation.value
|
||||
// Try current quick, with fallback to last known
|
||||
return try {
|
||||
withTimeout(timeoutMillis) {
|
||||
@@ -94,7 +94,7 @@ private class AndroidLocationService(
|
||||
} ?: lastKnownImmediate()
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
_location.value ?: LastLocationStore.lastKnown.value ?: lastKnownImmediate()
|
||||
_location.value ?: LastLocationStore.lastKnownLocation.value ?: lastKnownImmediate()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,10 +105,6 @@ private class AndroidLocationService(
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("FunctionName")
|
||||
internal fun AndroidLocationService(appContext: Context): LocationService =
|
||||
AndroidLocationService(appContext)
|
||||
|
||||
actual object LocationServiceProvider {
|
||||
private var instance: LocationService? = null
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package app.klottr.platform
|
||||
|
||||
import android.content.Context
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* App-internal way to expose applicationContext to platform actuals
|
||||
* without referencing it from app UI files.
|
||||
*/
|
||||
object AndroidAppContext {
|
||||
private val ref = AtomicReference<Context?>()
|
||||
fun install(appContext: Context) { ref.set(appContext.applicationContext) }
|
||||
fun get(): Context? = ref.get()
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package app.klottr.platform
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
|
||||
actual object AppNavigator {
|
||||
actual fun openUrl(url: String) {
|
||||
val c = AndroidAppContext.get() ?: return
|
||||
val i = Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
||||
try { c.startActivity(i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {}
|
||||
}
|
||||
actual fun openMap(lat: Double, lon: Double, label: String?) {
|
||||
val c = AndroidAppContext.get() ?: return
|
||||
val enc = Uri.encode(label ?: "Plats")
|
||||
val geo = Uri.parse("geo:$lat,$lon?q=$lat,$lon($enc)")
|
||||
val intent = Intent(Intent.ACTION_VIEW, geo).setPackage("com.google.android.apps.maps")
|
||||
try { c.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {
|
||||
try { c.startActivity(Intent(Intent.ACTION_VIEW, geo).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
actual object UiFeedback {
|
||||
actual fun showMessage(text: String, duration: UiFeedbackDuration) {
|
||||
val toastDuration = if (duration == UiFeedbackDuration.SHORT) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
|
||||
AndroidAppContext.get()?.let { Toast.makeText(it, text, toastDuration).show() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package app.klottr.platform
|
||||
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import app.klottr.platform.AndroidAppContext
|
||||
import app.klottr.work.OutboxWorker
|
||||
|
||||
actual object OutboxScheduler {
|
||||
actual fun scheduleUpload() {
|
||||
val c = AndroidAppContext.get() ?: return
|
||||
val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
|
||||
val req = OneTimeWorkRequestBuilder<OutboxWorker>().setConstraints(constraints).build()
|
||||
WorkManager.getInstance(c).enqueue(req)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package app.klottr.events
|
||||
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
|
||||
object FoundEvents {
|
||||
private val _foundUpdated = MutableSharedFlow<Unit>(extraBufferCapacity = 8)
|
||||
val foundUpdated: SharedFlow<Unit> = _foundUpdated
|
||||
|
||||
private val _locationTick = MutableSharedFlow<Unit>(extraBufferCapacity = 8)
|
||||
val locationTick: SharedFlow<Unit> = _locationTick
|
||||
|
||||
fun notifyFoundUpdated() { _foundUpdated.tryEmit(Unit) }
|
||||
fun notifyLocationTick() { _locationTick.tryEmit(Unit) }
|
||||
}
|
||||
@@ -42,7 +42,7 @@ data class LocationUpdates(
|
||||
/** Simple, common store (replaces various platform stores). */
|
||||
object LastLocationStore {
|
||||
private val _lastKnown = MutableStateFlow<GeoPoint?>(null)
|
||||
val lastKnown: StateFlow<GeoPoint?> = _lastKnown.asStateFlow()
|
||||
val lastKnownLocation: StateFlow<GeoPoint?> = _lastKnown.asStateFlow()
|
||||
|
||||
fun update(p: GeoPoint?) { _lastKnown.value = p }
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ fun isClickable( //
|
||||
|
||||
//Markera nya fynd i FoundStore baserat på delade entries (plattformneutral hjälpare)
|
||||
fun markNewFinds( //
|
||||
ctx: Any?, //Context-parameter hålls som Any? i KMP
|
||||
entries: List<NearbyEntryShared>, //Delade “Närliggande”-rader
|
||||
nowMillis: Long, //Tidpunkt för markering
|
||||
onMarked: () -> Unit //Callback om något faktiskt markerats nytt
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package app.klottr.platform
|
||||
|
||||
/**
|
||||
* Platform-independent navigation helpers used from common UI.
|
||||
* Android uses Intents; iOS opens via UIApplication.
|
||||
*/
|
||||
expect object AppNavigator {
|
||||
fun openUrl(url: String)
|
||||
fun openMap(lat: Double, lon: Double, label: String? = null)
|
||||
}
|
||||
|
||||
|
||||
enum class UiFeedbackDuration {
|
||||
SHORT,
|
||||
LONG
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight user feedback facade (e.g. toast / banner).
|
||||
* On iOS this can no-op or present a subtle HUD, implementation-defined.
|
||||
*/
|
||||
expect object UiFeedback {
|
||||
fun showMessage(text: String, duration: UiFeedbackDuration = UiFeedbackDuration.LONG)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package app.klottr.platform
|
||||
|
||||
/**
|
||||
* Schedule a one-shot upload job when network is connected.
|
||||
*/
|
||||
expect object OutboxScheduler {
|
||||
fun scheduleUpload()
|
||||
}
|
||||
@@ -3,12 +3,15 @@ package app.klottr.ui
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize // Vi fyller ytan
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.foundation.text.BasicText
|
||||
import app.klottr.location.GeoPoint
|
||||
import app.klottr.util.FoundEntry
|
||||
import app.klottr.nearby.foundSubtitle
|
||||
import app.klottr.nearby.layerDisplayName
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
/**
|
||||
* Material-fritt innehåll för "Hittat".
|
||||
@@ -18,8 +21,7 @@ import app.klottr.nearby.layerDisplayName
|
||||
@Composable
|
||||
fun FoundContent(
|
||||
entries: List<FoundEntry>,
|
||||
currentLat: Double?,
|
||||
currentLon: Double?,
|
||||
location: State<GeoPoint?>,
|
||||
showCoords: Boolean,
|
||||
// Förbättrade etiketter (klotter): nyckel = "layer|id"
|
||||
labelOverrides: Map<String, String>,
|
||||
@@ -55,8 +57,8 @@ fun FoundContent(
|
||||
subtitleFor = { f ->
|
||||
foundSubtitle(
|
||||
entry = f,
|
||||
currentLat = currentLat,
|
||||
currentLon = currentLon,
|
||||
currentLat = location.value?.lat,
|
||||
currentLon = location.value?.lon,
|
||||
showCoords = showCoords,
|
||||
distanceFormatter = distanceFormatter,
|
||||
coordsFormatter = coordsFormatter
|
||||
|
||||
@@ -2,9 +2,11 @@ package app.klottr.ui
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.unit.dp // För .dp i padding/spacedBy
|
||||
import app.klottr.location.GeoPoint
|
||||
import app.klottr.util.FoundEntry
|
||||
|
||||
@Composable
|
||||
@@ -12,8 +14,7 @@ fun KlottrHomeContent(
|
||||
contentPadding: PaddingValues,
|
||||
// FoundContent-parametrar (delat)
|
||||
entries: List<FoundEntry>,
|
||||
currentLat: Double?,
|
||||
currentLon: Double?,
|
||||
location: State<GeoPoint?>,
|
||||
showCoords: Boolean,
|
||||
labelOverrides: Map<String, String>,
|
||||
isClickable: (FoundEntry) -> Boolean,
|
||||
@@ -41,8 +42,7 @@ fun KlottrHomeContent(
|
||||
) {
|
||||
FoundContent(
|
||||
entries = entries,
|
||||
currentLat = currentLat,
|
||||
currentLon = currentLon,
|
||||
location = location,
|
||||
showCoords = showCoords,
|
||||
labelOverrides = labelOverrides,
|
||||
isClickable = isClickable,
|
||||
|
||||
@@ -53,7 +53,7 @@ private class IOSLocationService(
|
||||
_location.value
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
_location.value ?: LastLocationStore.lastKnown.value
|
||||
_location.value ?: LastLocationStore.lastKnownLocation.value
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package app.klottr.platform
|
||||
|
||||
import platform.Foundation.NSURL
|
||||
import platform.UIKit.UIApplication
|
||||
import platform.UIKit.UIApplicationOpenSettingsURLString
|
||||
import platform.UIKit.UIApplicationSharedApplication
|
||||
|
||||
actual object AppNavigator {
|
||||
actual fun openUrl(url: String) {
|
||||
val nsUrl = NSURL.URLWithString(url) ?: return
|
||||
UIApplication.sharedApplication.openURL(nsUrl)
|
||||
}
|
||||
actual fun openMap(lat: Double, lon: Double, label: String?) {
|
||||
// Use Apple Maps URL scheme
|
||||
val encoded = label?.let { it } ?: "Place"
|
||||
val url = "http://maps.apple.com/?ll=$lat,$lon&q=$encoded"
|
||||
openUrl(url)
|
||||
}
|
||||
}
|
||||
|
||||
actual object UiFeedback {
|
||||
actual fun showMessage(text: String, duration: UiFeedbackDuration) {
|
||||
// No-op or implement a lightweight HUD; keeping no-op by default.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package app.klottr.platform
|
||||
|
||||
actual object OutboxScheduler {
|
||||
actual fun scheduleUpload() {
|
||||
// iOS can use BGTaskScheduler / background URLSession; left as future hook.
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user