diff --git a/app/Controllers/MediaController.php b/app/Controllers/MediaController.php index db2e12bb..fa91dd92 100644 --- a/app/Controllers/MediaController.php +++ b/app/Controllers/MediaController.php @@ -188,6 +188,43 @@ public function download(Request $request, Response $response, string $userCode, return $this->streamMedia($request, $response, $this->storage, $media, 'attachment'); } + /** + * @param Request $request + * @param Response $response + * @param string $vanity + * @param string $id + * + * @return Response + * @throws HttpNotFoundException + * @throws HttpBadRequestException + */ + public function createVanity(Request $request, Response $response, int $id): Response + { + $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch(); + + $vanity = param($request, 'vanity'); + $vanity = preg_replace('/[^a-z0-9]+/', '-', strtolower($vanity)); + + //handle collisions + $collision = $this->database->query('SELECT * FROM `uploads` WHERE `code` = ? AND `id` != ? LIMIT 1',[$vanity, $id])->fetch(); + + if (!$media) { + throw new HttpNotFoundException($request); + } + + if ($vanity === '' || $collision) { + throw new HttpBadRequestException($request); + } + + $this->database->query('UPDATE `uploads` SET `code` = ? WHERE `id` = ?',[$vanity, $media->id]); + $media->code = $vanity; + $response->getBody()->write(json_encode($media)); + + $this->logger->info('User '.$this->session->get('username').' created a vanity link for media '.$media->id); + + return $response; + } + /** * @param Request $request * @param Response $response