133 خطوط
5.9 KiB
PHP
133 خطوط
5.9 KiB
PHP
<?php
|
|
|
|
namespace App\Modules\Assets\Http;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Modules\Assets\Application\AssetUsage;
|
|
use App\Modules\Assets\Domain\Asset;
|
|
use App\Modules\Assets\Http\Requests\StoreAssetRequest;
|
|
use App\Modules\Identity\Application\RolePermissions;
|
|
use App\Modules\Identity\Domain\Enums\Permission;
|
|
use App\Modules\Tenancy\Application\TenantContext;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Facades\URL;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
|
|
final class AssetController extends Controller
|
|
{
|
|
public function __construct(
|
|
private readonly TenantContext $tenant,
|
|
private readonly RolePermissions $permissions,
|
|
private readonly AssetUsage $usage,
|
|
) {}
|
|
|
|
public function index(Request $request): JsonResponse
|
|
{
|
|
$this->authorizeView($request);
|
|
$request->validate(['kind' => ['nullable', 'in:image,video,audio,document'], 'search' => ['nullable', 'string', 'max:120']]);
|
|
$counts = $this->usage->counts($this->tenant->id());
|
|
$assets = Asset::query()->where('organization_id', $this->tenant->id())
|
|
->when($request->filled('kind'), fn ($query) => $query->where('kind', $request->string('kind')))
|
|
->when($request->filled('search'), function ($query) use ($request) {
|
|
$search = '%'.str_replace(['%', '_'], ['\\%', '\\_'], $request->string('search')).'%';
|
|
$query->where('original_name', 'like', $search);
|
|
})->latest()->limit(200)->get()->map(fn (Asset $asset) => $this->payload($asset, $counts[$asset->getKey()] ?? 0));
|
|
|
|
return response()->json(['data' => $assets]);
|
|
}
|
|
|
|
public function store(StoreAssetRequest $request): JsonResponse
|
|
{
|
|
$this->authorizeManage($request);
|
|
$file = $request->file('file');
|
|
$hash = hash_file('sha256', $file->getRealPath());
|
|
$existing = Asset::query()->where('organization_id', $this->tenant->id())->where('sha256', $hash)->first();
|
|
if ($existing) {
|
|
return response()->json(['data' => $this->payload($existing, $this->usage->counts($this->tenant->id())[$existing->getKey()] ?? 0)]);
|
|
}
|
|
|
|
$kind = $this->kind((string) $file->getMimeType());
|
|
$asset = new Asset([
|
|
'organization_id' => $this->tenant->id(), 'uploaded_by' => $request->user()->getKey(),
|
|
'kind' => $kind, 'original_name' => $file->getClientOriginalName(), 'disk' => 'local',
|
|
'mime_type' => (string) $file->getMimeType(), 'size' => $file->getSize(), 'sha256' => $hash,
|
|
'alt_text' => $request->validated('altText'), 'metadata' => null,
|
|
]);
|
|
$asset->id = (string) Str::ulid();
|
|
$asset->path = $file->storeAs("assets/{$this->tenant->id()}/{$asset->getKey()}", $file->hashName(), 'local');
|
|
$asset->save();
|
|
|
|
return response()->json(['data' => $this->payload($asset, 0)], 201);
|
|
}
|
|
|
|
public function show(Request $request, string $asset): JsonResponse
|
|
{
|
|
$this->authorizeView($request);
|
|
$model = Asset::query()->where('organization_id', $this->tenant->id())->findOrFail($asset);
|
|
$usageCount = $this->usage->counts($this->tenant->id())[$model->getKey()] ?? 0;
|
|
|
|
return response()->json(['data' => $this->payload($model, $usageCount)]);
|
|
}
|
|
|
|
public function destroy(Request $request, string $asset): JsonResponse
|
|
{
|
|
$this->authorizeManage($request);
|
|
$data = $request->validate(['detach' => ['nullable', 'boolean']]);
|
|
$model = Asset::query()->where('organization_id', $this->tenant->id())->findOrFail($asset);
|
|
$usageCount = $this->usage->counts($this->tenant->id())[$model->getKey()] ?? 0;
|
|
if ($usageCount > 0 && ! ($data['detach'] ?? false)) {
|
|
throw ValidationException::withMessages(['asset' => ['This asset is used by course content and cannot be deleted.']]);
|
|
}
|
|
$disk = $model->disk;
|
|
$path = $model->path;
|
|
DB::transaction(function () use ($model, $usageCount): void {
|
|
if ($usageCount > 0) {
|
|
$this->usage->detach($this->tenant->id(), (string) $model->getKey());
|
|
}
|
|
$model->delete();
|
|
});
|
|
Storage::disk($disk)->delete($path);
|
|
|
|
return response()->json(status: 204);
|
|
}
|
|
|
|
public function content(Request $request, string $asset): StreamedResponse
|
|
{
|
|
abort_unless($request->hasValidRelativeSignature(), 403);
|
|
$model = Asset::query()->findOrFail($asset);
|
|
abort_unless(Storage::disk($model->disk)->exists($model->path), 404);
|
|
|
|
return Storage::disk($model->disk)->response($model->path, $model->original_name, ['Content-Type' => $model->mime_type, 'X-Content-Type-Options' => 'nosniff']);
|
|
}
|
|
|
|
private function payload(Asset $asset, int $usageCount): array
|
|
{
|
|
return [
|
|
'id' => $asset->getKey(), 'kind' => $asset->kind, 'name' => $asset->original_name,
|
|
'mimeType' => $asset->mime_type, 'size' => $asset->size, 'altText' => $asset->alt_text,
|
|
'usageCount' => $usageCount, 'createdAt' => $asset->created_at?->toISOString(),
|
|
'contentUrl' => URL::temporarySignedRoute('assets.content', now()->addMinutes(10), ['asset' => $asset->getKey()], absolute: false),
|
|
];
|
|
}
|
|
|
|
private function kind(string $mime): string
|
|
{
|
|
return str_starts_with($mime, 'image/') ? 'image' : (str_starts_with($mime, 'video/') ? 'video' : (str_starts_with($mime, 'audio/') ? 'audio' : 'document'));
|
|
}
|
|
|
|
private function authorizeView(Request $request): void
|
|
{
|
|
abort_unless($this->permissions->allows($request->user(), Permission::CoursesAuthor), 403);
|
|
}
|
|
|
|
private function authorizeManage(Request $request): void
|
|
{
|
|
$this->authorizeView($request);
|
|
}
|
|
}
|