Add YouTube video slide type #10

Merged
gnilebein merged 1 commits from feature/youtube-slide into main 2026-11-07 15:08:42 +01:00
14 changed files with 958 additions and 10 deletions

No files matched your search

+12 -2
View File
@@ -55,7 +55,8 @@ src/
HomeController Startseite, Anlegen (/create), Bestätigung, Join, Recover 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 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 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 ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid
Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal) Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal)
Model/ Polls → Slides → SlideOptions, Slides → Responses Model/ Polls → Slides → SlideOptions, Slides → Responses
@@ -64,6 +65,7 @@ src/
ResultsService Aggregiert Ergebnisse je Folientyp (JSON-Struktur im Docblock) ResultsService Aggregiert Ergebnisse je Folientyp (JSON-Struktur im Docblock)
PollStateService State-JSON für Presenter und Teilnehmende PollStateService State-JSON für Presenter und Teilnehmende
ThrottleService Rate-Limit pro IP (Cache 'throttle') 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 templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email
webroot/css/plenario.css Eigenes CSS, kein Framework webroot/css/plenario.css Eigenes CSS, kein Framework
webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Folien-Sortierung (Pointer Events + Pfeiltasten) 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), - `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` `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`, `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) `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 - `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. - 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. - 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) ### Neuen Folientyp hinzufügen (Checkliste)
1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php` 1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php`
+2
View File
@@ -63,6 +63,8 @@ return function (RouteBuilder $routes): void {
->setPatterns($token)->setPass(['id'])->setMethods(['POST']); ->setPatterns($token)->setPass(['id'])->setMethods(['POST']);
$admin->connect('/slides/reorder', 'Slides::reorder', ['_name' => 'slides:reorder']) $admin->connect('/slides/reorder', 'Slides::reorder', ['_name' => 'slides:reorder'])
->setPatterns($token)->setMethods(['POST']); ->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']) $admin->connect('/slides/{id}/reset', 'Slides::reset', ['_name' => 'slides:reset'])
->setPatterns($token)->setPass(['id'])->setMethods(['POST']); ->setPatterns($token)->setPass(['id'])->setMethods(['POST']);
}); });
+97 -1
View File
@@ -5,6 +5,7 @@ namespace App\Controller;
use App\Model\Entity\Slide; use App\Model\Entity\Slide;
use App\Model\Table\SlidesTable; use App\Model\Table\SlidesTable;
use App\Service\YouTubeService;
use Cake\Http\Exception\NotFoundException; use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response; use Cake\Http\Response;
@@ -208,7 +209,11 @@ class SlidesController extends AdminAppController
// Quiz voting is controlled by the presenter only. // Quiz voting is controlled by the presenter only.
$fields = array_values(array_diff($fields, ['is_voting_open'])); $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' => []]); $this->Slides->patchEntity($slide, $data, ['fields' => $fields, 'associated' => []]);
foreach ($youtube['errors'] as $field => $message) {
$slide->setError($field, $message);
}
$labels = SlidesTable::parseOptionLines($optionsText); $labels = SlidesTable::parseOptionLines($optionsText);
$correct = []; $correct = [];
@@ -231,15 +236,106 @@ class SlidesController extends AdminAppController
return false; 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)) { if (!$this->Slides->save($slide)) {
return false; return false;
} }
if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz()) { if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz()) {
$this->Slides->syncOptions($slide, $labels, $correct); $this->Slides->syncOptions($slide, $labels, $correct);
} }
if ($youtube['warning'] !== null) {
$this->Flash->warning($youtube['warning']);
}
return true; 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; namespace App\Model\Entity;
use App\Service\YouTubeService;
use Cake\I18n\DateTime; use Cake\I18n\DateTime;
use Cake\ORM\Entity; use Cake\ORM\Entity;
@@ -34,6 +35,7 @@ class Slide extends Entity
public const TYPE_SCALE = 'scale'; public const TYPE_SCALE = 'scale';
public const TYPE_CONTENT = 'content'; public const TYPE_CONTENT = 'content';
public const TYPE_QUIZ = 'quiz'; public const TYPE_QUIZ = 'quiz';
public const TYPE_YOUTUBE = 'youtube';
/** /**
* Quiz phases, see quizPhase(). * Quiz phases, see quizPhase().
@@ -63,6 +65,8 @@ class Slide extends Entity
self::TYPE_CONTENT => [], self::TYPE_CONTENT => [],
// time_limit in seconds, 0 = no limit (presenter ends the quiz) // time_limit in seconds, 0 = no limit (presenter ends the quiz)
self::TYPE_QUIZ => ['time_limit' => 30], 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_SCALE => __('Skala'),
self::TYPE_QUIZ => __('Quiz'), self::TYPE_QUIZ => __('Quiz'),
self::TYPE_CONTENT => __('Inhaltsfolie'), 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_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_QUIZ => __('Frage mit richtiger Antwort und Zeitlimit, aufgelöst wird erst am Ende.'),
self::TYPE_CONTENT => __('Nur Text anzeigen, ohne Abstimmung.'), 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 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; namespace App\Model\Table;
use App\Model\Entity\Slide; use App\Model\Entity\Slide;
use App\Service\YouTubeService;
use ArrayObject; use ArrayObject;
use Cake\Datasource\EntityInterface; use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface; use Cake\Event\EventInterface;
@@ -158,6 +159,19 @@ class SlidesTable extends Table
$settings['time_limit'] = $limit; $settings['time_limit'] = $limit;
} }
break; 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; return $settings;
+5
View File
@@ -219,6 +219,11 @@ class PollStateService
'isVotingOpen' => $slide->isVotingOpen(), 'isVotingOpen' => $slide->isVotingOpen(),
'isInteractive' => $slide->isInteractive(), 'isInteractive' => $slide->isInteractive(),
'settings' => $slide->getSettings(), '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.'),
};
}
}
+1
View File
@@ -36,6 +36,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);
<p class="stage__type" data-type></p> <p class="stage__type" data-type></p>
<h1 class="stage__question" data-question><?= __('Lade …') ?></h1> <h1 class="stage__question" data-question><?= __('Lade …') ?></h1>
<p class="stage__description" data-description></p> <p class="stage__description" data-description></p>
<div class="stage__media" data-media hidden></div>
<div class="stage__results" data-results></div> <div class="stage__results" data-results></div>
</main> </main>
+23
View File
@@ -47,6 +47,29 @@ $countdown = function (?int $remaining): string {
<p class="muted"><?= __('Warte, bis die erste Frage gestartet wird. Die Seite aktualisiert sich automatisch.') ?></p> <p class="muted"><?= __('Warte, bis die erste Frage gestartet wird. Die Seite aktualisiert sich automatisch.') ?></p>
</section> </section>
<?php elseif ($slide->isYouTube()) :
$watchUrl = $slide->youtubeWatchUrl(); ?>
<section class="card">
<p class="eyebrow"><?= __('Video') ?></p>
<h1><?= h($slide->question) ?></h1>
<?php if ($slide->description) : ?>
<div class="prose"><?= nl2br(h($slide->description)) ?></div>
<?php endif; ?>
<?php if ($watchUrl !== null) : ?>
<p class="video-link">
<a class="button button--primary button--block" href="<?= h($watchUrl) ?>" target="_blank" rel="noopener noreferrer">
▶ <?= __('Auf YouTube ansehen') ?>
</a>
</p>
<div class="copy-field share-field">
<input type="text" readonly value="<?= h($watchUrl) ?>" aria-label="<?= __('Link zum Video') ?>" data-copy-source>
<button type="button" class="button" hidden
data-share data-share-url="<?= h($watchUrl) ?>" data-share-title="<?= h($slide->question) ?>"
data-label-share="<?= __('Teilen') ?>" data-label-copy="<?= __('Link kopieren') ?>"><?= __('Teilen') ?></button>
</div>
<?php endif; ?>
</section>
<?php elseif (!$slide->isInteractive()) : ?> <?php elseif (!$slide->isInteractive()) : ?>
<section class="card"> <section class="card">
<h1><?= h($slide->question) ?></h1> <h1><?= h($slide->question) ?></h1>
+70 -3
View File
@@ -11,6 +11,9 @@
* @var list<array{label: string, correct: bool}> $quizOptions * @var list<array{label: string, correct: bool}> $quizOptions
* @var bool|null $hasResponses * @var bool|null $hasResponses
*/ */
use App\Service\YouTubeService;
$isNew = $slide->isNew(); $isNew = $slide->isNew();
$settings = $slide->getSettings(); $settings = $slide->getSettings();
$this->assign('title', $isNew ? __('Neue Folie') : __('Folie bearbeiten')); $this->assign('title', $isNew ? __('Neue Folie') : __('Folie bearbeiten'));
@@ -28,11 +31,75 @@ $optionsError = $slide->getError('options_text');
<?= $this->Form->create($slide, ['url' => $formUrl]) ?> <?= $this->Form->create($slide, ['url' => $formUrl]) ?>
<?= $this->Form->hidden('type') ?> <?= $this->Form->hidden('type') ?>
<?php if ($slide->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;
?>
<div class="youtube-fields" data-youtube-form="<?= h($this->Url->build(['_name' => 'slides:youtube-check', 'token' => $adminToken])) ?>">
<div class="input text required<?= $urlError ? ' error' : '' ?>">
<label for="youtube-url"><?= __('YouTube-Link') ?></label>
<div class="copy-field">
<input type="text" inputmode="url" id="youtube-url" name="settings[url]" maxlength="500" required
autocomplete="off" spellcheck="false" <?= $isNew ? 'autofocus' : '' ?>
value="<?= h((string)$settings['url']) ?>"
placeholder="https://www.youtube.com/watch?v=dQw4w9WgXcQ"
aria-describedby="youtube-url-hint youtube-status<?= $urlError ? ' youtube-url-error' : '' ?>"
<?= $urlError ? 'aria-invalid="true"' : '' ?> data-youtube-url>
<button type="button" class="button" data-youtube-check hidden><?= __('Link prüfen') ?></button>
</div>
<p class="hint" id="youtube-url-hint"><?= __('Links von youtube.com, youtu.be und Shorts funktionieren. Beim Speichern wird geprüft, ob das Video existiert und eingebettet werden darf.') ?></p>
<?php if ($urlError) : ?>
<div class="error-message" id="youtube-url-error"><?= h(implode(' ', (array)$urlError)) ?></div>
<?php endif; ?>
<p class="youtube-status" id="youtube-status" role="status" aria-live="polite" data-youtube-status></p>
</div>
<div class="youtube-preview" data-youtube-preview <?= $previewUrl ? '' : 'hidden' ?>>
<?php if ($previewUrl) : ?>
<iframe src="<?= h($previewUrl) ?>" title="<?= __('Vorschau des Videos') ?>" loading="lazy"
referrerpolicy="strict-origin" allow="encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe>
<?php endif; ?>
</div>
<div class="input text<?= $startError ? ' error' : '' ?>">
<label for="youtube-start"><?= __('Start bei (Minute:Sekunde, optional)') ?></label>
<input type="text" id="youtube-start" name="settings[start]" class="input-short" maxlength="10"
inputmode="numeric" autocomplete="off" value="<?= h($startValue) ?>"
placeholder="<?= h($linkStart !== null ? YouTubeService::formatTime($linkStart) : '0:00') ?>"
aria-describedby="youtube-start-hint<?= $startError ? ' youtube-start-error' : '' ?>"
<?= $startError ? 'aria-invalid="true"' : '' ?> data-youtube-start>
<p class="hint" id="youtube-start-hint" data-youtube-start-hint><?= $linkStart !== null
? __('Leer lassen, um beim Zeitpunkt aus dem Link ({0}) zu starten.', YouTubeService::formatTime($linkStart))
: __('Z. B. 1:30 oder nur die Minute (2). Leer lassen, um am Anfang bzw. beim Zeitpunkt aus dem Link (…&t=90s) zu starten.') ?></p>
<?php if ($startError) : ?>
<div class="error-message" id="youtube-start-error"><?= h(implode(' ', (array)$startError)) ?></div>
<?php endif; ?>
</div>
<?= $this->Form->control('settings.autoplay', [
'type' => 'checkbox',
'label' => __('Automatisch abspielen, sobald die Folie in der Präsentation erscheint'),
'checked' => (bool)$settings['autoplay'],
]) ?>
<p class="hint"><?= __('Manche Browser spielen Videos mit Ton erst automatisch ab, nachdem du in der Präsentation einmal geklickt oder eine Taste gedrückt hast.') ?></p>
</div>
<?php endif; ?>
<?= $this->Form->control('question', [ <?= $this->Form->control('question', [
'label' => $slide->type === 'content' ? __('Überschrift') : __('Frage'), 'label' => match ($slide->type) {
'content' => __('Überschrift'),
'youtube' => __('Titel'),
default => __('Frage'),
},
'maxlength' => 500, 'maxlength' => 500,
'required' => true, 'required' => !$slide->isYouTube(),
'autofocus' => $isNew, 'autofocus' => $isNew && !$slide->isYouTube(),
'placeholder' => $slide->isYouTube() ? __('Leer lassen, um den Titel des Videos zu übernehmen') : null,
'data-youtube-title' => $slide->isYouTube() ? '' : null,
]) ?> ]) ?>
<?= $this->Form->control('description', [ <?= $this->Form->control('description', [
'type' => 'textarea', 'type' => 'textarea',
@@ -0,0 +1,184 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Controller;
use App\Model\Entity\Slide;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\Http\TestSuite\HttpClientTrait;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* YouTube slides: creating (incl. link check), presenter embed, participant link.
*/
class YouTubeSlideTest extends TestCase
{
use HttpClientTrait;
use IntegrationTestTrait;
use PlenarioTestTrait;
/**
* @var list<string>
*/
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 <Video>',
'settings' => ['url' => 'https://youtu.be/dQw4w9WgXcQ', 'video_id' => 'dQw4w9WgXcQ', 'start' => 90, 'autoplay' => true],
]);
$poll = $this->goLive($poll, $slide);
$this->get("/admin/$token/state");
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertFalse($state['slide']['isInteractive']);
$this->assertSame(
'https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?rel=0&playsinline=1&start=90&autoplay=1',
$state['slide']['video']['embedUrl'],
);
$this->get('/p/' . $poll->join_code);
$this->assertResponseOk();
$this->assertResponseContains('Ein &lt;Video&gt;');
$this->assertResponseContains('href="https://www.youtube.com/watch?v=dQw4w9WgXcQ&amp;t=90s"');
$this->assertResponseContains('data-share');
$this->assertResponseNotContains('<iframe');
$this->post('/p/' . $poll->join_code . '/vote', ['slide_id' => $slide->id, 'text' => 'x']);
$this->assertSame(0, $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->count());
}
public function testEditFormShowsPreviewAndKeepsLinkTimecodeEmpty(): void
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_YOUTUBE, [
'settings' => ['url' => 'https://youtu.be/dQw4w9WgXcQ?t=43', 'video_id' => 'dQw4w9WgXcQ', 'start' => 43, 'autoplay' => false],
]);
$this->get("/admin/$token/slides/{$slide->id}/edit");
$this->assertResponseOk();
$this->assertResponseContains('referrerpolicy="strict-origin"');
$this->assertResponseContains('id="youtube-start" name="settings[start]" class="input-short" maxlength="10"');
$this->assertResponseContains('value=""');
$this->assertResponseContains('placeholder="0:43"');
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Service;
use App\Model\Entity\Slide;
use App\Model\Table\SlidesTable;
use App\Service\YouTubeService;
use Cake\Http\TestSuite\HttpClientTrait;
use Cake\TestSuite\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
/**
* Link parsing, timecodes and the oEmbed check of YouTube slides.
*/
class YouTubeServiceTest extends TestCase
{
use HttpClientTrait;
/**
* @return array<string, array{0: string, 1: string|null, 2: int|null}>
*/
public static function urlProvider(): array
{
return [
'watch' => ['https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'dQw4w9WgXcQ', null],
'watch with t' => ['https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=43s', 'dQw4w9WgXcQ', 43],
'watch t first, playlist' => ['https://youtube.com/watch?t=1m30s&v=dQw4w9WgXcQ&list=PL123', 'dQw4w9WgXcQ', 90],
'short link' => ['https://youtu.be/dQw4w9WgXcQ?t=90', 'dQw4w9WgXcQ', 90],
'short link with si' => ['https://youtu.be/dQw4w9WgXcQ?si=AbC123', 'dQw4w9WgXcQ', null],
'without scheme' => ['youtu.be/dQw4w9WgXcQ', 'dQw4w9WgXcQ', null],
'mobile' => ['https://m.youtube.com/watch?v=dQw4w9WgXcQ#t=1h2m3s', 'dQw4w9WgXcQ', 3723],
'shorts' => ['https://www.youtube.com/shorts/dQw4w9WgXcQ', 'dQw4w9WgXcQ', null],
'live' => ['https://www.youtube.com/live/dQw4w9WgXcQ?feature=share', 'dQw4w9WgXcQ', null],
'embed with start' => ['https://www.youtube.com/embed/dQw4w9WgXcQ?start=12', 'dQw4w9WgXcQ', 12],
'nocookie' => ['https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ', 'dQw4w9WgXcQ', null],
'bare id' => ['dQw4w9WgXcQ', 'dQw4w9WgXcQ', null],
'other host' => ['https://vimeo.com/123456789', null, null],
'fake host' => ['https://youtube.com.evil.example/watch?v=dQw4w9WgXcQ', null, null],
'channel' => ['https://www.youtube.com/@somechannel', null, null],
'id too short' => ['https://youtu.be/abc', null, null],
'empty' => ['', null, null],
];
}
#[DataProvider('urlProvider')]
public function testParseUrl(string $url, ?string $id, ?int $start): void
{
$parsed = YouTubeService::parseUrl($url);
if ($id === null) {
$this->assertNull($parsed);
return;
}
$this->assertSame(['videoId' => $id, 'start' => $start], $parsed);
}
public function testParseStartInput(): void
{
$this->assertSame(90, YouTubeService::parseStartInput('1:30'));
$this->assertSame(3723, YouTubeService::parseStartInput('1:02:03'));
$this->assertSame(120, YouTubeService::parseStartInput('2'), 'a plain number means minutes');
$this->assertSame(90, YouTubeService::parseStartInput('1m30s'));
$this->assertSame(0, YouTubeService::parseStartInput('0'));
$this->assertNull(YouTubeService::parseStartInput('1:75'));
$this->assertNull(YouTubeService::parseStartInput('abc'));
$this->assertSame(YouTubeService::MAX_START, YouTubeService::parseStartInput('99999'));
}
public function testFormatAndUrls(): void
{
$this->assertSame('0:00', YouTubeService::formatTime(0));
$this->assertSame('1:30', YouTubeService::formatTime(90));
$this->assertSame('1:02:03', YouTubeService::formatTime(3723));
$this->assertSame('https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=90s', YouTubeService::watchUrl('dQw4w9WgXcQ', 90));
$this->assertSame('https://www.youtube.com/watch?v=dQw4w9WgXcQ', YouTubeService::watchUrl('dQw4w9WgXcQ'));
$this->assertSame(
'https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?rel=0&playsinline=1&start=90&autoplay=1',
YouTubeService::embedUrl('dQw4w9WgXcQ', 90, true),
);
}
public function testSanitizeSettingsPrefersEnteredStartOverLinkTimecode(): void
{
$url = 'https://youtu.be/dQw4w9WgXcQ?t=43';
$fromLink = SlidesTable::sanitizeSettings(Slide::TYPE_YOUTUBE, ['url' => $url, 'start' => '', 'autoplay' => '1', 'x' => 1]);
$this->assertSame(['url' => $url, 'video_id' => 'dQw4w9WgXcQ', 'start' => 43, 'autoplay' => true], $fromLink);
$entered = SlidesTable::sanitizeSettings(Slide::TYPE_YOUTUBE, ['url' => $url, 'start' => '2:00']);
$this->assertSame(120, $entered['start']);
$this->assertFalse($entered['autoplay']);
$invalid = SlidesTable::sanitizeSettings(Slide::TYPE_YOUTUBE, ['url' => 'https://example.org']);
$this->assertSame('', $invalid['video_id']);
}
public function testCheckStatuses(): void
{
$service = new YouTubeService();
$this->mockClientGet('https://www.youtube.com/*', $this->newClientResponse(200, ['Content-Type: application/json'], '{"title":"Never Gonna Give You Up"}'));
$this->assertSame(['status' => YouTubeService::STATUS_OK, 'title' => 'Never Gonna Give You Up'], $service->check('dQw4w9WgXcQ'));
$this->cleanupMockResponses();
$this->mockClientGet('https://www.youtube.com/*', $this->newClientResponse(401, [], 'Unauthorized'));
$this->assertSame(YouTubeService::STATUS_NOT_EMBEDDABLE, $service->check('dQw4w9WgXcQ')['status']);
$this->cleanupMockResponses();
$this->mockClientGet('https://www.youtube.com/*', $this->newClientResponse(404, [], 'Not Found'));
$this->assertSame(YouTubeService::STATUS_NOT_FOUND, $service->check('dQw4w9WgXcQ')['status']);
$this->cleanupMockResponses();
$this->mockClientGet('https://www.youtube.com/*', $this->newClientResponse(503, [], ''));
$this->assertSame(YouTubeService::STATUS_UNREACHABLE, $service->check('dQw4w9WgXcQ')['status']);
}
}
+15
View File
@@ -145,6 +145,7 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; }
.badge--type-scale { background: #fdeed8; color: #9a5a00; } .badge--type-scale { background: #fdeed8; color: #9a5a00; }
.badge--type-content { background: #e3eefb; color: #1f6bb0; } .badge--type-content { background: #e3eefb; color: #1f6bb0; }
.badge--type-quiz { background: #f1e3fb; color: #7a2fb0; } .badge--type-quiz { background: #f1e3fb; color: #7a2fb0; }
.badge--type-youtube { background: #fde4e1; color: #b3261e; }
.message { padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; cursor: pointer; background: var(--surface-2); border-left: 4px solid var(--muted); } .message { padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; cursor: pointer; background: var(--surface-2); border-left: 4px solid var(--muted); }
.message.success { border-color: var(--ok); } .message.success { border-color: var(--ok); }
@@ -225,6 +226,17 @@ textarea { resize: vertical; }
.type-card--scale { border-top-color: var(--c3); } .type-card--scale { border-top-color: var(--c3); }
.type-card--content { border-top-color: var(--c4); } .type-card--content { border-top-color: var(--c4); }
.type-card--quiz { border-top-color: var(--c5); } .type-card--quiz { border-top-color: var(--c5); }
.type-card--youtube { border-top-color: #d93025; }
/* ---------------------------------------------------------------- slide form: youtube */
.youtube-status { margin: 6px 0 0; font-size: .9rem; color: var(--muted); }
.youtube-status:empty { display: none; }
.youtube-status.is-ok { color: var(--ok); }
.youtube-status.is-error { color: var(--danger); }
.youtube-preview { margin: 0 0 16px; }
.youtube-preview iframe, .stage__media iframe { display: block; width: 100%; aspect-ratio: 16 / 9; height: auto; border: 0; border-radius: 8px; background: #000; }
.video-link { margin: 16px 0 12px; }
.share-field input { min-width: 0; }
/* ---------------------------------------------------------------- slide form: quiz answers */ /* ---------------------------------------------------------------- slide form: quiz answers */
.quiz-options { border: 0; padding: 0; margin: 0 0 16px; } .quiz-options { border: 0; padding: 0; margin: 0 0 16px; }
@@ -390,6 +402,9 @@ body.present {
.stage__type { text-transform: uppercase; letter-spacing: .12em; color: var(--c1); font-weight: 700; margin: 0 0 .6em; } .stage__type { text-transform: uppercase; letter-spacing: .12em; color: var(--c1); font-weight: 700; margin: 0 0 .6em; }
.stage__question { font-size: clamp(2rem, 4.5vw, 4rem); margin-bottom: .3em; } .stage__question { font-size: clamp(2rem, 4.5vw, 4rem); margin-bottom: .3em; }
.stage__description { font-size: clamp(1.1rem, 2vw, 1.6rem); color: var(--muted); white-space: pre-line; margin-top: 0; } .stage__description { font-size: clamp(1.1rem, 2vw, 1.6rem); color: var(--muted); white-space: pre-line; margin-top: 0; }
.stage__media { width: min(100%, calc(62vh * 16 / 9)); margin: 1vh auto 0; }
.stage--video .stage__question { font-size: clamp(1.5rem, 3vw, 2.6rem); }
.stage--video .stage__description { font-size: clamp(1rem, 1.6vw, 1.3rem); }
.stage--content .stage__description { color: var(--text); font-size: clamp(1.3rem, 2.6vw, 2.2rem); } .stage--content .stage__description { color: var(--text); font-size: clamp(1.3rem, 2.6vw, 2.2rem); }
.stage__results { font-size: clamp(1rem, 1.8vw, 1.5rem); margin-top: 2vh; } .stage__results { font-size: clamp(1rem, 1.8vw, 1.5rem); margin-top: 2vh; }
.stage--closed .stage__type::after { content: " · Abstimmung geschlossen"; color: var(--muted); } .stage--closed .stage__type::after { content: " · Abstimmung geschlossen"; color: var(--muted); }
+145 -3
View File
@@ -3,6 +3,8 @@
* *
* Modules (auto-initialised by data attributes): * Modules (auto-initialised by data attributes):
* - [data-copy] copy the value of the sibling [data-copy-source] * - [data-copy] copy the value of the sibling [data-copy-source]
* - [data-share] native share sheet (Web Share API), fallback: copy like [data-copy]
* - [data-youtube-form] slide form: "Link prüfen" for YouTube slides (status + preview)
* - [data-presenter] presenter screen, polls /admin/{token}/state * - [data-presenter] presenter screen, polls /admin/{token}/state
* - [data-participant] participant page, polls /p/{code}/state * - [data-participant] participant page, polls /p/{code}/state
* - [data-countdown] quiz timer (data-remaining = seconds), fires `plenario:timeup` on document * - [data-countdown] quiz timer (data-remaining = seconds), fires `plenario:timeup` on document
@@ -501,9 +503,8 @@
// ------------------------------------------------------------------ copy // ------------------------------------------------------------------ copy
function initCopy() { /** Copies the value of the [data-copy-source] next to `button` and confirms on the button. */
document.querySelectorAll('[data-copy]').forEach(function (button) { function copyFrom(button) {
button.addEventListener('click', function () {
var source = button.parentNode.querySelector('[data-copy-source]'); var source = button.parentNode.querySelector('[data-copy-source]');
if (!source) { if (!source) {
return; return;
@@ -523,7 +524,125 @@
document.execCommand('copy'); document.execCommand('copy');
done(); done();
} }
}
function initCopy() {
document.querySelectorAll('[data-copy]').forEach(function (button) {
button.addEventListener('click', function () { copyFrom(button); });
}); });
}
// ------------------------------------------------------------------ share
/**
* [data-share]: native share sheet (smartphones) with data-share-url / data-share-title,
* otherwise copies the sibling [data-copy-source]. Hidden without JS.
*/
function initShare() {
document.querySelectorAll('[data-share]').forEach(function (button) {
var canShare = typeof navigator.share === 'function';
button.textContent = button.getAttribute(canShare ? 'data-label-share' : 'data-label-copy');
button.hidden = false;
button.addEventListener('click', function () {
if (!canShare) {
copyFrom(button);
return;
}
navigator.share({
title: button.getAttribute('data-share-title') || document.title,
url: button.getAttribute('data-share-url')
}).catch(function (error) {
if (!error || error.name !== 'AbortError') {
copyFrom(button);
}
});
});
});
}
// ------------------------------------------------------------------ youtube
function youtubeFrame(src, title) {
// The admin pages send no referrer at all; YouTube refuses to play without one.
// strict-origin sends only the origin, never the path with the admin token.
return el('iframe', {
src: src,
title: title,
referrerpolicy: 'strict-origin',
allow: 'autoplay; encrypted-media; picture-in-picture; fullscreen',
allowfullscreen: ''
});
}
/** [data-youtube-form]: "Link prüfen" in the slide form, shows status + preview. */
function initYouTubeForm(root) {
var url = root.getAttribute('data-youtube-form');
var input = root.querySelector('[data-youtube-url]');
var start = root.querySelector('[data-youtube-start]');
var startHint = root.querySelector('[data-youtube-start-hint]');
var button = root.querySelector('[data-youtube-check]');
var status = root.querySelector('[data-youtube-status]');
var preview = root.querySelector('[data-youtube-preview]');
var title = document.querySelector('[data-youtube-title]');
var lastChecked = null;
function show(text, kind) {
status.textContent = text;
status.classList.toggle('is-ok', kind === 'ok');
status.classList.toggle('is-error', kind === 'error');
}
function check() {
var value = input.value.trim();
if (value === '') {
show('Bitte gib einen YouTube-Link ein.', 'error');
input.focus();
return;
}
var key = value + '|' + start.value.trim();
if (key === lastChecked) {
return;
}
lastChecked = key;
button.disabled = true;
show('Link wird geprüft …');
postJson(url, { url: value, start: start.value }).then(function (result) {
var text = result.message;
if (result.ok && result.linkStart && start.value.trim() === '') {
text += ' Start bei ' + result.linkStart + ' (aus dem Link).';
}
show((result.ok ? '✓ ' : '') + text, result.ok ? 'ok' : 'error');
input.setAttribute('aria-invalid', result.ok ? 'false' : 'true');
preview.textContent = '';
preview.hidden = !result.embedUrl;
if (result.embedUrl) {
preview.appendChild(youtubeFrame(result.embedUrl, 'Vorschau des Videos'));
}
if (result.ok && result.title && title && title.value.trim() === '') {
title.value = result.title;
}
if (result.ok) {
start.placeholder = result.linkStart || '0:00';
if (startHint && result.linkStart) {
startHint.textContent = 'Leer lassen, um beim Zeitpunkt aus dem Link (' + result.linkStart + ') zu starten.';
}
}
}).catch(function () {
lastChecked = null;
show('Die Prüfung hat gerade nicht geklappt. Beim Speichern wird der Link erneut geprüft.', 'error');
}).then(function () {
button.disabled = false;
});
}
button.hidden = false;
button.addEventListener('click', check);
input.addEventListener('change', check);
input.addEventListener('paste', function () { setTimeout(check, 0); });
start.addEventListener('change', function () {
if (input.value.trim() !== '') {
check();
}
}); });
} }
@@ -537,6 +656,23 @@
var last = ''; var last = '';
var hideResults = false; var hideResults = false;
var state = null; var state = null;
var mediaKey = '';
/** Embeds the video of a YouTube slide; kept as is while the slide stays (no restart on polls). */
function renderMedia(slide) {
var media = q('[data-media]');
var video = slide && slide.video ? slide.video : null;
var key = video ? slide.id + '|' + video.embedUrl : '';
if (key === mediaKey) {
return;
}
mediaKey = key;
media.textContent = '';
media.hidden = !video;
if (video) {
media.appendChild(youtubeFrame(video.embedUrl, slide.question));
}
}
function render(newState) { function render(newState) {
var serialized = JSON.stringify(newState); var serialized = JSON.stringify(newState);
@@ -560,6 +696,8 @@
? 'Lege in der Verwaltung Fragen an.' ? 'Lege in der Verwaltung Fragen an.'
: 'Drücke → um zu starten.'; : 'Drücke → um zu starten.';
q('[data-results]').innerHTML = ''; q('[data-results]').innerHTML = '';
renderMedia(null);
root.classList.remove('stage--video');
q('[data-voting]').hidden = true; q('[data-voting]').hidden = true;
q('[data-participants]').textContent = ''; q('[data-participants]').textContent = '';
return; return;
@@ -572,6 +710,8 @@
q('[data-question]').textContent = slide.question; q('[data-question]').textContent = slide.question;
q('[data-description]').textContent = slide.description; q('[data-description]').textContent = slide.description;
root.classList.toggle('stage--content', !slide.isInteractive); root.classList.toggle('stage--content', !slide.isInteractive);
root.classList.toggle('stage--video', slide.type === 'youtube');
renderMedia(slide);
root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase); root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase);
var voting = q('[data-voting]'); var voting = q('[data-voting]');
@@ -1102,6 +1242,8 @@
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function () {
initCopy(); initCopy();
initShare();
document.querySelectorAll('[data-youtube-form]').forEach(initYouTubeForm);
document.querySelectorAll('[data-presenter]').forEach(initPresenter); document.querySelectorAll('[data-presenter]').forEach(initPresenter);
document.querySelectorAll('[data-participant]').forEach(initParticipant); document.querySelectorAll('[data-participant]').forEach(initParticipant);
document.querySelectorAll('[data-quiz-options]').forEach(initQuizOptions); document.querySelectorAll('[data-quiz-options]').forEach(initQuizOptions);