From 1c509e31c2cd9d2d83f289d0259012958fe66f8c Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sat, 7 Nov 2026 15:08:12 +0100 Subject: [PATCH] Add YouTube video slide type Admins paste a YouTube link (watch, youtu.be, shorts, live, embed). The link is checked via oEmbed on save and with a "check link" button (not found / not embeddable is rejected, unreachable saves with a warning). Start time can be entered or is taken from the link's timecode; autoplay is optional. The presenter embeds the video via youtube-nocookie.com; participants get the link plus a share button (Web Share API, falls back to copying). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 14 +- config/routes.php | 2 + src/Controller/SlidesController.php | 98 +++++++- src/Model/Entity/Slide.php | 42 +++- src/Model/Table/SlidesTable.php | 14 ++ src/Service/PollStateService.php | 5 + src/Service/YouTubeService.php | 234 ++++++++++++++++++ templates/Admin/present.php | 1 + templates/Participate/view.php | 23 ++ templates/Slides/form.php | 73 +++++- .../TestCase/Controller/YouTubeSlideTest.php | 184 ++++++++++++++ tests/TestCase/Service/YouTubeServiceTest.php | 115 +++++++++ webroot/css/plenario.css | 15 ++ webroot/js/plenario.js | 176 +++++++++++-- 14 files changed, 972 insertions(+), 24 deletions(-) create mode 100644 src/Service/YouTubeService.php create mode 100644 tests/TestCase/Controller/YouTubeSlideTest.php create mode 100644 tests/TestCase/Service/YouTubeServiceTest.php diff --git a/AGENTS.md b/AGENTS.md index 02fd63f..99080ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,8 @@ src/ HomeController Startseite, Anlegen (/create), Bestätigung, Join, Recover AdminAppController Basis für /admin/{token}: löst Poll über Token-Hash auf (404 sonst), setzt Privacy-Header AdminController Dashboard, Settings, Present, State-JSON, Control, QR, CSV-Export, Token rotieren, Löschen - SlidesController Folien-CRUD, Sortieren (Drag & Drop/Pfeiltasten via `reorder`, JSON; erfordert JS), Antworten zurücksetzen + SlidesController Folien-CRUD, Sortieren (Drag & Drop/Pfeiltasten via `reorder`, JSON; erfordert JS), Antworten zurücksetzen, + YouTube-Link prüfen (`youtubeCheck`, JSON) ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal) Model/ Polls → Slides → SlideOptions, Slides → Responses @@ -64,6 +65,7 @@ src/ ResultsService Aggregiert Ergebnisse je Folientyp (JSON-Struktur im Docblock) PollStateService State-JSON für Presenter und Teilnehmende ThrottleService Rate-Limit pro IP (Cache 'throttle') + YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client) templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email webroot/css/plenario.css Eigenes CSS, kein Framework webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Folien-Sortierung (Pointer Events + Pfeiltasten) @@ -74,7 +76,7 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures - `polls`: `title`, `email`, `admin_token_hash` (sha256), `admin_token_encrypted` (Security::encrypt), `join_code` (6 Zeichen, ohne 0/O/1/I/L), `current_slide_id`, `is_active`, `show_results_to_participants` -- `slides`: `type` (`choice|wordcloud|open|scale|content|quiz`), `question`, `description`, `position`, +- `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube`), `question`, `description`, `position`, `settings` (JSON, je Typ siehe `Slide::DEFAULT_SETTINGS`), `is_voting_open`, `voting_started_at` / `voting_ends_at` (nur Quiz: Start und Deadline, `null` = manuell beenden) - `slide_options`: Antwortoptionen für `choice` und `quiz`; `is_correct` markiert richtige Quiz-Antworten @@ -111,6 +113,14 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures - Ausgaben in Templates immer mit `h()` escapen. JS baut DOM mit `textContent`, nie `innerHTML` mit Nutzerdaten. - Routen nur benannt verwenden (`['_name' => 'admin', 'token' => $adminToken]`), keine Fallbacks einführen. +- YouTube-Folie (`youtube`): nicht interaktiv (wie `content`). Settings `url` (wie eingegeben), `video_id`, `start` (Sekunden), + `autoplay`. Startzeit-Feld leer = Timecode aus dem Link (`t`/`start`), sonst gewinnt das Feld (`1:30`, `2` = Minuten). + Beim Speichern prüft `SlidesController::prepareYouTube()` per oEmbed: nicht gefunden/nicht einbettbar = Fehler, + YouTube nicht erreichbar = speichern mit Warnung; leerer Titel wird mit dem Videotitel gefüllt. Eingebettet wird nur + im Presenter (`youtube-nocookie.com`), Teilnehmende sehen Link + Teilen-Button (Web Share API, sonst Kopieren). + Iframes brauchen `referrerpolicy="strict-origin"`, weil Admin-Seiten `no-referrer` senden und YouTube ohne Referrer + nicht abspielt (nur Origin, nie der Pfad mit Token). Tests mocken YouTube über `HttpClientTrait` (`mockClientGet`). + ### Neuen Folientyp hinzufügen (Checkliste) 1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php` diff --git a/config/routes.php b/config/routes.php index fc8de14..b8522c0 100644 --- a/config/routes.php +++ b/config/routes.php @@ -63,6 +63,8 @@ return function (RouteBuilder $routes): void { ->setPatterns($token)->setPass(['id'])->setMethods(['POST']); $admin->connect('/slides/reorder', 'Slides::reorder', ['_name' => 'slides:reorder']) ->setPatterns($token)->setMethods(['POST']); + $admin->connect('/slides/youtube-check', 'Slides::youtubeCheck', ['_name' => 'slides:youtube-check']) + ->setPatterns($token)->setMethods(['POST']); $admin->connect('/slides/{id}/reset', 'Slides::reset', ['_name' => 'slides:reset']) ->setPatterns($token)->setPass(['id'])->setMethods(['POST']); }); diff --git a/src/Controller/SlidesController.php b/src/Controller/SlidesController.php index 11548bd..f8cb81e 100644 --- a/src/Controller/SlidesController.php +++ b/src/Controller/SlidesController.php @@ -5,6 +5,7 @@ namespace App\Controller; use App\Model\Entity\Slide; use App\Model\Table\SlidesTable; +use App\Service\YouTubeService; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; @@ -208,7 +209,11 @@ class SlidesController extends AdminAppController // Quiz voting is controlled by the presenter only. $fields = array_values(array_diff($fields, ['is_voting_open'])); } + $youtube = $slide->isYouTube() ? $this->prepareYouTube($data) : ['errors' => [], 'warning' => null]; $this->Slides->patchEntity($slide, $data, ['fields' => $fields, 'associated' => []]); + foreach ($youtube['errors'] as $field => $message) { + $slide->setError($field, $message); + } $labels = SlidesTable::parseOptionLines($optionsText); $correct = []; @@ -231,15 +236,106 @@ class SlidesController extends AdminAppController return false; } - return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels, $correct): bool { + return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels, $correct, $youtube): bool { if (!$this->Slides->save($slide)) { return false; } if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz()) { $this->Slides->syncOptions($slide, $labels, $correct); } + if ($youtube['warning'] !== null) { + $this->Flash->warning($youtube['warning']); + } return true; }); } + + /** + * Checks a YouTube link (AJAX, "Link prüfen" in the slide form). Expects `url` + * and optionally `start`, answers with JSON. + * + * @return \Cake\Http\Response + */ + public function youtubeCheck(): Response + { + $this->request->allowMethod(['post']); + $url = trim((string)$this->request->getData('url', '')); + $parsed = YouTubeService::parseUrl($url); + if ($parsed === null) { + return $this->json([ + 'ok' => false, + 'message' => $url === '' ? __('Bitte gib einen YouTube-Link ein.') : $this->invalidYouTubeMessage(), + ]); + } + + $check = (new YouTubeService())->check($parsed['videoId']); + $ok = $check['status'] === YouTubeService::STATUS_OK || $check['status'] === YouTubeService::STATUS_UNREACHABLE; + $settings = SlidesTable::sanitizeSettings(Slide::TYPE_YOUTUBE, [ + 'url' => $url, + 'start' => (string)$this->request->getData('start', ''), + ]); + + return $this->json([ + 'ok' => $ok, + 'status' => $check['status'], + 'message' => YouTubeService::statusMessage($check['status']), + 'title' => $check['title'], + 'linkStart' => $parsed['start'] !== null ? YouTubeService::formatTime($parsed['start']) : null, + 'start' => YouTubeService::formatTime($settings['start']), + 'embedUrl' => $ok ? YouTubeService::embedUrl($parsed['videoId'], $settings['start']) : null, + ]); + } + + /** + * Validates the YouTube settings of the posted slide data and asks YouTube + * whether the video can be embedded. An empty title is filled with the video title. + * + * @param array $data Request data (question may be filled in) + * @return array{errors: array, warning: string|null} + */ + protected function prepareYouTube(array &$data): array + { + $settings = is_array($data['settings'] ?? null) ? $data['settings'] : []; + $url = trim((string)($settings['url'] ?? '')); + $start = trim((string)($settings['start'] ?? '')); + $errors = []; + $warning = null; + + if ($start !== '' && YouTubeService::parseStartInput($start) === null) { + $errors['youtube_start'] = __('Bitte gib die Startzeit als Minute:Sekunde an, z. B. 1:30 (oder nur die Minute).'); + } + + $parsed = YouTubeService::parseUrl($url); + if ($parsed === null) { + $errors['youtube_url'] = $url === '' ? __('Bitte gib einen YouTube-Link ein.') : $this->invalidYouTubeMessage(); + + return ['errors' => $errors, 'warning' => null]; + } + + $check = (new YouTubeService())->check($parsed['videoId']); + switch ($check['status']) { + case YouTubeService::STATUS_OK: + if (trim((string)($data['question'] ?? '')) === '' && $check['title'] !== null) { + $data['question'] = mb_substr($check['title'], 0, 500); + } + break; + case YouTubeService::STATUS_UNREACHABLE: + $warning = YouTubeService::statusMessage($check['status']) + . ' ' . __('Bitte teste das Video vor deiner Präsentation.'); + break; + default: + $errors['youtube_url'] = YouTubeService::statusMessage($check['status']); + } + + return ['errors' => $errors, 'warning' => $warning]; + } + + /** + * @return string + */ + protected function invalidYouTubeMessage(): string + { + return __('Das ist kein gültiger YouTube-Link. Kopiere die Adresse des Videos, z. B. https://www.youtube.com/watch?v=dQw4w9WgXcQ oder https://youtu.be/dQw4w9WgXcQ.'); + } } diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index 346a114..186f2cf 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace App\Model\Entity; +use App\Service\YouTubeService; use Cake\I18n\DateTime; use Cake\ORM\Entity; @@ -34,6 +35,7 @@ class Slide extends Entity public const TYPE_SCALE = 'scale'; public const TYPE_CONTENT = 'content'; public const TYPE_QUIZ = 'quiz'; + public const TYPE_YOUTUBE = 'youtube'; /** * Quiz phases, see quizPhase(). @@ -63,6 +65,8 @@ class Slide extends Entity self::TYPE_CONTENT => [], // time_limit in seconds, 0 = no limit (presenter ends the quiz) self::TYPE_QUIZ => ['time_limit' => 30], + // url as entered, video_id parsed from it, start in seconds + self::TYPE_YOUTUBE => ['url' => '', 'video_id' => '', 'start' => 0, 'autoplay' => false], ]; /** @@ -88,6 +92,7 @@ class Slide extends Entity self::TYPE_SCALE => __('Skala'), self::TYPE_QUIZ => __('Quiz'), self::TYPE_CONTENT => __('Inhaltsfolie'), + self::TYPE_YOUTUBE => __('YouTube-Video'), ]; } @@ -103,6 +108,7 @@ class Slide extends Entity self::TYPE_SCALE => __('Bewertung auf einer Skala, z. B. 1 bis 5.'), self::TYPE_QUIZ => __('Frage mit richtiger Antwort und Zeitlimit, aufgelöst wird erst am Ende.'), self::TYPE_CONTENT => __('Nur Text anzeigen, ohne Abstimmung.'), + self::TYPE_YOUTUBE => __('Video in der Präsentation abspielen, Teilnehmende bekommen den Link zum Teilen.'), ]; } @@ -121,7 +127,41 @@ class Slide extends Entity */ public function isInteractive(): bool { - return $this->type !== self::TYPE_CONTENT; + return !in_array($this->type, [self::TYPE_CONTENT, self::TYPE_YOUTUBE], true); + } + + /** + * @return bool + */ + public function isYouTube(): bool + { + return $this->type === self::TYPE_YOUTUBE; + } + + /** + * Link to the video on YouTube incl. start time, null without valid video. + * + * @return string|null + */ + public function youtubeWatchUrl(): ?string + { + $id = (string)$this->setting('video_id'); + + return $this->isYouTube() && $id !== '' ? YouTubeService::watchUrl($id, (int)$this->setting('start')) : null; + } + + /** + * Player URL for the presenter screen, null without valid video. + * + * @return string|null + */ + public function youtubeEmbedUrl(): ?string + { + $id = (string)$this->setting('video_id'); + + return $this->isYouTube() && $id !== '' + ? YouTubeService::embedUrl($id, (int)$this->setting('start'), (bool)$this->setting('autoplay')) + : null; } /** diff --git a/src/Model/Table/SlidesTable.php b/src/Model/Table/SlidesTable.php index fc5ee2c..d3fc22c 100644 --- a/src/Model/Table/SlidesTable.php +++ b/src/Model/Table/SlidesTable.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Model\Table; use App\Model\Entity\Slide; +use App\Service\YouTubeService; use ArrayObject; use Cake\Datasource\EntityInterface; use Cake\Event\EventInterface; @@ -158,6 +159,19 @@ class SlidesTable extends Table $settings['time_limit'] = $limit; } break; + case Slide::TYPE_YOUTUBE: + $url = mb_substr(trim((string)($input['url'] ?? '')), 0, 500); + $parsed = YouTubeService::parseUrl($url); + $settings['url'] = $url; + $settings['video_id'] = $parsed['videoId'] ?? ''; + // Form input "1:30" / "2" (minutes); an int is already seconds. Empty = timecode of the link. + $start = $input['start'] ?? ''; + if (!is_int($start)) { + $start = trim((string)$start) === '' ? null : YouTubeService::parseStartInput((string)$start); + } + $settings['start'] = max(0, min($start ?? $parsed['start'] ?? 0, YouTubeService::MAX_START)); + $settings['autoplay'] = filter_var($input['autoplay'] ?? false, FILTER_VALIDATE_BOOLEAN); + break; } return $settings; diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index f4a9a9e..f4bc2c9 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -219,6 +219,11 @@ class PollStateService 'isVotingOpen' => $slide->isVotingOpen(), 'isInteractive' => $slide->isInteractive(), 'settings' => $slide->getSettings(), + // YouTube slides: player URL for the presenter, link for sharing + 'video' => $slide->isYouTube() && $slide->youtubeEmbedUrl() !== null ? [ + 'embedUrl' => $slide->youtubeEmbedUrl(), + 'watchUrl' => $slide->youtubeWatchUrl(), + ] : null, ]; } } diff --git a/src/Service/YouTubeService.php b/src/Service/YouTubeService.php new file mode 100644 index 0000000..62515f1 --- /dev/null +++ b/src/Service/YouTubeService.php @@ -0,0 +1,234 @@ +client = $client ?? new Client(['timeout' => 4]); + } + + /** + * Extracts video id and timecode from a YouTube link (or a bare video id). + * + * @param string $input Link as entered + * @return array{videoId: string, start: int|null}|null Null if it is no YouTube video link + */ + public static function parseUrl(string $input): ?array + { + $input = trim($input); + if (preg_match(self::ID_PATTERN, $input)) { + return ['videoId' => $input, 'start' => null]; + } + if (!preg_match('#^https?://#i', $input)) { + $input = 'https://' . $input; + } + $parts = parse_url($input); + if ($parts === false) { + return null; + } + $host = strtolower((string)($parts['host'] ?? '')); + if (!in_array($host, self::HOSTS, true)) { + return null; + } + + parse_str((string)($parts['query'] ?? ''), $query); + $path = trim((string)($parts['path'] ?? ''), '/'); + $segments = $path === '' ? [] : explode('/', $path); + + $id = match (true) { + str_ends_with($host, 'youtu.be') => $segments[0] ?? '', + ($segments[0] ?? '') === 'watch' => is_string($query['v'] ?? null) ? $query['v'] : '', + in_array($segments[0] ?? '', ['embed', 'shorts', 'live', 'v', 'e'], true) => $segments[1] ?? '', + default => '', + }; + if (!preg_match(self::ID_PATTERN, $id)) { + return null; + } + + parse_str((string)($parts['fragment'] ?? ''), $fragment); + $start = null; + foreach ([$query['t'] ?? null, $query['start'] ?? null, $fragment['t'] ?? null] as $value) { + if (is_string($value) && $value !== '') { + $start = self::parseUrlTime($value); + if ($start !== null) { + break; + } + } + } + + return ['videoId' => $id, 'start' => $start]; + } + + /** + * Parses a timecode as used in YouTube links: `90`, `90s`, `1m30s`, `1h2m3s`. + * + * @param string $value Timecode + * @return int|null Seconds, null if invalid + */ + public static function parseUrlTime(string $value): ?int + { + $value = strtolower(trim($value)); + if (preg_match('/^\d+$/', $value)) { + return min((int)$value, self::MAX_START); + } + if (preg_match('/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/', $value, $m) && $value !== '') { + return min((int)($m[1] ?? 0) * 3600 + (int)($m[2] ?? 0) * 60 + (int)($m[3] ?? 0), self::MAX_START); + } + + return null; + } + + /** + * Parses the start time entered in the slide form: `1:30`, `1:02:03`, `2` (= minutes) + * or the link format `1m30s`. + * + * @param string $value Input + * @return int|null Seconds, null if invalid + */ + public static function parseStartInput(string $value): ?int + { + $value = str_replace(' ', '', trim($value)); + if (preg_match('/^\d+$/', $value)) { + return min((int)$value * 60, self::MAX_START); + } + if (preg_match('/^(?:(\d+):)?(\d+):([0-5]\d)$/', $value, $m)) { + return min((int)$m[1] * 3600 + (int)$m[2] * 60 + (int)$m[3], self::MAX_START); + } + + return preg_match('/[hms]$/i', $value) ? self::parseUrlTime($value) : null; + } + + /** + * @param int $seconds Seconds + * @return string `m:ss` or `h:mm:ss` + */ + public static function formatTime(int $seconds): string + { + $seconds = max(0, $seconds); + $h = intdiv($seconds, 3600); + $m = intdiv($seconds % 3600, 60); + $s = $seconds % 60; + + return $h > 0 ? sprintf('%d:%02d:%02d', $h, $m, $s) : sprintf('%d:%02d', $m, $s); + } + + /** + * Link to watch the video on YouTube (for participants). + * + * @param string $videoId Video id + * @param int $start Start in seconds + * @return string + */ + public static function watchUrl(string $videoId, int $start = 0): string + { + $query = ['v' => $videoId] + ($start > 0 ? ['t' => $start . 's'] : []); + + return 'https://www.youtube.com/watch?' . http_build_query($query); + } + + /** + * Player URL for the iframe on the presenter screen (privacy-enhanced mode). + * + * @param string $videoId Video id + * @param int $start Start in seconds + * @param bool $autoplay Start playing when the slide is shown + * @return string + */ + public static function embedUrl(string $videoId, int $start = 0, bool $autoplay = false): string + { + $query = ['rel' => 0, 'playsinline' => 1] + + ($start > 0 ? ['start' => $start] : []) + + ($autoplay ? ['autoplay' => 1] : []); + + return 'https://www.youtube-nocookie.com/embed/' . rawurlencode($videoId) . '?' . http_build_query($query); + } + + /** + * Asks YouTube (oEmbed) whether the video exists and may be embedded. + * + * @param string $videoId Video id + * @return array{status: string, title: string|null} status: one of the STATUS_* constants + */ + public function check(string $videoId): array + { + try { + $response = $this->client->get(self::OEMBED_URL, [ + 'url' => self::watchUrl($videoId), + 'format' => 'json', + ]); + } catch (Throwable) { + return ['status' => self::STATUS_UNREACHABLE, 'title' => null]; + } + + $code = $response->getStatusCode(); + if ($code === 200) { + $data = $response->getJson(); + $title = is_array($data) && is_string($data['title'] ?? null) ? trim($data['title']) : null; + + return ['status' => self::STATUS_OK, 'title' => $title !== '' ? $title : null]; + } + + return [ + 'status' => match (true) { + in_array($code, [401, 403], true) => self::STATUS_NOT_EMBEDDABLE, + in_array($code, [400, 404], true) => self::STATUS_NOT_FOUND, + default => self::STATUS_UNREACHABLE, + }, + 'title' => null, + ]; + } + + /** + * German message for a check status. + * + * @param string $status STATUS_* constant + * @return string + */ + public static function statusMessage(string $status): string + { + return match ($status) { + self::STATUS_OK => __('Das Video ist verfügbar und kann eingebettet werden.'), + self::STATUS_NOT_FOUND => __('Dieses Video gibt es nicht (mehr) oder es ist privat.'), + self::STATUS_NOT_EMBEDDABLE => __('Dieses Video darf nicht eingebettet werden (vom Kanal gesperrt). Bitte wähle ein anderes Video.'), + default => __('YouTube war gerade nicht erreichbar, das Video konnte nicht geprüft werden.'), + }; + } +} diff --git a/templates/Admin/present.php b/templates/Admin/present.php index e79cb07..adbb330 100644 --- a/templates/Admin/present.php +++ b/templates/Admin/present.php @@ -36,6 +36,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);

