Version 0.1.0. With Wiki layer, fornsok-layer, offline handling, and working configs
This commit is contained in:
2
.idea/deploymentTargetSelector.xml
generated
2
.idea/deploymentTargetSelector.xml
generated
@@ -4,7 +4,7 @@
|
||||
<selectionStates>
|
||||
<SelectionState runConfigName="app">
|
||||
<option name="selectionMode" value="DROPDOWN" />
|
||||
<DropdownSelection timestamp="2025-08-12T15:21:14.877340699Z">
|
||||
<DropdownSelection timestamp="2025-08-16T15:24:03.539393207Z">
|
||||
<Target type="DEFAULT_BOOT">
|
||||
<handle>
|
||||
<DeviceId pluginId="PhysicalDevice" identifier="serial=39151FDJG000HZ" />
|
||||
|
||||
1
.idea/misc.xml
generated
1
.idea/misc.xml
generated
@@ -1,4 +1,3 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
|
||||
|
||||
@@ -34,8 +34,8 @@ android {
|
||||
applicationId = "com.example.yorlik"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "0.0.4"
|
||||
versionCode = 5
|
||||
versionName = "0.1.0"
|
||||
|
||||
// BuildConfig-fält (åtkomst i Kotlin via BuildConfig.X)
|
||||
buildConfigField("String", "SERVER_API_BASE_URL", "\"${propOrEmpty("SERVER_API_BASE_URL")}\"")
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -11,8 +11,8 @@
|
||||
"type": "SINGLE",
|
||||
"filters": [],
|
||||
"attributes": [],
|
||||
"versionCode": 1,
|
||||
"versionName": "0.0.3",
|
||||
"versionCode": 5,
|
||||
"versionName": "0.1.0",
|
||||
"outputFile": "app-release.apk"
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,346 +1,342 @@
|
||||
package com.example.yorlik
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.location.Location
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.ActivityCompat
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.example.yorlik.net.Geocache
|
||||
import com.example.yorlik.net.NoteDTO
|
||||
import com.example.yorlik.util.*
|
||||
import com.google.android.gms.location.*
|
||||
import kotlinx.coroutines.*
|
||||
import com.example.yorlik.util.FoundStore
|
||||
import com.example.yorlik.util.FoundStore.LAYER_DM
|
||||
import com.example.yorlik.util.FoundStore.LAYER_KLOTTER
|
||||
import com.example.yorlik.util.FoundStore.LAYER_WIKI
|
||||
import com.example.yorlik.util.LastLocationStore
|
||||
import com.example.yorlik.util.SettingsStore
|
||||
import com.google.android.gms.location.LocationCallback
|
||||
import com.google.android.gms.location.LocationRequest
|
||||
import com.google.android.gms.location.LocationResult
|
||||
import com.google.android.gms.location.LocationServices
|
||||
import com.google.android.gms.location.Priority
|
||||
import com.google.android.gms.maps.model.LatLng
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.tasks.await
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
import android.util.Log
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class LocationService : Service() {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
companion object {
|
||||
private const val CHANNEL_LOCATION_ID = "yorlik_location" // för foreground, tyst
|
||||
private const val CHANNEL_HITS_ID = "yorlik_hits" // NY kanal för fynd-notiser
|
||||
|
||||
private var fused: FusedLocationProviderClient? = null
|
||||
const val ACTION_FOUND_UPDATED = "com.example.yorlik.ACTION_FOUND_UPDATED"
|
||||
const val ACTION_CLEAR_FOUND_SESSION = "com.example.yorlik.ACTION_CLEAR_FOUND_SESSION"
|
||||
const val ACTION_RESCAN_NOW = "com.example.yorlik.ACTION_RESCAN_NOW"
|
||||
const val ACTION_LOCATION_TICK = "com.example.yorlik.ACTION_LOCATION_TICK"
|
||||
|
||||
// Match & anti-spam
|
||||
private val NEW_HIT_RADIUS_M = 20.0 // nya träffar inom 20 m ska avisera direkt
|
||||
private val QUERY_RADIUS_M = 120 // fråga servern inom 120 m
|
||||
private val RESET_RADIUS_M = 200.0 // måste lämna >200 m för att samma ID ska kunna dingla igen
|
||||
private var activeCenterLat: Double? = null
|
||||
private var activeCenterLon: Double? = null
|
||||
private val suppressedIdsInZone = mutableSetOf<Long>() // ID:n avis. i denna zon (nollas när vi lämnar >200 m)
|
||||
}
|
||||
|
||||
// Inställning: endast nya träffar (kan växlas via SettingsStore)
|
||||
@Volatile private var onlyNewHits: Boolean = false
|
||||
private var prefListener: android.content.SharedPreferences.OnSharedPreferenceChangeListener? = null
|
||||
private val scope = CoroutineScope(Dispatchers.IO + Job())
|
||||
private val fused by lazy { LocationServices.getFusedLocationProviderClient(this) }
|
||||
|
||||
// Adaptivt intervall
|
||||
private val BASE_INTERVAL = 15_000L
|
||||
private var currentIntervalMs: Long = BASE_INTERVAL
|
||||
// Sessiontillstånd – används för “gå utanför ~200 m → tillåt om-avisering”
|
||||
private val notifiedWhileInside = mutableMapOf<String, Boolean>() // key(layer:id) -> om vi redan aviserat denna session.
|
||||
private val lastKnownDistance = mutableMapOf<String, Int>() // senaste uppmätta avståndet (meter).
|
||||
|
||||
// Minsta förflyttning
|
||||
private val BASE_MIN_DIST = 5f
|
||||
private var currentMinDistM: Float = BASE_MIN_DIST
|
||||
private lateinit var callback: LocationCallback
|
||||
|
||||
private var lastLocForSpeed: Location? = null
|
||||
private var lastLocTimeMs: Long = 0L
|
||||
private var requestRunning = false
|
||||
|
||||
// Lokalt cache-at serverresultat för snabb träffkontroll
|
||||
private var cachedNearby: List<NoteDTO> = emptyList()
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
val fineOk = ActivityCompat.checkSelfPermission(
|
||||
this, android.Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
val coarseOk = ActivityCompat.checkSelfPermission(
|
||||
this, android.Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
if (!fineOk && !coarseOk) { stopSelf(); return }
|
||||
|
||||
// Läs in inställning + lyssna på ändringar
|
||||
onlyNewHits = SettingsStore.getOnlyNewHits(this)
|
||||
prefListener = SettingsStore.observe(this) { key ->
|
||||
if (key == SettingsStore.KEY_ONLY_NEW_HITS) {
|
||||
onlyNewHits = SettingsStore.getOnlyNewHits(this)
|
||||
}
|
||||
}
|
||||
|
||||
Notifications.createChannels(this)
|
||||
startForeground(
|
||||
Notifications.ONGOING_ID,
|
||||
Notifications.buildOngoing(this, "Bevakar plats var ${currentIntervalMs/1000}s.")
|
||||
)
|
||||
|
||||
fused = LocationServices.getFusedLocationProviderClient(this)
|
||||
|
||||
// Direktmatch vid service-start – efter fused-assign och före startLocationUpdates
|
||||
scope.launch {
|
||||
val fusedLocal = fused
|
||||
try {
|
||||
val first = withTimeout(5000L) {
|
||||
fusedLocal?.lastLocation?.await()
|
||||
?: fusedLocal?.getCurrentLocation(
|
||||
com.google.android.gms.location.Priority.PRIORITY_HIGH_ACCURACY,
|
||||
null
|
||||
)?.await()
|
||||
}
|
||||
first?.let { firstFix ->
|
||||
val list = withContext(Dispatchers.IO) {
|
||||
Geocache.getNearby(
|
||||
lat = firstFix.latitude,
|
||||
lon = firstFix.longitude,
|
||||
radiusMeters = QUERY_RADIUS_M,
|
||||
ttlMs = 0L // bypassa cache vid start
|
||||
)
|
||||
}
|
||||
cachedNearby = list
|
||||
maybeMatch(firstFix)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Ignorera fel — ordinarie uppdateringar tar vid
|
||||
}
|
||||
}
|
||||
|
||||
startLocationUpdates(currentIntervalMs, currentMinDistM)
|
||||
}
|
||||
|
||||
private fun buildRequest(intervalMs: Long, minDistanceM: Float): LocationRequest =
|
||||
LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMs)
|
||||
.setMinUpdateIntervalMillis(intervalMs)
|
||||
.setMinUpdateDistanceMeters(minDistanceM)
|
||||
.setWaitForAccurateLocation(false) // egen "boost" vid behov
|
||||
.build()
|
||||
|
||||
private fun startLocationUpdates(intervalMs: Long, minDistanceM: Float) {
|
||||
if (requestRunning) {
|
||||
fused?.removeLocationUpdates(callback)
|
||||
requestRunning = false
|
||||
}
|
||||
fused?.requestLocationUpdates(buildRequest(intervalMs, minDistanceM), callback, mainLooper)
|
||||
requestRunning = true
|
||||
currentIntervalMs = intervalMs
|
||||
currentMinDistM = minDistanceM
|
||||
|
||||
DebugState.intervalMs.value = currentIntervalMs
|
||||
DebugState.minDistanceM.value = currentMinDistM
|
||||
|
||||
Notifications.updateOngoing(
|
||||
this,
|
||||
"Bevakar plats var ${currentIntervalMs/1000}s (min ${"%.1f".format(currentMinDistM)} m)."
|
||||
)
|
||||
}
|
||||
|
||||
private val callback = object : LocationCallback() {
|
||||
override fun onLocationResult(result: LocationResult) {
|
||||
val loc = result.lastLocation ?: return
|
||||
LastLocationStore.lastKnownLocation = loc
|
||||
DebugState.lastLat.value = loc.latitude
|
||||
DebugState.lastLon.value = loc.longitude
|
||||
|
||||
scope.launch {
|
||||
handleAntiSpamState(loc)
|
||||
|
||||
// Hämta närliggande (med cache) + en gångs cache-bypass om tomt
|
||||
try {
|
||||
val list = withContext(Dispatchers.IO) {
|
||||
Geocache.getNearby(
|
||||
lat = loc.latitude,
|
||||
lon = loc.longitude,
|
||||
radiusMeters = QUERY_RADIUS_M,
|
||||
ttlMs = 30_000L
|
||||
)
|
||||
}
|
||||
|
||||
// Skriv alltid över cachedNearby, även om list är tom
|
||||
cachedNearby = list
|
||||
|
||||
// Om tomt — gör en cache-bypass för att undvika "fastnat tomt"-läge
|
||||
if (list.isEmpty()) {
|
||||
val fresh = withContext(Dispatchers.IO) {
|
||||
Geocache.getNearby(
|
||||
lat = loc.latitude,
|
||||
lon = loc.longitude,
|
||||
radiusMeters = QUERY_RADIUS_M,
|
||||
ttlMs = 0L // bypassa cache
|
||||
)
|
||||
}
|
||||
cachedNearby = fresh
|
||||
}
|
||||
|
||||
// Matcha direkt mot senaste datat
|
||||
maybeMatch(loc)
|
||||
|
||||
} catch (t: Throwable) {
|
||||
Log.e("Yorlik", "getNearby failed", t)
|
||||
// Behåll tidigare cachedNearby som fallback — matcha ändå
|
||||
maybeMatch(loc)
|
||||
}
|
||||
|
||||
// Beräkna speed och närmaste avstånd EFTER att cachedNearby är uppdaterad
|
||||
val speed = estimateSpeedMps(loc)
|
||||
val nearest = nearestDistanceToAny(loc.latitude, loc.longitude, cachedNearby)
|
||||
|
||||
// Stilla? Sänk minDistance → försök boost → matcha ändå även om boost uteblir
|
||||
if (speed < 0.5f) {
|
||||
if (currentMinDistM > 0f) {
|
||||
startLocationUpdates(currentIntervalMs, 0f)
|
||||
}
|
||||
val boosted = tryAccuracyBoostOnce()
|
||||
if (boosted != null) {
|
||||
LastLocationStore.lastKnownLocation = boosted
|
||||
maybeMatch(boosted)
|
||||
} else {
|
||||
maybeMatch(loc)
|
||||
}
|
||||
} else {
|
||||
// Rör vi oss, matcha mot nuvarande position
|
||||
maybeMatch(loc)
|
||||
}
|
||||
|
||||
// Anpassa intervall & minDistance utifrån fart + kontext
|
||||
val desiredInterval = desiredIntervalForSpeed(speed)
|
||||
val desiredMinDist = desiredMinDistanceForContext(speed, nearest)
|
||||
val intervalChanged = abs(desiredInterval - currentIntervalMs) >= 500L
|
||||
val minDistChanged = kotlin.math.abs(desiredMinDist - currentMinDistM) >= 0.5f
|
||||
if (intervalChanged || minDistChanged) {
|
||||
startLocationUpdates(desiredInterval, desiredMinDist)
|
||||
} else {
|
||||
Notifications.updateOngoing(
|
||||
this@LocationService,
|
||||
"Senast: ${"%.5f".format(loc.latitude)}, ${"%.5f".format(loc.longitude)} – ${"%.1f".format(speed)} m/s, var ${currentIntervalMs/1000}s (min ${"%.1f".format(currentMinDistM)} m)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Prova en engångsfix med hög noggrannhet. Returnerar bättre location om lyckas. */
|
||||
private suspend fun tryAccuracyBoostOnce(): Location? = withContext(Dispatchers.Main) {
|
||||
val fusedLocal = fused ?: return@withContext null
|
||||
return@withContext try {
|
||||
withTimeout(7_000L) {
|
||||
fusedLocal.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||
}
|
||||
} catch (_: Exception) { null }
|
||||
}
|
||||
|
||||
/**
|
||||
* Match-logik:
|
||||
* - Visa nya ID:n inom 20 m även om vi står kvar i zonen.
|
||||
* - Visa aldrig samma ID igen förrän vi lämnat >200 m (hanteras av suppressedIdsInZone + reset).
|
||||
* - Om "onlyNewHits" är aktivt: avisera bara ID:n som aldrig setts tidigare.
|
||||
*/
|
||||
private fun maybeMatch(loc: Location) {
|
||||
// Kandidater inom 20 m
|
||||
val candidates = cachedNearby
|
||||
.asSequence()
|
||||
.filter { n -> distanceMeters(loc.latitude, loc.longitude, n.a, n.o) <= NEW_HIT_RADIUS_M }
|
||||
// Filtrera bort sådana vi redan dinglat i den här zonen
|
||||
.filter { n -> !suppressedIdsInZone.contains(n.i) }
|
||||
// Respektera "endast nya träffar" om valt
|
||||
.filter { n -> !onlyNewHits || !SeenHits.isSeen(this, n.i) }
|
||||
.toList()
|
||||
|
||||
if (candidates.isEmpty()) return
|
||||
|
||||
// Ta närmaste (enkelt urval)
|
||||
val hit = candidates.minBy { n -> distanceMeters(loc.latitude, loc.longitude, n.a, n.o) }
|
||||
|
||||
// Sätt zonens centrum när första träffen sker
|
||||
if (activeCenterLat == null || activeCenterLon == null) {
|
||||
activeCenterLat = hit.a
|
||||
activeCenterLon = hit.o
|
||||
}
|
||||
|
||||
// Lägg ID i zonens "suppress"-mängd så det inte tjatar förrän vi lämnat >200 m
|
||||
suppressedIdsInZone.add(hit.i)
|
||||
|
||||
// Logga träffen & markera som sedd
|
||||
val now = System.currentTimeMillis()
|
||||
HitLog.add(hit.t, hit.a, hit.o, now)
|
||||
SeenHits.markSeen(this, hit.i)
|
||||
|
||||
// Meddela UI + notis
|
||||
val entity = com.example.yorlik.data.NoteEntity(id = hit.i, lat = hit.a, lon = hit.o, text = hit.t, createdAt = hit.c)
|
||||
MatchBus.emit(entity)
|
||||
Notifications.showHit(this, entity)
|
||||
}
|
||||
|
||||
private fun nearestDistanceToAny(lat: Double, lon: Double, items: List<NoteDTO>): Double? {
|
||||
if (items.isEmpty()) return null
|
||||
var best: Double? = null
|
||||
for (n in items) {
|
||||
val d = distanceMeters(lat, lon, n.a, n.o)
|
||||
if (best == null || d < best!!) best = d
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
private fun estimateSpeedMps(loc: Location): Float {
|
||||
val s = loc.speed
|
||||
if (s.isFinite() && s >= 0f) return s
|
||||
val prev = lastLocForSpeed
|
||||
val nowMs = System.currentTimeMillis()
|
||||
val dt = (nowMs - lastLocTimeMs).coerceAtLeast(1)
|
||||
val v = if (prev != null) {
|
||||
val d = distanceMeters(prev.latitude, prev.longitude, loc.latitude, loc.longitude).toFloat()
|
||||
(d / (dt / 1000f))
|
||||
} else 0f
|
||||
lastLocForSpeed = loc
|
||||
lastLocTimeMs = nowMs
|
||||
return max(0f, v)
|
||||
}
|
||||
|
||||
private fun desiredIntervalForSpeed(speedMps: Float): Long =
|
||||
when {
|
||||
speedMps > 10f -> 1_000L
|
||||
speedMps > 3f -> 2_000L
|
||||
speedMps >= 1f -> 5_000L
|
||||
else -> 15_000L
|
||||
}
|
||||
|
||||
/** När vi är nära en plats och stilla → 0 m för att släppa igenom bättre fixar. */
|
||||
private fun desiredMinDistanceForContext(speedMps: Float, nearestMeters: Double?): Float {
|
||||
if (nearestMeters != null && nearestMeters < 60.0 && speedMps < 1.0f) {
|
||||
return 0f
|
||||
}
|
||||
return when {
|
||||
speedMps > 10f -> 0f
|
||||
speedMps > 3f -> 1f
|
||||
speedMps >= 1f -> 2f
|
||||
else -> 5f
|
||||
}
|
||||
}
|
||||
|
||||
/** Zon-reset: släpp allt bara när vi lämnat >200 m från zonens centrum. */
|
||||
private fun handleAntiSpamState(loc: Location) {
|
||||
val lat = activeCenterLat
|
||||
val lon = activeCenterLon
|
||||
if (lat == null || lon == null) return
|
||||
val d = distanceMeters(loc.latitude, loc.longitude, lat, lon)
|
||||
if (d > RESET_RADIUS_M) {
|
||||
activeCenterLat = null
|
||||
activeCenterLon = null
|
||||
suppressedIdsInZone.clear()
|
||||
}
|
||||
ensureChannel()
|
||||
startForeground(1, persistentNotification())
|
||||
startLocation()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
requestRunning = false
|
||||
try { fused?.removeLocationUpdates(callback) } catch (_: Exception) { }
|
||||
finally { fused = null }
|
||||
|
||||
try { scope.cancel() } catch (_: Exception) { }
|
||||
try { stopForeground(true) } catch (_: Exception) { }
|
||||
|
||||
// Avregistrera prefs-lyssnare
|
||||
SettingsStore.unobserve(this, prefListener)
|
||||
prefListener = null
|
||||
|
||||
try { fused.removeLocationUpdates(callback) } catch (_: Exception) {}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_CLEAR_FOUND_SESSION -> {
|
||||
notifiedWhileInside.clear()
|
||||
lastKnownDistance.clear()
|
||||
}
|
||||
ACTION_RESCAN_NOW -> {
|
||||
scope.launch {
|
||||
val loc = try {
|
||||
fused.lastLocation.await()
|
||||
?: fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||
} catch (_: Exception) { null }
|
||||
val L = loc ?: LastLocationStore.lastKnownLocation
|
||||
if (L != null) {
|
||||
// Håll last known i sync om vi faktiskt fick en färsk position
|
||||
LastLocationStore.lastKnownLocation = L
|
||||
|
||||
// Uppdatera away-flaggor för den position du ska scanna mot
|
||||
FoundStore.updateAwayFlags(this@LocationService, L.latitude, L.longitude)
|
||||
|
||||
// 1) Tala om att data (ev. away) kan ha ändrats
|
||||
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
|
||||
|
||||
// 2) Tvinga omritning av “Hittat” så avstånd/fetstil uppdateras direkt
|
||||
sendBroadcast(Intent(ACTION_LOCATION_TICK))
|
||||
|
||||
// 3) Kör matchningen
|
||||
checkMatches(L.latitude, L.longitude)
|
||||
|
||||
// Skicka ett tick så hittat uppdaterar avstånd/fet stil.
|
||||
sendBroadcast(Intent(ACTION_LOCATION_TICK))
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
// ---- Platsuppdateringar ----
|
||||
|
||||
private fun startLocation() {
|
||||
if (!hasLocationPerms()) return
|
||||
|
||||
val req = LocationRequest.create().apply {
|
||||
interval = 4_000L
|
||||
fastestInterval = 2_000L
|
||||
smallestDisplacement = 3f
|
||||
priority = Priority.PRIORITY_HIGH_ACCURACY
|
||||
maxWaitTime = 5_000L
|
||||
}
|
||||
|
||||
callback = object : LocationCallback() {
|
||||
override fun onLocationResult(result: LocationResult) {
|
||||
val loc = result.lastLocation ?: return
|
||||
LastLocationStore.lastKnownLocation = loc
|
||||
sendBroadcast(Intent(ACTION_LOCATION_TICK))
|
||||
|
||||
scope.launch {
|
||||
|
||||
// Uppdatera away-flaggor för ALLA sparade fynd utifrån aktuell position
|
||||
FoundStore.updateAwayFlags(this@LocationService, loc.latitude, loc.longitude)
|
||||
// (UI lyssnar på SharedPreferences, men vi pingar ändå för säkerhets skull)
|
||||
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
|
||||
|
||||
// Matcha på senaste
|
||||
checkMatches(loc.latitude, loc.longitude)
|
||||
|
||||
// Försök förfina om noggrannheten är sämre än ~30 m
|
||||
val acc = loc.accuracy
|
||||
if (acc.isFinite() && acc > 30f) {
|
||||
try {
|
||||
val refined = fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||
if (refined != null) {
|
||||
LastLocationStore.lastKnownLocation = refined
|
||||
sendBroadcast(Intent(ACTION_LOCATION_TICK))
|
||||
|
||||
FoundStore.updateAwayFlags(this@LocationService, refined.latitude, refined.longitude)
|
||||
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
|
||||
checkMatches(refined.latitude, refined.longitude)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
fused.requestLocationUpdates(req, callback, mainLooper)
|
||||
} catch (_: SecurityException) {
|
||||
// saknar tillstånd
|
||||
}
|
||||
}
|
||||
|
||||
private fun hasLocationPerms(): Boolean {
|
||||
val fine = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
val coarse = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
return fine || coarse
|
||||
}
|
||||
|
||||
// ---- Matchning ----
|
||||
|
||||
private suspend fun checkMatches(lat: Double, lon: Double) {
|
||||
// Just nu kör vi bara klotter här (20 m). Wikipedia/DigitaltMuseum/Fornsök scannas i UI vid behov.
|
||||
val showKlotter = SettingsStore.getShowKlotter(this)
|
||||
if (showKlotter) {
|
||||
val nearby: List<NoteDTO> = try {
|
||||
Geocache.getNearby(lat, lon, radiusMeters = 120, ttlMs = 0L)
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
for (n in nearby) {
|
||||
val d = distanceMeters(lat, lon, n.a, n.o).roundToInt()
|
||||
handleCandidate(
|
||||
layer = LAYER_KLOTTER,
|
||||
id = n.i.toString(),
|
||||
label = n.t.orEmpty(),
|
||||
pt = LatLng(n.a, n.o),
|
||||
distanceM = d,
|
||||
insideRadiusM = 20,
|
||||
onlyNew = SettingsStore.getOnlyNewHits(this)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun key(layer: String, id: String) = "$layer:$id"
|
||||
|
||||
private suspend fun handleCandidate(
|
||||
layer: String,
|
||||
id: String,
|
||||
label: String,
|
||||
pt: LatLng,
|
||||
distanceM: Int,
|
||||
insideRadiusM: Int,
|
||||
onlyNew: Boolean
|
||||
) {
|
||||
val k = key(layer, id)
|
||||
|
||||
// Session-baserad återinträdesdetektion (för att slå av påminnelse tills man gått utanför ~200 m)
|
||||
val OUTSIDE_RESET_M = 200
|
||||
val lastD = lastKnownDistance[k]
|
||||
lastKnownDistance[k] = distanceM
|
||||
val reenteredSession = (lastD != null && lastD > OUTSIDE_RESET_M && distanceM <= insideRadiusM)
|
||||
if (reenteredSession) {
|
||||
// tillåt ny notis denna session
|
||||
notifiedWhileInside[k] = false
|
||||
}
|
||||
|
||||
// Lagrings-baserad re-arm: om FoundStore flaggat "away=true" och vi nu är inne i radien
|
||||
val wasAwayStore = FoundStore.isAway(this, layer, id)
|
||||
|
||||
if (distanceM <= insideRadiusM) {
|
||||
val wasNotifiedThisSession = notifiedWhileInside[k] == true
|
||||
val alreadyFound = FoundStore.isFound(this, layer, id)
|
||||
val now = System.currentTimeMillis()
|
||||
|
||||
// Markera i FoundStore:
|
||||
// - alltid vid första fyndet
|
||||
// - även vid återinträde (wasAwayStore), oavsett onlyNew, så last_visit uppdateras
|
||||
// - (behåller session-reentry för bakåtkompabilitet)
|
||||
val shouldMark = !alreadyFound || wasAwayStore || (!onlyNew && reenteredSession)
|
||||
if (shouldMark) {
|
||||
val marked = FoundStore.markFound(this, layer, id, label, pt.latitude, pt.longitude, now)
|
||||
if (marked) sendBroadcast(Intent(ACTION_FOUND_UPDATED))
|
||||
}
|
||||
|
||||
// Notiser:
|
||||
// - onlyNew=true → bara för helt nya (inte för återinträde)
|
||||
// - onlyNew=false → en gång per session ELLER om re-arm via FoundStore (wasAwayStore) eller session-reentry
|
||||
val shouldNotify = if (onlyNew) {
|
||||
!alreadyFound && !wasNotifiedThisSession
|
||||
} else {
|
||||
!wasNotifiedThisSession || wasAwayStore || reenteredSession
|
||||
}
|
||||
if (shouldNotify) {
|
||||
val (title, text) = notificationTitleAndText(layer, label, distanceM)
|
||||
postNotification(k, title, text)
|
||||
}
|
||||
|
||||
// markera att vi nu befinner oss "inne"
|
||||
notifiedWhileInside[k] = true
|
||||
} else {
|
||||
if (distanceM > OUTSIDE_RESET_M) {
|
||||
// lämnat området tillräckligt långt → tillåt ny notis när vi kommer in igen
|
||||
notifiedWhileInside[k] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun notificationTitleAndText(layer: String, label: String, distanceM: Int): Pair<String, String> {
|
||||
val dist = "≈ ${distanceM} m"
|
||||
val shown = label.ifBlank {
|
||||
when (layer) {
|
||||
LAYER_KLOTTER -> "Okänt klotter"
|
||||
LAYER_WIKI -> "Wikipedia"
|
||||
LAYER_DM -> "DigitaltMuseum"
|
||||
else -> "Plats"
|
||||
}
|
||||
}
|
||||
val title = when (layer) {
|
||||
LAYER_KLOTTER -> "Funnet klotter"
|
||||
LAYER_WIKI -> "Funnen Wikipediaplats"
|
||||
LAYER_DM -> "Funnen DigitaltMuseum-plats"
|
||||
else -> "Funnen plats"
|
||||
}
|
||||
return title to "$shown • $dist"
|
||||
}
|
||||
|
||||
private fun postNotification(tag: String, title: String, text: String) {
|
||||
val builder = NotificationCompat.Builder(this, CHANNEL_HITS_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // har ingen effekt på 8+, men ok
|
||||
.setAutoCancel(true)
|
||||
|
||||
NotificationManagerCompat.from(this).notify(tag, 1001, builder.build())
|
||||
}
|
||||
|
||||
// ---- Foreground-notis & kanal ----
|
||||
|
||||
private fun ensureChannel() {
|
||||
if (Build.VERSION.SDK_INT >= 26) {
|
||||
val mgr = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
|
||||
// Foreground-kanal (tyst)
|
||||
val loc = NotificationChannel(
|
||||
CHANNEL_LOCATION_ID,
|
||||
"Yorlik plats",
|
||||
NotificationManager.IMPORTANCE_MIN
|
||||
).apply { description = "Bakgrundspositionering" }
|
||||
mgr.createNotificationChannel(loc)
|
||||
|
||||
// NY: Fynd-notiser (synliga)
|
||||
val hits = NotificationChannel(
|
||||
CHANNEL_HITS_ID,
|
||||
"Yorlik fynd",
|
||||
NotificationManager.IMPORTANCE_HIGH // vill du ha pling: HIGH
|
||||
).apply { description = "Aviseringar för nya/återkommande fynd" }
|
||||
mgr.createNotificationChannel(hits)
|
||||
}
|
||||
}
|
||||
|
||||
private fun persistentNotification(): Notification {
|
||||
return NotificationCompat.Builder(this, CHANNEL_LOCATION_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentTitle("Yorlik")
|
||||
.setContentText("Platsaktivering pågår")
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Hjälp ----
|
||||
|
||||
private fun distanceMeters(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double {
|
||||
val R = 6371000.0
|
||||
val dLat = Math.toRadians(bLat - aLat)
|
||||
val dLon = Math.toRadians(bLon - aLon)
|
||||
val s1 = Math.sin(dLat / 2)
|
||||
val s2 = Math.sin(dLon / 2)
|
||||
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
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,84 +1,295 @@
|
||||
package com.example.yorlik
|
||||
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.example.yorlik.net.DigitaltMuseum
|
||||
import com.example.yorlik.net.DigitaltMuseumItem
|
||||
import com.example.yorlik.net.Fornsok
|
||||
import com.example.yorlik.net.FornsokItem
|
||||
import com.example.yorlik.net.Geocache
|
||||
import com.example.yorlik.net.NoteDTO
|
||||
import com.example.yorlik.util.LastLocationStore
|
||||
import com.example.yorlik.net.Wikipedia
|
||||
import com.example.yorlik.net.WikipediaPage
|
||||
import com.example.yorlik.util.SettingsStore
|
||||
import com.google.android.gms.location.LocationServices as GmsLocationServices
|
||||
import com.google.android.gms.location.Priority
|
||||
import com.google.android.gms.maps.model.CameraPosition
|
||||
import com.google.android.gms.maps.model.LatLng
|
||||
import com.google.maps.android.compose.*
|
||||
|
||||
import kotlinx.coroutines.launch
|
||||
import com.google.android.gms.maps.CameraUpdateFactory
|
||||
import com.google.maps.android.compose.CameraPositionState
|
||||
import com.google.maps.android.compose.GoogleMap
|
||||
import com.google.maps.android.compose.MapProperties
|
||||
import com.google.maps.android.compose.MapType
|
||||
import com.google.maps.android.compose.Marker
|
||||
import com.google.maps.android.compose.MarkerState
|
||||
import com.google.maps.android.compose.MapUiSettings
|
||||
import com.google.maps.android.compose.rememberCameraPositionState
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.tasks.await
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Composable
|
||||
fun MapDialog(
|
||||
onClose: () -> Unit
|
||||
onClose: () -> Unit,
|
||||
initialLat: Double? = null, // ← NYTT (valfritt)
|
||||
initialLon: Double? = null // ← NYTT (valfritt)
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
val ctx = LocalContext.current // ✅ Hämtas i composable-kontext
|
||||
var items by remember { mutableStateOf<List<NoteDTO>>(emptyList()) }
|
||||
val cameraPositionState = rememberCameraPositionState()
|
||||
val context = LocalContext.current
|
||||
val configuration = LocalConfiguration.current
|
||||
val dialogWidth = (configuration.screenWidthDp.dp * 0.98f)
|
||||
val dialogHeight = (configuration.screenHeightDp.dp * 0.70f)
|
||||
|
||||
val satellite = SettingsStore.getSatelliteMap(context)
|
||||
val showKlotter = remember { SettingsStore.getShowKlotter(context) }
|
||||
val showWiki = remember { SettingsStore.getShowWikipedia(context) }
|
||||
val wikiRadius = remember { SettingsStore.getWikiRadiusMeters(context) }
|
||||
val showDm = remember { SettingsStore.getShowDigitaltMuseum(context) }
|
||||
val dmRadius = remember { SettingsStore.getDigitaltMuseumRadiusMeters(context) }
|
||||
val showFornsok = remember { SettingsStore.getShowFornsok(context) }
|
||||
val fornsokRadius = remember { SettingsStore.getFornsokRadiusMeters(context) }
|
||||
|
||||
var myLat by remember { mutableStateOf<Double?>(null) }
|
||||
var myLon by remember { mutableStateOf<Double?>(null) }
|
||||
|
||||
var klotter by remember { mutableStateOf<List<NoteDTO>>(emptyList()) }
|
||||
var wiki by remember { mutableStateOf<List<WikipediaPage>>(emptyList()) }
|
||||
var dm by remember { mutableStateOf<List<DigitaltMuseumItem>>(emptyList()) }
|
||||
var forn by remember { mutableStateOf<List<FornsokItem>>(emptyList()) }
|
||||
|
||||
var selLat by remember { mutableStateOf<Double?>(null) }
|
||||
var selLon by remember { mutableStateOf<Double?>(null) }
|
||||
var selTitle by remember { mutableStateOf<String?>(null) }
|
||||
var selUri by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
|
||||
val camState: CameraPositionState = rememberCameraPositionState {
|
||||
val lat = initialLat ?: myLat ?: 59.3293
|
||||
val lon = initialLon ?: myLon ?: 18.0686
|
||||
position = CameraPosition.fromLatLngZoom(LatLng(lat, lon), 16f)
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
// Centrera på aktuell plats och hämta marker inom 300 m
|
||||
var loc = LastLocationStore.lastKnownLocation
|
||||
if (loc == null) {
|
||||
try {
|
||||
val fused = GmsLocationServices.getFusedLocationProviderClient(ctx)
|
||||
loc = fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||
} catch (_: Exception) {}
|
||||
val fused = GmsLocationServices.getFusedLocationProviderClient(context)
|
||||
val loc = try {
|
||||
fused.lastLocation.await()
|
||||
?: fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||
} catch (_: Exception) { null }
|
||||
if (loc != null) {
|
||||
myLat = loc.latitude
|
||||
myLon = loc.longitude
|
||||
} else {
|
||||
myLat = 59.3293
|
||||
myLon = 18.0686
|
||||
}
|
||||
loc?.let {
|
||||
cameraPositionState.position = CameraPosition.fromLatLngZoom(
|
||||
LatLng(it.latitude, it.longitude),
|
||||
16f
|
||||
)
|
||||
items = Geocache.getNearby(
|
||||
it.latitude,
|
||||
it.longitude,
|
||||
radiusMeters = 300,
|
||||
ttlMs = 30_000L
|
||||
}
|
||||
|
||||
LaunchedEffect(myLat, myLon, showKlotter, showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
|
||||
val lat = myLat; val lon = myLon
|
||||
if (lat == null || lon == null) return@LaunchedEffect
|
||||
|
||||
if (showKlotter) {
|
||||
klotter = withContext(Dispatchers.IO) {
|
||||
Geocache.getNearby(lat = lat, lon = lon, radiusMeters = 300, ttlMs = 0L)
|
||||
}
|
||||
} else klotter = emptyList()
|
||||
|
||||
if (showWiki) {
|
||||
wiki = withContext(Dispatchers.IO) {
|
||||
Wikipedia.getNearby(lat = lat, lon = lon, radiusMeters = wikiRadius)
|
||||
}
|
||||
} else wiki = emptyList()
|
||||
|
||||
if (showDm) {
|
||||
dm = withContext(Dispatchers.IO) {
|
||||
DigitaltMuseum.getNearby(lat = lat, lon = lon, radiusMeters = dmRadius)
|
||||
}
|
||||
} else dm = emptyList()
|
||||
|
||||
if (showFornsok) {
|
||||
forn = withContext(Dispatchers.IO) {
|
||||
Fornsok.getNearby(lat = lat, lon = lon, radiusMeters = fornsokRadius)
|
||||
}
|
||||
} else forn = emptyList()
|
||||
}
|
||||
|
||||
LaunchedEffect(myLat, myLon) {
|
||||
val lat = myLat; val lon = myLon
|
||||
if (lat != null && lon != null) {
|
||||
camState.animate(
|
||||
CameraUpdateFactory.newLatLngZoom(LatLng(lat, lon), 16f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onClose,
|
||||
title = { Text("Karta (nära dig)") },
|
||||
title = { Text("Karta") },
|
||||
text = {
|
||||
GoogleMap(
|
||||
modifier = Modifier
|
||||
Box(
|
||||
Modifier
|
||||
.widthIn(max = dialogWidth)
|
||||
.heightIn(min = 320.dp, max = dialogHeight)
|
||||
.fillMaxWidth()
|
||||
.height(420.dp),
|
||||
cameraPositionState = cameraPositionState,
|
||||
properties = MapProperties(isMyLocationEnabled = true),
|
||||
uiSettings = MapUiSettings(zoomControlsEnabled = true, myLocationButtonEnabled = true)
|
||||
) {
|
||||
// Markers för närliggande platser – utan att visa textinnehåll
|
||||
items.forEach { n ->
|
||||
GoogleMap(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
cameraPositionState = camState,
|
||||
properties = MapProperties(
|
||||
isMyLocationEnabled = hasFgLocationPerms(context),
|
||||
mapType = if (satellite) MapType.SATELLITE else MapType.NORMAL
|
||||
),
|
||||
uiSettings = MapUiSettings(
|
||||
myLocationButtonEnabled = true,
|
||||
zoomControlsEnabled = false,
|
||||
compassEnabled = true
|
||||
)
|
||||
) {
|
||||
val lat = myLat; val lon = myLon
|
||||
|
||||
if (showKlotter) {
|
||||
klotter.forEach { n ->
|
||||
val d = if (lat != null && lon != null)
|
||||
distanceMeters(lat, lon, n.a, n.o).roundToInt() else Int.MAX_VALUE
|
||||
val label = if (d <= 20 && n.t.isNotBlank()) n.t else "Klotter"
|
||||
Marker(
|
||||
state = MarkerState(position = LatLng(n.a, n.o)),
|
||||
title = "Plats", // visar inte n.t
|
||||
snippet = "Gå hit för att se texten"
|
||||
title = label,
|
||||
snippet = "Klotter • ${if (d == Int.MAX_VALUE) "-" else "$d m"}",
|
||||
onClick = { selLat = n.a; selLon = n.o; selTitle = label; selUri = null; false }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showWiki) {
|
||||
wiki.forEach { w ->
|
||||
val d = if (lat != null && lon != null)
|
||||
distanceMeters(lat, lon, w.lat, w.lon).roundToInt() else Int.MAX_VALUE
|
||||
Marker(
|
||||
state = MarkerState(position = LatLng(w.lat, w.lon)),
|
||||
title = "Wikipedia\n${w.title}",
|
||||
snippet = "Wikipedia • ${if (d == Int.MAX_VALUE) "-" else "$d m"}",
|
||||
onClick = { selLat = w.lat; selLon = w.lon; selTitle = w.title; selUri = "https://sv.m.wikipedia.org/?curid=${w.pageId}"; false }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showDm) {
|
||||
dm.forEach { dmi ->
|
||||
val d = if (lat != null && lon != null)
|
||||
distanceMeters(lat, lon, dmi.lat, dmi.lon).roundToInt() else Int.MAX_VALUE
|
||||
Marker(
|
||||
state = MarkerState(position = LatLng(dmi.lat, dmi.lon)),
|
||||
title = "DigitaltMuseum\n${dmi.title}",
|
||||
snippet = "DigitaltMuseum • ${if (d == Int.MAX_VALUE) "-" else "$d m"}",
|
||||
onClick = { selLat = dmi.lat; selLon = dmi.lon; selTitle = dmi.title; selUri = null; false }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showFornsok) {
|
||||
forn.forEach { f ->
|
||||
val d = if (lat != null && lon != null)
|
||||
distanceMeters(lat, lon, f.lat, f.lon).roundToInt() else Int.MAX_VALUE
|
||||
val header = f.title // vi har inte 'type' längre
|
||||
|
||||
Marker(
|
||||
state = MarkerState(position = LatLng(f.lat, f.lon)),
|
||||
title = header, // visa objektets namn överst
|
||||
snippet = "Fornsök • ${if (d == Int.MAX_VALUE) "-" else "$d m"}",
|
||||
onClick = {
|
||||
selLat = f.lat; selLon = f.lon; selTitle = f.title
|
||||
selUri = f.uri // spara länk om den finns (för "Läs mer")
|
||||
false // visa infowindow
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(8.dp),
|
||||
horizontalAlignment = Alignment.End
|
||||
) {
|
||||
Button(
|
||||
onClick = { openInMaps(context, selLat, selLon, selTitle) },
|
||||
enabled = selLat != null && selLon != null
|
||||
) { Text("Maps") }
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
Button(
|
||||
onClick = { openWalkingDirections(context, selLat, selLon, selTitle) },
|
||||
enabled = selLat != null && selLon != null
|
||||
) { Text("Vägbeskrivning") }
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
selUri?.let { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it))) }
|
||||
},
|
||||
enabled = selUri != null
|
||||
) { Text("Läs mer") }
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(onClick = onClose) {
|
||||
Text("Stäng")
|
||||
}
|
||||
Button(onClick = onClose) { Text("Stäng") }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/* -------- Hjälpfunktioner -------- */
|
||||
|
||||
private fun openInMaps(ctx: Context, lat: Double?, lon: Double?, title: String?) {
|
||||
if (lat == null || lon == null) return
|
||||
val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon(${Uri.encode(title ?: "Plats")})")
|
||||
val intent = Intent(Intent.ACTION_VIEW, uri).apply {
|
||||
`package` = "com.google.android.apps.maps"
|
||||
}
|
||||
try {
|
||||
ctx.startActivity(intent)
|
||||
} catch (_: Exception) {
|
||||
ctx.startActivity(Intent(Intent.ACTION_VIEW, uri))
|
||||
}
|
||||
}
|
||||
|
||||
private fun openWalkingDirections(ctx: Context, lat: Double?, lon: Double?, title: String?) {
|
||||
if (lat == null || lon == null) return
|
||||
val label = Uri.encode(title ?: "Plats")
|
||||
val uri = Uri.parse("google.navigation?q=$lat,$lon($label)&mode=w")
|
||||
val intent = Intent(Intent.ACTION_VIEW, uri).apply {
|
||||
`package` = "com.google.android.apps.maps"
|
||||
}
|
||||
try {
|
||||
ctx.startActivity(intent)
|
||||
} catch (_: Exception) {
|
||||
openInMaps(ctx, lat, lon, title)
|
||||
}
|
||||
}
|
||||
|
||||
// Samma distans som i MainActivity
|
||||
private fun distanceMeters(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double {
|
||||
val R = 6371000.0
|
||||
val dLat = Math.toRadians(bLat - aLat)
|
||||
val dLon = Math.toRadians(bLon - aLon)
|
||||
val s1 = Math.sin(dLat / 2)
|
||||
val s2 = Math.sin(dLon / 2)
|
||||
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
|
||||
}
|
||||
|
||||
65
app/src/main/java/com/example/yorlik/OutboxStore.kt
Normal file
65
app/src/main/java/com/example/yorlik/OutboxStore.kt
Normal file
@@ -0,0 +1,65 @@
|
||||
package com.example.yorlik.util
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Enkel "utkorg" i SharedPreferences. Lagrar klotter som inte kunde postas
|
||||
* för att skickas senare när nätet kommer tillbaka.
|
||||
*/
|
||||
object OutboxStore {
|
||||
private const val PREFS = "yorlik_outbox"
|
||||
private const val KEY = "pending_json"
|
||||
|
||||
data class PendingNote(
|
||||
val lat: Double,
|
||||
val lon: Double,
|
||||
val text: String,
|
||||
val createdAt: Long
|
||||
)
|
||||
|
||||
private fun prefs(ctx: Context) =
|
||||
ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
fun add(context: Context, lat: Double, lon: Double, text: String, createdAt: Long) {
|
||||
val list = all(context).toMutableList()
|
||||
list.add(PendingNote(lat, lon, text, createdAt))
|
||||
save(context, list)
|
||||
}
|
||||
|
||||
fun all(context: Context): List<PendingNote> {
|
||||
val s = prefs(context).getString(KEY, "[]") ?: "[]"
|
||||
val arr = JSONArray(s)
|
||||
val out = ArrayList<PendingNote>(arr.length())
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.getJSONObject(i)
|
||||
out.add(
|
||||
PendingNote(
|
||||
lat = o.getDouble("lat"),
|
||||
lon = o.getDouble("lon"),
|
||||
text = o.getString("text"),
|
||||
createdAt = o.getLong("createdAt")
|
||||
)
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun replaceAll(context: Context, items: List<PendingNote>) {
|
||||
save(context, items)
|
||||
}
|
||||
|
||||
private fun save(context: Context, items: List<PendingNote>) {
|
||||
val arr = JSONArray()
|
||||
for (p in items) {
|
||||
val o = JSONObject()
|
||||
o.put("lat", p.lat)
|
||||
o.put("lon", p.lon)
|
||||
o.put("text", p.text)
|
||||
o.put("createdAt", p.createdAt)
|
||||
arr.put(o)
|
||||
}
|
||||
prefs(context).edit().putString(KEY, arr.toString()).apply()
|
||||
}
|
||||
}
|
||||
35
app/src/main/java/com/example/yorlik/OutboxWorker.kt
Normal file
35
app/src/main/java/com/example/yorlik/OutboxWorker.kt
Normal file
@@ -0,0 +1,35 @@
|
||||
package com.example.yorlik.work
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.example.yorlik.net.createNote
|
||||
import com.example.yorlik.util.OutboxStore
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
val ctx = applicationContext
|
||||
val pending = OutboxStore.all(ctx)
|
||||
if (pending.isEmpty()) return Result.success()
|
||||
|
||||
val keep = mutableListOf<OutboxStore.PendingNote>()
|
||||
for (p in pending) {
|
||||
val ok = try {
|
||||
createNote(p.lat, p.lon, p.text, p.createdAt)
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
if (!ok) keep.add(p)
|
||||
}
|
||||
OutboxStore.replaceAll(ctx, keep)
|
||||
return if (keep.isEmpty()) Result.success() else Result.retry()
|
||||
}
|
||||
}
|
||||
36
app/src/main/java/com/example/yorlik/net/DigitaltMuseum.kt
Normal file
36
app/src/main/java/com/example/yorlik/net/DigitaltMuseum.kt
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.example.yorlik.net
|
||||
|
||||
import android.util.Log
|
||||
|
||||
data class DigitaltMuseumItem(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val lat: Double,
|
||||
val lon: Double,
|
||||
val url: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
suspend fun getNearby(
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
radiusMeters: Int
|
||||
): List<DigitaltMuseumItem> {
|
||||
return try {
|
||||
// TODO: Implementera riktig anrop mot DigitaltMuseum API här.
|
||||
emptyList()
|
||||
} catch (t: Throwable) {
|
||||
Log.w("DigitaltMuseum", "getNearby failed: ${t.message}")
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
}
|
||||
593
app/src/main/java/com/example/yorlik/net/Fornsok.kt
Normal file
593
app/src/main/java/com/example/yorlik/net/Fornsok.kt
Normal file
@@ -0,0 +1,593 @@
|
||||
package com.example.yorlik.net
|
||||
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
import java.util.Locale
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
|
||||
// Utökad med desc (=pres:description). Nya fält har default → inga brytande ändringar.
|
||||
data class FornsokItem(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val lat: Double,
|
||||
val lon: Double,
|
||||
val uri: String? = null,
|
||||
val serviceName: String? = null,
|
||||
val desc: String? = null
|
||||
)
|
||||
|
||||
object Fornsok {
|
||||
|
||||
private const val TAG = "Fornsok"
|
||||
private const val BASE = "https://kulturarvsdata.se/ksamsok/api"
|
||||
private const val HITS = 200
|
||||
private const val MAX_PAGES_FAST = 3 // presentation-schemat
|
||||
private const val MAX_PAGES_FALLBACK = 3 // fullt schema (tyngre)
|
||||
|
||||
suspend fun getNearby(
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
radiusMeters: Int
|
||||
): List<FornsokItem> = withContext(Dispatchers.IO) {
|
||||
|
||||
val bbox = bboxWgs84(lat, lon, radiusMeters)
|
||||
Log.d(
|
||||
TAG,
|
||||
"BBox W,S,E,N = ${fmt6(bbox.w)} ${fmt6(bbox.s)} ${fmt6(bbox.e)} ${fmt6(bbox.n)} (radie=${radiusMeters} m)"
|
||||
)
|
||||
|
||||
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")"""
|
||||
Log.d(TAG, "CQL = $cqlBase")
|
||||
|
||||
// Fas 1: presentation (snabb)
|
||||
val fast = queryAndParse(cqlBase, usePresentation = true, maxPages = MAX_PAGES_FAST)
|
||||
if (fast.isNotEmpty()) {
|
||||
Log.d(TAG, "FÄRDIGA FORNSÖK-OBJEKT (presentation): ${fast.size} st")
|
||||
return@withContext fast
|
||||
}
|
||||
|
||||
// Fas 2: fullt schema (utan recordSchema)
|
||||
Log.d(TAG, "Inga coords via presentation – provar fullt schema (utan recordSchema).")
|
||||
val full = queryAndParse(cqlBase, usePresentation = false, maxPages = MAX_PAGES_FALLBACK)
|
||||
Log.d(TAG, "FÄRDIGA FORNSÖK-OBJEKT (fullt schema): ${full.size} st")
|
||||
return@withContext full
|
||||
}
|
||||
|
||||
// För detaljrutan från Hittat: hämta titel + desc + coords för ett känt entityUri
|
||||
suspend fun getByEntityUri(entityUri: String): FornsokItem? = withContext(Dispatchers.IO) {
|
||||
val cql = """entityUri="$entityUri""""
|
||||
val url = buildUrl(cql, startRecord = 1, usePresentation = true)
|
||||
Log.d(TAG, "Detalj: GET $url")
|
||||
val root = httpGetJson(url) ?: return@withContext null
|
||||
val result = root.optJSONObject("result") ?: return@withContext null
|
||||
|
||||
val recordsNode = result.opt("records")
|
||||
val recordArr: JSONArray = when (recordsNode) {
|
||||
is JSONObject -> {
|
||||
val r = recordsNode.opt("record")
|
||||
when (r) {
|
||||
is JSONArray -> r
|
||||
is JSONObject -> JSONArray().put(r)
|
||||
else -> JSONArray()
|
||||
}
|
||||
}
|
||||
else -> JSONArray()
|
||||
}
|
||||
if (recordArr.length() == 0) return@withContext null
|
||||
|
||||
// Ta första giltiga posten
|
||||
for (i in 0 until recordArr.length()) {
|
||||
val rec = recordArr.optJSONObject(i) ?: continue
|
||||
|
||||
val svc = (findStringDeep(rec, "serviceName")
|
||||
?: findStringDeep(rec, "pres:service"))
|
||||
?.lowercase()
|
||||
|
||||
val looksFornsok = (svc == "kmr_lamningar" || svc == "fmi") ||
|
||||
entityUri.contains("/raa/lamning/", true) ||
|
||||
entityUri.contains("/raa/fmi/", true) ||
|
||||
entityUri.contains("/raa/fmis/", true) ||
|
||||
entityUri.contains("/raa/fornsok", true)
|
||||
|
||||
val ll = extractLatLonPresentation(rec) ?: extractLatLonGeneric(rec) ?: continue
|
||||
val (latV, lonV) = ll
|
||||
|
||||
val title = findStringDeep(rec, "pres:itemLabel")
|
||||
?: findStringDeep(rec, "pres:title")
|
||||
?: "Fornlämning"
|
||||
|
||||
val desc = findStringDeep(rec, "pres:description")
|
||||
val svcName = svc ?: "fornsok"
|
||||
|
||||
if (looksFornsok) {
|
||||
return@withContext FornsokItem(
|
||||
id = entityUri,
|
||||
title = title,
|
||||
lat = latV,
|
||||
lon = lonV,
|
||||
uri = entityUri,
|
||||
serviceName = svcName,
|
||||
desc = desc
|
||||
)
|
||||
}
|
||||
}
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
// ------------------- HTTP + parse -------------------
|
||||
|
||||
private fun buildUrl(cql: String, startRecord: Int, usePresentation: Boolean): String {
|
||||
val sb = StringBuilder()
|
||||
.append("version=1.1")
|
||||
.append("&method=search")
|
||||
.append("&hitsPerPage=").append(HITS)
|
||||
.append("&startRecord=").append(startRecord)
|
||||
|
||||
if (usePresentation) {
|
||||
val fields =
|
||||
"pres:entityUri,pres:id,pres:itemPosition,pres:coordinates,pres:latitude,pres:longitude,pres:title,pres:itemLabel,pres:service,serviceName,pres:description"
|
||||
sb.append("&recordSchema=presentation")
|
||||
sb.append("&fields=").append(URLEncoder.encode(fields, "UTF-8"))
|
||||
}
|
||||
sb.append("&query=").append(URLEncoder.encode(cql, "UTF-8").replace("+", "%20"))
|
||||
return "$BASE?$sb"
|
||||
}
|
||||
|
||||
private fun httpGetJson(url: String): JSONObject? {
|
||||
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 10000
|
||||
readTimeout = 20000
|
||||
setRequestProperty("Accept", "application/json")
|
||||
setRequestProperty("User-Agent", "Yorlik/0.1.x (Android)")
|
||||
}
|
||||
return try {
|
||||
val code = conn.responseCode
|
||||
val ctype = conn.getHeaderField("Content-Type")
|
||||
Log.d(TAG, "HTTP $code Content-Type=$ctype")
|
||||
if (code !in 200..299) return null
|
||||
val body = conn.inputStream.use { it.readBytes().toString(Charsets.UTF_8) }
|
||||
if (body.isBlank()) return null
|
||||
JSONObject(body)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun queryAndParse(cql: String, usePresentation: Boolean, maxPages: Int): List<FornsokItem> {
|
||||
val out = LinkedHashMap<String, FornsokItem>()
|
||||
var start = 1
|
||||
var page = 1
|
||||
var totalHitsFromServer = -1
|
||||
|
||||
while (page <= maxPages) {
|
||||
val url = buildUrl(cql, start, usePresentation)
|
||||
Log.d(TAG, "Sida $page: GET $url")
|
||||
val root = httpGetJson(url) ?: break
|
||||
|
||||
val result = root.optJSONObject("result") ?: break
|
||||
if (totalHitsFromServer < 0) {
|
||||
totalHitsFromServer = result.optInt("totalHits", -1)
|
||||
Log.d(TAG, "totalHits (server): $totalHitsFromServer")
|
||||
}
|
||||
|
||||
val recordsNode = result.opt("records")
|
||||
val recordArr: JSONArray = when (recordsNode) {
|
||||
is JSONObject -> {
|
||||
val r = recordsNode.opt("record")
|
||||
when (r) {
|
||||
is JSONArray -> r
|
||||
is JSONObject -> JSONArray().put(r)
|
||||
else -> JSONArray()
|
||||
}
|
||||
}
|
||||
else -> JSONArray()
|
||||
}
|
||||
|
||||
if (recordArr.length() == 0) {
|
||||
Log.d(TAG, "Ingen records.record på denna sida.")
|
||||
break
|
||||
}
|
||||
|
||||
var visited = 0
|
||||
var nonKmrFmi = 0
|
||||
var noCoords = 0
|
||||
var added = 0
|
||||
|
||||
for (i in 0 until recordArr.length()) {
|
||||
val rec = recordArr.optJSONObject(i) ?: continue
|
||||
visited++
|
||||
|
||||
val svc = (findStringDeep(rec, "serviceName")
|
||||
?: findStringDeep(rec, "pres:service"))
|
||||
?.lowercase()
|
||||
|
||||
val entityUri = findStringDeep(rec, "pres:entityUri")
|
||||
?: findStringDeep(rec, "entityUri")
|
||||
?: findStringDeep(rec, "item")
|
||||
|
||||
val presId = findStringDeep(rec, "pres:id")
|
||||
|
||||
// --- Koordinater ---
|
||||
val ll = if (usePresentation) {
|
||||
extractLatLonPresentation(rec) ?: extractLatLonGeneric(rec)
|
||||
} else {
|
||||
extractLatLonGeneric(rec)
|
||||
}
|
||||
if (ll == null) {
|
||||
noCoords++
|
||||
continue
|
||||
}
|
||||
val (latV, lonV) = ll
|
||||
|
||||
// Klassificera som Fornsök/FMIS/KMR
|
||||
val looksFornsok = when {
|
||||
svc == "kmr_lamningar" || svc == "fmi" -> true
|
||||
entityUri?.contains("/raa/fmi/", ignoreCase = true) == true -> true
|
||||
entityUri?.contains("/raa/fmis/", ignoreCase = true) == true -> true
|
||||
entityUri?.contains("/raa/lamning/", ignoreCase = true) == true -> true
|
||||
entityUri?.contains("/raa/fornsok", ignoreCase = true) == true -> true
|
||||
else -> false
|
||||
}
|
||||
if (!looksFornsok) {
|
||||
nonKmrFmi++
|
||||
continue
|
||||
}
|
||||
|
||||
// Titel + beskrivning (presentation innehåller ofta description)
|
||||
val title = findStringDeep(rec, "pres:itemLabel")
|
||||
?: findStringDeep(rec, "pres:title")
|
||||
?: findStringDeep(rec, "title")
|
||||
?: findStringDeep(rec, "label")
|
||||
?: "Fornlämning"
|
||||
|
||||
val description = findStringDeep(rec, "pres:description")
|
||||
|
||||
// Stabilt id
|
||||
val id = when {
|
||||
entityUri != null -> entityUri
|
||||
presId != null -> "kmr:$presId"
|
||||
else -> "${title}@${fmt6(latV)},${fmt6(lonV)}"
|
||||
}
|
||||
|
||||
if (!out.containsKey(id)) {
|
||||
out[id] = FornsokItem(
|
||||
id = id,
|
||||
title = title,
|
||||
lat = latV,
|
||||
lon = lonV,
|
||||
uri = entityUri,
|
||||
serviceName = svc,
|
||||
desc = description
|
||||
)
|
||||
added++
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(
|
||||
TAG,
|
||||
"Sida: genomgång visited=$visited, nonKmrFmi=$nonKmrFmi, noCoords=$noCoords, tillagda=$added, ack=${out.size}"
|
||||
)
|
||||
|
||||
// Fler sidor?
|
||||
if (totalHitsFromServer > 0) {
|
||||
val maxByHits = (totalHitsFromServer + HITS - 1) / HITS
|
||||
if (page >= maxByHits) break
|
||||
}
|
||||
start += HITS
|
||||
page++
|
||||
|
||||
if (out.size >= 150) break
|
||||
}
|
||||
|
||||
return out.values.toList()
|
||||
}
|
||||
|
||||
// ------------------- Lat/Lon extraktion -------------------
|
||||
|
||||
/** Presentation-schema – vägar inkl. gml:coordinates.content och gml:pos/posList. */
|
||||
private fun extractLatLonPresentation(rec: JSONObject): Pair<Double, Double>? {
|
||||
// 1) pres:itemPosition = "POINT(lon lat)"
|
||||
val pos = findStringDeep(rec, "pres:itemPosition")
|
||||
if (!pos.isNullOrBlank()) {
|
||||
val lonLat = parseWktPoint(pos)
|
||||
if (lonLat != null) return Pair(lonLat.second, lonLat.first) // lat, lon
|
||||
}
|
||||
|
||||
// 2) pres:coordinates = [{lat:.., lon|lng:..}, ...]
|
||||
val coords = findArrayDeep(rec, "pres:coordinates")
|
||||
if (coords != null && coords.length() > 0) {
|
||||
val c0 = coords.optJSONObject(0)
|
||||
if (c0 != null) {
|
||||
val lat = numOrNull(c0.opt("lat")) ?: numOrNull(c0.opt("latitude"))
|
||||
val lon = numOrNull(c0.opt("lon")) ?: numOrNull(c0.opt("lng")) ?: numOrNull(c0.opt("longitude"))
|
||||
if (lat != null && lon != null) return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
|
||||
// 3) pres:latitude/pres:longitude
|
||||
val latStr = findStringDeep(rec, "pres:latitude")
|
||||
val lonStr = findStringDeep(rec, "pres:longitude")
|
||||
if (!latStr.isNullOrBlank() && !lonStr.isNullOrBlank()) {
|
||||
val la = latStr.replace(",", ".").toDoubleOrNull()
|
||||
val lo = lonStr.replace(",", ".").toDoubleOrNull()
|
||||
if (la != null && lo != null) return Pair(la, lo)
|
||||
}
|
||||
|
||||
// 4) georss:where -> gml:Point -> gml:coordinates { content: "lon, lat" }
|
||||
val gmlCoordsObj = findObjectDeep(rec, "gml:coordinates")
|
||||
if (gmlCoordsObj != null) {
|
||||
val content = gmlCoordsObj.optString("content")
|
||||
if (!content.isNullOrBlank()) {
|
||||
val lonLat = parseLonLat(content)
|
||||
if (lonLat != null) return Pair(lonLat.second, lonLat.first)
|
||||
}
|
||||
}
|
||||
|
||||
// 5) gml:pos eller gml:posList (sträng med "lon lat [lon lat …]")
|
||||
val gmlPos = findStringDeep(rec, "gml:pos")
|
||||
if (!gmlPos.isNullOrBlank()) {
|
||||
parsePosOrPosList(gmlPos)?.let { return it }
|
||||
}
|
||||
val gmlPosListStr = findStringDeep(rec, "gml:posList")
|
||||
if (!gmlPosListStr.isNullOrBlank()) {
|
||||
parsePosOrPosList(gmlPosListStr)?.let { return it }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** Fullt schema – skanna allt efter koordinater (GeoRSS/GML/JSON-LD). */
|
||||
private fun extractLatLonGeneric(node: Any?): Pair<Double, Double>? {
|
||||
return scanForLatLon(node)?.takeIf { isValidLatLon(it.first, it.second) }
|
||||
}
|
||||
|
||||
/** Rekursiv sökning efter lat/lon i godtycklig JSON-struktur. */
|
||||
private fun scanForLatLon(node: Any?): Pair<Double, Double>? {
|
||||
when (node) {
|
||||
is JSONObject -> {
|
||||
val it = node.keys()
|
||||
while (it.hasNext()) {
|
||||
val k = it.next()
|
||||
val v = node.opt(k)
|
||||
|
||||
// WKT POINT(lon lat)
|
||||
if (v is String && v.contains("POINT", ignoreCase = true)) {
|
||||
parseWktPoint(v)?.let { (lon, lat) ->
|
||||
if (isValidLatLon(lat, lon)) return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
|
||||
// gml:coordinates → objekt med content eller sträng
|
||||
if (k.endsWith("coordinates", true)) {
|
||||
when (v) {
|
||||
is String -> {
|
||||
parseLonLat(v)?.let { (lon, lat) ->
|
||||
if (isValidLatLon(lat, lon)) return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
is JSONObject -> {
|
||||
val s = v.optString("content")
|
||||
if (!s.isNullOrBlank()) {
|
||||
parseLonLat(s)?.let { (lon, lat) ->
|
||||
if (isValidLatLon(lat, lon)) return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gml:pos / gml:posList
|
||||
if (k.endsWith("pos", true) || k.endsWith("posList", true)) {
|
||||
when (v) {
|
||||
is String -> parsePosOrPosList(v)?.let { return it }
|
||||
is JSONObject -> {
|
||||
val s = v.optString("content")
|
||||
if (!s.isNullOrBlank()) parsePosOrPosList(s)?.let { return it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Objekt med {lat, lon|long|lng} etc.
|
||||
if (v is JSONObject) {
|
||||
val lat = numOrNull(v.opt("lat"))
|
||||
?: numOrNull(v.opt("latitude"))
|
||||
?: numOrNull(v.opt("wgs84_pos:lat"))
|
||||
val lon = numOrNull(v.opt("lon"))
|
||||
?: numOrNull(v.opt("lng"))
|
||||
?: numOrNull(v.opt("long"))
|
||||
?: numOrNull(v.opt("longitude"))
|
||||
?: numOrNull(v.opt("wgs84_pos:long"))
|
||||
if (lat != null && lon != null && isValidLatLon(lat, lon)) {
|
||||
return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
|
||||
// Array med två tal → [lon, lat] eller [lat, lon]
|
||||
if (v is JSONArray && v.length() == 2) {
|
||||
val a = numOrNull(v.opt(0))
|
||||
val b = numOrNull(v.opt(1))
|
||||
if (a != null && b != null) {
|
||||
if (isValidLatLon(b, a)) return Pair(b, a)
|
||||
if (isValidLatLon(a, b)) return Pair(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
// Rekursion
|
||||
scanForLatLon(v)?.let { return it }
|
||||
}
|
||||
}
|
||||
is JSONArray -> {
|
||||
if (node.length() >= 2) {
|
||||
if (node.length() % 2 == 0) {
|
||||
val a0 = numOrNull(node.opt(0))
|
||||
val a1 = numOrNull(node.opt(1))
|
||||
if (a0 != null && a1 != null) {
|
||||
if (isValidLatLon(a1, a0)) return Pair(a1, a0)
|
||||
if (isValidLatLon(a0, a1)) return Pair(a0, a1)
|
||||
}
|
||||
}
|
||||
for (i in 0 until node.length()) {
|
||||
scanForLatLon(node.opt(i))?.let { return it }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ------------------- Utils -------------------
|
||||
|
||||
private data class BBox(val w: Double, val s: Double, val e: Double, val n: Double)
|
||||
|
||||
private fun bboxWgs84(lat: Double, lon: Double, rMeters: Int): BBox {
|
||||
val r = rMeters.coerceAtLeast(1)
|
||||
val dLat = r / 111_320.0
|
||||
val dLon = r / (111_320.0 * cos(lat * PI / 180.0)).coerceAtLeast(1e-6)
|
||||
return BBox(
|
||||
w = lon - dLon,
|
||||
s = lat - dLat,
|
||||
e = lon + dLon,
|
||||
n = lat + dLat
|
||||
)
|
||||
}
|
||||
|
||||
private fun findStringDeep(node: Any?, key: String): String? {
|
||||
when (node) {
|
||||
is JSONObject -> {
|
||||
if (node.has(key)) {
|
||||
val v = node.opt(key)
|
||||
if (v is String && v.isNotBlank()) return v
|
||||
}
|
||||
val it = node.keys()
|
||||
while (it.hasNext()) {
|
||||
val k = it.next()
|
||||
val child = node.opt(k)
|
||||
val r = findStringDeep(child, key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
is JSONArray -> {
|
||||
for (i in 0 until node.length()) {
|
||||
val r = findStringDeep(node.opt(i), key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findObjectDeep(node: Any?, key: String): JSONObject? {
|
||||
when (node) {
|
||||
is JSONObject -> {
|
||||
if (node.has(key)) {
|
||||
val v = node.opt(key)
|
||||
if (v is JSONObject) return v
|
||||
}
|
||||
val it = node.keys()
|
||||
while (it.hasNext()) {
|
||||
val k = it.next()
|
||||
val child = node.opt(k)
|
||||
val r = findObjectDeep(child, key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
is JSONArray -> {
|
||||
for (i in 0 until node.length()) {
|
||||
val r = findObjectDeep(node.opt(i), key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findArrayDeep(node: Any?, key: String): JSONArray? {
|
||||
when (node) {
|
||||
is JSONObject -> {
|
||||
if (node.has(key)) {
|
||||
val v = node.opt(key)
|
||||
if (v is JSONArray) return v
|
||||
}
|
||||
val it = node.keys()
|
||||
while (it.hasNext()) {
|
||||
val k = it.next()
|
||||
val child = node.opt(k)
|
||||
val r = findArrayDeep(child, key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
is JSONArray -> {
|
||||
for (i in 0 until node.length()) {
|
||||
val r = findArrayDeep(node.opt(i), key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun parseWktPoint(s: String): Pair<Double, Double>? {
|
||||
val idx = s.indexOf("POINT", ignoreCase = true)
|
||||
if (idx < 0) return null
|
||||
val open = s.indexOf('(', idx)
|
||||
val close = s.indexOf(')', open + 1)
|
||||
if (open < 0 || close < 0) return null
|
||||
val inner = s.substring(open + 1, close).trim()
|
||||
val parts = inner.split(Regex("\\s+"))
|
||||
if (parts.size >= 2) {
|
||||
val lon = parts[0].replace(",", ".").toDoubleOrNull()
|
||||
val lat = parts[1].replace(",", ".").toDoubleOrNull()
|
||||
if (lon != null && lat != null) return Pair(lon, lat)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun parseLonLat(txt: String): Pair<Double, Double>? {
|
||||
val cleaned = txt.replace(";", ",").trim()
|
||||
val parts = cleaned.split(",")
|
||||
if (parts.size >= 2) {
|
||||
val lon = parts[0].trim().replace(",", ".").toDoubleOrNull()
|
||||
val lat = parts[1].trim().replace(",", ".").toDoubleOrNull()
|
||||
if (lon != null && lat != null) return Pair(lon, lat)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Tolkar gml:pos/gml:posList (första paret). Hanterar både "lon lat" och "lat lon". */
|
||||
private fun parsePosOrPosList(s: String): Pair<Double, Double>? {
|
||||
val parts = s.trim().split(Regex("\\s+"))
|
||||
if (parts.size >= 2) {
|
||||
val a = parts[0].replace(",", ".").toDoubleOrNull()
|
||||
val b = parts[1].replace(",", ".").toDoubleOrNull()
|
||||
if (a != null && b != null) {
|
||||
if (isValidLatLon(b, a)) return Pair(b, a)
|
||||
if (isValidLatLon(a, b)) return Pair(a, b)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun isValidLatLon(lat: Double, lon: Double): Boolean {
|
||||
return lat in -90.0..90.0 && lon in -180.0..180.0 && !(abs(lat) < 1e-9 && abs(lon) < 1e-9)
|
||||
}
|
||||
|
||||
private fun numOrNull(any: Any?): Double? = when (any) {
|
||||
is Number -> any.toDouble()
|
||||
is String -> any.replace(",", ".").toDoubleOrNull()
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun fmt6(d: Double): String = String.format(Locale.US, "%.6f", d)
|
||||
private fun fmt8(d: Double): String = String.format(Locale.US, "%.8f", d)
|
||||
}
|
||||
98
app/src/main/java/com/example/yorlik/net/Wikipedia.kt
Normal file
98
app/src/main/java/com/example/yorlik/net/Wikipedia.kt
Normal file
@@ -0,0 +1,98 @@
|
||||
package com.example.yorlik.net
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
data class WikipediaPage(
|
||||
val pageId: Long,
|
||||
val title: String,
|
||||
val lat: Double,
|
||||
val lon: Double
|
||||
)
|
||||
|
||||
data class WikipediaDetail(
|
||||
val pageId: Long,
|
||||
val title: String,
|
||||
val extract: String
|
||||
)
|
||||
|
||||
object Wikipedia {
|
||||
|
||||
suspend fun getNearby(lat: Double, lon: Double, radiusMeters: Int): List<WikipediaPage> {
|
||||
val coord = "${lat}|${lon}"
|
||||
val params = mapOf(
|
||||
"action" to "query",
|
||||
"list" to "geosearch",
|
||||
"gscoord" to coord,
|
||||
"gsradius" to radiusMeters.toString(),
|
||||
"gslimit" to "50",
|
||||
"format" to "json",
|
||||
"formatversion" to "2"
|
||||
)
|
||||
val query = params.entries.joinToString("&") { (k, v) ->
|
||||
"${URLEncoder.encode(k, "UTF-8")}=${URLEncoder.encode(v, "UTF-8")}"
|
||||
}
|
||||
val url = URL("https://sv.wikipedia.org/w/api.php?$query")
|
||||
|
||||
val conn = (url.openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = "GET"
|
||||
connectTimeout = 8000
|
||||
readTimeout = 8000
|
||||
setRequestProperty("User-Agent", "Yorlik/0.0.5 (Android)")
|
||||
}
|
||||
conn.useCaches = false
|
||||
|
||||
val code = conn.responseCode
|
||||
if (code != 200) return emptyList()
|
||||
|
||||
val body = conn.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }
|
||||
val root = JSONObject(body)
|
||||
val arr = root.optJSONObject("query")?.optJSONArray("geosearch") ?: return emptyList()
|
||||
|
||||
val out = ArrayList<WikipediaPage>(arr.length())
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.optJSONObject(i) ?: continue
|
||||
val id = o.optLong("pageid")
|
||||
val t = o.optString("title")
|
||||
val a = o.optDouble("lat")
|
||||
val g = o.optDouble("lon")
|
||||
out.add(WikipediaPage(id, t, a, g))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
suspend fun getExtract(pageId: Long): WikipediaDetail {
|
||||
val params = mapOf(
|
||||
"action" to "query",
|
||||
"prop" to "extracts",
|
||||
"exintro" to "1",
|
||||
"explaintext" to "1",
|
||||
"format" to "json",
|
||||
"formatversion" to "2",
|
||||
"pageids" to pageId.toString()
|
||||
)
|
||||
val query = params.entries.joinToString("&") { (k, v) ->
|
||||
"${URLEncoder.encode(k, "UTF-8")}=${URLEncoder.encode(v, "UTF-8")}"
|
||||
}
|
||||
val url = URL("https://sv.wikipedia.org/w/api.php?$query")
|
||||
|
||||
val conn = (url.openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = "GET"
|
||||
connectTimeout = 8000
|
||||
readTimeout = 8000
|
||||
setRequestProperty("User-Agent", "Yorlik/0.0.5 (Android)")
|
||||
}
|
||||
val code = conn.responseCode
|
||||
if (code != 200) return WikipediaDetail(pageId, "", "")
|
||||
|
||||
val body = conn.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }
|
||||
val root = JSONObject(body)
|
||||
val pages = root.optJSONObject("query")?.optJSONArray("pages")
|
||||
val p = if (pages != null && pages.length() > 0) pages.optJSONObject(0) else null
|
||||
val title = p?.optString("title") ?: ""
|
||||
val extract = p?.optString("extract") ?: ""
|
||||
return WikipediaDetail(pageId, title, extract)
|
||||
}
|
||||
}
|
||||
224
app/src/main/java/com/example/yorlik/util/FoundStore.kt
Normal file
224
app/src/main/java/com/example/yorlik/util/FoundStore.kt
Normal file
@@ -0,0 +1,224 @@
|
||||
package com.example.yorlik.util
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
|
||||
data class FoundEntry(
|
||||
val layer: String,
|
||||
val id: String, // ex. klotter-id, wiki pageId eller DigitaltMuseum-id
|
||||
val label: String, // visningsnamn: klottertext / wikititel / DM-titel
|
||||
val lat: Double,
|
||||
val lon: Double,
|
||||
val timeMillis: Long
|
||||
)
|
||||
|
||||
object FoundStore {
|
||||
private const val PREF = "yorlik_found_store"
|
||||
private const val KEY_KEYS = "keys" // StringSet
|
||||
|
||||
// Lager
|
||||
const val LAYER_KLOTTER = "klotter"
|
||||
const val LAYER_WIKI = "wiki"
|
||||
const val LAYER_DM = "dm" // <— DigitaltMuseum
|
||||
|
||||
// Har man varit 200 m bort så skall man få aviseringar igen.
|
||||
private const val AWAY_THRESHOLD_METERS = 200 // kan ändras senare
|
||||
|
||||
private fun key(layer: String, id: String) = "$layer|$id"
|
||||
private fun prefs(ctx: Context) = ctx.getSharedPreferences(PREF, Context.MODE_PRIVATE)
|
||||
|
||||
fun isFound(ctx: Context, layer: String, id: String): Boolean {
|
||||
val k = key(layer, id)
|
||||
val set = prefs(ctx).getStringSet(KEY_KEYS, emptySet()) ?: emptySet()
|
||||
return set.contains(k)
|
||||
}
|
||||
|
||||
/**
|
||||
* Markera som funnet. Sparar första fyndtiden; uppdaterar inte om det redan finns.
|
||||
* @return true om nytt fynd sparades, annars false.
|
||||
*/
|
||||
@Synchronized
|
||||
fun markFound(
|
||||
ctx: Context,
|
||||
layer: String,
|
||||
id: String,
|
||||
label: String,
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
timeMillis: Long
|
||||
): Boolean {
|
||||
val p = prefs(ctx)
|
||||
val k = key(layer, id)
|
||||
val set = p.getStringSet(KEY_KEYS, emptySet())?.toMutableSet() ?: mutableSetOf()
|
||||
|
||||
val existingJson = p.getString(k, null)
|
||||
val existed = existingJson != null
|
||||
val prev = try {
|
||||
if (existingJson != null) JSONObject(existingJson) else null
|
||||
} catch (_: Throwable) { null }
|
||||
|
||||
// Re-arm: om vi tidigare markerats som "borta" (away=true) ska anropet räknas som "ny" igen
|
||||
val wasAway = prev?.optBoolean("away", false) ?: false
|
||||
|
||||
// Backwards kompatibelt default: om first_visit saknas, använd äldre "time" som första besök, annars nu
|
||||
val firstVisit = prev?.optLong("first_visit", -1L)?.takeIf { it > 0 }
|
||||
?: (prev?.optLong("time", timeMillis) ?: timeMillis)
|
||||
val lastVisit = timeMillis
|
||||
|
||||
// Uppgradera label om vi har en bättre än tidigare (inte tom och inte "Okänt klotter")
|
||||
val oldLabel = (prev?.optString("label", "") ?: "").trim()
|
||||
val incoming = label.trim()
|
||||
val betterIncoming = incoming.isNotBlank() && !incoming.equals("Okänt klotter", ignoreCase = true)
|
||||
val newLabel = when {
|
||||
betterIncoming -> incoming
|
||||
oldLabel.isNotBlank() -> oldLabel
|
||||
else -> incoming
|
||||
}
|
||||
|
||||
// Skriv ihop objektet (behåll "time" som "senaste besök" för UI:t)
|
||||
val obj = (prev ?: JSONObject()).apply {
|
||||
put("layer", layer)
|
||||
put("id", id)
|
||||
put("label", newLabel)
|
||||
put("lat", lat)
|
||||
put("lon", lon)
|
||||
put("time", lastVisit) // legacy-fält som UI:t redan läser
|
||||
put("first_visit", firstVisit)
|
||||
put("last_visit", lastVisit)
|
||||
put("away", false) // vi är "inne" igen vid markering
|
||||
}
|
||||
|
||||
val e = p.edit()
|
||||
e.putString(k, obj.toString())
|
||||
if (!existed) {
|
||||
set.add(k)
|
||||
e.putStringSet(KEY_KEYS, set)
|
||||
}
|
||||
// Se till att key-listan innehåller posten (även om den fanns sedan tidigare)
|
||||
if (!set.contains(k)) {
|
||||
set.add(k)
|
||||
e.putStringSet(KEY_KEYS, set)
|
||||
}
|
||||
|
||||
e.apply()
|
||||
|
||||
// "Ny träff" om första gången ELLER om vi varit bortom tröskeln tidigare (wasAway)
|
||||
return !existed || wasAway
|
||||
}
|
||||
|
||||
fun isAway(ctx: Context, layer: String, id: String): Boolean {
|
||||
val p = prefs(ctx)
|
||||
val k = key(layer, id)
|
||||
val js = p.getString(k, null) ?: return false
|
||||
return try { JSONObject(js).optBoolean("away", false) } catch (_: Throwable) { false }
|
||||
}
|
||||
|
||||
fun getFirstVisitMillis(ctx: Context, layer: String, id: String): Long? {
|
||||
val p = prefs(ctx)
|
||||
val k = key(layer, id)
|
||||
val js = p.getString(k, null) ?: return null
|
||||
return try {
|
||||
val obj = JSONObject(js)
|
||||
when {
|
||||
obj.has("first_visit") -> obj.optLong("first_visit")
|
||||
obj.has("time") -> obj.optLong("time") // bakåtkompatibelt
|
||||
else -> null
|
||||
}
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
|
||||
fun getLastVisitMillis(ctx: Context, layer: String, id: String): Long? {
|
||||
val p = prefs(ctx)
|
||||
val k = key(layer, id)
|
||||
val js = p.getString(k, null) ?: return null
|
||||
return try {
|
||||
val obj = JSONObject(js)
|
||||
when {
|
||||
obj.has("last_visit") -> obj.optLong("last_visit")
|
||||
obj.has("time") -> obj.optLong("time") // bakåtkompatibelt
|
||||
else -> null
|
||||
}
|
||||
} catch (_: Throwable) { null }
|
||||
}
|
||||
|
||||
/**
|
||||
* Sätt away=true för alla sparade fynd där nuvarande position är > tröskeln (default 200 m).
|
||||
* Lagringen sker i samma JSON-objekt som övriga fält (away-flaggan uppdateras och skrivs tillbaka).
|
||||
*/
|
||||
fun updateAwayFlags(
|
||||
ctx: Context,
|
||||
currentLat: Double,
|
||||
currentLon: Double,
|
||||
thresholdMeters: Int = AWAY_THRESHOLD_METERS
|
||||
) {
|
||||
val p = prefs(ctx)
|
||||
val keys = p.getStringSet(KEY_KEYS, emptySet()) ?: emptySet()
|
||||
if (keys.isEmpty()) return
|
||||
|
||||
var touched = false
|
||||
val e = p.edit()
|
||||
|
||||
for (k in keys) {
|
||||
val js = p.getString(k, null) ?: continue
|
||||
val obj = try { JSONObject(js) } catch (_: Throwable) { continue }
|
||||
|
||||
val lat = obj.optDouble("lat", Double.NaN)
|
||||
val lon = obj.optDouble("lon", Double.NaN)
|
||||
if (lat.isNaN() || lon.isNaN()) continue
|
||||
|
||||
val dist = distanceMeters(currentLat, currentLon, lat, lon)
|
||||
val isAway = obj.optBoolean("away", false)
|
||||
|
||||
if (dist > thresholdMeters && !isAway) {
|
||||
obj.put("away", true)
|
||||
e.putString(k, obj.toString())
|
||||
touched = true
|
||||
}
|
||||
}
|
||||
|
||||
if (touched) e.apply()
|
||||
}
|
||||
|
||||
/** Samma Haversine som i MainActivity, men privat här så FoundStore kan räkna själv. */
|
||||
private fun distanceMeters(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double {
|
||||
val R = 6371000.0
|
||||
val dLat = Math.toRadians(bLat - aLat)
|
||||
val dLon = Math.toRadians(bLon - aLon)
|
||||
val s1 = Math.sin(dLat / 2)
|
||||
val s2 = Math.sin(dLon / 2)
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** Hämtar alla fynd (senaste först). */
|
||||
fun getAll(ctx: Context): List<FoundEntry> {
|
||||
val p = prefs(ctx)
|
||||
val set = p.getStringSet(KEY_KEYS, emptySet()) ?: emptySet()
|
||||
val list = ArrayList<FoundEntry>(set.size)
|
||||
for (k in set) {
|
||||
val s = p.getString(k, null) ?: continue
|
||||
try {
|
||||
val o = JSONObject(s)
|
||||
list += FoundEntry(
|
||||
layer = o.optString("layer"),
|
||||
id = o.optString("id"),
|
||||
label = o.optString("label"),
|
||||
lat = o.optDouble("lat"),
|
||||
lon = o.optDouble("lon"),
|
||||
timeMillis = o.optLong("time")
|
||||
)
|
||||
} catch (_: Throwable) {
|
||||
// Ignorera trasiga poster
|
||||
}
|
||||
}
|
||||
return list.sortedByDescending { it.timeMillis }
|
||||
}
|
||||
|
||||
/** Rensar alla fynd. */
|
||||
fun clearAll(ctx: Context) {
|
||||
prefs(ctx).edit().clear().apply()
|
||||
}
|
||||
}
|
||||
57
app/src/main/java/com/example/yorlik/util/RecentHitsStore.kt
Normal file
57
app/src/main/java/com/example/yorlik/util/RecentHitsStore.kt
Normal file
@@ -0,0 +1,57 @@
|
||||
package com.example.yorlik.util
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Beständig lista över de senaste träffarna ("Funnet klotter") över appstarter.
|
||||
* Lagrar de senaste 200 med (text, lat, lon, timeMillis), nyast först.
|
||||
*/
|
||||
object RecentHitsStore {
|
||||
private const val PREFS = "yorlik_recent_hits"
|
||||
private const val KEY = "hits_json"
|
||||
private const val MAX = 200
|
||||
|
||||
private fun prefs(ctx: Context) = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
fun append(ctx: Context, entry: HitEntry) {
|
||||
val arr = JSONArray(prefs(ctx).getString(KEY, "[]") ?: "[]")
|
||||
// stoppa in först (nyast först)
|
||||
val obj = JSONObject()
|
||||
obj.put("text", entry.text)
|
||||
obj.put("lat", entry.lat)
|
||||
obj.put("lon", entry.lon)
|
||||
obj.put("timeMillis", entry.timeMillis)
|
||||
// ny lista: [obj] + befintligt, upp till MAX
|
||||
val newArr = JSONArray()
|
||||
newArr.put(obj)
|
||||
for (i in 0 until arr.length()) {
|
||||
if (i + 1 >= MAX) break
|
||||
newArr.put(arr.getJSONObject(i))
|
||||
}
|
||||
prefs(ctx).edit().putString(KEY, newArr.toString()).apply()
|
||||
}
|
||||
|
||||
fun list(ctx: Context): List<HitEntry> {
|
||||
val s = prefs(ctx).getString(KEY, "[]") ?: "[]"
|
||||
val arr = JSONArray(s)
|
||||
val out = ArrayList<HitEntry>(arr.length())
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.getJSONObject(i)
|
||||
out.add(
|
||||
HitEntry(
|
||||
text = o.optString("text"),
|
||||
lat = o.optDouble("lat"),
|
||||
lon = o.optDouble("lon"),
|
||||
timeMillis = o.optLong("timeMillis")
|
||||
)
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun clear(ctx: Context) {
|
||||
prefs(ctx).edit().remove(KEY).apply()
|
||||
}
|
||||
}
|
||||
@@ -3,33 +3,97 @@ package com.example.yorlik.util
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
|
||||
/**
|
||||
* Enkel inställnings-hanterare via SharedPreferences.
|
||||
* Nyckeln "only_new_hits" styr om vi bara ska avisera helt nya träffar.
|
||||
*/
|
||||
object SettingsStore {
|
||||
private const val PREFS = "yorlik_settings"
|
||||
|
||||
// Keys (befintliga)
|
||||
const val KEY_ONLY_NEW_HITS = "only_new_hits"
|
||||
private const val PREFS_NAME = "yorlik_settings"
|
||||
const val KEY_SATELLITE_MAP = "satellite_map"
|
||||
const val KEY_NIGHT_MODE = "night_mode"
|
||||
|
||||
const val KEY_SHOW_COORDS = "show_coordinates"
|
||||
|
||||
const val KEY_SHOW_KLOTTER = "show_klotter"
|
||||
|
||||
const val KEY_SHOW_WIKIPEDIA = "show_wikipedia"
|
||||
const val KEY_WIKI_RADIUS = "wiki_radius_m"
|
||||
|
||||
const val KEY_SHOW_DM = "show_digitaltmuseum"
|
||||
const val KEY_DM_RADIUS = "digitaltmuseum_radius_m"
|
||||
|
||||
// Nya: Fornsök
|
||||
const val KEY_SHOW_FORNSOK = "show_fornsok"
|
||||
const val KEY_FORNSOK_RADIUS = "fornsok_radius_m"
|
||||
|
||||
private fun prefs(ctx: Context): SharedPreferences =
|
||||
ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
fun getOnlyNewHits(ctx: Context): Boolean =
|
||||
prefs(ctx).getBoolean(KEY_ONLY_NEW_HITS, false)
|
||||
// --- Observers ---
|
||||
|
||||
fun setOnlyNewHits(ctx: Context, value: Boolean) {
|
||||
prefs(ctx).edit().putBoolean(KEY_ONLY_NEW_HITS, value).apply()
|
||||
}
|
||||
|
||||
/** Registrera en lyssnare för förändringar. Returnera lyssnaren så att den kan tas bort. */
|
||||
fun observe(ctx: Context, onKeyChanged: (String?) -> Unit): SharedPreferences.OnSharedPreferenceChangeListener {
|
||||
fun observe(ctx: Context, onChanged: (key: String?) -> Unit): SharedPreferences.OnSharedPreferenceChangeListener {
|
||||
val p = prefs(ctx)
|
||||
val l = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> onKeyChanged(key) }
|
||||
val l = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
onChanged(key)
|
||||
}
|
||||
p.registerOnSharedPreferenceChangeListener(l)
|
||||
return l
|
||||
}
|
||||
|
||||
fun unobserve(ctx: Context, listener: SharedPreferences.OnSharedPreferenceChangeListener?) {
|
||||
if (listener != null) prefs(ctx).unregisterOnSharedPreferenceChangeListener(listener)
|
||||
if (listener == null) return
|
||||
try { prefs(ctx).unregisterOnSharedPreferenceChangeListener(listener) } catch (_: Exception) {}
|
||||
}
|
||||
|
||||
// --- Only new hits ---
|
||||
|
||||
fun getOnlyNewHits(ctx: Context): Boolean = prefs(ctx).getBoolean(KEY_ONLY_NEW_HITS, false)
|
||||
fun setOnlyNewHits(ctx: Context, v: Boolean) { prefs(ctx).edit().putBoolean(KEY_ONLY_NEW_HITS, v).apply() }
|
||||
|
||||
// --- Satellite map ---
|
||||
|
||||
fun getSatelliteMap(ctx: Context): Boolean = prefs(ctx).getBoolean(KEY_SATELLITE_MAP, false)
|
||||
fun setSatelliteMap(ctx: Context, v: Boolean) { prefs(ctx).edit().putBoolean(KEY_SATELLITE_MAP, v).apply() }
|
||||
|
||||
// --- Night mode ---
|
||||
|
||||
fun getNightMode(ctx: Context): Boolean = prefs(ctx).getBoolean(KEY_NIGHT_MODE, false)
|
||||
fun setNightMode(ctx: Context, v: Boolean) { prefs(ctx).edit().putBoolean(KEY_NIGHT_MODE, v).apply() }
|
||||
|
||||
// -- Show coordinates ---
|
||||
|
||||
fun getShowCoordinates(ctx: Context): Boolean = prefs(ctx).getBoolean(KEY_SHOW_COORDS, false)
|
||||
fun setShowCoordinates(ctx: Context, v: Boolean) { prefs(ctx).edit().putBoolean(KEY_SHOW_COORDS, v).apply() }
|
||||
|
||||
// --- Klotter ---
|
||||
|
||||
fun getShowKlotter(ctx: Context): Boolean = prefs(ctx).getBoolean(KEY_SHOW_KLOTTER, true)
|
||||
fun setShowKlotter(ctx: Context, v: Boolean) { prefs(ctx).edit().putBoolean(KEY_SHOW_KLOTTER, v).apply() }
|
||||
|
||||
// --- Wikipedia ---
|
||||
|
||||
fun getShowWikipedia(ctx: Context): Boolean = prefs(ctx).getBoolean(KEY_SHOW_WIKIPEDIA, true)
|
||||
fun setShowWikipedia(ctx: Context, v: Boolean) { prefs(ctx).edit().putBoolean(KEY_SHOW_WIKIPEDIA, v).apply() }
|
||||
|
||||
fun getWikiRadiusMeters(ctx: Context): Int = prefs(ctx).getInt(KEY_WIKI_RADIUS, 200)
|
||||
fun setWikiRadiusMeters(ctx: Context, meters: Int) { prefs(ctx).edit().putInt(KEY_WIKI_RADIUS, meters).apply() }
|
||||
|
||||
// --- DigitaltMuseum ---
|
||||
|
||||
fun getShowDigitaltMuseum(ctx: Context): Boolean = prefs(ctx).getBoolean(KEY_SHOW_DM, false)
|
||||
fun setShowDigitaltMuseum(ctx: Context, v: Boolean) { prefs(ctx).edit().putBoolean(KEY_SHOW_DM, v).apply() }
|
||||
|
||||
fun getDigitaltMuseumRadiusMeters(ctx: Context): Int = prefs(ctx).getInt(KEY_DM_RADIUS, 500)
|
||||
fun setDigitaltMuseumRadiusMeters(ctx: Context, meters: Int) {
|
||||
prefs(ctx).edit().putInt(KEY_DM_RADIUS, meters).apply()
|
||||
}
|
||||
|
||||
// --- Fornsök (NYTT) ---
|
||||
|
||||
fun getShowFornsok(ctx: Context): Boolean = prefs(ctx).getBoolean(KEY_SHOW_FORNSOK, false)
|
||||
fun setShowFornsok(ctx: Context, v: Boolean) { prefs(ctx).edit().putBoolean(KEY_SHOW_FORNSOK, v).apply() }
|
||||
|
||||
fun getFornsokRadiusMeters(ctx: Context): Int = prefs(ctx).getInt(KEY_FORNSOK_RADIUS, 200)
|
||||
fun setFornsokRadiusMeters(ctx: Context, meters: Int) {
|
||||
prefs(ctx).edit().putInt(KEY_FORNSOK_RADIUS, meters).apply()
|
||||
}
|
||||
}
|
||||
|
||||
26
app/src/main/java/com/example/yorlik/util/WikiHitIndex.kt
Normal file
26
app/src/main/java/com/example/yorlik/util/WikiHitIndex.kt
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.example.yorlik.util
|
||||
|
||||
import android.content.Context
|
||||
|
||||
object WikiHitIndex {
|
||||
private const val PREFS = "yorlik_wiki_hit_index"
|
||||
|
||||
private fun prefs(ctx: Context) = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
fun put(ctx: Context, timeMillis: Long, pageId: Long) {
|
||||
prefs(ctx).edit().putLong(timeMillis.toString(), pageId).apply()
|
||||
}
|
||||
|
||||
fun isWiki(ctx: Context, timeMillis: Long): Boolean {
|
||||
return prefs(ctx).contains(timeMillis.toString())
|
||||
}
|
||||
|
||||
fun getPageId(ctx: Context, timeMillis: Long): Long? {
|
||||
val v = prefs(ctx).getLong(timeMillis.toString(), Long.MIN_VALUE)
|
||||
return if (v == Long.MIN_VALUE) null else v
|
||||
}
|
||||
|
||||
fun clear(ctx: Context) {
|
||||
prefs(ctx).edit().clear().apply()
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Reference in New Issue
Block a user