store picfit image extension in the ID

This commit is contained in:
Thibault Duplessis 2021-09-01 18:24:23 +02:00
parent 68603c3821
commit fad5cad609

View file

@ -46,9 +46,15 @@ final class PicfitApi(coll: Coll, ws: StandaloneWSClient, config: PicfitConfig)(
def upload(rel: String, uploaded: Uploaded, userId: String): Fu[PicfitImage] = def upload(rel: String, uploaded: Uploaded, userId: String): Fu[PicfitImage] =
if (uploaded.fileSize > uploadMaxBytes) if (uploaded.fileSize > uploadMaxBytes)
fufail(s"File size must not exceed ${uploadMaxMb}MB.") fufail(s"File size must not exceed ${uploadMaxMb}MB.")
else { else
uploaded.contentType collect {
case "image/png" => "png"
case "image/jpeg" => "jpg"
} match {
case None => fufail(s"Invalid file type: ${uploaded.contentType | "unknown"}")
case Some(extension) => {
val image = PicfitImage( val image = PicfitImage(
_id = PicfitImage.Id(lila.common.ThreadLocalRandom nextString 10), _id = PicfitImage.Id(s"${lila.common.ThreadLocalRandom nextString 10}.$extension"),
user = userId, user = userId,
rel = rel, rel = rel,
name = sanitizeName(uploaded.filename), name = sanitizeName(uploaded.filename),
@ -60,6 +66,7 @@ final class PicfitApi(coll: Coll, ws: StandaloneWSClient, config: PicfitConfig)(
deletePrevious(image) >> deletePrevious(image) >>
coll.insert.one(image) inject image coll.insert.one(image) inject image
} }
}
private def deletePrevious(image: PicfitImage): Funit = private def deletePrevious(image: PicfitImage): Funit =
coll coll
@ -74,17 +81,12 @@ final class PicfitApi(coll: Coll, ws: StandaloneWSClient, config: PicfitConfig)(
private object picfitServer { private object picfitServer {
def store(image: PicfitImage, from: Uploaded): Funit = from.contentType collect { def store(image: PicfitImage, from: Uploaded): Funit = {
case "image/png" => "png"
case "image/jpeg" => "jpg"
} match {
case None => fufail(s"Invalid file type: ${from.contentType | "unknown"}")
case Some(extension) => {
type Part = MultipartFormData.FilePart[Source[ByteString, _]] type Part = MultipartFormData.FilePart[Source[ByteString, _]]
import WSBodyWritables._ import WSBodyWritables._
val part: Part = MultipartFormData.FilePart( val part: Part = MultipartFormData.FilePart(
key = "data", key = "data",
filename = s"${image.id.value}.$extension", filename = image.id.value,
contentType = from.contentType, contentType = from.contentType,
ref = FileIO.fromPath(from.ref.path), ref = FileIO.fromPath(from.ref.path),
fileSize = from.fileSize fileSize = from.fileSize
@ -100,7 +102,6 @@ final class PicfitApi(coll: Coll, ws: StandaloneWSClient, config: PicfitConfig)(
} }
.monSuccess(_.picfit.uploadTime(image.user)) .monSuccess(_.picfit.uploadTime(image.user))
} }
}
def delete(image: PicfitImage): Funit = def delete(image: PicfitImage): Funit =
ws.url(s"${config.endpointPost}/${image.id}").delete().flatMap { ws.url(s"${config.endpointPost}/${image.id}").delete().flatMap {