app(write): on UploadFailed, queue to outbox via shared use case; persist image locally and schedule upload worker

This commit is contained in:
2025-09-14 23:23:04 +02:00
parent c65f230665
commit 9deca99711
2 changed files with 164 additions and 42 deletions

View File

@@ -107,7 +107,9 @@ import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager import androidx.work.WorkManager
import app.klottr.create.CreateNoteOutcome import app.klottr.create.CreateNoteOutcome
import app.klottr.create.QueueOutboxOutcome
import app.klottr.create.createNoteFlow import app.klottr.create.createNoteFlow
import app.klottr.create.queueNoteDocOutbox
import app.klottr.data.AppDatabase import app.klottr.data.AppDatabase
import app.klottr.data.NoteRepository import app.klottr.data.NoteRepository
import app.klottr.location.AndroidLocationProvider import app.klottr.location.AndroidLocationProvider
@@ -1076,57 +1078,144 @@ private fun KlottrApp(
showWrite = false showWrite = false
} }
is CreateNoteOutcome.UploadFailed -> { is CreateNoteOutcome.UploadFailed -> { // Fallback till offline-utkorg även när bilduppladdning misslyckas
val msg = outcome.message ?: "Bilduppladdning misslyckades." val titleText = draft.title.trim()
Toast.makeText(context, msg, Toast.LENGTH_LONG).show() val bodyText = draft.body.trim()
resetSavingCounter++
// Stanna i dialogen (samma beteende som tidigare)
}
is CreateNoteOutcome.CreateFailed -> { val queued = withContext(Dispatchers.IO) {
// Offline: spara till utkorgen (oförändrat beteende) queueNoteDocOutbox(
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, lat = selLat,
lon = selLon, lon = selLon,
title = titleText, title = titleText,
body = bodyText, body = bodyText,
createdAt = created, createdAt = created,
radiusM = Config.DEFAULT_KLOTTER_RADIUS_M, radiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
imagePath = imagePath, hasImage = (draft.imageUri != null),
imageMime = imageMime persistImageIfAny = {
val uri = draft.imageUri ?: return@queueNoteDocOutbox null
val mime = context.contentResolver.getType(uri) ?: "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(uri)?.use { ins ->
outFile.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) }
}
outFile.absolutePath to mime
} catch (_: Exception) {
null
}
},
addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime ->
OutboxStore.addDoc(
context = context,
lat = la,
lon = lo,
title = t,
body = b,
createdAt = ts,
radiusM = rad,
imagePath = imagePath,
imageMime = imageMime
)
},
scheduleUpload = {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val req = OneTimeWorkRequestBuilder<OutboxWorker>()
.setConstraints(constraints).build()
WorkManager.getInstance(context).enqueue(req)
}
) )
Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show() }
val constraints = Constraints.Builder() when (queued) {
.setRequiredNetworkType(NetworkType.CONNECTED) QueueOutboxOutcome.Queued -> {
.build() Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show()
val req = OneTimeWorkRequestBuilder<OutboxWorker>() showWrite = false
.setConstraints(constraints).build() }
WorkManager.getInstance(context).enqueue(req) QueueOutboxOutcome.ImagePersistFailed -> {
showWrite = false val msg = outcome.message ?: "Bilduppladdning misslyckades."
Toast.makeText(context, "$msg\nKunde inte spara bilden lokalt.", Toast.LENGTH_LONG).show()
// Stanna kvar i dialogen
}
}
}
is CreateNoteOutcome.CreateFailed -> {
// Lägg i utkorgen via delad use-case (offline)
val titleText = draft.title.trim()
val bodyText = draft.body.trim()
val queued = withContext(Dispatchers.IO) {
queueNoteDocOutbox(
lat = selLat,
lon = selLon,
title = titleText,
body = bodyText,
createdAt = created,
radiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
hasImage = (draft.imageUri != null),
persistImageIfAny = {
// Spara vald bild till appens outbox-mapp, returnera (path, mime) eller null vid fel
val uri = draft.imageUri ?: return@queueNoteDocOutbox null
val mime = context.contentResolver.getType(uri) ?: "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(uri)?.use { ins ->
outFile.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) }
}
outFile.absolutePath to mime
} catch (_: Exception) {
null
}
},
addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime ->
OutboxStore.addDoc(
context = context,
lat = la,
lon = lo,
title = t,
body = b,
createdAt = ts,
radiusM = rad,
imagePath = imagePath,
imageMime = imageMime
)
},
scheduleUpload = {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val req = OneTimeWorkRequestBuilder<OutboxWorker>()
.setConstraints(constraints).build()
WorkManager.getInstance(context).enqueue(req)
}
)
}
when (queued) {
QueueOutboxOutcome.Queued -> {
Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show()
showWrite = false
}
QueueOutboxOutcome.ImagePersistFailed -> {
Toast.makeText(context, "Kunde inte spara bilden lokalt.", Toast.LENGTH_LONG).show()
// Stanna kvar i dialogen, låt användaren försöka igen eller spara utan bild
}
}
} }
} }
} finally { } finally {

View File

@@ -0,0 +1,33 @@
package app.klottr.create
/** Resultat från outbox-köning (offline). */
sealed class QueueOutboxOutcome {
data object Queued : QueueOutboxOutcome() // Lyckades lägga i utkorgen
data object ImagePersistFailed : QueueOutboxOutcome() // Bilden kunde inte sparas lokalt
}
/**
* Orkestrerar offline-flödet: ev. spara bild lokalt → lägg DOC i outbox → schemalägg uppladdning.
* Plattformsspecifika detaljer injiceras via lambdas (DI).
*/
suspend fun queueNoteDocOutbox(
lat: Double,
lon: Double,
title: String,
body: String,
createdAt: Long,
radiusM: Int,
hasImage: Boolean,
persistImageIfAny: suspend () -> Pair<String, String>?, // returnerar (imagePath, imageMime) eller null vid fel
addOutboxDoc: (lat: Double, lon: Double, title: String, body: String, createdAt: Long, radiusM: Int, imagePath: String?, imageMime: String?) -> Unit,
scheduleUpload: () -> Unit
): QueueOutboxOutcome {
val (imagePath, imageMime) = if (hasImage) {
val res = persistImageIfAny() ?: return QueueOutboxOutcome.ImagePersistFailed
res
} else null to null
addOutboxDoc(lat, lon, title, body, createdAt, radiusM, imagePath, imageMime)
scheduleUpload()
return QueueOutboxOutcome.Queued
}