Skip to content

Commit

Permalink
Change storage stuff and 'properly' handle non existing files
Browse files Browse the repository at this point in the history
  • Loading branch information
powercasgamer committed Nov 11, 2023
1 parent 37dddac commit 6adf478
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
27 changes: 19 additions & 8 deletions app/src/main/kotlin/dev/mizule/imagery/app/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -91,35 +91,46 @@ class App(private val config: Config) {
return
}

val fileName = getRandomString() + file.extension()
val id = getRandomString()
val fileName = id + file.extension()
val filePath = storageDir.resolve(fileName)
filePath.outputStream().use {
file.content().copyTo(it)
}

val uploadedFile = UploadedFile(
fileName,
id,
"user",
System.currentTimeMillis(),
fileName,
file.filename(),
file.extension(),
MimeTypes.getDefaultMimeByExtension(file.extension()),
)

dataNode.node(uploadedFile.id).set(uploadedFile)
dataNode.node(id).set(uploadedFile)
dataLoader.save(dataNode) // TODO: probably shouldn't be done during the http request

cache.put(fileName, FileCacheEntry(uploadedFile, filePath))
ctx.json(mapOf("data" to ImageLookupResult("${config.baseUrl}/$fileName")))
}

private fun serveUploadedFile(ctx: Context) {
cache.getIfPresent(ctx.pathParam("id"))
?.also { (uploadedFile, path) ->
ctx.result(path.inputStream())
.contentType(ContentType.getContentTypeByExtension(uploadedFile.extension) ?: ContentType.IMAGE_PNG)
val id = ctx.pathParam("id")
cache.get(id) {
val node = dataNode.node(id)
if (node != null && !node.virtual()) {
val uploadedNode = node.get(UploadedFile::class.java)!!
FileCacheEntry(uploadedNode, storageDir.resolve(uploadedNode.fileName))
} else {
// cry
ctx.result("This image does not exists").status(HttpStatus.NOT_FOUND)
null
}
?: ctx.status(HttpStatus.NOT_FOUND)
}?.also { (uploadedFile, path) ->
ctx.result(path.inputStream())
.contentType(ContentType.getContentTypeByExtension(uploadedFile.extension) ?: ContentType.IMAGE_PNG)
}?: ctx.result("This image does not exists").status(HttpStatus.NOT_FOUND)
}

fun start() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ data class UploadedFile(
val user: String,
val uploadedDate: Long,
val fileName: String,
val originalFileName: String,
val extension: String,
val mimeType: String,
)

0 comments on commit 6adf478

Please sign in to comment.