feat(shared): add KMP upload_image.php (multipart) and delegate Android uploads
This commit is contained in:
@@ -233,10 +233,9 @@ suspend fun fetchNearby(
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Laddar upp en bild (Uri) till upload_image.php.
|
||||
* Returnerar image_id eller null om något gick fel.
|
||||
* Laddar upp en bild (Uri) via delad KMP-klient.
|
||||
* Returnerar image_id eller null; sätter Api.lastUploadError vid fel.
|
||||
*/
|
||||
suspend fun uploadImageFromUri(
|
||||
context: Context,
|
||||
@@ -258,52 +257,43 @@ suspend fun uploadImageFromUri(
|
||||
mime.startsWith("image/") -> "upload.img"
|
||||
else -> "upload.bin"
|
||||
}
|
||||
val imgPart = MultipartBody.Part.createFormData(
|
||||
name = "image",
|
||||
|
||||
val bytes = runCatching { tmp.readBytes() }.getOrNull() ?: return null
|
||||
|
||||
val res = try {
|
||||
KlottrApiShared.uploadImage(
|
||||
baseUrl = ApiConfig.SERVER_API_BASE_URL,
|
||||
apiKey = ApiConfig.SERVER_API_KEY,
|
||||
bearerToken = app.klottr.util.Auth.idToken,
|
||||
data = bytes,
|
||||
filename = filename,
|
||||
body = tmp.asRequestBody(mime.toMediaTypeOrNull())
|
||||
mime = mime,
|
||||
lat = lat,
|
||||
lon = lon
|
||||
)
|
||||
|
||||
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) {
|
||||
} catch (t: Throwable) {
|
||||
app.klottr.util.AppLog.d { "uploadImage exception: ${t.message}" }
|
||||
Api.lastUploadError = "Uppladdningen misslyckades."
|
||||
return null
|
||||
}
|
||||
|
||||
app.klottr.util.AppLog.d { "uploadImage code=${resp.code()} body=${resp.body()}"}
|
||||
if (!resp.isSuccessful) {
|
||||
val err = resp.errorBody()?.string()
|
||||
app.klottr.util.AppLog.d { "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()})."
|
||||
app.klottr.util.AppLog.d { "uploadImage code=200 ok=${res.ok} imageId=${res.imageId} width=${res.width} height=${res.height}" }
|
||||
|
||||
if (!res.ok || res.imageId == null) {
|
||||
Api.lastUploadError = res.errorMessage ?: "Uppladdningen misslyckades."
|
||||
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
|
||||
return res.imageId
|
||||
} finally {
|
||||
tmp.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Laddar upp en bild från en lokal fil (används av OutboxWorker).
|
||||
* Returnerar image_id eller null.
|
||||
* Laddar upp en bild från lokal fil via delad KMP-klient.
|
||||
* Returnerar image_id eller null; sätter Api.lastUploadError vid fel.
|
||||
*/
|
||||
suspend fun uploadImageFromFile(
|
||||
context: Context,
|
||||
@@ -312,6 +302,7 @@ suspend fun uploadImageFromFile(
|
||||
lat: Double,
|
||||
lon: Double
|
||||
): Long? {
|
||||
Api.lastUploadError = null
|
||||
val mime = mimeHint ?: "application/octet-stream"
|
||||
|
||||
val filename = when {
|
||||
@@ -325,37 +316,36 @@ suspend fun uploadImageFromFile(
|
||||
else -> if (file.name.contains('.')) file.name else "upload.bin"
|
||||
}
|
||||
|
||||
val imgPart = MultipartBody.Part.createFormData(
|
||||
name = "image",
|
||||
val bytes = runCatching { file.readBytes() }.getOrNull() ?: return null
|
||||
|
||||
val res = try {
|
||||
KlottrApiShared.uploadImage(
|
||||
baseUrl = ApiConfig.SERVER_API_BASE_URL,
|
||||
apiKey = ApiConfig.SERVER_API_KEY,
|
||||
bearerToken = app.klottr.util.Auth.idToken,
|
||||
data = bytes,
|
||||
filename = filename,
|
||||
body = file.asRequestBody(mime.toMediaTypeOrNull())
|
||||
mime = mime,
|
||||
lat = lat,
|
||||
lon = lon
|
||||
)
|
||||
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) {
|
||||
} catch (t: Throwable) {
|
||||
app.klottr.util.AppLog.d { "uploadImage(file) exception: ${t.message}" }
|
||||
Api.lastUploadError = "Uppladdningen misslyckades."
|
||||
return null
|
||||
}
|
||||
|
||||
app.klottr.util.AppLog.d { "uploadImage(file) code=${resp.code()} body=${resp.body()}"}
|
||||
if (!resp.isSuccessful) {
|
||||
val err = resp.errorBody()?.string()
|
||||
app.klottr.util.AppLog.d { "uploadImage(file) FAIL code=${resp.code()} err=$err"}
|
||||
app.klottr.util.AppLog.d { "uploadImage(file) ok=${res.ok} imageId=${res.imageId}" }
|
||||
|
||||
if (!res.ok || res.imageId == null) {
|
||||
Api.lastUploadError = res.errorMessage ?: "Uppladdningen misslyckades."
|
||||
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
|
||||
Api.lastUploadError = null
|
||||
return res.imageId
|
||||
}
|
||||
if (!ok) return null
|
||||
|
||||
return body.imageId
|
||||
}
|
||||
|
||||
/**
|
||||
* Skapar en not – returnerar true om servern svarar { ok: true } och HTTP 200.
|
||||
|
||||
@@ -42,6 +42,16 @@ data class NoteImageDTO(
|
||||
val etag: String? = null
|
||||
)
|
||||
|
||||
/** Resultat från upload_image.php (delad) */
|
||||
data class UploadImageResultShared(
|
||||
val ok: Boolean,
|
||||
val imageId: Long?,
|
||||
val width: Int?,
|
||||
val height: Int?,
|
||||
val errorMessage: String?
|
||||
)
|
||||
|
||||
|
||||
data class NoteDetailBody(
|
||||
val id: Long,
|
||||
val lat: Double,
|
||||
|
||||
@@ -3,11 +3,14 @@ package app.klottr.net
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.client.request.forms.formData
|
||||
import io.ktor.client.request.forms.submitForm
|
||||
import io.ktor.client.request.forms.submitFormWithBinaryData
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.Headers
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.Parameters
|
||||
import io.ktor.http.contentType
|
||||
@@ -468,4 +471,91 @@ object KlottrApiShared {
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
/**
|
||||
* KMP-variant av upload_image.php (multipart/form-data).
|
||||
* Tar bilddata som ByteArray + filnamn + mime. Returnerar resultat med ev. felmeddelande.
|
||||
*/
|
||||
suspend fun uploadImage(
|
||||
baseUrl: String,
|
||||
apiKey: String,
|
||||
bearerToken: String?,
|
||||
data: ByteArray,
|
||||
filename: String,
|
||||
mime: String,
|
||||
lat: Double,
|
||||
lon: Double
|
||||
): UploadImageResultShared {
|
||||
val url = ensureSlash(baseUrl) + "upload_image.php"
|
||||
|
||||
val resp = try {
|
||||
client.submitFormWithBinaryData(
|
||||
url = url,
|
||||
formData = formData {
|
||||
append(
|
||||
key = "image",
|
||||
value = data,
|
||||
headers = Headers.build {
|
||||
append(HttpHeaders.ContentType, mime)
|
||||
append(HttpHeaders.ContentDisposition, "filename=$filename")
|
||||
}
|
||||
)
|
||||
append("lat", lat.toString())
|
||||
append("lon", lon.toString())
|
||||
}
|
||||
) {
|
||||
header("X-API-Key", apiKey)
|
||||
if (bearerToken != null) header(HttpHeaders.Authorization, "Bearer $bearerToken")
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
return UploadImageResultShared(
|
||||
ok = false, imageId = null, width = null, height = null,
|
||||
errorMessage = "Uppladdningen misslyckades (nätverksfel)."
|
||||
)
|
||||
}
|
||||
|
||||
val code = resp.status.value
|
||||
val obj = try { resp.body<JsonObject>() } catch (_: Throwable) { null }
|
||||
|
||||
// Hjälpare för att extrahera ev. fel från servern (kompatibelt med PHP-svaret)
|
||||
fun extractError(o: JsonObject?): String? {
|
||||
if (o == null) return if (code != 200) "Uppladdningen misslyckades (kod $code)." else null
|
||||
val err = o["error"]?.jsonPrimitive?.contentOrNull
|
||||
val max = o["max"]?.jsonPrimitive?.contentOrNull
|
||||
val maxBytes = o["max_bytes"]?.jsonPrimitive?.longOrNull
|
||||
return when {
|
||||
err?.equals("file_too_large", true) == true && max != null -> "Bilden är för stor. Max $max."
|
||||
err?.equals("file_too_large", true) == true && maxBytes != null -> "Bilden är för stor. Max ${maxBytes / (1024 * 1024)} MB."
|
||||
!err.isNullOrBlank() -> err
|
||||
code != 200 -> "Uppladdningen misslyckades (kod $code)."
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
if (code != 200) {
|
||||
return UploadImageResultShared(
|
||||
ok = false, imageId = null, width = null, height = null,
|
||||
errorMessage = extractError(obj)
|
||||
)
|
||||
}
|
||||
|
||||
// Tolka svar med bred "ok"-logik + image_id/width/height
|
||||
val okPrim = obj?.get("ok")?.jsonPrimitive
|
||||
val ok = when {
|
||||
okPrim == null -> true
|
||||
okPrim.booleanOrNull != null -> okPrim.boolean
|
||||
okPrim.longOrNull != null -> okPrim.long != 0L
|
||||
okPrim.contentOrNull != null -> okPrim.content.equals("true", true) || okPrim.content == "1" || okPrim.content.equals("ok", true)
|
||||
else -> true
|
||||
}
|
||||
val imageId = obj?.get("image_id")?.jsonPrimitive?.longOrNull
|
||||
val width = obj?.get("width")?.jsonPrimitive?.intOrNull
|
||||
val height = obj?.get("height")?.jsonPrimitive?.intOrNull
|
||||
val errMsg = extractError(obj)
|
||||
|
||||
return UploadImageResultShared(
|
||||
ok = ok, imageId = imageId, width = width, height = height, errorMessage = if (ok) null else errMsg
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user