From 92ec35700e4b7156d69a18b63192be76e867485d Mon Sep 17 00:00:00 2001 From: Nick Hansen <110249144+nickhnsn@users.noreply.github.com> Date: Fri, 9 Aug 2024 21:44:27 +0200 Subject: [PATCH] Add optional code param in upload request --- app/Controllers/UploadController.php | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/app/Controllers/UploadController.php b/app/Controllers/UploadController.php index f2ecee96..d25ce9c0 100644 --- a/app/Controllers/UploadController.php +++ b/app/Controllers/UploadController.php @@ -107,7 +107,7 @@ public function uploadEndpoint(Request $request, Response $response): Response } try { - $response = $this->saveMedia($response, $file, $user); + $response = $this->saveMedia($response, $file, $user, param($request, 'code')); } catch (Exception $e) { $this->updateUserQuota($request, $user->id, $file->getSize(), true); throw $e; @@ -118,6 +118,7 @@ public function uploadEndpoint(Request $request, Response $response): Response /** * @param Request $request * @param Response $response + * @param $code * @return UploadedFileInterface * @throws ValidationException */ @@ -182,11 +183,19 @@ protected function validateUser(Request $request, Response $response, UploadedFi * @throws \League\Flysystem\FileExistsException * @throws \League\Flysystem\FileNotFoundException */ - protected function saveMedia(Response $response, UploadedFileInterface $file, $user) + protected function saveMedia(Response $response, UploadedFileInterface $file, $user, $code) { - do { - $code = humanRandomString(); - } while ($this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `code` = ?', $code)->fetch()->count > 0); + if ($code === null) { + do { + $code = humanRandomString(); + } while ($this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `code` = ?', $code)->fetch()->count > 0); + } else { + $existingCodeCount = $this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `code` = ?', $code)->fetch()->count; + if ($existingCodeCount > 0) { + $this->json['message'] = 'Custom url code already exists.'; + return json($response, $this->json, 409); + } + } $fileInfo = pathinfo($file->getClientFilename()); $storagePath = "$user->user_code/$code.$fileInfo[extension]";