From 0ac128d6a2df3a84f49a4d86cfbf501bbbb52a43 Mon Sep 17 00:00:00 2001 From: ilotterytea Date: Sun, 1 Jun 2025 00:01:49 +0400 Subject: feat: file thumbnails --- public/upload.php | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) (limited to 'public/upload.php') diff --git a/public/upload.php b/public/upload.php index 3ef0a0c..ae550c9 100644 --- a/public/upload.php +++ b/public/upload.php @@ -1,13 +1,14 @@ &1', - FILE_DIRECTORY, + FILE_UPLOAD_DIRECTORY, $file_id, $file_data['extension'], escapeshellarg($url) @@ -112,12 +113,42 @@ try { error_log(sprintf("Failed to download a file (URL: %s): %s", $url, implode('\n', $output))); throw new RuntimeException('Failed to download a file! Try again later.'); } - } else if (isset($paste) && !file_put_contents(FILE_DIRECTORY . sprintf('/%s.%s', $file_id, $file_data['extension']), $paste)) { + } else if (isset($paste) && !file_put_contents(FILE_UPLOAD_DIRECTORY . sprintf('/%s.%s', $file_id, $file_data['extension']), $paste)) { throw new RuntimeException('Failed to paste a text! Try again later.'); - } else if (isset($file) && !move_uploaded_file($file['tmp_name'], FILE_DIRECTORY . sprintf('/%s.%s', $file_id, $file_data['extension']))) { + } else if (isset($file) && !move_uploaded_file($file['tmp_name'], FILE_UPLOAD_DIRECTORY . sprintf('/%s.%s', $file_id, $file_data['extension']))) { throw new RuntimeException("Failed to save the file. Try again later."); } + if (FILE_THUMBNAILS && !is_dir(FILE_THUMBNAIL_DIRECTORY) && !mkdir(FILE_THUMBNAIL_DIRECTORY, 0777, true)) { + throw new RuntimeException('Failed to create a directory for thumbnails'); + } + + if ( + FILE_THUMBNAILS && ( + ( + str_starts_with($file_data['mime'], 'image/') && + $thumbnail_error = generate_image_thumbnail( + FILE_UPLOAD_DIRECTORY . "/{$file_id}.{$file_data['extension']}", + FILE_THUMBNAIL_DIRECTORY . "/{$file_id}.webp", + FILE_THUMBNAIL_SIZE[0], + FILE_THUMBNAIL_SIZE[1] + ) + ) || + ( + str_starts_with($file_data['mime'], 'video/') && + $thumbnail_error = generate_video_thumbnail( + FILE_UPLOAD_DIRECTORY . "/{$file_id}.{$file_data['extension']}", + FILE_THUMBNAIL_DIRECTORY . "/{$file_id}", + FILE_THUMBNAIL_DIRECTORY . "/{$file_id}.webp", + FILE_THUMBNAIL_SIZE[0], + FILE_THUMBNAIL_SIZE[1] + ) + ) + ) + ) { + throw new RuntimeException("Failed to create a thumbnail (Error code {$thumbnail_error})"); + } + if ($_SERVER['HTTP_ACCEPT'] == 'application/json') { json_response($file_data, null, 201); } else { -- cgit v1.2.3