+
diff --git a/templates/Participate/view.php b/templates/Participate/view.php index 49160f6..d7235d2 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -47,6 +47,29 @@ $countdown = function (?int $remaining): string {

+ isYouTube()) : + $watchUrl = $slide->youtubeWatchUrl(); ?> +
+

+

question) ?>

+ description) : ?> +
description)) ?>
+ + + + + +
+ isInteractive()) : ?>

question) ?>

diff --git a/templates/Slides/form.php b/templates/Slides/form.php index 6acae1e..7411f81 100644 --- a/templates/Slides/form.php +++ b/templates/Slides/form.php @@ -11,6 +11,9 @@ * @var list $quizOptions * @var bool|null $hasResponses */ + +use App\Service\YouTubeService; + $isNew = $slide->isNew(); $settings = $slide->getSettings(); $this->assign('title', $isNew ? __('Neue Folie') : __('Folie bearbeiten')); @@ -28,11 +31,75 @@ $optionsError = $slide->getError('options_text'); Form->create($slide, ['url' => $formUrl]) ?> Form->hidden('type') ?> + isYouTube()) : + $urlError = $slide->getError('youtube_url'); + $startError = $slide->getError('youtube_start'); + $linkStart = YouTubeService::parseUrl((string)$settings['url'])['start'] ?? null; + // Leave the field empty when the start comes from the link, so a changed link wins. + $startValue = $this->getRequest()->is(['post', 'put', 'patch']) + ? (string)$this->getRequest()->getData('settings.start', '') + : ((int)$settings['start'] > 0 && (int)$settings['start'] !== $linkStart ? YouTubeService::formatTime((int)$settings['start']) : ''); + $previewUrl = $settings['video_id'] !== '' && !$urlError + ? YouTubeService::embedUrl((string)$settings['video_id'], (int)$settings['start']) + : null; + ?> +
+
+ +
+ + value="" + placeholder="https://www.youtube.com/watch?v=dQw4w9WgXcQ" + aria-describedby="youtube-url-hint youtube-status" + data-youtube-url> + +
+

