Files
laraundfelix/app/Http/Controllers/Member/LibraryController.php
LarsandCursor 1fb48783bf
Deploy Test / test (push) Successful in 25s
Deploy Test / deploy (push) Successful in 27s
Spiele Filme in allen Playern über die gespeicherte Qualitätsleiter.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 21:48:33 +01:00

390 lines
14 KiB
PHP

<?php
namespace App\Http\Controllers\Member;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\EditorialDimension;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Entitlement\DecideAccess;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus;
use App\Domain\Media\DeliveryLog;
use App\Domain\Media\FilmPlayback;
use App\Domain\Media\HlsPlaylist;
use App\Domain\Media\MediaRendition;
use App\Http\Controllers\Controller;
use App\Http\CourseOutline;
use App\Http\LibraryCatalog;
use App\Http\SignedLink;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
class LibraryController extends Controller
{
public function index(Request $request, ?string $sicht = null): View
{
$catalog = app(LibraryCatalog::class)->index($request->user());
$untouched = $catalog['programs'] === [] && $catalog['modules'] === [] && $catalog['materials'] === [];
$query = trim((string) $request->query('q', ''));
$nutzung = (string) $request->query('nutzung', '');
$dimensionIds = array_values(array_filter(array_map(intval(...), (array) $request->query('dimension', []))));
$dimensions = app(IdentityDimension::class);
foreach (['programs', 'modules'] as $shelf) {
if ($query !== '') {
$catalog[$shelf] = array_values(array_filter(
$catalog[$shelf],
fn (array $card): bool => $this->matches($card, $query),
));
}
if ($dimensionIds !== []) {
$catalog[$shelf] = array_values(array_filter(
$catalog[$shelf],
fn (array $card): bool => $dimensions->matches($card['composition'], $dimensionIds),
));
}
if (in_array($nutzung, ['nutzbar', 'teilweise', 'nicht enthalten'], true)) {
$catalog[$shelf] = array_values(array_filter(
$catalog[$shelf],
fn (array $card): bool => ($card['coverage'] ?? '') === $nutzung,
));
}
}
if ($query !== '') {
$catalog['materials'] = array_values(array_filter(
$catalog['materials'],
fn (array $card): bool => $this->matches($card, $query),
));
}
if ($dimensionIds !== []) {
$catalog['materials'] = array_values(array_filter(
$catalog['materials'],
function (array $card) use ($dimensions, $dimensionIds): bool {
$release = $card['article']->currentRelease;
$subject = $release?->rootCompositionVersion?->composition
?? $release?->rootElementVersion?->element
?? $card['article'];
return $dimensions->matches($subject, $dimensionIds);
},
));
}
if ($nutzung === 'teilweise' || $nutzung === 'nicht enthalten') {
$catalog['materials'] = [];
}
return view('member.library', [
...$catalog,
'query' => $query,
'sicht' => $sicht,
'nutzung' => $nutzung,
'dimensionIds' => $dimensionIds,
'filterDimensions' => EditorialDimension::query()->with('values')->orderBy('label')->get(),
'libraryEmpty' => $untouched,
]);
}
public function programs(Request $request): View
{
return $this->index($request, 'programme');
}
public function modules(Request $request): View
{
return $this->index($request, 'module');
}
public function program(Request $request, Composition $composition): View
{
return view('member.program', app(LibraryCatalog::class)->program($request->user(), $composition));
}
public function materials(Request $request): View
{
return view('member.materials', [
'grants' => $this->grantQuery($request)->with('article.currentRelease.contents.elementVersion.element')->get(),
]);
}
public function grants(Request $request): View
{
return view('member.grants', [
'grants' => $this->grantQuery($request)->get(),
]);
}
public function show(Request $request, LicenseArticle $article): View
{
$release = $article->currentRelease()->with('contents.elementVersion.element.pillars')->first();
$entries = [];
if ($release !== null) {
foreach ($release->contents as $content) {
$version = $content->elementVersion;
$class = $version->element->output_class;
$metadata = is_array($version->metadata) ? $version->metadata : [];
$action = $class === 'film' || $class === 'audio' ? 'streamen' : 'ansehen';
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, $action);
$file = $metadata['file'] ?? null;
$entries[] = [
'content' => $content,
'version' => $version,
'role' => $content->role,
'action' => $action,
'allowed' => $decision->allowed,
'reason' => $decision->reason,
'decision' => is_numeric($metadata['decision_seconds'] ?? null)
? (int) $metadata['decision_seconds']
: null,
'playable' => $decision->allowed && is_string($file) && $file !== '' && ($class === 'film' || $class === 'audio'),
'playback' => app(FilmPlayback::class)->mode($version->id),
'pillars' => $version->element->pillars->pluck('name')->all(),
'url' => $decision->allowed
? SignedLink::temporary('member.media', now()->addMinutes(10), [
'article' => $article->id,
'release' => $release->id,
'version' => $version->id,
'action' => $action,
'reader' => $request->user()->id,
])
: null,
];
}
}
return view('member.article', [
'article' => $article,
'release' => $release,
'entries' => $entries,
'title' => app(CourseOutline::class)->title($article),
'kind' => app(CourseOutline::class)->kindLabel($article),
]);
}
public function media(
Request $request,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
string $action,
): View|StreamedResponse|Response {
abort_unless(in_array($action, ['ansehen', 'streamen', 'laden'], true), 404);
abort_unless((int) $request->query('reader') === $request->user()->id, 403);
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, $action);
abort_unless($decision->allowed && $decision->grant !== null, 403, $decision->reason);
$version->loadMissing('element');
$master = $action === 'streamen' ? MediaRendition::masterPath($version->id) : null;
if (is_string($master)) {
return $this->playlist($request, $article, $release, $version, $decision->grant, $master);
}
$file = $version->metadata['file'] ?? null;
if (! is_string($file) || $file === '' || str_contains($file, '..')) {
$delivery = app(DeliveryLog::class)->write(
$decision->grant,
$article,
$release,
$version,
$action,
'text',
hash('sha256', (string) $version->body),
'k2',
);
return view('member.read', [
'article' => $article,
'version' => $version,
'license' => $decision->grant->rights_snapshot['purpose'] ?? null,
'reader' => $request->user()->name,
'copy' => $delivery->copy_id,
]);
}
return $this->fileResponse($decision->grant, $article, $release, $version, $action, $file, 'bestand');
}
public function rendition(
Request $request,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
string $datei,
): Response|StreamedResponse {
abort_unless((int) $request->query('reader') === $request->user()->id, 403);
abort_unless($this->renditionBelongsTo($version->id, $datei), 404);
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, 'streamen');
abort_unless($decision->allowed && $decision->grant !== null, 403, $decision->reason);
if (str_ends_with($datei, '.m3u8')) {
return $this->playlist(
$request,
$article,
$release,
$version,
$decision->grant,
$datei,
str_ends_with($datei, 'master.m3u8'),
);
}
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($datei), 404);
return $disk->response($datei, basename($datei), ['Content-Disposition' => 'inline']);
}
public function thumbnail(Request $request, string $kind, int $subject): StreamedResponse
{
abort_unless(in_array($kind, ['komposition', 'element'], true), 404);
$model = $kind === 'komposition'
? Composition::query()->findOrFail($subject)
: ContentElement::query()->findOrFail($subject);
$path = $model->thumbnail_path;
abort_unless(is_string($path) && str_starts_with($path, 'vorschau/') && ! str_contains($path, '..'), 404);
abort_unless($this->maySeeThumbnail($request, $kind, $subject), 403);
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($path), 404);
return $disk->response($path);
}
/**
* @param array<string, mixed> $card
*/
private function matches(array $card, string $query): bool
{
$haystack = mb_strtolower(($card['title'] ?? '').' '.($card['summary'] ?? ''));
return str_contains($haystack, mb_strtolower($query));
}
private function playlist(
Request $request,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
Grant $grant,
string $path,
bool $record = true,
): Response {
abort_unless($this->renditionBelongsTo($version->id, $path), 404);
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($path), 404);
$rewritten = app(HlsPlaylist::class)->rewrite(
$disk->get($path),
$path,
fn (string $target): string => SignedLink::temporary('member.rendition', now()->addMinutes(10), [
'article' => $article->id,
'release' => $release->id,
'version' => $version->id,
'datei' => $target,
'reader' => $request->user()->id,
]),
);
$copy = '';
if ($record) {
$delivery = app(DeliveryLog::class)->write(
$grant,
$article,
$release,
$version,
'streamen',
'hls',
hash('sha256', $rewritten),
'k0',
);
$copy = $delivery->copy_id;
}
return response($rewritten, 200, [
'Content-Type' => 'application/vnd.apple.mpegurl',
'X-License-Copy' => $copy,
]);
}
private function fileResponse(
Grant $grant,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
string $action,
string $file,
string $format,
): StreamedResponse {
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($file) && ! str_contains($file, '..'), 404);
$delivery = app(DeliveryLog::class)->write(
$grant,
$article,
$release,
$version,
$action,
$format,
hash_file('sha256', $disk->path($file)) ?: null,
'k0',
);
return $disk->response($file, basename($file), [
'Content-Disposition' => $action === 'laden' ? 'attachment' : 'inline',
'X-License-Copy' => $delivery->copy_id,
]);
}
private function renditionBelongsTo(int $versionId, string $path): bool
{
$prefix = 'ableitungen/'.$versionId;
return ($path === $prefix || str_starts_with($path, $prefix.'/')) && ! str_contains($path, '..');
}
private function maySeeThumbnail(Request $request, string $kind, int $subject): bool
{
$grants = $this->grantQuery($request)->with('article.currentRelease.contents.elementVersion', 'article.currentRelease.rootCompositionVersion')->get();
foreach ($grants as $grant) {
$release = $grant->article->currentRelease;
if ($release === null) {
continue;
}
if ($kind === 'komposition' && $release->rootCompositionVersion?->composition_id === $subject) {
return true;
}
if ($kind === 'element' && $release->contents->contains(
fn ($content): bool => $content->elementVersion?->content_element_id === $subject,
)) {
return true;
}
}
return false;
}
private function grantQuery(Request $request)
{
return Grant::query()
->where('status', GrantStatus::Aktiv)
->whereHas('acquisition', fn ($query) => $query->where('party_id', $request->user()->party_id))
->with('article.currentRelease')
->orderBy('id');
}
}