Media module, users hardening, README and token ledger
This commit is contained in:
1 parent
f86f5aea28
commit
9f2a21fa1f
22 files changed
+827
-24
No files matched your search
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* The storage behind the media library could not store, return or delete a file.
|
||||
* `status` is 404 when the file is gone, 0 otherwise.
|
||||
*/
|
||||
class MediaStorageException extends RuntimeException
|
||||
{
|
||||
public function __construct(string $message, public readonly int $status = 0, public readonly ?int $retryAfter = null)
|
||||
{
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager');
|
||||
|
||||
$this->app->singleton(Support\MediaUsage::class);
|
||||
|
||||
$this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry(
|
||||
$app['config']->get('manager.available', []),
|
||||
$app['config']->get('manager.modules', []),
|
||||
|
||||
@@ -2,10 +2,90 @@
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* One file in the media library. The row is the bookkeeping; the file itself is stored on the
|
||||
* filesystem disk `disk` under `location`.
|
||||
*/
|
||||
class Media extends Model
|
||||
{
|
||||
protected $hidden = ['disk', 'location'];
|
||||
|
||||
public function getTable(): string
|
||||
{
|
||||
return config('manager.table_prefix').'media';
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['size' => 'integer', 'width' => 'integer', 'height' => 'integer', 'focus_x' => 'float', 'focus_y' => 'float'];
|
||||
}
|
||||
|
||||
public function uploader(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(config('manager.user_model'), 'uploaded_by');
|
||||
}
|
||||
|
||||
public function isImage(): bool
|
||||
{
|
||||
return str_starts_with($this->mime_type, 'image/');
|
||||
}
|
||||
|
||||
/**
|
||||
* The start of this file's address. It holds the id, so it stays the same when the file is
|
||||
* renamed, and is what content is searched for to see where a file is used.
|
||||
*/
|
||||
public function urlPrefix(): string
|
||||
{
|
||||
return '/media-files/'.$this->id.'/';
|
||||
}
|
||||
|
||||
/**
|
||||
* The address visitors load the file from. It ends in /view on purpose: web servers tend to
|
||||
* answer anything that ends in .jpg themselves, as a file on disk, and never ask the app.
|
||||
*/
|
||||
public function url(): string
|
||||
{
|
||||
return $this->urlPrefix().rawurlencode($this->filename).'/view';
|
||||
}
|
||||
|
||||
/**
|
||||
* The focus point of the image behind an address from the library, as a CSS `object-position`
|
||||
* value ("30% 65%"). Null for any other address, or when no focus point was set.
|
||||
*/
|
||||
public static function focusFor(?string $url): ?string
|
||||
{
|
||||
if ($url === null || preg_match('#^/media-files/(\d+)/#', $url, $match) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$media = static::query()->whereKey((int) $match[1])->whereNotNull('focus_x')->whereNotNull('focus_y')->first(['id', 'focus_x', 'focus_y']);
|
||||
|
||||
return $media instanceof self
|
||||
? round((float) $media->focus_x * 100, 2).'% '.round((float) $media->focus_y * 100, 2).'%'
|
||||
: null;
|
||||
}
|
||||
|
||||
/** What the manager shows. Never includes where the file is stored. */
|
||||
public function toLibraryItem(int $usageCount = 0): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'filename' => $this->filename,
|
||||
'url' => $this->url(),
|
||||
'mime_type' => $this->mime_type,
|
||||
'is_image' => $this->isImage(),
|
||||
'size' => $this->size,
|
||||
'width' => $this->width,
|
||||
'height' => $this->height,
|
||||
'alt' => $this->alt,
|
||||
'focus_x' => $this->focus_x,
|
||||
'focus_y' => $this->focus_y,
|
||||
'uploaded_by' => $this->uploader?->name,
|
||||
'created_at' => $this->created_at?->toIso8601String(),
|
||||
'usage_count' => $usageCount,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,148 @@
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
/** First opzet: lists the records as JSON. The screens come with the frontend. */
|
||||
public function index()
|
||||
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(Media::query()->latest()->paginate(25));
|
||||
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);
|
||||
|
||||
$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);
|
||||
|
||||
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'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Media;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/** Passes a media file on to the browser, with ETag and byte ranges (video needs them). */
|
||||
class MediaFileController
|
||||
{
|
||||
/**
|
||||
* Types a browser may show as they are. Anything else is offered as a download, so a
|
||||
* stored file can never run as a page on this domain.
|
||||
*/
|
||||
private const array INLINE_TYPES = [
|
||||
'image/jpeg', 'image/png', 'image/webp', 'image/gif',
|
||||
'video/mp4', 'video/webm',
|
||||
'application/pdf',
|
||||
];
|
||||
|
||||
public function __invoke(Request $request, MediaLibrary $library, string $media): Response
|
||||
{
|
||||
$media = Media::query()->findOrFail((int) $media);
|
||||
|
||||
$headers = $this->headers($media);
|
||||
|
||||
// A media id never gets other content, so what the browser has is still right.
|
||||
if (in_array($headers['ETag'], $request->getETags(), true)) {
|
||||
return response('', 304, $headers);
|
||||
}
|
||||
|
||||
$range = $this->range($request, $media->size);
|
||||
|
||||
if ($range === null) {
|
||||
return response('', 416, ['Content-Range' => "bytes */{$media->size}"] + $headers);
|
||||
}
|
||||
|
||||
[$start, $end, $partial] = $range;
|
||||
$length = $end - $start + 1;
|
||||
|
||||
$headers['Content-Length'] = (string) $length;
|
||||
|
||||
if ($partial) {
|
||||
$headers['Content-Range'] = "bytes {$start}-{$end}/{$media->size}";
|
||||
}
|
||||
|
||||
if ($request->isMethod('HEAD')) {
|
||||
return response('', $partial ? 206 : 200, $headers);
|
||||
}
|
||||
|
||||
try {
|
||||
$stream = $library->open($media);
|
||||
} catch (MediaStorageException $e) {
|
||||
if ($e->status === 404) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return response('This file is temporarily unavailable.', 503, ['Retry-After' => (string) ($e->retryAfter ?? 30), 'Cache-Control' => 'no-store']);
|
||||
}
|
||||
|
||||
return response()->stream(fn () => $this->send($stream, $start, $length), $partial ? 206 : 200, $headers);
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
private function headers(Media $media): array
|
||||
{
|
||||
$inline = in_array($media->mime_type, self::INLINE_TYPES, true);
|
||||
$name = str_replace(['"', '\\', "\r", "\n"], '', $media->filename);
|
||||
|
||||
return [
|
||||
'Content-Type' => $inline ? $media->mime_type : 'application/octet-stream',
|
||||
'Content-Disposition' => ($inline ? 'inline' : 'attachment').'; filename="'.$name.'"',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Accept-Ranges' => 'bytes',
|
||||
'Cache-Control' => 'public, max-age=31536000, immutable',
|
||||
'ETag' => '"'.($media->checksum ?? 'media-'.$media->id).'"',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The part of the file the browser asks for: [first byte, last byte, is it a part].
|
||||
* Null when the request asks for bytes the file does not have.
|
||||
*
|
||||
* @return array{int, int, bool}|null
|
||||
*/
|
||||
private function range(Request $request, int $size): ?array
|
||||
{
|
||||
$header = $request->headers->get('Range');
|
||||
$whole = [0, max($size - 1, 0), false];
|
||||
|
||||
// No range, an empty file, or something other than one plain byte range: send it all.
|
||||
if ($header === null || $size === 0 || preg_match('/^bytes=(\d*)-(\d*)$/', trim($header), $match) !== 1) {
|
||||
return $whole;
|
||||
}
|
||||
|
||||
[, $first, $last] = $match;
|
||||
|
||||
if ($first === '' && $last === '') {
|
||||
return $whole;
|
||||
}
|
||||
|
||||
if ($first === '') {
|
||||
// "bytes=-500": the last 500 bytes.
|
||||
$start = max($size - (int) $last, 0);
|
||||
$end = $size - 1;
|
||||
} else {
|
||||
$start = (int) $first;
|
||||
$end = $last === '' ? $size - 1 : min((int) $last, $size - 1);
|
||||
}
|
||||
|
||||
if ($start >= $size || $start > $end) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [$start, $end, true];
|
||||
}
|
||||
|
||||
/** @param resource $stream */
|
||||
private function send($stream, int $start, int $length): void
|
||||
{
|
||||
try {
|
||||
if ($start > 0 && stream_get_meta_data($stream)['seekable']) {
|
||||
fseek($stream, $start);
|
||||
} else {
|
||||
$skip = $start;
|
||||
|
||||
while ($skip > 0 && ! feof($stream)) {
|
||||
$chunk = fread($stream, min(65536, $skip));
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
break;
|
||||
}
|
||||
|
||||
$skip -= strlen($chunk);
|
||||
}
|
||||
}
|
||||
|
||||
while ($length > 0 && ! feof($stream)) {
|
||||
$chunk = fread($stream, min(65536, $length));
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
break;
|
||||
}
|
||||
|
||||
echo $chunk;
|
||||
flush();
|
||||
|
||||
$length -= strlen($chunk);
|
||||
}
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Media;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Support\MediaUsage;
|
||||
|
||||
/**
|
||||
* The one place that knows where media files physically are. Everything else works with Media
|
||||
* rows and their URLs. New uploads go to the disk in config('manager.media.disk'); an existing
|
||||
* file is always read from and deleted on the disk its own row names.
|
||||
*/
|
||||
class MediaLibrary
|
||||
{
|
||||
public function __construct(private readonly MediaUsage $usage) {}
|
||||
|
||||
/** @throws MediaStorageException */
|
||||
public function store(UploadedFile $file, ?Authenticatable $uploader = null, ?string $disk = null): Media
|
||||
{
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
$baseName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
|
||||
$filename = (Str::slug($baseName) ?: 'file').($extension !== '' ? '.'.$extension : '');
|
||||
$path = $file->getRealPath();
|
||||
|
||||
if ($path === false) {
|
||||
throw new MediaStorageException('The uploaded file could not be read.');
|
||||
}
|
||||
|
||||
$mimeType = $file->getMimeType() ?? 'application/octet-stream';
|
||||
$dimensions = str_starts_with($mimeType, 'image/') ? @getimagesize($path) : false;
|
||||
$disk ??= config('manager.media.disk');
|
||||
|
||||
$location = $file->store('media/'.now()->format('Y/m'), $disk);
|
||||
|
||||
if ($location === false) {
|
||||
throw new MediaStorageException('The file could not be stored.');
|
||||
}
|
||||
|
||||
return Media::create([
|
||||
'disk' => $disk,
|
||||
'location' => $location,
|
||||
'name' => Str::limit(trim($baseName) !== '' ? trim($baseName) : 'File', 250, ''),
|
||||
'filename' => $filename,
|
||||
'mime_type' => $mimeType,
|
||||
'size' => (int) $file->getSize(),
|
||||
'checksum' => hash_file('sha256', $path) ?: null,
|
||||
'width' => $dimensions !== false ? $dimensions[0] : null,
|
||||
'height' => $dimensions !== false ? $dimensions[1] : null,
|
||||
'uploaded_by' => $uploader?->getAuthIdentifier(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* How full the library is: what all files together take, how much it may hold
|
||||
* (`manager.media.max_total_gb`) and what is left. In bytes.
|
||||
*
|
||||
* @return array{used: int, limit: int, left: int}
|
||||
*/
|
||||
public function room(): array
|
||||
{
|
||||
$configured = config('manager.media.max_total_gb');
|
||||
$limit = (int) round((is_numeric($configured) ? max(0.0, (float) $configured) : 15.0) * 1_000_000_000);
|
||||
$used = (int) Media::query()->sum('size');
|
||||
|
||||
return ['used' => $used, 'limit' => $limit, 'left' => max(0, $limit - $used)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a file's content as a stream. Read it and close it.
|
||||
*
|
||||
* @return resource
|
||||
*
|
||||
* @throws MediaStorageException with status 404 when the file is gone
|
||||
*/
|
||||
public function open(Media $media)
|
||||
{
|
||||
$stream = Storage::disk($media->disk)->readStream($media->location);
|
||||
|
||||
if (! is_resource($stream)) {
|
||||
throw new MediaStorageException('The file is no longer there.', 404);
|
||||
}
|
||||
|
||||
return $stream;
|
||||
}
|
||||
|
||||
/** Delete the file and then its row. When the storage refuses, the row stays. */
|
||||
public function delete(Media $media): void
|
||||
{
|
||||
$disk = Storage::disk($media->disk);
|
||||
|
||||
if ($disk->exists($media->location) && ! $disk->delete($media->location)) {
|
||||
throw new MediaStorageException('The file could not be deleted.');
|
||||
}
|
||||
|
||||
$media->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* How often each media file is used, keyed by media id: how many of the registered sources
|
||||
* (MediaUsage) hold its address. Nothing registered means 0.
|
||||
*
|
||||
* @param iterable<Media> $items
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function usageCounts(iterable $items): array
|
||||
{
|
||||
$haystacks = $this->usage->haystacks();
|
||||
$counts = [];
|
||||
|
||||
foreach ($items as $media) {
|
||||
$prefix = $media->urlPrefix();
|
||||
$counts[$media->id] = count(array_filter($haystacks, fn (string $text) => str_contains($text, $prefix)));
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace IriksIT\Manager\Modules\Media;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
@@ -38,4 +41,9 @@ class MediaModule extends BaseModule
|
||||
['label' => 'Media', 'route' => 'manager.media.index', 'permission' => 'media.view'],
|
||||
];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
RateLimiter::for('media-files', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.media.per_minute', 600)))->by((string) $request->ip()));
|
||||
}
|
||||
}
|
||||
@@ -8,18 +8,26 @@ return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create(config('manager.table_prefix').'media', function (Blueprint $table) {
|
||||
$users = (new (config('manager.user_model')))->getTable();
|
||||
|
||||
// The file itself is elsewhere: `disk` says where, `location` is its path there.
|
||||
Schema::create(config('manager.table_prefix').'media', function (Blueprint $table) use ($users) {
|
||||
$table->id();
|
||||
$table->string('disk');
|
||||
$table->string('path');
|
||||
$table->string('disk', 40);
|
||||
$table->string('location');
|
||||
$table->string('name');
|
||||
$table->string('filename');
|
||||
$table->string('mime_type');
|
||||
$table->string('mime_type', 100);
|
||||
$table->unsignedBigInteger('size');
|
||||
$table->string('checksum', 64)->nullable();
|
||||
$table->unsignedInteger('width')->nullable();
|
||||
$table->unsignedInteger('height')->nullable();
|
||||
$table->string('title')->nullable();
|
||||
$table->text('description')->nullable();
|
||||
$table->unsignedBigInteger('uploaded_by')->nullable()->index();
|
||||
$table->string('alt', 500)->nullable();
|
||||
// The part of an image that must stay in view when it is cropped to fit:
|
||||
// 0-1 from the left and from the top.
|
||||
$table->decimal('focus_x', 5, 4)->nullable();
|
||||
$table->decimal('focus_y', 5, 4)->nullable();
|
||||
$table->foreignId('uploaded_by')->nullable()->constrained($users)->nullOnDelete();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Media\MediaFileController;
|
||||
|
||||
// Files of the media library, for visitors. No session and no cookies: this is a file, not a
|
||||
// page, and the browser may cache it for good. The address ends in /view on purpose: web servers
|
||||
// tend to answer anything that ends in .jpg themselves and never ask the app.
|
||||
Route::get('/media-files/{media}/{filename}/view', MediaFileController::class)
|
||||
->whereNumber('media')
|
||||
->middleware('throttle:media-files')
|
||||
->name('manager.media.file');
|
||||
@@ -4,3 +4,7 @@ use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Media\MediaController;
|
||||
|
||||
Route::get('/media', [MediaController::class, 'index'])->name('media.index')->middleware('can:media.view');
|
||||
Route::get('/media/items', [MediaController::class, 'items'])->name('media.items')->middleware('can:media.view');
|
||||
Route::post('/media', [MediaController::class, 'store'])->name('media.store')->middleware('can:media.upload');
|
||||
Route::put('/media/{media}', [MediaController::class, 'update'])->name('media.update')->middleware('can:media.edit')->whereNumber('media');
|
||||
Route::delete('/media/{media}', [MediaController::class, 'destroy'])->name('media.destroy')->middleware('can:media.delete')->whereNumber('media');
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace IriksIT\Manager\Modules\Pages;
|
||||
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\MediaUsage;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
class PagesModule extends BaseModule
|
||||
@@ -35,4 +37,10 @@ class PagesModule extends BaseModule
|
||||
['label' => 'Pages', 'route' => 'manager.pages.index', 'permission' => 'pages.edit'],
|
||||
];
|
||||
}
|
||||
|
||||
/** Where the media library looks for the use of a file: the texts of the pages. */
|
||||
public function boot(): void
|
||||
{
|
||||
app(MediaUsage::class)->register(fn () => Page::query()->get(['body'])->flatMap(fn (Page $row) => array_values($row->only(['body']))));
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace IriksIT\Manager\Modules\Posts;
|
||||
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\MediaUsage;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
class PostsModule extends BaseModule
|
||||
@@ -38,4 +40,10 @@ class PostsModule extends BaseModule
|
||||
['label' => 'Posts', 'route' => 'manager.posts.index', 'permission' => 'posts.view'],
|
||||
];
|
||||
}
|
||||
|
||||
/** Where the media library looks for the use of a file: the texts of the posts. */
|
||||
public function boot(): void
|
||||
{
|
||||
app(MediaUsage::class)->register(fn () => Post::query()->get(['body', 'excerpt'])->flatMap(fn (Post $row) => array_values($row->only(['body', 'excerpt']))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* Where media is used. A module or the host app registers a source: a closure that returns the
|
||||
* texts which may contain the address of a media file (a post body, a cover, a page text).
|
||||
* The media library counts the files whose address appears in them. No sources, no counts.
|
||||
*/
|
||||
final class MediaUsage
|
||||
{
|
||||
/** @var list<Closure(): iterable<mixed>> */
|
||||
private array $sources = [];
|
||||
|
||||
/** @param Closure(): iterable<mixed> $source */
|
||||
public function register(Closure $source): void
|
||||
{
|
||||
$this->sources[] = $source;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function haystacks(): array
|
||||
{
|
||||
$texts = [];
|
||||
|
||||
foreach ($this->sources as $source) {
|
||||
foreach ($source() as $text) {
|
||||
$texts[] = is_string($text) ? $text : '';
|
||||
}
|
||||
}
|
||||
|
||||
return $texts;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user