Files
ai-stylegallery/app/Http/Controllers/Api/ImageController.php

324 lines
13 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Api\Plugins\PluginLoader;
use App\Models\ApiProvider;
use App\Models\Style;
use App\Models\Image;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use App\Models\Setting;
class ImageController extends Controller
{
public function index(Request $request)
{
$publicUploadsPath = public_path('storage/uploads');
// Ensure the directory exists
if (!File::exists($publicUploadsPath)) {
File::makeDirectory($publicUploadsPath, 0755, true);
}
// Get files from the public/storage/uploads directory
$diskFiles = File::files($publicUploadsPath);
$diskImagePaths = [];
foreach ($diskFiles as $file) {
// Store path relative to public/storage/
$diskImagePaths[] = 'uploads/' . $file->getFilename();
}
$dbImagePaths = Image::pluck('path')->toArray();
// Add images from disk that are not in the database
$imagesToAdd = array_diff($diskImagePaths, $dbImagePaths);
foreach ($imagesToAdd as $path) {
Image::create(['path' => $path, 'is_public' => true]);
}
// Remove images from database that are not on disk
$imagesToRemove = array_diff($dbImagePaths, $diskImagePaths);
Image::whereIn('path', $imagesToRemove)->delete();
// Fetch images from the database after synchronization
$query = Image::orderBy('updated_at', 'desc');
// If user is not authenticated, filter by is_public, but also include their temporary images
if (!auth()->check()) {
$query->where(function ($q) {
$q->where('is_public', true)->orWhere('is_temp', true);
});
} else {
// If user is authenticated, show all their images
}
$newImageTimespanMinutes = Setting::where('key', 'new_image_timespan_minutes')->first()->value ?? 60; // Default to 60 minutes
$images = $query->get()->map(function ($image) use ($newImageTimespanMinutes) {
$image->is_new = Carbon::parse($image->created_at)->diffInMinutes(Carbon::now()) <= $newImageTimespanMinutes;
return $image;
});
$formattedImages = [];
foreach ($images as $image) {
$formattedImages[] = [
'image_id' => $image->id,
'path' => asset('storage/' . $image->path),
'name' => basename($image->path),
'is_temp' => (bool) $image->is_temp,
'is_public' => (bool) $image->is_public,
'is_new' => (bool) $image->is_new,
];
}
return response()->json($formattedImages);
}
public function upload(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,bmp,gif,webp|max:10240', // Max 10MB
]);
$file = $request->file('image');
$fileName = uniqid() . '.' . $file->getClientOriginalExtension();
$destinationPath = public_path('storage/uploads');
// Ensure the directory exists
if (!File::exists($destinationPath)) {
File::makeDirectory($destinationPath, 0755, true);
}
$file->move($destinationPath, $fileName);
$relativePath = 'uploads/' . $fileName; // Path relative to public/storage/
$image = Image::create([
'path' => $relativePath,
'is_public' => true,
]);
return response()->json([
'message' => __('api.image_uploaded_successfully'),
'image_id' => $image->id,
'path' => asset('storage/' . $relativePath),
]);
}
public function styleChangeRequest(Request $request)
{
// Same-origin check
$appUrl = config('app.url');
$referer = $request->headers->get('referer');
if ($referer && parse_url($referer, PHP_URL_HOST) !== parse_url($appUrl, PHP_URL_HOST)) {
return response()->json(['error' => 'Unauthorized: Request must originate from the same domain.'], 403);
}
$request->validate([
'image_id' => 'required|exists:images,id',
'style_id' => 'nullable|exists:styles,id',
]);
$image = Image::find($request->image_id);
$style = null;
if ($request->style_id) {
$style = Style::with(['aiModel' => function ($query) {
$query->where('enabled', true)->with(['apiProviders' => function ($query) {
$query->where('enabled', true);
}]);
}])->find($request->style_id);
} else {
// Attempt to get default style from settings
$defaultStyleSetting = \App\Models\Setting::where('key', 'default_style_id')->first();
if ($defaultStyleSetting && $defaultStyleSetting->value) {
$style = Style::with(['aiModel' => function ($query) {
$query->where('enabled', true)->with(['apiProviders' => function ($query) {
$query->where('enabled', true);
}]);
}])->find($defaultStyleSetting->value);
}
}
if (!$style || !$style->aiModel || $style->aiModel->apiProviders->isEmpty()) {
return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
}
try {
$apiProvider = $style->aiModel->apiProviders->first(); // Get the first enabled API provider
if (!$apiProvider) {
return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
}
$plugin = PluginLoader::getPlugin($apiProvider->plugin, $apiProvider);
$result = $plugin->processImageStyleChange($image, $style);
// Update the image model with the ComfyUI prompt_id and style_id
$image->comfyui_prompt_id = $result['prompt_id'];
$image->style_id = $style->id;
$image->save();
// Return the prompt_id for WebSocket tracking
return response()->json([
'message' => 'Style change request sent.',
'prompt_id' => $result['prompt_id'],
'image_uuid' => $image->uuid, // Pass image UUID for frontend tracking
]);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
public function keepImage(Request $request)
{
$request->validate([
'image_id' => 'required|exists:images,id',
]);
$image = Image::find($request->image_id);
if (!$image) {
return response()->json(['error' => __('api.image_not_found')], 404);
}
$image->is_temp = false;
$image->save();
return response()->json(['message' => __('api.image_kept_successfully')]);
}
public function deleteImage(Image $image)
{
try {
// Delete from the public/storage directory
File::delete(public_path('storage/' . $image->path));
$image->delete();
return response()->json(['message' => __('api.image_deleted_successfully')]);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
public function getStatus(Request $request)
{
$request->validate([
'image_id' => 'required|exists:images,id',
'api_provider_name' => 'required|string',
]);
$image = Image::find($request->image_id);
$apiProvider = ApiProvider::where('name', $request->api_provider_name)->first();
if (!$image || !$apiProvider) {
return response()->json(['error' => __('api.image_or_provider_not_found')], 404);
}
try {
$plugin = PluginLoader::getPlugin($apiProvider->name);
$status = $plugin->getStatus($image->uuid); // Annahme: Image Model hat eine UUID
return response()->json($status);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
public function fetchStyledImage(string $promptId)
{
Log::info('fetchStyledImage called.', ['prompt_id' => $promptId]);
try {
// Find the image associated with the prompt_id, eagerly loading relationships
$image = Image::with(['style.aiModel.apiProviders' => function ($query) {
$query->where('enabled', true);
}])->where('comfyui_prompt_id', $promptId)->first();
if (!$image) {
Log::warning('fetchStyledImage: Image not found for prompt_id.', ['prompt_id' => $promptId]);
return response()->json(['error' => __('api.image_not_found')], 404);
}
Log::info('fetchStyledImage: Image found.', ['image_id' => $image->id, 'image_uuid' => $image->uuid, 'comfyui_prompt_id' => $image->comfyui_prompt_id]);
// Get the style and API provider associated with the image
$style = $image->style;
if (!$style) {
Log::warning('fetchStyledImage: Style not found for image.', ['image_id' => $image->id]);
return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
}
Log::info('fetchStyledImage: Style found.', ['style_id' => $style->id, 'style_name' => $style->title]);
if (!$style->aiModel) {
Log::warning('fetchStyledImage: AI Model not found for style.', ['style_id' => $style->id]);
return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
}
Log::info('fetchStyledImage: AI Model found.', ['ai_model_id' => $style->aiModel->id, 'ai_model_name' => $style->aiModel->name]);
if ($style->aiModel->apiProviders->isEmpty()) {
Log::warning('fetchStyledImage: No enabled API Providers found for AI Model.', ['ai_model_id' => $style->aiModel->id]);
return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
}
$apiProvider = $style->aiModel->apiProviders->first();
Log::info('fetchStyledImage: API Provider found.', ['api_provider_id' => $apiProvider->id, 'api_provider_name' => $apiProvider->name]);
Log::info('Fetching base64 image from plugin.', ['prompt_id' => $promptId, 'api_provider' => $apiProvider->name]);
// Use the plugin to get the final image data (e.g., from ComfyUI's history/view)
$plugin = PluginLoader::getPlugin($apiProvider->plugin, $apiProvider);
$base64Image = $plugin->waitForResult($promptId); // Re-purpose waitForResult for final fetch
if (empty($base64Image)) {
Log::error('Received empty base64 image from plugin.', ['prompt_id' => $promptId]);
return response()->json(['error' => 'Received empty image data.'], 500);
}
Log::info('Base64 image received. Decoding and saving.');
$decodedImage = base64_decode(preg_replace('#^data:image/\w+;base64, #i', '', $base64Image));
$newImageName = 'styled_' . uniqid() . '.png';
$newImagePathRelative = 'uploads/' . $newImageName;
$newImageFullPath = public_path('storage/' . $newImagePathRelative);
if (!File::exists(public_path('storage/uploads'))) {
File::makeDirectory(public_path('storage/uploads'), 0755, true);
Log::info('Created uploads directory.', ['path' => public_path('storage/uploads')]);
}
File::put($newImageFullPath, $decodedImage); // Save using File facade
Log::info('Image saved to disk.', ['path' => $newImageFullPath]);
$newImage = Image::create([
'path' => $newImagePathRelative, // Store relative path
'original_image_id' => $image->id,
'style_id' => $style->id,
'is_temp' => true,
]);
Log::info('New image record created in database.', ['image_id' => $newImage->id, 'path' => $newImage->path]);
return response()->json([
'message' => 'Styled image fetched successfully',
'styled_image' => [
'id' => $newImage->id,
'path' => asset('storage/' . $newImage->path),
'is_temp' => $newImage->is_temp,
],
]);
} catch (\Exception $e) {
Log::error('Error in fetchStyledImage: ' . $e->getMessage(), ['exception' => $e]);
return response()->json(['error' => $e->getMessage()], 500);
}
}
public function getComfyUiUrl()
{
$apiProvider = ApiProvider::where('plugin', 'comfyui')->where('enabled', true)->first();
if (!$apiProvider) {
return response()->json(['error' => 'No enabled ComfyUI API provider found.'], 404);
}
return response()->json(['comfyui_url' => rtrim($apiProvider->api_url, '/')]);
}
}