diff --git a/app/build.gradle.kts b/app/build.gradle.kts index fc778f0..e40c296 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -35,7 +35,7 @@ android { minSdk = 26 targetSdk = 35 versionCode = 1 - versionName = "0.0.1" + versionName = "0.0.3" // BuildConfig-fält (åtkomst i Kotlin via BuildConfig.X) buildConfigField("String", "SERVER_API_BASE_URL", "\"${propOrEmpty("SERVER_API_BASE_URL")}\"") diff --git a/app/release/app-release.apk b/app/release/app-release.apk new file mode 100644 index 0000000..a16c3f1 Binary files /dev/null and b/app/release/app-release.apk differ diff --git a/app/release/baselineProfiles/0/app-release.dm b/app/release/baselineProfiles/0/app-release.dm new file mode 100644 index 0000000..8bb189d Binary files /dev/null and b/app/release/baselineProfiles/0/app-release.dm differ diff --git a/app/release/baselineProfiles/1/app-release.dm b/app/release/baselineProfiles/1/app-release.dm new file mode 100644 index 0000000..6c9c50b Binary files /dev/null and b/app/release/baselineProfiles/1/app-release.dm differ diff --git a/app/release/output-metadata.json b/app/release/output-metadata.json new file mode 100644 index 0000000..5a62869 --- /dev/null +++ b/app/release/output-metadata.json @@ -0,0 +1,37 @@ +{ + "version": 3, + "artifactType": { + "type": "APK", + "kind": "Directory" + }, + "applicationId": "com.example.yorlik", + "variantName": "release", + "elements": [ + { + "type": "SINGLE", + "filters": [], + "attributes": [], + "versionCode": 1, + "versionName": "0.0.3", + "outputFile": "app-release.apk" + } + ], + "elementType": "File", + "baselineProfiles": [ + { + "minApi": 28, + "maxApi": 30, + "baselineProfiles": [ + "baselineProfiles/1/app-release.dm" + ] + }, + { + "minApi": 31, + "maxApi": 2147483647, + "baselineProfiles": [ + "baselineProfiles/0/app-release.dm" + ] + } + ], + "minSdkVersionForDexing": 26 +} \ No newline at end of file diff --git a/app/release/yorlik0.0.3.apk b/app/release/yorlik0.0.3.apk new file mode 100644 index 0000000..a16c3f1 Binary files /dev/null and b/app/release/yorlik0.0.3.apk differ diff --git a/app/src/main/ic_launcher-playstore.png b/app/src/main/ic_launcher-playstore.png new file mode 100644 index 0000000..fc1ec02 Binary files /dev/null and b/app/src/main/ic_launcher-playstore.png differ diff --git a/app/src/main/java/com/example/yorlik/LocationService.kt b/app/src/main/java/com/example/yorlik/LocationService.kt index d163e7c..18e77f0 100644 --- a/app/src/main/java/com/example/yorlik/LocationService.kt +++ b/app/src/main/java/com/example/yorlik/LocationService.kt @@ -14,10 +14,12 @@ import kotlinx.coroutines.tasks.await import kotlin.math.abs import kotlin.math.max import kotlin.math.min +import android.util.Log class LocationService : Service() { - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private var fused: FusedLocationProviderClient? = null // Match & anti-spam @@ -27,6 +29,7 @@ class LocationService : Service() { private var activeNoteId: Long? = null private var activeCenterLat: Double? = null private var activeCenterLon: Double? = null + private var lastHitAtMs: Long = 0L // tidsbaserad reset // Adaptivt intervall private val BASE_INTERVAL = 15_000L @@ -67,6 +70,35 @@ class LocationService : Service() { ) fused = LocationServices.getFusedLocationProviderClient(this) + + // Direktmatch vid service-start – måste ligga efter fused-assign och före startLocationUpdates + scope.launch { + val fusedLocal = fused + try { + val first = withTimeout(5000L) { + fusedLocal?.lastLocation?.await() // <-- FIX: vänta in Task + ?: 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 helt vid start + ) + } + cachedNearby = list + maybeMatch(firstFix) + } + } catch (_: Exception) { + // Ignorera fel — vi försöker igen vid ordinarie uppdatering + } + } + startLocationUpdates(currentIntervalMs, currentMinDistM) } @@ -106,35 +138,64 @@ class LocationService : Service() { scope.launch { handleAntiSpamState(loc) - // 1) Hämta (eller återanvänd) punkter via geohash-cache (TTL 30 s) - cachedNearby = Geocache.getNearby( - lat = loc.latitude, - lon = loc.longitude, - radiusMeters = QUERY_RADIUS_M, - ttlMs = 30_000L - ) - - // 2) Om vi är nära någon sparad punkt och står still → accuracy boost - val nearest = nearestDistanceToAny(loc.latitude, loc.longitude, cachedNearby) - val speed = estimateSpeedMps(loc) - DebugState.speedMps.value = speed - - if (nearest != null && nearest < 60.0 && speed < 1.0f) { - // Tillfälligt: inga rörelsekrav så att bättre fixar levereras även när man står still - if (currentMinDistM > 0f) startLocationUpdates(currentIntervalMs, 0f) - - // Engångsfix med hög noggrannhet (Google Maps-likt beteende) - tryAccuracyBoostOnce()?.let { better -> - LastLocationStore.lastKnownLocation = better - // matcha direkt med den bättre fixen - maybeMatch(better) + // 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 + ) } - } else { - // Normal match + + // 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 det senaste + maybeMatch(loc) + + } catch (t: Throwable) { + Log.e("Yorlik", "getNearby failed", t) + // Behåll tidigare cachedNearby som fallback — matcha ändå maybeMatch(loc) } - // 3) Anpassa intervall & minDistance utifrån fart + kontext + // 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 @@ -155,7 +216,6 @@ class LocationService : Service() { private suspend fun tryAccuracyBoostOnce(): Location? = withContext(Dispatchers.Main) { val fusedLocal = fused ?: return@withContext null return@withContext try { - // Timeout-skydd via withTimeout withTimeout(7_000L) { fusedLocal.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await() } @@ -168,10 +228,11 @@ class LocationService : Service() { distanceMeters(loc.latitude, loc.longitude, n.a, n.o) <= ACTIVE_RADIUS_M } ?: return - // Spärra plats tills vi lämnat >200 m + // Spärra plats tills vi lämnat >200 m (eller tills tidsfönster gått ut) activeNoteId = hit.i activeCenterLat = hit.a activeCenterLon = hit.o + lastHitAtMs = System.currentTimeMillis() val now = System.currentTimeMillis() HitLog.add(hit.t, hit.a, hit.o, now) @@ -232,7 +293,8 @@ class LocationService : Service() { val lat = activeCenterLat ?: return val lon = activeCenterLon ?: return val d = distanceMeters(loc.latitude, loc.longitude, lat, lon) - if (d > RESET_RADIUS_M) { + val tooOld = (System.currentTimeMillis() - lastHitAtMs) > 10 * 60_000L // 10 min + if (d > RESET_RADIUS_M || tooOld) { activeNoteId = null activeCenterLat = null activeCenterLon = null @@ -240,9 +302,13 @@ class LocationService : Service() { } override fun onDestroy() { - fused?.removeLocationUpdates(callback) requestRunning = false - scope.cancel() + try { fused?.removeLocationUpdates(callback) } catch (_: Exception) { } + finally { fused = null } + + try { scope.cancel() } catch (_: Exception) { } + try { stopForeground(true) } catch (_: Exception) { } + super.onDestroy() } diff --git a/app/src/main/java/com/example/yorlik/MainActivity.kt b/app/src/main/java/com/example/yorlik/MainActivity.kt index bf455dd..c9baf4e 100644 --- a/app/src/main/java/com/example/yorlik/MainActivity.kt +++ b/app/src/main/java/com/example/yorlik/MainActivity.kt @@ -1,12 +1,14 @@ package com.example.yorlik import android.Manifest +import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent +import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn @@ -20,19 +22,19 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat +import com.example.yorlik.BuildConfig import com.example.yorlik.data.NoteEntity import com.example.yorlik.net.Geocache import com.example.yorlik.net.NoteDTO import com.example.yorlik.net.createNote import com.example.yorlik.util.* -import com.example.yorlik.BuildConfig -import kotlinx.coroutines.launch -import kotlinx.coroutines.tasks.await import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.common.api.ApiException import com.google.android.gms.location.LocationServices as GmsLocationServices import com.google.android.gms.location.Priority +import kotlinx.coroutines.launch +import kotlinx.coroutines.tasks.await import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter @@ -41,57 +43,105 @@ class MainActivity : ComponentActivity() { private lateinit var signInClient: GoogleSignInClient - private val permissionLauncher = registerForActivityResult( - ActivityResultContracts.RequestMultiplePermissions() - ) { - startLocationService(this) - } + // Flagga för tvåsteg (BG efter FG) + private var pendingBgRequest: Boolean = false - private val signInLauncher = registerForActivityResult( - ActivityResultContracts.StartActivityForResult() - ) { res -> - val task = GoogleSignIn.getSignedInAccountFromIntent(res.data) - try { - val acct = task.getResult(ApiException::class.java) - if (acct != null) { - Auth.save(this, acct) - if (Auth.idToken == null) { - android.widget.Toast.makeText( - this, - "ID-token saknas – kontrollera WEB_CLIENT_ID i BuildConfig och på servern.", - android.widget.Toast.LENGTH_LONG - ).show() - } - } - } catch (_: Exception) { - // Ignorera – användaren avbröt eller fel - } - } + // ---- LAUNCHERS ---- + + // 1) FG + (ev) notiser + private lateinit var fgPermissionLauncher: ActivityResultLauncher> + + // 2) BG (separat för att undvika själv‑referens i init) + private lateinit var bgPermissionLauncher: ActivityResultLauncher + + // 3) Google‑inloggning + private lateinit var signInLauncher: ActivityResultLauncher override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + // --- Init sign-in client signInClient = Auth.signInClient(this) - Auth.refreshSilently(this) { /* ignorerar resultat här */ } + Auth.refreshSilently(this) { /* no-op */ } + // --- Registrera launchers (OBS: görs i onCreate) + fgPermissionLauncher = + registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grants -> + val fineOk = grants[Manifest.permission.ACCESS_FINE_LOCATION] == true + val coarseOk = grants[Manifest.permission.ACCESS_COARSE_LOCATION] == true + val locOk = fineOk || coarseOk + + val postNotifGranted = if (Build.VERSION.SDK_INT >= 33) { + grants[Manifest.permission.POST_NOTIFICATIONS] == true + } else true + + android.util.Log.d( + "YorlikPerm", + "FG result locOk=$locOk post=$postNotifGranted pendingBg=$pendingBgRequest" + ) + + if (locOk) { + startLocationService(this) + // Be om BG i steg 2 om markerat och relevant + if (pendingBgRequest && Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this)) { + bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) + } + pendingBgRequest = false + } + } + + bgPermissionLauncher = + registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + android.util.Log.d("YorlikPerm", "BG result granted=$granted") + // inget ytterligare krävs här; service kör redan om FG fanns + } + + signInLauncher = + registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res -> + val task = GoogleSignIn.getSignedInAccountFromIntent(res.data) + try { + val acct = task.getResult(ApiException::class.java) + if (acct != null) { + Auth.save(this, acct) + if (Auth.idToken == null) { + android.widget.Toast.makeText( + this, + "ID-token saknas – kontrollera WEB_CLIENT_ID (Web client) och SHA‑1 i Android‑klienterna.", + android.widget.Toast.LENGTH_LONG + ).show() + } else { + android.util.Log.d( + "YorlikAuth", + "Inloggad: ${acct.email} (tokenLen=${Auth.idToken?.length})" + ) + } + } + } catch (e: Exception) { + android.util.Log.e("YorlikAuth", "GoogleSignIn fel", e) + } + } + + // Be om behörigheter (FG först; ev. BG i steg 2) requestAllRuntimePermissions() - startLocationService(this) + + // Starta service direkt om FG redan finns + if (hasFgLocationPerms(this)) { + startLocationService(this) + } setContent { MaterialTheme { YorlikScreen( openSettings = { openAppSettings() }, requestPerms = { requestAllRuntimePermissions() }, - signIn = { - val intent = signInClient.signInIntent - signInLauncher.launch(intent) - }, + signIn = { signInLauncher.launch(signInClient.signInIntent) }, signOut = { Auth.clear(this) } ) } } } + // ---- PERMISSION REQUESTS ---- private fun requestAllRuntimePermissions() { val perms = mutableListOf( Manifest.permission.ACCESS_FINE_LOCATION, @@ -100,35 +150,48 @@ class MainActivity : ComponentActivity() { if (Build.VERSION.SDK_INT >= 33) { perms += Manifest.permission.POST_NOTIFICATIONS } - perms += Manifest.permission.ACCESS_BACKGROUND_LOCATION - permissionLauncher.launch(perms.toTypedArray()) + + // BG begärs separat efter FG (Android 10+) + pendingBgRequest = Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this) + + fgPermissionLauncher.launch(perms.toTypedArray()) } private fun openAppSettings() { - val intent = android.content.Intent( + val intent = Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName") - ).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) } + ).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } startActivity(intent) } } +// ---- Hjälpfunktioner (utanför klassen) ---- + private fun startLocationService(ctx: android.content.Context) { - val i = android.content.Intent(ctx, LocationService::class.java) + val i = Intent(ctx, LocationService::class.java) ctx.startForegroundService(i) } -/** Snabb koll av platsbehörigheter */ -private fun hasLocationPerms(ctx: android.content.Context): Boolean { +/** Endast foreground‑platsbehörigheter (räcker för UI + start av service) */ +private fun hasFgLocationPerms(ctx: android.content.Context): Boolean { val fine = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) == - android.content.pm.PackageManager.PERMISSION_GRANTED + android.content.pm.PackageManager.PERMISSION_GRANTED val coarse = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) == - android.content.pm.PackageManager.PERMISSION_GRANTED - val bg = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == - android.content.pm.PackageManager.PERMISSION_GRANTED - return (fine || coarse) && bg + android.content.pm.PackageManager.PERMISSION_GRANTED + return fine || coarse } +/** Bakgrundsbehörighet (Android 10+) – används för diagnos/valfri steg 2‑begäran */ +private fun hasBgLocationPerm(ctx: android.content.Context): Boolean { + return if (Build.VERSION.SDK_INT >= 29) { + ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == + android.content.pm.PackageManager.PERMISSION_GRANTED + } else true +} + +// ---- UI ---- + @Composable fun YorlikScreen( openSettings: () -> Unit, @@ -155,19 +218,17 @@ fun YorlikScreen( var placesLoading by remember { mutableStateOf(false) } var placesError by remember { mutableStateOf(null) } - var permsGranted by remember { mutableStateOf(hasLocationPerms(context)) } + // UI kräver bara FG‑behörighet + var permsGranted by remember { mutableStateOf(hasFgLocationPerms(context)) } var showPermDialog by remember { mutableStateOf(!permsGranted) } val loggedIn by Auth.loggedIn.collectAsState() val userEmail by Auth.emailFlow.collectAsState() LaunchedEffect(Unit) { - // Försök återställa inloggning tyst; UI uppdateras via flödena i Auth Auth.refreshSilently(context) { /* no-op */ } - - // Efter en kort stund: kolla platsbehörigheter och visa ev. dialog kotlinx.coroutines.delay(1000) - permsGranted = hasLocationPerms(context) + permsGranted = hasFgLocationPerms(context) showPermDialog = !permsGranted } @@ -326,10 +387,10 @@ fun YorlikScreen( PermissionDialog( onRequest = { requestPerms() - // kolla igen + // kolla igen efter liten stund scope.launch { kotlinx.coroutines.delay(1500) - val ok = hasLocationPerms(context) + val ok = hasFgLocationPerms(context) showPermDialog = !ok } }, diff --git a/app/src/main/java/com/example/yorlik/net/Api.kt b/app/src/main/java/com/example/yorlik/net/Api.kt index aa03ad0..9c773b4 100644 --- a/app/src/main/java/com/example/yorlik/net/Api.kt +++ b/app/src/main/java/com/example/yorlik/net/Api.kt @@ -12,19 +12,27 @@ import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.* import com.example.yorlik.util.Auth import com.example.yorlik.BuildConfig +import java.util.concurrent.TimeUnit +/** + * Läser bas‑URL och API‑nyckel från BuildConfig (hålls i local.properties → buildConfigField). + * Byt inte namn här – resten av appen förväntar sig NoteDTO/CreateBody/YorlikApi. + */ object ApiConfig { - val SERVER_API_BASE_URL: String get() = BuildConfig.SERVER_API_BASE_URL + val SERVER_API_BASE_URL: String get() = ensureTrailingSlash(BuildConfig.SERVER_API_BASE_URL) val SERVER_API_KEY: String get() = BuildConfig.SERVER_API_KEY + + private fun ensureTrailingSlash(u: String): String = + if (u.endsWith("/")) u else "$u/" } -/** Kompakta fält enligt nearby.php */ +/** Kompakta fält enligt nearby.php (behållna som i v0.0.1) */ data class NoteDTO( val i: Long, // id val a: Double, // lat val o: Double, // lon val t: String, // text - val c: Long, // createdAt + val c: Long, // createdAt (ms) val u: String // updated_at (ISO) ) @@ -37,6 +45,7 @@ data class CreateBody( val userId: String? = null // fylls från Auth.userId (Google sub) ) +/** Dina endpoints – samma namn/banor som i v0.0.1 */ interface YorlikApi { @POST("create.php") suspend fun create(@Body body: CreateBody): RResponse> @@ -52,11 +61,13 @@ interface YorlikApi { ): RResponse> } +/** Lägger API‑nyckel + ev. Google ID‑token (Bearer) på varje request. */ private class ApiKeyInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val b = chain.request().newBuilder() .header("X-API-Key", ApiConfig.SERVER_API_KEY) - // Lägg med Google ID-token om vi har en (Bearer) + + // Lägg med Google ID-token om vi har en (för server‑side verifikation) Auth.idToken?.let { token -> b.header("Authorization", "Bearer $token") } @@ -64,51 +75,86 @@ private class ApiKeyInterceptor : Interceptor { } } +/** Retrofit/OkHttp build – med timeouts och logg i debug. */ object Api { - private val moshi = Moshi.Builder() - .addLast(KotlinJsonAdapterFactory()) - .build() - - private val log = HttpLoggingInterceptor().apply { - level = HttpLoggingInterceptor.Level.BASIC + private val moshi: Moshi by lazy { + Moshi.Builder() + .addLast(KotlinJsonAdapterFactory()) + .build() } - private val client = OkHttpClient.Builder() - .addInterceptor(ApiKeyInterceptor()) - .addInterceptor(log) - .build() + private val http: OkHttpClient by lazy { + OkHttpClient.Builder() + .addInterceptor(ApiKeyInterceptor()) + .connectTimeout(10, TimeUnit.SECONDS) + .readTimeout(10, TimeUnit.SECONDS) + .writeTimeout(10, TimeUnit.SECONDS) + .also { b -> + if (BuildConfig.DEBUG) { + val log = HttpLoggingInterceptor() + log.level = HttpLoggingInterceptor.Level.BASIC + b.addInterceptor(log) + } + } + .build() + } - private val retrofit = Retrofit.Builder() - .baseUrl(ApiConfig.SERVER_API_BASE_URL) - .client(client) - .addConverterFactory(MoshiConverterFactory.create(moshi)) - .build() + private val retrofit: Retrofit by lazy { + Retrofit.Builder() + .baseUrl(ApiConfig.SERVER_API_BASE_URL) + .client(http) + .addConverterFactory(MoshiConverterFactory.create(moshi)) + .build() + } val svc: YorlikApi = retrofit.create(YorlikApi::class.java) } +/** Resultatcontainer för cache/ETag‑flödet. */ data class NearbyResult( - val code: Int, - val items: List, - val etag: String? + val code: Int, // HTTP‑kod (200, 304, etc.) + val items: List, // tom lista om 304/inga nya + val etag: String? // serverns ETag (om någon) ) +/** + * Hämtar nearby med stöd för ETag och "since". + * Kasta inte exception – returnera bara kod + lista + ny etag. + */ suspend fun fetchNearby( lat: Double, lon: Double, radiusMeters: Int, sinceMs: Long, - lastEtag: String? + lastEtag: String? = null, + limit: Int = 200 ): NearbyResult { - val resp = Api.svc.nearby(lat, lon, radiusMeters, sinceMs, 200, lastEtag) - val newEtag = resp.headers()["ETag"]?.trim('"') + val resp = try { + Api.svc.nearby( + lat = lat, + lon = lon, + radiusMeters = radiusMeters, + sinceMs = sinceMs, + limit = limit, + etag = lastEtag + ) + } catch (t: Throwable) { + // Nätfel – presentera som “inga nya” men kod 599 (icke‑standard) för att kunna skilja i logik + return NearbyResult(code = 599, items = emptyList(), etag = lastEtag) + } + + val newEtag = resp.headers()["ETag"] ?: lastEtag + val body = if (resp.isSuccessful) resp.body().orEmpty() else emptyList() return NearbyResult( code = resp.code(), - items = resp.body().orEmpty(), + items = body, etag = newEtag ) } +/** + * Skapar en not – returnerar true om servern svarar { ok: true } och HTTP 200. + */ suspend fun createNote( lat: Double, lon: Double, @@ -119,6 +165,10 @@ suspend fun createNote( lat = lat, lon = lon, text = text, createdAt = createdAt, userId = Auth.userId // Google “sub” när inloggad (annars null) ) - val resp = Api.svc.create(body) + val resp = try { + Api.svc.create(body) + } catch (_: Throwable) { + return false + } return resp.isSuccessful && (resp.body()?.get("ok") == true) -} \ No newline at end of file +} diff --git a/app/src/main/java/com/example/yorlik/net/Geocache.kt b/app/src/main/java/com/example/yorlik/net/Geocache.kt index 0661d61..3e1906d 100644 --- a/app/src/main/java/com/example/yorlik/net/Geocache.kt +++ b/app/src/main/java/com/example/yorlik/net/Geocache.kt @@ -1,122 +1,149 @@ package com.example.yorlik.net -import kotlin.math.abs +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.util.concurrent.ConcurrentHashMap import kotlin.math.floor +import kotlin.math.roundToInt /** - * En enkel geohash-baserad cache av nearby-svar per "ruta". - * - Precision 7 ≈ ~150 m rutor. - * - 30 s TTL (kan överstyras). - * - Använder ETag + since mot servern för minimala nyttodata. + * Robust cache och hämtning av närliggande anslag. + * + * Offentlig API behålls: getNearby(lat, lon, radiusMeters, ttlMs) + * - Returnerar alltid en lista (ev. tom) och KASTAR INTE. + * - Använder intern cache per "ruta" (~110 m) så UI/Service får stabila svar. + * - Vid nätfel: faller tillbaka till cache (om det finns). + * - Om första hämtet blir tomt: gör EN omfråga utan cache (force refresh). */ object Geocache { - private const val DEFAULT_TTL_MS = 30_000L - private const val GEOHASH_PREC = 7 private data class Entry( - var items: List, - var etag: String?, - var sinceMs: Long, - var fetchedAt: Long + val timeMs: Long, + val items: List, + val etag: String?, + val sinceMs: Long ) - private val map = HashMap() + // Cache per “ruta” (~0.001 grad ≈ 111 m) + radius-bucket för att separera olika radier + private val cache = ConcurrentHashMap() + /** + * Huvudmetod, kompatibel med v0.0.1. + * + * @param ttlMs hur länge vi litar på cache innan vi försöker hämta nytt + */ suspend fun getNearby( lat: Double, lon: Double, radiusMeters: Int, - ttlMs: Long = DEFAULT_TTL_MS - ): List { - val tile = geohash(lat, lon, GEOHASH_PREC) + ttlMs: Long + ): List = withContext(Dispatchers.IO) { + val key = keyFor(lat, lon, radiusMeters) val now = System.currentTimeMillis() - val existing = map[tile] - // Färsk cache? returnera direkt - if (existing != null && now - existing.fetchedAt < ttlMs) { - return existing.items + // 1) Snabbträff i giltig cache + cache[key]?.let { e -> + if ((now - e.timeMs) <= ttlMs) { + return@withContext e.items + } } - // Annars hämta från servern med ETag/since - val etag = existing?.etag - val since = existing?.sinceMs ?: 0L - val res = fetchNearby(lat, lon, radiusMeters, since, etag) + // 2) Försök hämta nytt med ETag/since om vi har det + val prev = cache[key] + val first = safeFetch( + lat = lat, + lon = lon, + radiusMeters = radiusMeters, + sinceMs = prev?.sinceMs ?: 0L, + etag = prev?.etag + ) - return when (res.code) { - 200 -> { - // Uppdatera entry (öka since om vi fått nyare) - val newSince = if (res.items.isNotEmpty()) { - maxOf(since, res.items.maxOf { it.c }) - } else since - map[tile] = Entry( - items = res.items, - etag = res.etag ?: etag, - sinceMs = newSince, - fetchedAt = now - ) - res.items - } - 304 -> { - // Inget nytt – ”förläng” bara entrys ålder om det fanns en - if (existing != null) { - existing.fetchedAt = now - if (res.etag != null) existing.etag = res.etag - existing.items - } else { - emptyList() - } - } + // Hantera 304/not-modified och nätfel (kod 599 i fetchNearby) + val firstItems = when (first.code) { + 304 -> prev?.items.orEmpty() + 200 -> first.items else -> { - // Server- eller nätfel – fall tillbaka till ev. gammal cache - existing?.items ?: emptyList() + // Nätfel/annat → fall tillbaka till cache om vi har något + return@withContext prev?.items.orEmpty() } } - } - // ------------------------------------------------------------- - // Minimal geohash-encoder (base32), tillräcklig för klientcache - // ------------------------------------------------------------- - private val base32 = "0123456789bcdefghjkmnpqrstuvwxyz".toCharArray() + // Uppdatera cache efter första försöket + val firstSince = if (firstItems.isNotEmpty()) + firstItems.maxOfOrNull { it.c } ?: (prev?.sinceMs ?: 0L) + else + (prev?.sinceMs ?: 0L) - private fun geohash(lat: Double, lon: Double, precision: Int): String { - var minLat = -90.0 - var maxLat = 90.0 - var minLon = -180.0 - var maxLon = 180.0 + cache[key] = Entry( + timeMs = now, + items = firstItems, + etag = first.etag ?: prev?.etag, + sinceMs = firstSince + ) - val result = StringBuilder() - var isEven = true - var bit = 0 - var ch = 0 + // 3) Om listan är tom: gör EN omfråga utan cache/since (force refresh) + if (firstItems.isEmpty()) { + val fresh = safeFetch( + lat = lat, + lon = lon, + radiusMeters = radiusMeters, + sinceMs = 0L, + etag = null + ) - while (result.length < precision) { - if (isEven) { - val mid = (minLon + maxLon) / 2 - if (lon > mid) { - ch = ch or (1 shl (4 - bit)) - minLon = mid - } else { - maxLon = mid - } - } else { - val mid = (minLat + maxLat) / 2 - if (lat > mid) { - ch = ch or (1 shl (4 - bit)) - minLat = mid - } else { - maxLat = mid - } + val items = when (fresh.code) { + 200 -> fresh.items + 304 -> prev?.items.orEmpty() // borde inte inträffa utan etag, men säkra ändå + else -> prev?.items.orEmpty() } - isEven = !isEven - if (bit < 4) { - bit++ - } else { - result.append(base32[ch]) - bit = 0 - ch = 0 - } + val since = if (items.isNotEmpty()) + items.maxOfOrNull { it.c } ?: firstSince + else firstSince + + cache[key] = Entry( + timeMs = now, + items = items, + etag = fresh.etag ?: first.etag ?: prev?.etag, + sinceMs = since + ) + + return@withContext items } - return result.toString() + + return@withContext firstItems } + + // Skyddad fetch som aldrig kastar – använder Api.fetchNearby från din Api.kt + private suspend fun safeFetch( + lat: Double, + lon: Double, + radiusMeters: Int, + sinceMs: Long, + etag: String? + ): NearbyResult = try { + fetchNearby( + lat = roundCoord(lat), + lon = roundCoord(lon), + radiusMeters = radiusMeters.coerceIn(50, 2000), + sinceMs = sinceMs, + lastEtag = etag, + limit = 200 + ) + } catch (_: Throwable) { + NearbyResult(code = 599, items = emptyList(), etag = etag) + } + + // Samma avrundning som du redan använder i UI när du sparar + private fun roundCoord(v: Double): Double = ((v * 1e6).roundToInt() / 1e6) + + // Bygg en nyckel av "ruta" (0.001 grad) + radius bucket (avrundad till närmaste 50 m) + private fun keyFor(lat: Double, lon: Double, radiusMeters: Int): String { + val cellLat = floor(lat * 1000.0) / 1000.0 + val cellLon = floor(lon * 1000.0) / 1000.0 + val r = ((radiusMeters + 25) / 50) * 50 // 0..2000 i steg om 50 + return "${cellLat.format3()},${cellLon.format3()}|r=$r" + } + + private fun Double.format3(): String = String.format("%.3f", this) } diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..036d09b --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..036d09b --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/app/src/main/res/mipmap-anydpi/ic_launcher.xml deleted file mode 100644 index 6f3b755..0000000 --- a/app/src/main/res/mipmap-anydpi/ic_launcher.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml deleted file mode 100644 index 6f3b755..0000000 --- a/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp index c209e78..ee380b9 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..ded76b3 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp index b2dfe3d..58cd0c9 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp index 4f0f1d6..ca596f8 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..fdf1248 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp index 62b611d..dedfea2 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp index 948a307..185ef94 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..e865dea Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp index 1b9a695..94ead3e 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp index 28d4b77..5e1e647 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..c853118 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp index 9287f50..6f776f8 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp index aa7d642..4785470 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..d6f0c1f Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp index 9126ae3..30583b8 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values/ic_launcher_background.xml b/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..c5d5899 --- /dev/null +++ b/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file