Yorlik v0.2.0. Nu med brödtext och bilder. Och positionsvisning när man klottrar. Och cachning och en del annat.
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import java.time.Instant
|
||||
|
||||
plugins {
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
id("com.android.application")
|
||||
@@ -34,8 +36,13 @@ android {
|
||||
applicationId = "com.example.yorlik"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 5
|
||||
versionName = "0.1.0"
|
||||
versionCode = 7
|
||||
versionName = "0.2.0"
|
||||
|
||||
// Byggtid i UTC (ISO 8601) genereras vid build-konfiguration
|
||||
val buildTimeUtc = Instant.now().toString()
|
||||
buildConfigField("String", "BUILD_TIME_UTC", "\"$buildTimeUtc\"")
|
||||
|
||||
|
||||
// BuildConfig-fält (åtkomst i Kotlin via BuildConfig.X)
|
||||
buildConfigField("String", "SERVER_API_BASE_URL", "\"${propOrEmpty("SERVER_API_BASE_URL")}\"")
|
||||
|
||||
@@ -6,18 +6,26 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.SharedPreferences
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.rememberTransformableState
|
||||
import androidx.compose.foundation.gestures.transformable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
@@ -30,6 +38,7 @@ import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CenterAlignedTopAppBar
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Divider
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
@@ -43,21 +52,33 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.content.pm.PackageInfoCompat
|
||||
import com.example.yorlik.BuildConfig
|
||||
import com.example.yorlik.data.AppDatabase
|
||||
import com.example.yorlik.data.NoteRepository
|
||||
import com.example.yorlik.net.ApiConfig
|
||||
import com.example.yorlik.util.Config
|
||||
import com.example.yorlik.net.DigitaltMuseum
|
||||
import com.example.yorlik.net.DigitaltMuseumItem
|
||||
import com.example.yorlik.net.Fornsok
|
||||
@@ -67,6 +88,10 @@ import com.example.yorlik.net.NoteDTO
|
||||
import com.example.yorlik.net.Wikipedia
|
||||
import com.example.yorlik.net.WikipediaPage
|
||||
import com.example.yorlik.net.createNote
|
||||
import com.example.yorlik.net.fetchNoteDetail
|
||||
import com.example.yorlik.net.imageUrl
|
||||
import com.example.yorlik.net.uploadImageFromUri
|
||||
import com.example.yorlik.net.createNoteDoc
|
||||
import com.example.yorlik.ui.theme.YorlikTheme
|
||||
import com.example.yorlik.util.Auth
|
||||
import com.example.yorlik.util.FoundStore
|
||||
@@ -74,17 +99,31 @@ 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.OutboxStore
|
||||
import com.example.yorlik.util.SettingsStore
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
||||
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 com.google.android.gms.maps.model.CameraPosition
|
||||
import com.google.android.gms.maps.model.LatLng
|
||||
import com.google.android.gms.maps.CameraUpdateFactory
|
||||
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.MapUiSettings
|
||||
import com.google.maps.android.compose.Marker
|
||||
import com.google.maps.android.compose.MarkerState
|
||||
import com.google.maps.android.compose.rememberCameraPositionState
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.tasks.await
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.time.Instant
|
||||
@@ -190,6 +229,18 @@ private data class OpenWiki(val pageId: Long, val lat: Double?, val lon: Double?
|
||||
|
||||
private data class OpenFornsok(val item: com.example.yorlik.net.FornsokItem)
|
||||
|
||||
data class NoteHandle(val id: String, val lat: Double, val lon: Double, val label: String)
|
||||
|
||||
private fun extractTitleFromCompact(t: String): String =
|
||||
t.substringBefore('\n').ifBlank { "Okänt klotter" }
|
||||
|
||||
|
||||
private data class DocumentDraft(
|
||||
val title: String,
|
||||
val body: String,
|
||||
val imageUri: Uri?
|
||||
)
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun YorlikApp(
|
||||
@@ -224,11 +275,12 @@ private fun YorlikApp(
|
||||
|
||||
// UI-state
|
||||
var showWrite by remember { mutableStateOf(false) }
|
||||
var resetSavingCounter by remember { mutableStateOf(0) }
|
||||
var showNearby by remember { mutableStateOf(false) }
|
||||
var showMap by remember { mutableStateOf(false) }
|
||||
var showSettings by remember { mutableStateOf(false) }
|
||||
|
||||
var locationTick by remember { mutableStateOf(0) }
|
||||
var showLoginRequired by remember { mutableStateOf(false) }
|
||||
|
||||
|
||||
// Nearby-data
|
||||
@@ -424,7 +476,9 @@ private fun YorlikApp(
|
||||
}
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { showWrite = true }) { Text("Klottra") }
|
||||
Button(onClick = {
|
||||
if (loggedIn) showWrite = true else showLoginRequired = true
|
||||
}) { Text("Klottra") }
|
||||
|
||||
Button(onClick = {
|
||||
nearbyLoading = true
|
||||
@@ -498,6 +552,46 @@ private fun YorlikApp(
|
||||
if (forceEmptyFound) emptyList()
|
||||
else FoundStore.getAll(context)
|
||||
}
|
||||
// Buffra detalj + bild för kända klotter inom radien → snabbare öppning
|
||||
LaunchedEffect(foundList) {
|
||||
val my = com.example.yorlik.util.LastLocationStore.lastKnownLocation
|
||||
val myLat = my?.latitude
|
||||
val myLon = my?.longitude
|
||||
foundList.forEach { f ->
|
||||
if (f.layer == com.example.yorlik.util.FoundStore.LAYER_KLOTTER) {
|
||||
val inside = if (myLat != null && myLon != null)
|
||||
distanceMeters(myLat, myLon, f.lat, f.lon) <= com.example.yorlik.util.Config.DEFAULT_KLOTTER_RADIUS_M
|
||||
else true
|
||||
if (inside) {
|
||||
val idL = f.id.toLongOrNull() ?: return@forEach
|
||||
if (com.example.yorlik.util.NoteDetailCache.get(idL) == null) {
|
||||
// Hämta detalj med NOTISENS koordinater (ger rätt “bevis” på servern)
|
||||
val detail = withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
com.example.yorlik.net.fetchNoteDetail(idL, f.lat, f.lon)
|
||||
}
|
||||
if (detail != null) {
|
||||
com.example.yorlik.util.NoteDetailCache.put(idL, detail)
|
||||
val img = detail.image
|
||||
if (img != null && img.id > 0 && com.example.yorlik.util.ImageBitmapCache.get(img.id) == null) {
|
||||
withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
val url = com.example.yorlik.net.imageUrl(img.id, detail.id, f.lat, f.lon)
|
||||
val resp = com.example.yorlik.net.Api.svc.getImageStream(url)
|
||||
if (resp.isSuccessful) {
|
||||
resp.body()?.byteStream()?.use { ins ->
|
||||
android.graphics.BitmapFactory.decodeStream(ins)?.let { bmp ->
|
||||
com.example.yorlik.util.ImageBitmapCache.put(img.id, bmp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundList.isEmpty()) {
|
||||
Text("Inga fynd ännu.")
|
||||
} else {
|
||||
@@ -647,8 +741,24 @@ private fun YorlikApp(
|
||||
|
||||
// Karta
|
||||
if (showMap) {
|
||||
MapDialog(onClose = { showMap = false })
|
||||
MapDialog(
|
||||
onClose = { showMap = false },
|
||||
onKlotterClick = { id, la, lo, label ->
|
||||
openKlotter = OpenKlotter(id = id, lat = la, lon = lo, label = label)
|
||||
},
|
||||
onOpenUrl = { _, url ->
|
||||
val i = Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
||||
try { context.startActivity(i) } catch (_: Exception) {}
|
||||
},
|
||||
isKnownNote = { noteId ->
|
||||
// Känd = finns i Hittat (FoundStore) → ska alltid visa titel
|
||||
com.example.yorlik.util.FoundStore
|
||||
.getAll(context)
|
||||
.any { it.layer == com.example.yorlik.util.FoundStore.LAYER_KLOTTER && it.id == noteId.toString() }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// Inställningar
|
||||
if (showSettings) {
|
||||
@@ -734,62 +844,164 @@ private fun YorlikApp(
|
||||
)
|
||||
}
|
||||
|
||||
// Skrivdialog
|
||||
// Skrivdialog (dokument)
|
||||
var isSavingDoc by remember { mutableStateOf(false) }
|
||||
if (showWrite) {
|
||||
WriteDialog(
|
||||
// Lagra positionen när man klickat Klottra:
|
||||
val initial = com.example.yorlik.util.LastLocationStore.lastKnownLocation
|
||||
val initialLat = initial?.latitude
|
||||
val initialLon = initial?.longitude
|
||||
|
||||
WriteDocDialog(
|
||||
onClose = { showWrite = false },
|
||||
onSave = { text ->
|
||||
val loc = LastLocationStore.lastKnownLocation
|
||||
if (loc == null) {
|
||||
Toast.makeText(context, "Ingen plats ännu – försök igen!", Toast.LENGTH_SHORT).show()
|
||||
return@WriteDialog
|
||||
onSave = { draft, selLat, selLon ->
|
||||
if (!loggedIn) {
|
||||
Toast.makeText(context, "Du måste logga in för att kunna klottra.", Toast.LENGTH_SHORT).show()
|
||||
return@WriteDocDialog
|
||||
}
|
||||
val created = System.currentTimeMillis()
|
||||
val requestId = java.util.UUID.randomUUID().toString()
|
||||
|
||||
val ctx = context
|
||||
scope.launch(Dispatchers.IO) {
|
||||
val ok = createNote(loc.latitude, loc.longitude, text, created)
|
||||
if (isSavingDoc) return@WriteDocDialog
|
||||
isSavingDoc = true
|
||||
scope.launch {
|
||||
try {
|
||||
// 1) Ladda ev. upp bilden först (passera alltid *vald* position)
|
||||
val imgId = withContext(Dispatchers.IO) {
|
||||
draft.imageUri?.let { uri ->
|
||||
uploadImageFromUri(context, uri, selLat, selLon)
|
||||
}
|
||||
}
|
||||
if (draft.imageUri != null && imgId == null) {
|
||||
withContext(Dispatchers.Main) {
|
||||
if (!ok) {
|
||||
Toast.makeText(ctx, "Offline. Klottret skickas så fort vi får kontakt.", Toast.LENGTH_LONG).show()
|
||||
com.example.yorlik.util.OutboxStore.add(
|
||||
context = ctx,
|
||||
lat = loc.latitude,
|
||||
lon = loc.longitude,
|
||||
text = text,
|
||||
createdAt = created
|
||||
val msg = com.example.yorlik.net.Api.lastUploadError
|
||||
?: "Bilduppladdning misslyckades."
|
||||
Toast.makeText(context, msg, Toast.LENGTH_LONG).show()
|
||||
resetSavingCounter++
|
||||
}
|
||||
return@launch
|
||||
}
|
||||
|
||||
// 2) Skapa klotter på *vald* position
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
createNoteDoc(
|
||||
lat = selLat,
|
||||
lon = selLon,
|
||||
title = draft.title.trim(),
|
||||
body = draft.body.trim(),
|
||||
imageId = imgId,
|
||||
radiusM = com.example.yorlik.util.Config.DEFAULT_KLOTTER_RADIUS_M,
|
||||
createdAt = created,
|
||||
clientRequestId = requestId
|
||||
)
|
||||
val constraints = androidx.work.Constraints.Builder()
|
||||
.setRequiredNetworkType(androidx.work.NetworkType.CONNECTED)
|
||||
.build()
|
||||
val req = androidx.work.OneTimeWorkRequestBuilder<com.example.yorlik.work.OutboxWorker>()
|
||||
.setConstraints(constraints)
|
||||
.build()
|
||||
androidx.work.WorkManager.getInstance(ctx).enqueue(req)
|
||||
} else {
|
||||
// Försök mappa tillbaka direkt
|
||||
}
|
||||
|
||||
if (ok) {
|
||||
Toast.makeText(context, "Sparat.", Toast.LENGTH_SHORT).show()
|
||||
// (valfritt) hitta posten nära *vald* position och markera som funnen
|
||||
scope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
val nearby = Geocache.getNearby(
|
||||
lat = loc.latitude, lon = loc.longitude,
|
||||
radiusMeters = 100, ttlMs = 0L
|
||||
lat = selLat, lon = selLon, radiusMeters = 100, ttlMs = 0L
|
||||
)
|
||||
val match = nearby.firstOrNull { it.t == text && abs(it.c - created) <= 2_000 }
|
||||
val combined = buildString {
|
||||
if (draft.title.isNotBlank()) append(draft.title).append("\n\n")
|
||||
append(draft.body.trim())
|
||||
}.trim()
|
||||
val match = nearby.firstOrNull {
|
||||
it.t == combined && kotlin.math.abs(it.c - created) <= 2_000
|
||||
}
|
||||
if (match != null) {
|
||||
FoundStore.markFound(
|
||||
ctx, LAYER_KLOTTER, match.i.toString(),
|
||||
label = match.t, lat = match.a, lon = match.o, timeMillis = System.currentTimeMillis()
|
||||
com.example.yorlik.util.FoundStore.markFound(
|
||||
context,
|
||||
com.example.yorlik.util.FoundStore.LAYER_KLOTTER,
|
||||
match.i.toString(),
|
||||
label = match.t,
|
||||
lat = match.a,
|
||||
lon = match.o,
|
||||
timeMillis = System.currentTimeMillis()
|
||||
)
|
||||
withContext(Dispatchers.Main) {
|
||||
ctx.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
|
||||
context.sendBroadcast(
|
||||
Intent(com.example.yorlik.LocationService.ACTION_FOUND_UPDATED)
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (_: Throwable) { }
|
||||
}
|
||||
Toast.makeText(ctx, "Sparat.", Toast.LENGTH_SHORT).show()
|
||||
showWrite = false
|
||||
} else {
|
||||
// OFFLINE: lägg i utkorg som DOC (spara *vald* position + lokal bild)
|
||||
val titleText = draft.title.trim()
|
||||
val bodyText = draft.body.trim()
|
||||
var imagePath: String? = null
|
||||
var imageMime: String? = null
|
||||
if (draft.imageUri != null) {
|
||||
val mime = context.contentResolver.getType(draft.imageUri!!) ?: "image/jpeg"
|
||||
val ext = when {
|
||||
mime.equals("image/jpeg", true) || mime.equals("image/jpg", true) -> ".jpg"
|
||||
mime.equals("image/png", true) -> ".png"
|
||||
else -> ".img"
|
||||
}
|
||||
val outDir = java.io.File(context.filesDir, "outbox").apply { mkdirs() }
|
||||
val outFile = java.io.File(outDir, "img_${created}$ext")
|
||||
try {
|
||||
context.contentResolver.openInputStream(draft.imageUri!!)?.use { ins ->
|
||||
outFile.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) }
|
||||
}
|
||||
imagePath = outFile.absolutePath
|
||||
imageMime = mime
|
||||
} catch (_: Exception) {
|
||||
imagePath = null; imageMime = null
|
||||
}
|
||||
}
|
||||
|
||||
com.example.yorlik.util.OutboxStore.addDoc(
|
||||
context = context,
|
||||
lat = selLat,
|
||||
lon = selLon,
|
||||
title = titleText,
|
||||
body = bodyText,
|
||||
createdAt = created,
|
||||
radiusM = com.example.yorlik.util.Config.DEFAULT_KLOTTER_RADIUS_M,
|
||||
imagePath = imagePath,
|
||||
imageMime = imageMime
|
||||
)
|
||||
Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show()
|
||||
|
||||
val constraints = androidx.work.Constraints.Builder()
|
||||
.setRequiredNetworkType(androidx.work.NetworkType.CONNECTED)
|
||||
.build()
|
||||
val req = androidx.work.OneTimeWorkRequestBuilder<com.example.yorlik.work.OutboxWorker>()
|
||||
.setConstraints(constraints).build()
|
||||
androidx.work.WorkManager.getInstance(context).enqueue(req)
|
||||
showWrite = false
|
||||
}
|
||||
} finally {
|
||||
isSavingDoc = false
|
||||
}
|
||||
}
|
||||
},
|
||||
initialLat = initialLat,
|
||||
initialLon = initialLon,
|
||||
resetSavingCounter = resetSavingCounter
|
||||
)
|
||||
}
|
||||
|
||||
if (showLoginRequired) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { showLoginRequired = false },
|
||||
title = { androidx.compose.material3.Text("Inloggning krävs") },
|
||||
text = { androidx.compose.material3.Text("Du måste logga in för att kunna klottra.") },
|
||||
confirmButton = {
|
||||
androidx.compose.material3.Button(onClick = {
|
||||
showLoginRequired = false
|
||||
onLogin() // använder samma onLogin som redan används av “Logga in”-knappen
|
||||
}) { androidx.compose.material3.Text("Logga in") }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.Button(onClick = { showLoginRequired = false }) {
|
||||
androidx.compose.material3.Text("Stäng")
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -895,7 +1107,7 @@ private fun NearbyDialog(
|
||||
|
||||
val display = when {
|
||||
!known.isNullOrBlank() && known != "Okänt klotter" -> known
|
||||
d <= 20 && n.t.isNotBlank() -> n.t
|
||||
d <= Config.DEFAULT_KLOTTER_RADIUS_M && n.t.isNotBlank() -> n.t
|
||||
else -> "Okänt klotter"
|
||||
}
|
||||
add(
|
||||
@@ -906,7 +1118,7 @@ private fun NearbyDialog(
|
||||
lat = n.a,
|
||||
lon = n.o,
|
||||
distanceM = d,
|
||||
insideRadiusM = 20,
|
||||
insideRadiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||||
click = { onKlotterClick(n.i.toString(), n.a, n.o, display) }
|
||||
)
|
||||
)
|
||||
@@ -949,35 +1161,218 @@ private fun NearbyDialog(
|
||||
}
|
||||
|
||||
/* ---------- Skrivdialog ---------- */
|
||||
|
||||
@Composable
|
||||
private fun WriteDialog(
|
||||
private fun WriteDocDialog(
|
||||
onClose: () -> Unit,
|
||||
onSave: (String) -> Unit
|
||||
onSave: (DocumentDraft, Double, Double) -> Unit,
|
||||
resetSavingCounter: Int = 0,
|
||||
initialLat: Double? = null,
|
||||
initialLon: Double? = null
|
||||
) {
|
||||
var text by remember { mutableStateOf("") }
|
||||
val context = LocalContext.current
|
||||
var title by remember { mutableStateOf("") }
|
||||
var body by remember { mutableStateOf("") }
|
||||
var imageUri by remember { mutableStateOf<Uri?>(null) }
|
||||
var saving by remember(resetSavingCounter) { mutableStateOf(false) }
|
||||
val picker = rememberLauncherForActivityResult(PickVisualMedia()) { uri ->
|
||||
imageUri = uri
|
||||
}
|
||||
var selectedLat by remember { mutableStateOf<Double?>(initialLat) }
|
||||
var selectedLon by remember { mutableStateOf<Double?>(initialLon) }
|
||||
var lastPosUpdateMs by remember { mutableStateOf(System.currentTimeMillis()) }
|
||||
var titleError by remember { mutableStateOf<String?>(null) }
|
||||
val titleFocus = remember { FocusRequester() }
|
||||
|
||||
|
||||
val camState = rememberCameraPositionState {
|
||||
val lat = selectedLat ?: 59.3293
|
||||
val lon = selectedLon ?: 18.0686
|
||||
position = CameraPosition.fromLatLngZoom(LatLng(lat, lon), 20f) // max-zoom
|
||||
}
|
||||
LaunchedEffect(selectedLat, selectedLon) {
|
||||
val lat = selectedLat; val lon = selectedLon
|
||||
if (lat != null && lon != null) {
|
||||
camState.animate(
|
||||
CameraUpdateFactory.newLatLngZoom(LatLng(lat, lon), 20f)
|
||||
)
|
||||
}
|
||||
}
|
||||
val satellite = com.example.yorlik.util.SettingsStore.getSatelliteMap(context)
|
||||
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onClose,
|
||||
title = { Text("Klottra här") },
|
||||
text = {
|
||||
Column {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
// --- Kartförhandsvisning: utanför scroll, med FAST höjd ---
|
||||
if (selectedLat != null && selectedLon != null) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(180.dp) // fast höjd → korrekt mätning, undviker "svart"
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
) {
|
||||
GoogleMap(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
cameraPositionState = camState,
|
||||
properties = MapProperties(
|
||||
isMyLocationEnabled = hasFgLocationPerms(context),
|
||||
mapType = if (satellite) MapType.SATELLITE else MapType.NORMAL
|
||||
),
|
||||
uiSettings = MapUiSettings(
|
||||
myLocationButtonEnabled = false,
|
||||
zoomControlsEnabled = false,
|
||||
compassEnabled = false,
|
||||
tiltGesturesEnabled = false,
|
||||
rotationGesturesEnabled = false,
|
||||
scrollGesturesEnabled = false,
|
||||
zoomGesturesEnabled = false
|
||||
)
|
||||
) {
|
||||
Marker(state = MarkerState(position = LatLng(selectedLat!!, selectedLon!!)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
"Markören visar var klottret sparas.",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
|
||||
// Endast knapp, högerställd. Ingen koordinattext.
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 8.dp),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Button(
|
||||
onClick = {
|
||||
val L = com.example.yorlik.util.LastLocationStore.lastKnownLocation
|
||||
if (L == null) {
|
||||
Toast.makeText(context, "Ingen plats ännu – försök igen.", Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
selectedLat = L.latitude
|
||||
selectedLon = L.longitude
|
||||
lastPosUpdateMs = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
) { Text("Uppdatera position") }
|
||||
}
|
||||
|
||||
// --- Formdel: scrollbar ---
|
||||
val scroll = rememberScrollState()
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.verticalScroll(scroll)
|
||||
.imePadding(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
value = title,
|
||||
onValueChange = {
|
||||
title = it
|
||||
if (titleError != null && it.isNotBlank()) titleError = null // rensa fel när man börjar skriva något annat än blanksteg
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(titleFocus),
|
||||
label = { Text("Rubrik") }, // inte längre “(valfri)”
|
||||
singleLine = true,
|
||||
isError = titleError != null, // röd ram när fel
|
||||
supportingText = {
|
||||
if (titleError != null) {
|
||||
Text(
|
||||
titleError!!,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Bildförhandsvisning (om vald)
|
||||
val bmp: Bitmap? = remember(imageUri) {
|
||||
if (imageUri == null) return@remember null
|
||||
try {
|
||||
context.contentResolver.openInputStream(imageUri!!).use { ins ->
|
||||
BitmapFactory.decodeStream(ins)
|
||||
}
|
||||
} catch (_: Exception) { null }
|
||||
}
|
||||
if (bmp != null) {
|
||||
Image(
|
||||
bitmap = bmp.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp, max = 240.dp)
|
||||
.clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Fit
|
||||
)
|
||||
}
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = {
|
||||
picker.launch(PickVisualMediaRequest(PickVisualMedia.ImageOnly))
|
||||
}) { Text(if (imageUri == null) "Välj bild" else "Byt bild") }
|
||||
|
||||
if (imageUri != null) {
|
||||
Button(onClick = { imageUri = null }) { Text("Ta bort bild") }
|
||||
}
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = body,
|
||||
onValueChange = { body = it },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp),
|
||||
placeholder = { Text("Din text…") }
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(onClick = { onSave(text) }, enabled = text.isNotBlank()) { Text("Spara") }
|
||||
Button(
|
||||
onClick = {
|
||||
if (saving) return@Button
|
||||
val titleText = title.trim()
|
||||
if (titleText.isEmpty()) {
|
||||
titleError = "Rubrik får inte vara tom"
|
||||
Toast.makeText(context, "Rubrik får inte vara tom", Toast.LENGTH_SHORT).show()
|
||||
return@Button
|
||||
}
|
||||
|
||||
if (selectedLat == null || selectedLon == null) {
|
||||
Toast.makeText(context, "Ingen plats ännu – klicka ”Uppdatera position”.", Toast.LENGTH_SHORT).show()
|
||||
return@Button
|
||||
}
|
||||
saving = true
|
||||
onSave(
|
||||
DocumentDraft(title.trim(), body.trim(), imageUri),
|
||||
selectedLat!!,
|
||||
selectedLon!!
|
||||
)
|
||||
},
|
||||
enabled = !saving && selectedLat != null && selectedLon != null
|
||||
) {
|
||||
if (saving) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
} else {
|
||||
Text("Spara")
|
||||
}
|
||||
}
|
||||
},
|
||||
dismissButton = { Button(onClick = onClose) { Text("Avbryt") } }
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
/* ---------- Inställningar (scroll + “Stäng” synlig) ---------- */
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@@ -1039,6 +1434,31 @@ private fun SettingsDialog(
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val pInfo = remember {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
context.packageManager.getPackageInfo(
|
||||
context.packageName,
|
||||
PackageManager.PackageInfoFlags.of(0)
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getPackageInfo(context.packageName, 0)
|
||||
}
|
||||
}
|
||||
val versionCode = PackageInfoCompat.getLongVersionCode(pInfo)
|
||||
|
||||
Text(
|
||||
"Yorlik v${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE}) • build ${versionCode}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Text(
|
||||
"Byggd ${BuildConfig.BUILD_TIME_UTC}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Divider()
|
||||
|
||||
// Snabbinställningar
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -1081,7 +1501,7 @@ private fun SettingsDialog(
|
||||
Switch(checked = showKlotter, onCheckedChange = onShowKlotterChanged)
|
||||
}
|
||||
Text(
|
||||
"Radie: 20 meter",
|
||||
"Radie: ${Config.DEFAULT_KLOTTER_RADIUS_M} meter",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -1246,94 +1666,243 @@ private fun KlotterDialog(
|
||||
var loading by remember { mutableStateOf(true) }
|
||||
var text by remember { mutableStateOf(label) }
|
||||
var titleText by remember { mutableStateOf(label.ifBlank { "Okänt klotter" }) }
|
||||
var imgBitmap by remember { mutableStateOf<Bitmap?>(null) }
|
||||
var showImageViewer by remember { mutableStateOf(false) }
|
||||
var prefilledFromCache by remember { mutableStateOf(false) }
|
||||
|
||||
// Snabb hydrering från cache om vi redan har detalj/bild
|
||||
LaunchedEffect(id) {
|
||||
val idL = id.toLongOrNull()
|
||||
if (idL != null) {
|
||||
com.example.yorlik.util.NoteDetailCache.get(idL)?.let { d ->
|
||||
titleText = d.title.ifBlank { "Okänt klotter" }
|
||||
text = d.body.ifBlank { titleText }
|
||||
val img = d.image
|
||||
prefilledFromCache = true
|
||||
loading = false
|
||||
|
||||
if (img != null && img.id > 0) {
|
||||
com.example.yorlik.util.ImageBitmapCache.get(img.id)?.let { bmp ->
|
||||
imgBitmap = bmp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(id, lat, lon, label) {
|
||||
loading = true
|
||||
loading = !prefilledFromCache
|
||||
|
||||
val baseLabel = label.trim()
|
||||
// Är vi inom 20 m? (samma regel som i listan)
|
||||
val isKnown = baseLabel.isNotBlank() && baseLabel != "Okänt klotter"
|
||||
Log.d("Yorlik", "KlotterDialog start id=$id isKnown=$isKnown label='${baseLabel.take(40)}'")
|
||||
|
||||
// Hämta ev. färsk plats (fallback LastLocationStore)
|
||||
val my = com.example.yorlik.util.LastLocationStore.lastKnownLocation
|
||||
val within20 = my?.let { distanceMeters(it.latitude, it.longitude, lat, lon) <= 20.0 } ?: false
|
||||
|
||||
if (baseLabel.isNotBlank()) {
|
||||
// Vi har redan en känd text (t.ex. sparad i FoundStore) → använd den oavsett avstånd
|
||||
titleText = baseLabel
|
||||
text = baseLabel
|
||||
loading = false
|
||||
return@LaunchedEffect
|
||||
val fused = GmsLocationServices.getFusedLocationProviderClient(context)
|
||||
val current = try {
|
||||
fused.lastLocation.await()
|
||||
?: fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
// Här är label tom – försök bara slå upp texten om vi är inom 20 m.
|
||||
val enriched = if (within20) withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val nearby = Geocache.getNearby(lat = lat, lon = lon, radiusMeters = 60, ttlMs = 0L)
|
||||
nearby.firstOrNull { it.i.toString() == id }
|
||||
} catch (_: Exception) { null }
|
||||
val qLat = current?.latitude ?: my?.latitude
|
||||
val qLon = current?.longitude ?: my?.longitude
|
||||
|
||||
val withinRadius = if (qLat != null && qLon != null) {
|
||||
distanceMeters(qLat, qLon, lat, lon) <= Config.DEFAULT_KLOTTER_RADIUS_M.toDouble()
|
||||
} else false
|
||||
|
||||
// Försök hämta detalj/bild om posten är känd (Hittat) ELLER vi är inom radien
|
||||
val canAttempt = isKnown || withinRadius
|
||||
Log.d("Yorlik", "KlotterDialog canAttempt=$canAttempt withinRadius=$withinRadius")
|
||||
|
||||
if (canAttempt) {
|
||||
// get_note.php ska få: Hittat => NOTISENS coords, annars besökarens (fallback notisens)
|
||||
val reqLat = if (isKnown) lat else (qLat ?: lat)
|
||||
val reqLon = if (isKnown) lon else (qLon ?: lon)
|
||||
|
||||
val detail = withContext(Dispatchers.IO) {
|
||||
try { fetchNoteDetail(id.toLong(), reqLat, reqLon) } catch (_: Throwable) { null }
|
||||
}
|
||||
Log.d("Yorlik", "detail fetch id=$id ok=${detail != null}")
|
||||
|
||||
if (detail != null) {
|
||||
// Sätt titel + brödtext från servern
|
||||
titleText = detail.title.ifBlank { "Okänt klotter" }
|
||||
text = detail.body.ifBlank { titleText }
|
||||
|
||||
// Lagra detalj i cache för snabb öppning nästa gång
|
||||
runCatching {
|
||||
com.example.yorlik.util.NoteDetailCache.put(detail.id, detail)
|
||||
}
|
||||
|
||||
// Bild: bygg URL som innehåller NOTISENS koordinater (servern kräver koordinat-bevis)
|
||||
val imgMeta = detail.image
|
||||
if (imgMeta != null && imgMeta.id > 0) {
|
||||
val partial = imgMeta.url?.trim().orEmpty()
|
||||
val fullUrl = if (partial.isNotEmpty()) {
|
||||
val absolute = ApiConfig.SERVER_API_BASE_URL + partial
|
||||
if (absolute.contains("lat=") && absolute.contains("lon=")) {
|
||||
absolute
|
||||
} else {
|
||||
val sep = if (absolute.contains("?")) "&" else "?"
|
||||
absolute + "${sep}lat=$lat&lon=$lon" // NOTISENS coords
|
||||
}
|
||||
} else {
|
||||
imageUrl(imgMeta.id, detail.id, lat, lon) // NOTISENS coords
|
||||
}
|
||||
|
||||
val resp = withContext(Dispatchers.IO) {
|
||||
runCatching { com.example.yorlik.net.Api.svc.getImageStream(fullUrl) }.getOrNull()
|
||||
}
|
||||
Log.d("Yorlik", "img GET code=${resp?.code()} url=$fullUrl")
|
||||
|
||||
val bmp = if (resp?.isSuccessful == true) {
|
||||
resp.body()?.byteStream()?.use { BitmapFactory.decodeStream(it) }
|
||||
} else null
|
||||
|
||||
val foundText = enriched?.t?.takeIf { !it.isNullOrBlank() }
|
||||
|
||||
if (foundText != null) {
|
||||
titleText = foundText
|
||||
text = foundText
|
||||
} else {
|
||||
// Fortfarande inget – visa “okänt” + förklaring om vi är för långt bort
|
||||
titleText = "Okänt klotter"
|
||||
text = if (!within20) {
|
||||
"Okänt klotter. Du måste vara inom 20\u00A0m för att se texten."
|
||||
} else {
|
||||
"Okänt klotter."
|
||||
if (bmp != null) {
|
||||
imgBitmap = bmp
|
||||
// cachea för snabb öppning nästa gång
|
||||
val imgId = imgMeta.id
|
||||
if (imgId > 0) com.example.yorlik.util.ImageBitmapCache.put(imgId, bmp)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Kunde inte få detalj – behåll ev. fallback (endast om ej känd och långt bort)
|
||||
if (!isKnown && !withinRadius) {
|
||||
titleText = "Okänt klotter"
|
||||
text = "Okänt klotter. Du måste vara inom ${Config.DEFAULT_KLOTTER_RADIUS_M}\u00A0m för att se texten."
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Verkligen okänd och för långt bort
|
||||
titleText = "Okänt klotter"
|
||||
text = "Okänt klotter. Du måste vara inom ${Config.DEFAULT_KLOTTER_RADIUS_M}\u00A0m för att se texten."
|
||||
}
|
||||
|
||||
loading = false
|
||||
}
|
||||
|
||||
|
||||
AlertDialog(
|
||||
Dialog(
|
||||
onDismissRequest = onClose,
|
||||
title = { Text(titleText) },
|
||||
text = {
|
||||
if (loading) {
|
||||
Text("Söker …")
|
||||
} else {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.85f) // 85% av skärmens bredd
|
||||
.clip(RoundedCornerShape(16.dp)),
|
||||
tonalElevation = 6.dp,
|
||||
shadowElevation = 6.dp,
|
||||
color = MaterialTheme.colorScheme.surface
|
||||
) {
|
||||
// --- Lägg här exakt samma innehåll du redan hade i AlertDialog ---
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Text(text = titleText, style = MaterialTheme.typography.titleLarge)
|
||||
|
||||
// Visa ev. bild oavsett loading (cache kan ha satt den)
|
||||
if (imgBitmap != null) {
|
||||
Image(
|
||||
bitmap = imgBitmap!!.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp, max = 320.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { showImageViewer = true },
|
||||
contentScale = ContentScale.Fit
|
||||
)
|
||||
}
|
||||
|
||||
// Laddningsindikator som INTE döljer texten
|
||||
if (loading && text.isBlank() && imgBitmap == null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
Text("Laddar …")
|
||||
}
|
||||
}
|
||||
|
||||
// Brödtext alltid synlig (även under loading)
|
||||
Text(text)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
|
||||
// Knappar på EN rad: Maps till vänster, Stäng till höger
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Button(
|
||||
onClick = {
|
||||
val labelEnc = Uri.encode(titleText)
|
||||
val labelEnc = Uri.encode(titleText.ifBlank { "Plats" })
|
||||
val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon($labelEnc)")
|
||||
val intent = Intent(Intent.ACTION_VIEW, uri).apply {
|
||||
`package` = "com.google.android.apps.maps"
|
||||
}
|
||||
val intent = Intent(Intent.ACTION_VIEW, uri).apply { `package` = "com.google.android.apps.maps" }
|
||||
try { context.startActivity(intent) } catch (_: Exception) {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
|
||||
}
|
||||
}
|
||||
) { Text("Maps") }
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
val labelEnc = Uri.encode(titleText)
|
||||
val uri = Uri.parse("google.navigation?q=$lat,$lon($labelEnc)&mode=w")
|
||||
val intent = Intent(Intent.ACTION_VIEW, uri).apply {
|
||||
`package` = "com.google.android.apps.maps"
|
||||
}
|
||||
try { context.startActivity(intent) } catch (_: Exception) {
|
||||
val fallback = Uri.parse("geo:$lat,$lon?q=$lat,$lon($labelEnc)")
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, fallback))
|
||||
Spacer(Modifier.weight(1f))
|
||||
|
||||
Button(onClick = onClose) { Text("Stäng") }
|
||||
}
|
||||
}
|
||||
) { Text("Vägbeskrivning") }
|
||||
// --- Slut på innehåll ---
|
||||
}
|
||||
}
|
||||
if (showImageViewer && imgBitmap != null) {
|
||||
ImageViewerDialog(bitmap = imgBitmap!!, onClose = { showImageViewer = false })
|
||||
}
|
||||
},
|
||||
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun ImageViewerDialog(bitmap: Bitmap, onClose: () -> Unit) {
|
||||
androidx.compose.ui.window.Dialog(
|
||||
onDismissRequest = onClose,
|
||||
properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color.Black)
|
||||
) {
|
||||
var scale by remember { mutableStateOf(1f) }
|
||||
var offset by remember { mutableStateOf(Offset.Zero) }
|
||||
val state = rememberTransformableState { zoomChange, panChange, _ ->
|
||||
val newScale = (scale * zoomChange).coerceIn(1f, 6f)
|
||||
val scaledPan = panChange * (newScale / scale)
|
||||
scale = newScale
|
||||
offset += scaledPan
|
||||
}
|
||||
|
||||
Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.graphicsLayer(
|
||||
scaleX = scale,
|
||||
scaleY = scale,
|
||||
translationX = offset.x,
|
||||
translationY = offset.y
|
||||
)
|
||||
.transformable(state),
|
||||
contentScale = ContentScale.Fit
|
||||
)
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(12.dp)
|
||||
) {
|
||||
Button(onClick = onClose) { Text("Stäng") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WikiArticleDialog(
|
||||
|
||||
@@ -3,9 +3,14 @@ package com.example.yorlik
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -21,6 +26,7 @@ import com.example.yorlik.net.Geocache
|
||||
import com.example.yorlik.net.NoteDTO
|
||||
import com.example.yorlik.net.Wikipedia
|
||||
import com.example.yorlik.net.WikipediaPage
|
||||
import com.example.yorlik.util.Config
|
||||
import com.example.yorlik.util.SettingsStore
|
||||
import com.google.android.gms.location.LocationServices as GmsLocationServices
|
||||
import com.google.android.gms.location.Priority
|
||||
@@ -32,6 +38,7 @@ 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.MarkerInfoWindow
|
||||
import com.google.maps.android.compose.MarkerState
|
||||
import com.google.maps.android.compose.MapUiSettings
|
||||
import com.google.maps.android.compose.rememberCameraPositionState
|
||||
@@ -43,8 +50,11 @@ import kotlin.math.roundToInt
|
||||
@Composable
|
||||
fun MapDialog(
|
||||
onClose: () -> Unit,
|
||||
initialLat: Double? = null, // ← NYTT (valfritt)
|
||||
initialLon: Double? = null // ← NYTT (valfritt)
|
||||
onKlotterClick: (id: String, lat: Double, lon: Double, label: String) -> Unit,
|
||||
onOpenUrl: (title: String, url: String) -> Unit,
|
||||
isKnownNote: (Long) -> Boolean,
|
||||
initialLat: Double? = null,
|
||||
initialLon: Double? = null
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val configuration = LocalConfiguration.current
|
||||
@@ -72,6 +82,8 @@ fun MapDialog(
|
||||
var selLon by remember { mutableStateOf<Double?>(null) }
|
||||
var selTitle by remember { mutableStateOf<String?>(null) }
|
||||
var selUri by remember { mutableStateOf<String?>(null) }
|
||||
var selId by remember { mutableStateOf<String?>(null) } // klotter-id vid behov
|
||||
var selLayer by remember { mutableStateOf<String?>(null) } // "Klotter", "Wikipedia", "Fornsök", ...
|
||||
|
||||
|
||||
val camState: CameraPositionState = rememberCameraPositionState {
|
||||
@@ -157,31 +169,78 @@ fun MapDialog(
|
||||
)
|
||||
) {
|
||||
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(
|
||||
|
||||
val titleLine = n.t.substringBefore('\n').ifBlank { "Okänt klotter" }
|
||||
val radius = com.example.yorlik.util.Config.DEFAULT_KLOTTER_RADIUS_M
|
||||
val visited = isKnownNote(n.i.toLong())
|
||||
val within = (d != Int.MAX_VALUE && d <= radius)
|
||||
val display = if (visited || (within && titleLine != "Okänt klotter")) titleLine else "Okänt klotter"
|
||||
|
||||
MarkerInfoWindow(
|
||||
state = MarkerState(position = LatLng(n.a, n.o)),
|
||||
title = label,
|
||||
snippet = "Klotter • ${if (d == Int.MAX_VALUE) "-" else "$d m"}",
|
||||
onClick = { selLat = n.a; selLon = n.o; selTitle = label; selUri = null; false }
|
||||
onClick = {
|
||||
// Sätt koordinater + titel så “Maps”/“Vägbeskrivning” får rätt namn
|
||||
selLat = n.a; selLon = n.o; selTitle = display; selUri = null
|
||||
false // låt infowindow visas
|
||||
},
|
||||
onInfoWindowClick = {
|
||||
// Öppna detaljrutan (samma som i Hittat/Närliggande)
|
||||
onKlotterClick(n.i.toString(), n.a, n.o, display)
|
||||
}
|
||||
) {
|
||||
// Läslig bubblan med bakgrund
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
|
||||
shape = RoundedCornerShape(8.dp)
|
||||
) {
|
||||
Column(Modifier.padding(8.dp)) {
|
||||
Text("Klotter", style = MaterialTheme.typography.labelMedium)
|
||||
Text(display, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
"Läs mer",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.clickable {
|
||||
onKlotterClick(n.i.toString(), n.a, n.o, display)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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(
|
||||
MarkerInfoWindow(
|
||||
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 }
|
||||
)
|
||||
onClick = {
|
||||
selLat = w.lat; selLon = w.lon; selTitle = null; selUri = "https://sv.m.wikipedia.org/?curid=${w.pageId}"
|
||||
false
|
||||
},
|
||||
onInfoWindowClick = {
|
||||
onOpenUrl(w.title, "https://sv.m.wikipedia.org/?curid=${w.pageId}")
|
||||
}
|
||||
) {
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
|
||||
shape = RoundedCornerShape(8.dp)
|
||||
) {
|
||||
Column(Modifier.padding(8.dp)) {
|
||||
Text("Wikipedia", style = MaterialTheme.typography.labelMedium)
|
||||
Text(w.title, style = MaterialTheme.typography.bodyMedium)
|
||||
Text("Läs mer", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,12 +248,26 @@ fun MapDialog(
|
||||
dm.forEach { dmi ->
|
||||
val d = if (lat != null && lon != null)
|
||||
distanceMeters(lat, lon, dmi.lat, dmi.lon).roundToInt() else Int.MAX_VALUE
|
||||
Marker(
|
||||
MarkerInfoWindow(
|
||||
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 }
|
||||
)
|
||||
//onClick = {
|
||||
// selLat = dmi.lat; selLon = dmi.lon; selTitle = dmi.title; selUri = dmi.uri
|
||||
// false
|
||||
//},
|
||||
//onInfoWindowClick = { dmi.uri?.let { onOpenUrl(dmi.title, it) } }
|
||||
) {
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
|
||||
shape = RoundedCornerShape(8.dp)
|
||||
) {
|
||||
Column(Modifier.padding(8.dp)) {
|
||||
Text("DigitaltMuseum", style = MaterialTheme.typography.labelMedium)
|
||||
Text(dmi.title, style = MaterialTheme.typography.bodyMedium)
|
||||
Text("Läs mer", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,17 +276,23 @@ fun MapDialog(
|
||||
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(
|
||||
MarkerInfoWindow(
|
||||
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
|
||||
onClick = { selLat = f.lat; selLon = f.lon; selTitle = null; selUri = f.uri; false },
|
||||
onInfoWindowClick = { f.uri?.let { onOpenUrl(f.title, it) } }
|
||||
) {
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
|
||||
shape = RoundedCornerShape(8.dp)
|
||||
) {
|
||||
Column(Modifier.padding(8.dp)) {
|
||||
Text("Fornsök", style = MaterialTheme.typography.labelMedium)
|
||||
Text(f.title, style = MaterialTheme.typography.bodyMedium)
|
||||
Text("Läs mer", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,6 +303,7 @@ fun MapDialog(
|
||||
.padding(8.dp),
|
||||
horizontalAlignment = Alignment.End
|
||||
) {
|
||||
|
||||
Button(
|
||||
onClick = { openInMaps(context, selLat, selLon, selTitle) },
|
||||
enabled = selLat != null && selLon != null
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,13 @@ import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.example.yorlik.net.createNote
|
||||
import com.example.yorlik.net.createNoteDoc
|
||||
import com.example.yorlik.net.uploadImageFromFile
|
||||
import com.example.yorlik.util.OutboxStore
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Försöker skicka allt som ligger i utkorgen (offline-klotter).
|
||||
@@ -15,20 +21,85 @@ class OutboxWorker(
|
||||
params: WorkerParameters
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
|
||||
private fun sha256Hex(s: String): String {
|
||||
val md = MessageDigest.getInstance("SHA-256")
|
||||
val bytes = md.digest(s.toByteArray(Charsets.UTF_8))
|
||||
val sb = StringBuilder(bytes.size * 2)
|
||||
for (b in bytes) {
|
||||
val i = b.toInt() and 0xff
|
||||
if (i < 16) sb.append('0')
|
||||
sb.append(i.toString(16))
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
val ctx = applicationContext
|
||||
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)
|
||||
// Stabil nyckel per pending-post (idempotens)
|
||||
val sig = buildString {
|
||||
append(p.createdAt).append(':')
|
||||
append(p.lat).append(':')
|
||||
append(p.lon).append(':')
|
||||
// säkerställ att vi skiljer på text- och doc-varianten i signaturen
|
||||
when {
|
||||
p.title != null || p.body != null -> {
|
||||
append(p.title ?: "")
|
||||
append('#')
|
||||
append(p.body ?: "")
|
||||
}
|
||||
else -> append(p.text ?: "")
|
||||
}
|
||||
}
|
||||
val reqId = "obx-" + sha256Hex(sig).take(48)
|
||||
|
||||
when {
|
||||
// DOC med ev. bild
|
||||
(p.title != null || p.body != null) -> {
|
||||
val imgId: Long? = if (p.imagePath != null && p.imageMime != null) {
|
||||
val f = File(p.imagePath)
|
||||
if (f.exists()) {
|
||||
uploadImageFromFile(applicationContext, f, p.imageMime, p.lat, p.lon)
|
||||
} else null
|
||||
} else null
|
||||
|
||||
createNoteDoc(
|
||||
lat = p.lat,
|
||||
lon = p.lon,
|
||||
title = p.title ?: "",
|
||||
body = p.body ?: (p.text ?: ""),
|
||||
imageId = imgId,
|
||||
radiusM = p.radiusM,
|
||||
createdAt = p.createdAt,
|
||||
clientRequestId = reqId
|
||||
)
|
||||
}
|
||||
|
||||
// TEXT-variant (som tidigare)
|
||||
else -> {
|
||||
createNote(
|
||||
lat = p.lat,
|
||||
lon = p.lon,
|
||||
text = p.text ?: "",
|
||||
createdAt = p.createdAt,
|
||||
clientRequestId = reqId
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
if (!ok) keep.add(p)
|
||||
}
|
||||
|
||||
|
||||
OutboxStore.replaceAll(ctx, keep)
|
||||
return if (keep.isEmpty()) Result.success() else Result.retry()
|
||||
}
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
package com.example.yorlik.net
|
||||
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.Json
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Response
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import retrofit2.Response as RResponse
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.moshi.MoshiConverterFactory
|
||||
import retrofit2.http.*
|
||||
import retrofit2.http.Url
|
||||
import com.example.yorlik.util.Auth
|
||||
import com.example.yorlik.BuildConfig
|
||||
import java.io.File
|
||||
import java.util.concurrent.TimeUnit
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.asRequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
|
||||
/**
|
||||
* Läser bas‑URL och API‑nyckel från BuildConfig (hålls i local.properties → buildConfigField).
|
||||
@@ -25,6 +37,9 @@ object ApiConfig {
|
||||
private fun ensureTrailingSlash(u: String): String =
|
||||
if (u.endsWith("/")) u else "$u/"
|
||||
}
|
||||
// v0.1.1: helper för säkra bild-URL:er. Bygger API-URL till get_image.php (kräver aktuell lat/lon för närhetslås)
|
||||
fun imageUrl(imageId: Long, noteId: Long, lat: Double, lon: Double): String =
|
||||
"${ApiConfig.SERVER_API_BASE_URL}get_image.php?id=$imageId¬e=$noteId&lat=$lat&lon=$lon"
|
||||
|
||||
/** Kompakta fält enligt nearby.php (behållna som i v0.0.1) */
|
||||
data class NoteDTO(
|
||||
@@ -42,13 +57,90 @@ data class CreateBody(
|
||||
val lon: Double,
|
||||
val text: String,
|
||||
val createdAt: Long,
|
||||
val userId: String? = null // fylls från Auth.userId (Google sub)
|
||||
val userId: String? = null, // fylls från Auth.userId (Google sub)
|
||||
val clientRequestId: String? = null
|
||||
|
||||
)
|
||||
|
||||
/** Svar från upload_image.php */
|
||||
data class UploadImageResp(
|
||||
val ok: Any? = null,
|
||||
@Json(name = "image_id") val imageId: Long? = null,
|
||||
val width: Int? = null,
|
||||
val height: Int? = null
|
||||
)
|
||||
|
||||
|
||||
/** Ny body till create.php när vi skickar dokument (rubrik/brödtext/bild) */
|
||||
data class CreateDocBody(
|
||||
val lat: Double,
|
||||
val lon: Double,
|
||||
val title: String,
|
||||
val body: String,
|
||||
val imageId: Long? = null,
|
||||
val radiusM: Int = 20,
|
||||
val createdAt: Long,
|
||||
val userId: String? = null, // Google "sub" (bakåtkomp)
|
||||
val clientRequestId: String? = null
|
||||
)
|
||||
|
||||
/** Svar från get_note.php */
|
||||
data class NoteImageDTO(
|
||||
val id: Long,
|
||||
val url: String? = null,
|
||||
val width: Int? = null,
|
||||
val height: Int? = null,
|
||||
val etag: String? = null
|
||||
)
|
||||
|
||||
data class NoteDetailDTO(
|
||||
val id: Long,
|
||||
val lat: Double,
|
||||
val lon: Double,
|
||||
val title: String,
|
||||
val body: String,
|
||||
val image: NoteImageDTO? = null
|
||||
)
|
||||
|
||||
data class NoteDetailBody(
|
||||
val id: Long,
|
||||
val lat: Double,
|
||||
val lon: Double
|
||||
)
|
||||
|
||||
|
||||
/** Dina endpoints – samma namn/banor som i v0.0.1 */
|
||||
interface YorlikApi {
|
||||
|
||||
@Multipart
|
||||
@POST("upload_image.php")
|
||||
suspend fun uploadImage(
|
||||
@Part image: MultipartBody.Part,
|
||||
@Part("lat") lat: RequestBody,
|
||||
@Part("lon") lon: RequestBody
|
||||
): RResponse<UploadImageResp>
|
||||
|
||||
/** Ny variant till samma create.php när vi skickar dokument */
|
||||
|
||||
@POST("create.php")
|
||||
suspend fun create(@Body body: CreateBody): RResponse<Map<String, Any>>
|
||||
suspend fun createDoc(
|
||||
@Body body: CreateDocBody,
|
||||
@Header("X-Idempotency-Key") idempotencyKey: String? = null
|
||||
): RResponse<Map<String, Any>>
|
||||
|
||||
/** Hämta full text + bild‐meta när användaren är på plats */
|
||||
|
||||
@POST("get_note.php")
|
||||
suspend fun getNote(@Body body: NoteDetailBody): RResponse<NoteDetailDTO>
|
||||
|
||||
@GET
|
||||
suspend fun getImageStream(@Url url: String): RResponse<ResponseBody>
|
||||
|
||||
@POST("create.php")
|
||||
suspend fun create(
|
||||
@Body body: CreateBody,
|
||||
@Header("X-Idempotency-Key") idempotencyKey: String? = null
|
||||
): RResponse<Map<String, Any>>
|
||||
|
||||
@GET("nearby.php")
|
||||
suspend fun nearby(
|
||||
@@ -77,6 +169,9 @@ private class ApiKeyInterceptor : Interceptor {
|
||||
|
||||
/** Retrofit/OkHttp build – med timeouts och logg i debug. */
|
||||
object Api {
|
||||
|
||||
@Volatile var lastUploadError: String? = null
|
||||
|
||||
private val moshi: Moshi by lazy {
|
||||
Moshi.Builder()
|
||||
.addLast(KotlinJsonAdapterFactory())
|
||||
@@ -92,7 +187,9 @@ object Api {
|
||||
.also { b ->
|
||||
if (BuildConfig.DEBUG) {
|
||||
val log = HttpLoggingInterceptor()
|
||||
log.level = HttpLoggingInterceptor.Level.BASIC
|
||||
// log.level = HttpLoggingInterceptor.Level.BASIC
|
||||
// log.level = HttpLoggingInterceptor.Level.HEADERS
|
||||
log.level = HttpLoggingInterceptor.Level.BODY
|
||||
b.addInterceptor(log)
|
||||
}
|
||||
}
|
||||
@@ -152,6 +249,132 @@ suspend fun fetchNearby(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Laddar upp en bild (Uri) till upload_image.php.
|
||||
* Returnerar image_id eller null om något gick fel.
|
||||
*/
|
||||
suspend fun uploadImageFromUri(
|
||||
context: Context,
|
||||
uri: Uri,
|
||||
lat: Double,
|
||||
lon: Double
|
||||
): Long? {
|
||||
Api.lastUploadError = null
|
||||
val mime = context.contentResolver.getType(uri) ?: "application/octet-stream"
|
||||
val tmp = kotlin.runCatching { java.io.File.createTempFile("yorlik_up", ".bin", context.cacheDir) }.getOrNull() ?: return null
|
||||
try {
|
||||
context.contentResolver.openInputStream(uri)?.use { ins ->
|
||||
tmp.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) }
|
||||
} ?: return null
|
||||
|
||||
val filename = when {
|
||||
mime.equals("image/jpeg", true) || mime.equals("image/jpg", true) -> "upload.jpg"
|
||||
mime.equals("image/png", true) -> "upload.png"
|
||||
mime.startsWith("image/") -> "upload.img"
|
||||
else -> "upload.bin"
|
||||
}
|
||||
val imgPart = MultipartBody.Part.createFormData(
|
||||
name = "image",
|
||||
filename = filename,
|
||||
body = tmp.asRequestBody(mime.toMediaTypeOrNull())
|
||||
)
|
||||
|
||||
val latPart = lat.toString().toRequestBody("text/plain".toMediaTypeOrNull())
|
||||
val lonPart = lon.toString().toRequestBody("text/plain".toMediaTypeOrNull())
|
||||
|
||||
val resp = try { Api.svc.uploadImage(imgPart, latPart, lonPart) } catch (t: Throwable) {
|
||||
Log.d("Yorlik", "uploadImage exception: ${t.message}")
|
||||
return null
|
||||
}
|
||||
|
||||
Log.d("Yorlik", "uploadImage code=${resp.code()} body=${resp.body()}")
|
||||
if (!resp.isSuccessful) {
|
||||
val err = resp.errorBody()?.string()
|
||||
Log.d("Yorlik", "uploadImage FAIL code=${resp.code()} err=$err")
|
||||
// Försök plocka ut {"error": "...", "max": "..."} om servern skickar det
|
||||
Api.lastUploadError = extractApiErrorMessage(err) ?: "Uppladdningen misslyckades (kod ${resp.code()})."
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
val body = resp.body() ?: return null
|
||||
Api.lastUploadError = null
|
||||
|
||||
|
||||
// tolka ok-fältet brett
|
||||
val ok = when (val v = body.ok) {
|
||||
is Boolean -> v
|
||||
is Number -> v.toInt() != 0
|
||||
is String -> v.equals("true", true) || v == "1" || v.equals("ok", true)
|
||||
else -> true // 200 utan ok → anta OK
|
||||
}
|
||||
if (!ok) return null
|
||||
|
||||
return body.imageId
|
||||
} finally {
|
||||
tmp.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Laddar upp en bild från en lokal fil (används av OutboxWorker).
|
||||
* Returnerar image_id eller null.
|
||||
*/
|
||||
suspend fun uploadImageFromFile(
|
||||
context: Context,
|
||||
file: File,
|
||||
mimeHint: String?,
|
||||
lat: Double,
|
||||
lon: Double
|
||||
): Long? {
|
||||
val mime = mimeHint ?: "application/octet-stream"
|
||||
|
||||
val filename = when {
|
||||
mime.equals("image/jpeg", true) || mime.equals("image/jpg", true) -> {
|
||||
if (file.name.contains('.')) file.name else "upload.jpg"
|
||||
}
|
||||
mime.equals("image/png", true) -> {
|
||||
if (file.name.contains('.')) file.name else "upload.png"
|
||||
}
|
||||
mime.startsWith("image/") -> file.name
|
||||
else -> if (file.name.contains('.')) file.name else "upload.bin"
|
||||
}
|
||||
|
||||
val imgPart = MultipartBody.Part.createFormData(
|
||||
name = "image",
|
||||
filename = filename,
|
||||
body = file.asRequestBody(mime.toMediaTypeOrNull())
|
||||
)
|
||||
val latPart = lat.toString().toRequestBody("text/plain".toMediaTypeOrNull())
|
||||
val lonPart = lon.toString().toRequestBody("text/plain".toMediaTypeOrNull())
|
||||
|
||||
val resp = try { Api.svc.uploadImage(imgPart, latPart, lonPart) } catch (t: Throwable) {
|
||||
Log.d("Yorlik", "uploadImage(file) exception: ${t.message}")
|
||||
return null
|
||||
}
|
||||
|
||||
Log.d("Yorlik", "uploadImage(file) code=${resp.code()} body=${resp.body()}")
|
||||
if (!resp.isSuccessful) {
|
||||
val err = resp.errorBody()?.string()
|
||||
Log.d("Yorlik", "uploadImage(file) FAIL code=${resp.code()} err=$err")
|
||||
return null
|
||||
}
|
||||
|
||||
val body = resp.body() ?: return null
|
||||
val ok = when (val v = body.ok) {
|
||||
is Boolean -> v
|
||||
is Number -> v.toInt() != 0
|
||||
is String -> v.equals("true", true) || v == "1" || v.equals("ok", true)
|
||||
else -> true
|
||||
}
|
||||
if (!ok) return null
|
||||
|
||||
return body.imageId
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Skapar en not – returnerar true om servern svarar { ok: true } och HTTP 200.
|
||||
*/
|
||||
@@ -159,16 +382,109 @@ suspend fun createNote(
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
text: String,
|
||||
createdAt: Long
|
||||
createdAt: Long,
|
||||
clientRequestId: String?
|
||||
): Boolean {
|
||||
if (com.example.yorlik.util.Auth.idToken == null || com.example.yorlik.util.Auth.userId == null) {
|
||||
return false
|
||||
}
|
||||
|
||||
val body = CreateBody(
|
||||
lat = lat, lon = lon, text = text, createdAt = createdAt,
|
||||
userId = Auth.userId // Google “sub” när inloggad (annars null)
|
||||
userId = Auth.userId,
|
||||
clientRequestId = clientRequestId
|
||||
)
|
||||
val resp = try {
|
||||
Api.svc.create(body)
|
||||
Api.svc.create(body, idempotencyKey = clientRequestId)
|
||||
} catch (_: Throwable) {
|
||||
return false
|
||||
}
|
||||
return resp.isSuccessful && (resp.body()?.get("ok") == true)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Skapar notis med rubrik/brödtext/bild/radius.
|
||||
* Returnerar true om servern svarar { ok: true }.
|
||||
*/
|
||||
|
||||
suspend fun createNoteDoc(
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
title: String,
|
||||
body: String,
|
||||
imageId: Long?,
|
||||
radiusM: Int,
|
||||
createdAt: Long,
|
||||
clientRequestId: String?
|
||||
): Boolean {
|
||||
if (com.example.yorlik.util.Auth.idToken == null || com.example.yorlik.util.Auth.userId == null) {
|
||||
return false
|
||||
}
|
||||
val payload = CreateDocBody(
|
||||
lat = lat, lon = lon,
|
||||
title = title, body = body,
|
||||
imageId = imageId, radiusM = radiusM,
|
||||
createdAt = createdAt,
|
||||
userId = Auth.userId,
|
||||
clientRequestId = clientRequestId
|
||||
)
|
||||
val resp = try { Api.svc.createDoc(payload, idempotencyKey = clientRequestId) } catch (_: Throwable) { return false }
|
||||
if (!resp.isSuccessful) return false
|
||||
val okField = resp.body()?.get("ok")
|
||||
return when (okField) {
|
||||
is Boolean -> okField
|
||||
is Number -> okField.toInt() != 0
|
||||
is String -> okField.equals("true", true) || okField == "1" || okField.equals("ok", true)
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
suspend fun fetchNoteDetail(id: Long, lat: Double, lon: Double): NoteDetailDTO? {
|
||||
val body = NoteDetailBody(id = id, lat = lat, lon = lon)
|
||||
return try {
|
||||
val resp = Api.svc.getNote(body)
|
||||
android.util.Log.d("Yorlik", "get_note code=${resp.code()} ok=${resp.isSuccessful}")
|
||||
if (!resp.isSuccessful) {
|
||||
val err = resp.errorBody()?.string()
|
||||
android.util.Log.d("Yorlik", "get_note err=$err")
|
||||
null
|
||||
} else {
|
||||
resp.body()
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.d("Yorlik", "get_note exception: ${t.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//suspend fun fetchNoteDetail(id: Long, lat: Double, lon: Double): NoteDetailDTO? {
|
||||
// val body = mapOf("id" to id, "lat" to lat, "lon" to lon)
|
||||
// val resp = try { Api.svc.getNote(body) } catch (_: Throwable) { return null }
|
||||
// if (!resp.isSuccessful) return null
|
||||
// return resp.body()
|
||||
//}
|
||||
|
||||
private data class ApiErr(val error: String? = null, val max: String? = null, @Json(name = "max_bytes") val maxBytes: Long? = null)
|
||||
|
||||
private fun extractApiErrorMessage(json: String?): String? {
|
||||
if (json.isNullOrBlank()) return null
|
||||
return try {
|
||||
// Minimal Moshi parse – filen har redan Moshi på classpath
|
||||
val moshi = Moshi.Builder().build()
|
||||
val adapter = moshi.adapter(ApiErr::class.java)
|
||||
val e = adapter.fromJson(json)
|
||||
return when {
|
||||
e?.error?.equals("file_too_large", true) == true ->
|
||||
e?.max?.let { "Bilden är för stor. Max $it." }
|
||||
?: e?.maxBytes?.let { "Bilden är för stor. Max ${it / (1024 * 1024)} MB." }
|
||||
?: "Bilden är för stor."
|
||||
!e?.error.isNullOrBlank() -> e?.error
|
||||
else -> null
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
24
app/src/main/java/com/example/yorlik/util/Config.kt
Normal file
24
app/src/main/java/com/example/yorlik/util/Config.kt
Normal file
@@ -0,0 +1,24 @@
|
||||
package com.example.yorlik.util
|
||||
|
||||
object Config {
|
||||
// Finns redan hos dig:
|
||||
const val DEFAULT_KLOTTER_RADIUS_M: Int = 20
|
||||
|
||||
// ---- LAGER-REGISTRET (flexibelt) ----
|
||||
data class LayerSpec(val id: String, val displayName: String, val defaultRadiusM: Int?)
|
||||
|
||||
object Layers {
|
||||
// Du kan lägga till fler senare utan att pilla i kartan
|
||||
val REGISTRY: Map<String, LayerSpec> = mapOf(
|
||||
"klotter" to LayerSpec("klotter", "Klotter", DEFAULT_KLOTTER_RADIUS_M),
|
||||
"wikipedia" to LayerSpec("wikipedia", "Wikipedia", null),
|
||||
"fornsok" to LayerSpec("fornsok", "Fornsök", null),
|
||||
"dm" to LayerSpec("dm", "DigitaltMuseum", null)
|
||||
)
|
||||
|
||||
fun name(id: String): String = REGISTRY[id]?.displayName
|
||||
?: id.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
|
||||
|
||||
fun radius(id: String): Int? = REGISTRY[id]?.defaultRadiusM
|
||||
}
|
||||
}
|
||||
23
app/src/main/java/com/example/yorlik/util/NoteCache.kt
Normal file
23
app/src/main/java/com/example/yorlik/util/NoteCache.kt
Normal file
@@ -0,0 +1,23 @@
|
||||
package com.example.yorlik.util
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.example.yorlik.net.NoteDetailDTO
|
||||
import java.util.LinkedHashMap
|
||||
|
||||
object NoteDetailCache {
|
||||
private const val MAX = 16
|
||||
private val map = object : LinkedHashMap<Long, NoteDetailDTO>(MAX, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, NoteDetailDTO>?): Boolean = size > MAX
|
||||
}
|
||||
@Synchronized fun get(id: Long): NoteDetailDTO? = map[id]
|
||||
@Synchronized fun put(id: Long, d: NoteDetailDTO) { map[id] = d }
|
||||
}
|
||||
|
||||
object ImageBitmapCache {
|
||||
private const val MAX = 8
|
||||
private val map = object : LinkedHashMap<Long, Bitmap>(MAX, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, Bitmap>?): Boolean = size > MAX
|
||||
}
|
||||
@Synchronized fun get(id: Long): Bitmap? = map[id]
|
||||
@Synchronized fun put(id: Long, bmp: Bitmap) { map[id] = bmp }
|
||||
}
|
||||
126
app/src/main/java/com/example/yorlik/util/OutboxStore.kt
Normal file
126
app/src/main/java/com/example/yorlik/util/OutboxStore.kt
Normal file
@@ -0,0 +1,126 @@
|
||||
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 createdAt: Long,
|
||||
// TEXT-variant (som tidigare)
|
||||
val text: String? = null,
|
||||
// DOC-variant (ny)
|
||||
val title: String? = null,
|
||||
val body: String? = null,
|
||||
val radiusM: Int = 20,
|
||||
// BILD (ny) – lagras som LOKAL fil i appens lagring
|
||||
val imagePath: String? = null,
|
||||
val imageMime: String? = null
|
||||
)
|
||||
|
||||
|
||||
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 = lat,
|
||||
lon = lon,
|
||||
createdAt = createdAt,
|
||||
text = text
|
||||
)
|
||||
)
|
||||
save(context, list)
|
||||
}
|
||||
|
||||
|
||||
fun addDoc(
|
||||
context: Context,
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
title: String,
|
||||
body: String,
|
||||
createdAt: Long,
|
||||
radiusM: Int,
|
||||
imagePath: String?, // absolut sökväg till vår lokala kopia (om vald)
|
||||
imageMime: String? // "image/jpeg" osv (om vald)
|
||||
) {
|
||||
val list = all(context).toMutableList()
|
||||
list.add(
|
||||
PendingNote(
|
||||
lat = lat, lon = lon, createdAt = createdAt,
|
||||
title = title, body = body, radiusM = radiusM,
|
||||
imagePath = imagePath, imageMime = imageMime
|
||||
)
|
||||
)
|
||||
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)
|
||||
|
||||
val lat = o.getDouble("lat")
|
||||
val lon = o.getDouble("lon")
|
||||
val createdAt = o.getLong("createdAt")
|
||||
|
||||
// text fanns alltid förr – men gör den valfri nu
|
||||
val text = if (o.has("text")) o.optString("text", null).let { if (it.isNullOrEmpty()) null else it } else null
|
||||
|
||||
// nya fält (kan saknas i äldre JSON)
|
||||
val title = if (o.has("title")) o.optString("title", null).let { if (it.isNullOrEmpty()) null else it } else null
|
||||
val body = if (o.has("body")) o.optString("body", null).let { if (it.isNullOrEmpty()) null else it } else null
|
||||
val radiusM = if (o.has("radiusM")) o.optInt("radiusM", 20) else 20
|
||||
val imagePath = if (o.has("imagePath")) o.optString("imagePath", null).let { if (it.isNullOrEmpty()) null else it } else null
|
||||
val imageMime = if (o.has("imageMime")) o.optString("imageMime", null).let { if (it.isNullOrEmpty()) null else it } else null
|
||||
|
||||
out.add(
|
||||
PendingNote(
|
||||
lat = lat, lon = lon, createdAt = createdAt,
|
||||
text = text,
|
||||
title = title, body = body, radiusM = radiusM,
|
||||
imagePath = imagePath, imageMime = imageMime
|
||||
)
|
||||
)
|
||||
}
|
||||
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("createdAt", p.createdAt)
|
||||
// skriv bara nycklar som har värden
|
||||
p.text?.let { o.put("text", it) }
|
||||
p.title?.let { o.put("title", it) }
|
||||
p.body?.let { o.put("body", it) }
|
||||
if (p.radiusM != 20) o.put("radiusM", p.radiusM)
|
||||
p.imagePath?.let { o.put("imagePath", it) }
|
||||
p.imageMime?.let { o.put("imageMime", it) }
|
||||
arr.put(o)
|
||||
}
|
||||
prefs(context).edit().putString(KEY, arr.toString()).apply()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
[versions]
|
||||
agp = "8.12.0"
|
||||
agp = "8.12.1"
|
||||
kotlin = "2.0.21"
|
||||
coreKtx = "1.16.0"
|
||||
junit = "4.13.2"
|
||||
|
||||
Reference in New Issue
Block a user