Local random photo camera php backend

WIth the google photo integration going. well Stupid (and im going to move off the cloud anyway) I made a local random image persenter. in a php script.
Put it in a (locally only) webserver. and point to your images.

WIth a post command curl -X POST http://myhappyserver/local/photo.php the current photo is blocked and never shown again.

you can create a camera using the image as still image. and create an action (hold for example) to run the post command in a shell command

$directory = '/mnt/usb/nextcloud/Camera';
$cacheFile = './random_image_cache.json';
$cacheDuration = 300; // Cache duration in seconds

// Function to recursively collect all image files
function getAllImages($dir) {
    $images = [];
    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif','webp'];

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($iterator as $file) {
        if ($file->isFile() && in_array(strtolower($file->getExtension()), $allowedExtensions)) {
            $images[] = $file->getPathname();
        }
    }

    return $images;
}

// Load or initialize cache
$cacheData = file_exists($cacheFile) ? json_decode(file_get_contents($cacheFile), true) : ['image' => null, 'timestamp' => 0, 'blocked_images' => []];

// Handle POST request to block the current image
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($cacheData['image'])) {
        $cacheData['blocked_images'][] = $cacheData['image'];
        $cacheData['blocked_images'] = array_unique($cacheData['blocked_images']); // Ensure no duplicates
        file_put_contents($cacheFile, json_encode($cacheData));
        echo "Image blocked successfully.";
    } else {
        http_response_code(400);
        echo "No image to block.";
    }
    exit;
}

// Handle GET request to serve a random image
$allImages = getAllImages($directory);
$remainingImages = array_diff($allImages, $cacheData['blocked_images']);

if (empty($remainingImages)) {
    http_response_code(404);
    echo "No unblocked images available.";
    exit;
}

// Use cached image if still valid
if (isset($cacheData['image']) && (time() - $cacheData['timestamp']) < $cacheDuration) {
    $randomImage = $cacheData['image'];
} else {
    // Select a new random image
    $randomImage = $remainingImages[array_rand($remainingImages)];
    $cacheData['image'] = $randomImage;
    $cacheData['timestamp'] = time();
    file_put_contents($cacheFile, json_encode($cacheData));
}

// Detect MIME type of the image
$mimeType = mime_content_type($randomImage);

header("Content-Type: $mimeType");
readfile($randomImage);
?>
1 Like