+ +
+ +

+
+
> + + + +
+
+ + data-youtube-start> +

+ +
+ +
+ Form->control('settings.autoplay', [ + 'type' => 'checkbox', + 'label' => __('Automatisch abspielen, sobald die Folie in der Präsentation erscheint'), + 'checked' => (bool)$settings['autoplay'], + ]) ?> +

+
+ Form->control('question', [ - 'label' => $slide->type === 'content' ? __('Überschrift') : __('Frage'), + 'label' => match ($slide->type) { + 'content' => __('Überschrift'), + 'youtube' => __('Titel'), + default => __('Frage'), + }, 'maxlength' => 500, - 'required' => true, - 'autofocus' => $isNew, + 'required' => !$slide->isYouTube(), + 'autofocus' => $isNew && !$slide->isYouTube(), + 'placeholder' => $slide->isYouTube() ? __('Leer lassen, um den Titel des Videos zu übernehmen') : null, + 'data-youtube-title' => $slide->isYouTube() ? '' : null, ]) ?> Form->control('description', [ 'type' => 'textarea', diff --git a/tests/TestCase/Controller/YouTubeSlideTest.php b/tests/TestCase/Controller/YouTubeSlideTest.php new file mode 100644 index 0000000..37bfa43 --- /dev/null +++ b/tests/TestCase/Controller/YouTubeSlideTest.php @@ -0,0 +1,184 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + protected function mockOembed(int $code, string $body = ''): void + { + // Registering a mock also makes unexpected requests fail instead of hitting the network. + $this->mockClientGet('https://www.youtube.com/*', $this->newClientResponse($code, ['Content-Type: application/json'], $body)); + } + + public function testAddSlideUsesTimecodeOfLinkAndVideoTitle(): void + { + [$poll, $token] = $this->createPoll(); + $this->mockOembed(200, '{"title":"Never Gonna Give You Up"}'); + + $this->post("/admin/$token/slides/add?type=youtube", [ + 'type' => 'youtube', + 'question' => '', + 'settings' => ['url' => 'https://youtu.be/dQw4w9WgXcQ?t=43', 'start' => '', 'autoplay' => '1'], + ]); + + $this->assertRedirect(['_name' => 'admin', 'token' => $token]); + $slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail(); + $this->assertSame('Never Gonna Give You Up', $slide->question); + $this->assertSame(['url' => 'https://youtu.be/dQw4w9WgXcQ?t=43', 'video_id' => 'dQw4w9WgXcQ', 'start' => 43, 'autoplay' => true], $slide->settings); + $this->assertFalse($slide->isInteractive()); + } + + public function testEnteredStartWins(): void + { + [$poll, $token] = $this->createPoll(); + $this->mockOembed(200, '{"title":"Video"}'); + + $this->post("/admin/$token/slides/add?type=youtube", [ + 'type' => 'youtube', + 'question' => 'Mein Titel', + 'settings' => ['url' => 'https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=43s', 'start' => '1:30'], + ]); + + $this->assertRedirect(); + $slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail(); + $this->assertSame('Mein Titel', $slide->question); + $this->assertSame(90, $slide->setting('start')); + $this->assertFalse($slide->setting('autoplay')); + } + + public function testInvalidLinkAndStartAreRejected(): void + { + [$poll, $token] = $this->createPoll(); + $this->post("/admin/$token/slides/add?type=youtube", [ + 'type' => 'youtube', + 'question' => 'Video', + 'settings' => ['url' => 'https://vimeo.com/123', 'start' => '1:99'], + ]); + + $this->assertResponseOk(); + $this->assertResponseContains('kein gültiger YouTube-Link'); + $this->assertResponseContains('Startzeit'); + $this->assertResponseContains('value="1:99"'); + $this->assertSame(0, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count()); + } + + public function testVideoThatMayNotBeEmbeddedIsRejected(): void + { + [$poll, $token] = $this->createPoll(); + $this->mockOembed(401); + + $this->post("/admin/$token/slides/add?type=youtube", [ + 'type' => 'youtube', + 'question' => 'Video', + 'settings' => ['url' => 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'], + ]); + + $this->assertResponseOk(); + $this->assertResponseContains('darf nicht eingebettet werden'); + $this->assertSame(0, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count()); + } + + public function testUnreachableYouTubeSavesWithWarning(): void + { + [$poll, $token] = $this->createPoll(); + $this->mockOembed(503); + + $this->post("/admin/$token/slides/add?type=youtube", [ + 'type' => 'youtube', + 'question' => 'Video', + 'settings' => ['url' => 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'], + ]); + + $this->assertRedirect(); + $this->assertFlashMessageAt(0, 'YouTube war gerade nicht erreichbar, das Video konnte nicht geprüft werden. Bitte teste das Video vor deiner Präsentation.'); + $this->assertSame(1, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count()); + } + + public function testCheckEndpoint(): void + { + [, $token] = $this->createPoll(); + $this->mockOembed(200, '{"title":"Never Gonna Give You Up"}'); + + $this->post("/admin/$token/slides/youtube-check", ['url' => 'https://youtu.be/dQw4w9WgXcQ?t=90', 'start' => '']); + $this->assertResponseOk(); + $this->assertHeader('Referrer-Policy', 'no-referrer'); + $json = json_decode((string)$this->_response->getBody(), true); + $this->assertTrue($json['ok']); + $this->assertSame('Never Gonna Give You Up', $json['title']); + $this->assertSame('1:30', $json['linkStart']); + $this->assertStringContainsString('youtube-nocookie.com/embed/dQw4w9WgXcQ', $json['embedUrl']); + $this->assertStringContainsString('start=90', $json['embedUrl']); + + $this->post("/admin/$token/slides/youtube-check", ['url' => 'kein link']); + $json = json_decode((string)$this->_response->getBody(), true); + $this->assertFalse($json['ok']); + } + + public function testPresenterGetsEmbedAndParticipantGetsShareLink(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_YOUTUBE, [ + 'question' => 'Ein