From 80981284cd235ecd6d39fb9ae1afe019f1049ad4 Mon Sep 17 00:00:00 2001 From: Fabian Norlin Date: Sun, 14 Sep 2025 19:42:39 +0200 Subject: [PATCH] =?UTF-8?q?shared(create):=20add=20createNoteFlow=20use=20?= =?UTF-8?q?case=20(upload=E2=86=92create=20orchestration)=20with=20CreateN?= =?UTF-8?q?oteOutcome=20app(main):=20use=20createNoteFlow=20in=20WriteDocD?= =?UTF-8?q?ialog=20onSave;=20keep=20offline=20outbox=20path=20unchanged?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/src/main/java/app/klottr/MainActivity.kt | 210 +++++++++--------- .../app/klottr/create/CreateNoteFlow.kt | 30 +++ 2 files changed, 140 insertions(+), 100 deletions(-) create mode 100644 shared/src/commonMain/kotlin/app/klottr/create/CreateNoteFlow.kt diff --git a/app/src/main/java/app/klottr/MainActivity.kt b/app/src/main/java/app/klottr/MainActivity.kt index 186953e..17bb5da 100644 --- a/app/src/main/java/app/klottr/MainActivity.kt +++ b/app/src/main/java/app/klottr/MainActivity.kt @@ -106,6 +106,8 @@ import androidx.work.Constraints import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager +import app.klottr.create.CreateNoteOutcome +import app.klottr.create.createNoteFlow import app.klottr.data.AppDatabase import app.klottr.data.NoteRepository import app.klottr.location.AndroidLocationProvider @@ -1010,116 +1012,124 @@ private fun KlottrApp( 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) - } + val titleText = draft.title.trim() + val bodyText = draft.body.trim() + + // Kör delat online-flöde i IO-tråd + val outcome = withContext(Dispatchers.IO) { + createNoteFlow( + hasImage = draft.imageUri != null, + uploadImage = { + // Plattformsspecifik bilduppladdning (oförändrad funktion i :app) + uploadImageFromUri(context, draft.imageUri!!, selLat, selLon) + }, + createNote = { imageId -> + createNoteDoc( + lat = selLat, + lon = selLon, + title = titleText, + body = bodyText, + imageId = imageId, + radiusM = Config.DEFAULT_KLOTTER_RADIUS_M, + createdAt = created, + clientRequestId = requestId + ) + }, + getUploadError = { Api.lastUploadError } + ) } - if (draft.imageUri != null && imgId == null) { - withContext(Dispatchers.Main) { - val msg = Api.lastUploadError - ?: "Bilduppladdning misslyckades." + + when (outcome) { + is CreateNoteOutcome.Success -> { + Toast.makeText(context, "Sparat.", Toast.LENGTH_SHORT).show() + + // Förladda närliggande post och ev. bild (oförändrat beteende) + scope.launch(Dispatchers.IO) { + try { + val nearby = Geocache.getNearby( + lat = selLat, lon = selLon, radiusMeters = 100, ttlMs = 0L + ) + val combined = buildString { + if (titleText.isNotBlank()) append(titleText).append("\n\n") + append(bodyText) + }.trim() + val match = nearby.firstOrNull { + it.t == combined && abs(it.c - created) <= 2_000 + } + if (match != null) { + FoundStore.markFound( + context, + LAYER_KLOTTER, + match.i.toString(), + label = match.t, + lat = match.a, + lon = match.o, + timeMillis = System.currentTimeMillis() + ) + withContext(Dispatchers.Main) { + context.sendBroadcast( + Intent(LocationService.Companion.ACTION_FOUND_UPDATED) + ) + } + } + } catch (_: Throwable) { } + } + + showWrite = false + } + + is CreateNoteOutcome.UploadFailed -> { + val msg = outcome.message ?: "Bilduppladdning misslyckades." Toast.makeText(context, msg, Toast.LENGTH_LONG).show() resetSavingCounter++ + // Stanna i dialogen (samma beteende som tidigare) } - 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 = Config.DEFAULT_KLOTTER_RADIUS_M, - createdAt = created, - clientRequestId = requestId - ) - } - - 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 = selLat, lon = selLon, radiusMeters = 100, ttlMs = 0L - ) - 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 && abs(it.c - created) <= 2_000 + is CreateNoteOutcome.CreateFailed -> { + // Offline: spara till utkorgen (oförändrat beteende) + 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" } - if (match != null) { - FoundStore.markFound( - context, - LAYER_KLOTTER, - match.i.toString(), - label = match.t, - lat = match.a, - lon = match.o, - timeMillis = System.currentTimeMillis() - ) - withContext(Dispatchers.Main) { - context.sendBroadcast( - Intent(LocationService.Companion.ACTION_FOUND_UPDATED) - ) + val outDir = File(context.filesDir, "outbox").apply { mkdirs() } + val outFile = 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 } - } catch (_: Throwable) { } - } - 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 = File(context.filesDir, "outbox").apply { mkdirs() } - val outFile = 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 } + + OutboxStore.addDoc( + context = context, + lat = selLat, + lon = selLon, + title = titleText, + body = bodyText, + createdAt = created, + radiusM = Config.DEFAULT_KLOTTER_RADIUS_M, + imagePath = imagePath, + imageMime = imageMime + ) + Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show() + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + val req = OneTimeWorkRequestBuilder() + .setConstraints(constraints).build() + WorkManager.getInstance(context).enqueue(req) + showWrite = false } - - OutboxStore.addDoc( - context = context, - lat = selLat, - lon = selLon, - title = titleText, - body = bodyText, - createdAt = created, - radiusM = Config.DEFAULT_KLOTTER_RADIUS_M, - imagePath = imagePath, - imageMime = imageMime - ) - Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show() - - val constraints = Constraints.Builder() - .setRequiredNetworkType(NetworkType.CONNECTED) - .build() - val req = OneTimeWorkRequestBuilder() - .setConstraints(constraints).build() - WorkManager.getInstance(context).enqueue(req) - showWrite = false } } finally { isSavingDoc = false diff --git a/shared/src/commonMain/kotlin/app/klottr/create/CreateNoteFlow.kt b/shared/src/commonMain/kotlin/app/klottr/create/CreateNoteFlow.kt new file mode 100644 index 0000000..5b73d70 --- /dev/null +++ b/shared/src/commonMain/kotlin/app/klottr/create/CreateNoteFlow.kt @@ -0,0 +1,30 @@ +package app.klottr.create + +/** Resultat från create-flödet. */ +sealed class CreateNoteOutcome { + data object Success : CreateNoteOutcome() + data class UploadFailed(val message: String?) : CreateNoteOutcome() + data object CreateFailed : CreateNoteOutcome() +} + +/** + * Orkestrerar online-flödet: ev. bilduppladdning → skapa notis. + * Plattformsspecifika detaljer injiceras via lambdas. + */ +suspend fun createNoteFlow( + hasImage: Boolean, + uploadImage: suspend () -> Long?, // Körs bara om hasImage = true + createNote: suspend (imageId: Long?) -> Boolean, // Skapa klotter med ev. imageId + getUploadError: () -> String? = { null } // För t.ex. Api.lastUploadError (valfritt) +): CreateNoteOutcome { + val imageId: Long? = if (hasImage) { + val id = uploadImage() + if (id == null) return CreateNoteOutcome.UploadFailed(getUploadError()) + id + } else { + null + } + + val ok = createNote(imageId) + return if (ok) CreateNoteOutcome.Success else CreateNoteOutcome.CreateFailed +}