Files
laravel-manager-packagist/src/Modules/Media/MediaController.php
T

153 lines
5.3 KiB
PHP

<?php
namespace IriksIT\Manager\Modules\Media;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Models\Media;
use IriksIT\Manager\Support\AuditTrail;
/**
* The media library. The library (also when opened as a picker from another form) loads and
* changes its items through these JSON actions.
*/
class MediaController
{
private const UNAVAILABLE = 'The file storage is not available right now. Try again in a moment.';
public function __construct(private readonly MediaLibrary $library) {}
public function index(): JsonResponse
{
return response()->json($this->limits());
}
public function items(): JsonResponse
{
$media = Media::query()->with('uploader')->latest()->latest('id')->get();
$usage = $this->library->usageCounts($media);
return response()->json([
'items' => $media->map(fn (Media $item) => $item->toLibraryItem($usage[$item->id] ?? 0))->values(),
...$this->limits(),
]);
}
public function store(Request $request): JsonResponse
{
$request->validate([
'file' => ['required', 'file', 'mimes:'.implode(',', $this->extensions()), 'max:'.($this->maxMegabytes() * 1024)],
...$this->focusRules(),
]);
$file = $request->file('file');
abort_unless($file instanceof UploadedFile, 422);
$room = $this->library->room();
if ($file->getSize() > $room['left']) {
$message = 'The media library is full: this file does not fit in the room that is left. Remove files that are no longer used, or raise manager.media.max_total_gb.';
return response()->json(['message' => $message, 'errors' => ['file' => [$message]], 'storage' => $room], 422);
}
try {
$media = $this->library->store($file, $request->user());
} catch (MediaStorageException $e) {
return $this->unavailable($e);
}
if ($media->isImage()) {
$media->update($this->focus($request));
}
return response()->json(['item' => $media->load('uploader')->toLibraryItem(), 'storage' => $this->library->room()], 201);
}
public function update(Request $request, string $media): JsonResponse
{
$media = Media::query()->findOrFail($media);
app(AuditTrail::class)->about($media);
$request->validate([
'name' => ['required', 'string', 'max:250'],
'alt' => ['nullable', 'string', 'max:500'],
...$this->focusRules(),
]);
$alt = $request->string('alt')->trim()->toString();
$media->update([
'name' => $request->string('name')->trim()->toString(),
'alt' => $alt !== '' ? $alt : null,
// Only when the request says something about it; renaming keeps the focus point.
...($media->isImage() && $request->has('focus_x') ? $this->focus($request) : []),
]);
$usage = $this->library->usageCounts([$media]);
return response()->json(['item' => $media->load('uploader')->toLibraryItem($usage[$media->id] ?? 0)]);
}
public function destroy(string $media): JsonResponse
{
$media = Media::query()->findOrFail($media);
app(AuditTrail::class)->about($media);
try {
$this->library->delete($media);
} catch (MediaStorageException $e) {
return $this->unavailable($e);
}
return response()->json(['deleted' => true, 'storage' => $this->library->room()]);
}
/** @return array<string, list<string>> */
private function focusRules(): array
{
return [
'focus_x' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_y'],
'focus_y' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_x'],
];
}
/** @return array{focus_x: float|null, focus_y: float|null} both null when none was sent */
private function focus(Request $request): array
{
$x = $request->input('focus_x');
$y = $request->input('focus_y');
$set = is_numeric($x) && is_numeric($y);
return ['focus_x' => $set ? round((float) $x, 4) : null, 'focus_y' => $set ? round((float) $y, 4) : null];
}
/** The reason goes to the log; the browser only hears that it did not work. */
private function unavailable(MediaStorageException $e): JsonResponse
{
Log::warning('Media storage failed.', ['error' => $e->getMessage(), 'status' => $e->status]);
return response()->json(['message' => self::UNAVAILABLE], 502);
}
/** @return array{max_file_mb: int, extensions: list<string>, storage: array{used: int, limit: int, left: int}} */
private function limits(): array
{
return ['max_file_mb' => $this->maxMegabytes(), 'extensions' => $this->extensions(), 'storage' => $this->library->room()];
}
private function maxMegabytes(): int
{
return max(1, config()->integer('manager.media.max_file_mb'));
}
/** @return list<string> */
private function extensions(): array
{
return array_values(array_filter(config()->array('manager.media.extensions'), 'is_string'));
}
}