photo-viewer-backend/php/get.php

113 lines
2.8 KiB
PHP

<?php
include_once __DIR__ . "/logging.php";
define("ROOT_URL", "http://localhost/");
define("ROOT_DIR", "/var/www/localhost/");
define("IMG_DIR", "img/");
define("THUMBNAIL_DIR", "thumbnails/");
define("THUMBNAIL_SCRIPT", __DIR__ . "/../scripts/resize-img");
define("IMAGE_EXTENSIONS", [
'jpg',
'jpeg',
'png',
'gif',
'tiff',
'bmp',
'webp',
'svg',
]);
define("VIDEO_EXTENSIONS", [
'mp4',
]);
define("FILE_EXTENSIONS", array_merge(IMAGE_EXTENSIONS, VIDEO_EXTENSIONS));
main();
function main(): void {
$data = json_decode(file_get_contents('php://input'), true);
$array = [];
$category = $data["category"];
$directory = ROOT_DIR.IMG_DIR.$category;
if (!is_dir($directory)) goto encode;
foreach (scandir($directory) as $file) {
if ($file === ".") continue;
if ($category === "" && $file === "..") continue;
$path = add_seperator_ab("/", $category, $file);
$is_dir = is_dir(ROOT_DIR.IMG_DIR.$path);
if (!$is_dir && !is_valid_file_type($file)) continue;
$file_item = [];
$file_item["is_dir"] = $is_dir;
if ($is_dir) {
$file_item["url"] = ROOT_URL.IMG_DIR.$path;
$file_item["thumbnail_url"] = null;
} else {
$file_item["url"] = ROOT_URL.IMG_DIR.$path;
$file_item["thumbnail_url"] = create_thumbnail($category, $file);
}
array_push($array, $file_item);
}
encode:
echo json_encode($array);
}
function create_thumbnail(string $category, string $file): string | null {
if (!is_image_file_type($file)) return null;
$path = add_seperator_ab("/", $category, $file);
$original_file = ROOT_DIR.IMG_DIR.$path;
$thumbnail_directory = ROOT_DIR.THUMBNAIL_DIR.IMG_DIR.add_seperator_ab("/", $category, "");
$thumbnail_file = $thumbnail_directory.$file;
if (file_exists($thumbnail_file)) {
log_print("$thumbnail_file exists, skipping gneeration");
goto return_thumbnail;
}
try {
if (!is_dir($thumbnail_directory)) mkdir($thumbnail_directory, 0777, true);
}
catch(Exception $e) {
log_error($e->getMessage());
}
log_print(THUMBNAIL_SCRIPT." '$original_file' '$thumbnail_file'");
$output = shell_exec(THUMBNAIL_SCRIPT." '$original_file' '$thumbnail_file' 2>&1");
log_print($output);
if ($output === false) {
log_error("Thumbnail failed");
return ROOT_URL.IMG_DIR.$path;
}
return_thumbnail:
return ROOT_URL.THUMBNAIL_DIR.IMG_DIR.$path;
}
function add_seperator_ab(string $separator, string $a, string $b): string {
if ($a === "") return $b;
return $a.$separator.$b;
}
function is_valid_file_type(string $filename): bool {
foreach (FILE_EXTENSIONS as $file_extension) {
if (str_ends_with($filename, $file_extension)) return true;
}
return false;
}
function is_image_file_type(string $filename): bool {
foreach(IMAGE_EXTENSIONS as $file_extension) {
if(str_ends_with($filename, $file_extension)) return true;
}
return false;
}
?>