Add YouTube video slide type
CI / Deploy / test (push) Successful in 46s
CI / Deploy / deploy (push) Skipped

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 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Opus 5.5 committed 2026-11-07 15:08:12 +01:00
1 parent 93aeae1884
commit 1c509e31c2
14 files changed
+972 -24

No files matched your search

+97 -1
View File
@@ -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<string, mixed> $data Request data (question may be filled in)
* @return array{errors: array<string, string>, 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.');
}
}
+41 -1
View File
@@ -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;
}
/**
+14
View File
@@ -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;
+5
View File
@@ -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,
];
}
}
+234
View File
@@ -0,0 +1,234 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Cake\Http\Client;
use Throwable;
/**
* YouTube helpers for video slides: parses links and timecodes, builds
* watch/embed URLs and checks via oEmbed whether a video exists and may be embedded.
*
* Supported links: youtube.com/watch?v=…, youtu.be/…, /shorts/…, /live/…, /embed/…,
* youtube-nocookie.com/embed/… (also m. / music. subdomains) and a bare 11 character video id.
* Timecodes are read from `t` / `start` (query or fragment), e.g. `90`, `90s`, `1m30s`, `1h2m3s`.
*/
class YouTubeService
{
public const STATUS_OK = 'ok';
public const STATUS_NOT_FOUND = 'not_found';
public const STATUS_NOT_EMBEDDABLE = 'not_embeddable';
public const STATUS_UNREACHABLE = 'unreachable';
/**
* Longest accepted start time (12 hours).
*/
public const MAX_START = 43200;
public const OEMBED_URL = 'https://www.youtube.com/oembed';
protected const ID_PATTERN = '/^[A-Za-z0-9_-]{11}$/';
protected const HOSTS = [
'youtube.com', 'www.youtube.com', 'm.youtube.com', 'music.youtube.com',
'youtube-nocookie.com', 'www.youtube-nocookie.com', 'youtu.be', 'www.youtu.be',
];
protected Client $client;
/**
* @param \Cake\Http\Client|null $client HTTP client (default: 4 s timeout)
*/
public function __construct(?Client $client = null)
{
$this->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.'),
};
}
}