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")}\"")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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()
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user