From ee6a3bfd4f6999a326b61b41c5c3abfdbc3435c0 Mon Sep 17 00:00:00 2001 From: Azzurite Date: Tue, 7 Jun 2022 22:00:33 +0200 Subject: [PATCH] Fix UncivServer not correctly handling put request --- .../src/com/unciv/app/server/UncivServer.kt | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/server/src/com/unciv/app/server/UncivServer.kt b/server/src/com/unciv/app/server/UncivServer.kt index c4d869b2b2853..71d15260d5d45 100644 --- a/server/src/com/unciv/app/server/UncivServer.kt +++ b/server/src/com/unciv/app/server/UncivServer.kt @@ -13,9 +13,12 @@ import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.utils.io.jvm.javaio.* import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.io.FileNotFoundException +import java.time.Instant internal object UncivServer { @@ -45,33 +48,35 @@ private class UncivServerRunner : CliktCommand() { embeddedServer(Netty, port = serverPort) { routing { get("/isalive") { - println("Received isalive request from ${call.request.local.remoteHost}") + log.info("Received isalive request from ${call.request.local.remoteHost}") call.respondText("true") } put("/files/{fileName}") { val fileName = call.parameters["fileName"] ?: throw Exception("No fileName!") + log.info("Receiving file: ${fileName}") + val file = File(fileFolderName, fileName) withContext(Dispatchers.IO) { - val receivedBytes = - call.request.receiveChannel().toInputStream().readBytes() - val textString = String(receivedBytes) - println("Received text: $textString") - File(fileFolderName, fileName).writeText(textString) + file.outputStream().use { + call.request.receiveChannel().toInputStream().copyTo(it) + } } + call.respond(HttpStatusCode.OK) } get("/files/{fileName}") { val fileName = call.parameters["fileName"] ?: throw Exception("No fileName!") - println("Get file: $fileName") + log.info("File requested: $fileName") val file = File(fileFolderName, fileName) if (!file.exists()) { + log.info("File $fileName not found") call.respond(HttpStatusCode.NotFound, "File does not exist") return@get } - val fileText = file.readText() - println("Text read: $fileText") + val fileText = withContext(Dispatchers.IO) { file.readText() } call.respondText(fileText) } delete("/files/{fileName}") { val fileName = call.parameters["fileName"] ?: throw Exception("No fileName!") + log.info("Deleting file: $fileName") val file = File(fileFolderName, fileName) if (!file.exists()) { call.respond(HttpStatusCode.NotFound, "File does not exist") @@ -82,4 +87,4 @@ private class UncivServerRunner : CliktCommand() { } }.start(wait = true) } -} \ No newline at end of file +}