diff --git a/AGENTS.md b/AGENTS.md index 3005a9f..b172d4a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,7 @@ src/ 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 + EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal) Model/ Polls → Slides → SlideOptions, Slides → Responses Service/ @@ -67,6 +68,7 @@ src/ ThrottleService Rate-Limit pro IP (Cache 'throttle') YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client) QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen + SlideControlService Folien-Aktionen open/close/toggle/stage/question (Presenter und Einbettung gemeinsam) templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email webroot/css/plenario.css Eigenes CSS, kein Framework; Farben nur als Tokens (Hell/Dunkel, siehe Theme unten) webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Folien-Sortierung (Pointer Events + Pfeiltasten) @@ -76,7 +78,9 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures ### Datenmodell - `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`, + `embed_key` (Einbett-Schlüssel), `embed_seen_at` (letztes Lebenszeichen der eingebetteten Live-Folie), + `paused_slide_id` (Folie vor der Pause) - `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube|qa`), `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), @@ -136,6 +140,19 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures 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`). +- **Pause:** `current_slide_id = null` + `paused_slide_id` = Pause (Teilnehmende sehen „Kurze Pause“), ohne + `paused_slide_id` = noch nicht gestartet. Immer über `Poll::showSlide()` / `showEmbeddedSlide()` / `pause()` setzen, + nie `current_slide_id` direkt. Presenter: P pausiert, ←/→ setzt bei der pausierten Folie fort. +- **Einbettung** (`/e/{key}/{id}`, `EmbedController`): eigener `embed_key` statt Admin-Token (darf nur diese Folie zeigen, + live schalten, pausieren und `SlideControlService`-Aktionen), wird beim ersten Dashboard-Aufruf erzeugt + (`ensureEmbedKey`, idempotent) und lässt sich neu erzeugen. Die Seite schaltet sich live, solange sie sichtbar ist + (IntersectionObserver + `visibilitychange`), sendet Heartbeats und beim Verschwinden `pause` (sendBeacon). + `pause` wirkt nur, wenn die eigene Folie noch live ist; `heartbeat` holt keine Folie zurück, die im Presenter + gewechselt wurde. Bleiben Heartbeats aus (`Plenario.embed.timeoutSeconds`), pausiert `PollsTable::pauseIfEmbedStale()` + beim nächsten State-Abruf. Embed-Routen haben **keinen CSRF-Check** (Third-Party-Iframe ohne Cookies, der Schlüssel + ist die Berechtigung, siehe `Application::middleware()`) und erlauben Framing per CSP `frame-ancestors` + (`EMBED_FRAME_ANCESTORS`); alle anderen Seiten bleiben `X-Frame-Options: SAMEORIGIN`. + ### Neuen Folientyp hinzufügen (Checkliste) 1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php` diff --git a/config/.env.example b/config/.env.example index 243de31..87cd847 100644 --- a/config/.env.example +++ b/config/.env.example @@ -36,3 +36,8 @@ THROTTLE_CREATE_PER_HOUR=10 THROTTLE_RECOVER_PER_HOUR=5 # How often presenter and participant pages poll for updates (ms) POLL_INTERVAL_MS=2000 +# Embedded slides (/e/{key}/{slide}, e.g. Canva): heartbeat interval and timeout until pause (s) +EMBED_HEARTBEAT_SECONDS=5 +EMBED_TIMEOUT_SECONDS=20 +# CSP frame-ancestors of embed pages, e.g. "https://*.canva.com https://*.iframe.ly" ('*' = any site) +EMBED_FRAME_ANCESTORS=* diff --git a/config/Migrations/20261107150000_AddEmbedToPolls.php b/config/Migrations/20261107150000_AddEmbedToPolls.php new file mode 100644 index 0000000..ec78029 --- /dev/null +++ b/config/Migrations/20261107150000_AddEmbedToPolls.php @@ -0,0 +1,29 @@ +table('polls') + ->addColumn('embed_key', 'string', ['limit' => 64, 'null' => true, 'default' => null, 'after' => 'join_code']) + ->addColumn('embed_seen_at', 'datetime', ['null' => true, 'default' => null, 'after' => 'current_slide_id']) + ->addColumn('paused_slide_id', 'integer', ['null' => true, 'default' => null, 'after' => 'embed_seen_at']) + ->addIndex(['embed_key'], ['unique' => true]) + ->update(); + } +} diff --git a/config/app.php b/config/app.php index 7d776f2..7e27c73 100644 --- a/config/app.php +++ b/config/app.php @@ -40,6 +40,15 @@ return [ 'recoverPerHour' => (int)env('THROTTLE_RECOVER_PER_HOUR', 5), ], 'pollIntervalMs' => (int)env('POLL_INTERVAL_MS', 2000), + // Slides embedded in other presentation software (/e/{key}/{slide}, e.g. Canva). + 'embed' => [ + // A visible embedded slide reports every N seconds that it is still on screen ... + 'heartbeatSeconds' => (int)env('EMBED_HEARTBEAT_SECONDS', 5), + // ... without a report for this long, the poll is paused (presentation moved on / closed). + 'timeoutSeconds' => (int)env('EMBED_TIMEOUT_SECONDS', 20), + // CSP frame-ancestors of the embed pages ('*' = any site; the URL itself is the secret). + 'frameAncestors' => (string)env('EMBED_FRAME_ANCESTORS', '*'), + ], ], /* diff --git a/config/routes.php b/config/routes.php index b8522c0..1775391 100644 --- a/config/routes.php +++ b/config/routes.php @@ -38,6 +38,20 @@ return function (RouteBuilder $routes): void { ->setPass(['code']) ->setMethods(['POST']); + // --- embedded slides (secret embed key, e.g. Canva) ----------------- + // No CSRF check here (see Application::middleware()): runs in third-party iframes + // without cookies, the key in the URL is the authorisation. + $builder->scope('/e/{key}/{id}', function (RouteBuilder $embed): void { + $patterns = ['key' => '[A-Za-z0-9_-]{20,64}', 'id' => '\d+']; + + $embed->connect('/', 'Embed::view', ['_name' => 'embed'])->setPatterns($patterns); + $embed->connect('/state', 'Embed::state', ['_name' => 'embed:state'])->setPatterns($patterns); + foreach (['activate', 'heartbeat', 'pause', 'control'] as $action) { + $embed->connect('/' . $action, 'Embed::' . $action, ['_name' => 'embed:' . $action]) + ->setPatterns($patterns)->setMethods(['POST']); + } + }); + // --- admin (secret token) ----------------------------------------- $builder->scope('/admin/{token}', function (RouteBuilder $admin): void { $token = ['token' => '[A-Za-z0-9_-]{20,64}', 'id' => '\d+']; @@ -47,6 +61,8 @@ return function (RouteBuilder $routes): void { ->setPatterns($token)->setMethods(['POST']); $admin->connect('/rotate-token', 'Admin::rotateToken', ['_name' => 'admin:rotate']) ->setPatterns($token)->setMethods(['POST']); + $admin->connect('/rotate-embed-key', 'Admin::rotateEmbedKey', ['_name' => 'admin:rotate-embed']) + ->setPatterns($token)->setMethods(['POST']); $admin->connect('/delete', 'Admin::delete', ['_name' => 'admin:delete']) ->setPatterns($token)->setMethods(['POST']); $admin->connect('/present', 'Admin::present', ['_name' => 'admin:present'])->setPatterns($token); diff --git a/src/Application.php b/src/Application.php index 98ef0b9..c925801 100644 --- a/src/Application.php +++ b/src/Application.php @@ -29,6 +29,7 @@ use Cake\Http\MiddlewareQueue; use Cake\ORM\Locator\TableLocator; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; +use Psr\Http\Message\ServerRequestInterface; /** * Application setup class. @@ -93,9 +94,15 @@ class Application extends BaseApplication // Cross Site Request Forgery (CSRF) Protection Middleware // https://book.cakephp.org/5/en/security/csrf.html#cross-site-request-forgery-csrf-middleware - ->add(new CsrfProtectionMiddleware([ + ->add((new CsrfProtectionMiddleware([ 'httponly' => true, - ])); + ]))->skipCheckCallback( + // Embedded slides run in third-party iframes (no cookies); the secret key is the authorisation. + fn(ServerRequestInterface $request): bool => (bool)preg_match( + '/^embed(:|$)/', + (string)($request->getAttribute('params')['_name'] ?? ''), + ), + )); return $middlewareQueue; } diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 0467b5b..625a1c5 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -9,6 +9,7 @@ use App\Model\Table\ResponsesTable; use App\Model\Table\SlidesTable; use App\Service\PollStateService; use App\Service\QaService; +use App\Service\SlideControlService; use App\Service\VoteService; use Cake\Core\Configure; use Cake\Http\Exception\BadRequestException; @@ -55,8 +56,10 @@ class AdminController extends AdminAppController $typeLabels = Slide::typeLabels(); $typeDescriptions = Slide::typeDescriptions(); $joinUrl = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true); + // Created on first visit, so every slide has its embed URL ready to copy. + $embedKey = $this->Polls->ensureEmbedKey($this->poll); - $this->set(compact('slides', 'responseCounts', 'typeLabels', 'typeDescriptions', 'joinUrl')); + $this->set(compact('slides', 'responseCounts', 'typeLabels', 'typeDescriptions', 'joinUrl', 'embedKey')); } /** @@ -102,6 +105,20 @@ class AdminController extends AdminAppController return $this->redirect($this->adminUrl()); } + /** + * New embed key: all embed URLs (e.g. in Canva) stop working and must be inserted again. + * + * @return \Cake\Http\Response|null + */ + public function rotateEmbedKey(): ?Response + { + $this->request->allowMethod(['post']); + $this->Polls->rotateEmbedKey($this->poll); + $this->Flash->success(__('Neue Einbett-Links erstellt. Die bisherigen Links funktionieren nicht mehr – füge die neuen in deine Präsentation ein.')); + + return $this->redirect($this->adminUrl() + ['#' => 'embed']); + } + /** * Deletes the whole poll incl. slides and responses. * @@ -130,13 +147,13 @@ class AdminController extends AdminAppController */ public function present(): void { - if ($this->poll->current_slide_id === null) { + if ($this->poll->current_slide_id === null && !$this->poll->isPaused()) { $first = $this->Slides->find() ->where(['poll_id' => $this->poll->id]) ->orderBy(['position' => 'ASC', 'id' => 'ASC']) ->first(); if ($first !== null) { - $this->poll->current_slide_id = $first->id; + $this->poll->showSlide($first->id); $this->Polls->saveOrFail($this->poll); } } @@ -159,11 +176,12 @@ class AdminController extends AdminAppController /** * Presenter controls. Field `action`: - * goto (+ slide_id), next, prev, open, close, toggle, stop, - * Q&A: stage (+ stage: collect|vote|discuss), question (+ step: 1|-1) + * goto (+ slide_id), next, prev, stop (pause), and the slide actions of + * SlideControlService (open, close, toggle, stage, question). * * On a Q&A slide that is being discussed, next/prev step through the questions - * first (like builds in presentation software), toggle switches to the next stage. + * first (like builds in presentation software). While paused, next/prev resume + * the slide that was live before. * * Answers with the new state as JSON for XHR requests, otherwise redirects back. * @@ -177,68 +195,51 @@ class AdminController extends AdminAppController $ids = array_map(fn(Slide $s) => $s->id, $slides); $index = array_search($this->poll->current_slide_id, $ids, true); $current = $index === false ? null : $slides[$index]; - $qa = new QaService(); - if ($current !== null && $current->isQa()) { - if ($action === 'toggle') { - // No-op while discussing (last stage). - $qa->advance($current); - $action = 'none'; - } elseif (in_array($action, ['next', 'prev'], true) && $qa->moveFocus($current, $action === 'next' ? 1 : -1)) { - $action = 'none'; - } + if ( + $current !== null + && $current->isQa() + && in_array($action, ['next', 'prev'], true) + && (new QaService())->moveFocus($current, $action === 'next' ? 1 : -1) + ) { + $action = 'none'; } switch ($action) { case 'none': break; - case 'stage': - case 'question': - if ($current === null || !$current->isQa()) { - throw new BadRequestException('Not a Q&A slide'); - } - if ($action === 'question') { - $qa->moveFocus($current, (int)$this->request->getData('step') < 0 ? -1 : 1); - break; - } - $stage = (string)$this->request->getData('stage'); - if (!in_array($stage, Slide::QA_STAGES, true)) { - throw new BadRequestException('Unknown stage'); - } - $qa->setStage($current, $stage); - break; case 'goto': $target = (int)$this->request->getData('slide_id'); if (!in_array($target, $ids, true)) { throw new BadRequestException('Unknown slide'); } - $this->poll->current_slide_id = $target; + $this->poll->showSlide($target); break; case 'next': case 'prev': - if ($ids !== []) { - $index = $index === false ? 0 : $index + ($action === 'next' ? 1 : -1); - $this->poll->current_slide_id = $ids[max(0, min(count($ids) - 1, $index))]; + if ($ids === []) { + break; } + if ($index === false && in_array($this->poll->paused_slide_id, $ids, true)) { + $this->poll->showSlide((int)$this->poll->paused_slide_id); + break; + } + $index = $index === false ? 0 : $index + ($action === 'next' ? 1 : -1); + $this->poll->showSlide($ids[max(0, min(count($ids) - 1, $index))]); break; case 'stop': - $this->poll->current_slide_id = null; - break; - case 'open': - case 'close': - case 'toggle': - if ($index !== false) { - // Opening a quiz (re)starts its timer, see Slide::setVotingOpen(). - $slide = $slides[$index]; - $slide->setVotingOpen(match ($action) { - 'open' => true, - 'close' => false, - default => !$slide->isVotingOpen(), - }); - $this->Slides->saveOrFail($slide); - } + $this->poll->pause(); break; default: - throw new BadRequestException('Unknown action'); + if (!in_array($action, SlideControlService::ACTIONS, true)) { + throw new BadRequestException('Unknown action'); + } + if ($current === null) { + if (in_array($action, ['stage', 'question'], true)) { + throw new BadRequestException('Not a Q&A slide'); + } + break; + } + (new SlideControlService())->apply($current, $action, (array)$this->request->getData()); } $this->Polls->saveOrFail($this->poll); diff --git a/src/Controller/EmbedController.php b/src/Controller/EmbedController.php new file mode 100644 index 0000000..d979e24 --- /dev/null +++ b/src/Controller/EmbedController.php @@ -0,0 +1,223 @@ +fetchTable('Polls'); + $this->Polls = $polls; + /** @var \App\Model\Table\SlidesTable $slides */ + $slides = $this->fetchTable('Slides'); + $this->Slides = $slides; + } + + /** + * @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event + * @return void + */ + public function beforeFilter(EventInterface $event): void + { + parent::beforeFilter($event); + + /** @var \App\Model\Entity\Poll|null $poll */ + $poll = $this->Polls->find('byEmbedKey', key: (string)$this->request->getParam('key'))->first(); + /** @var \App\Model\Entity\Slide|null $slide */ + $slide = $poll === null ? null : $this->Slides->find() + ->where(['Slides.id' => (int)$this->request->getParam('id'), 'Slides.poll_id' => $poll->id]) + ->contain(['SlideOptions']) + ->first(); + if ($poll === null || $slide === null) { + throw new NotFoundException(__('Diese eingebettete Folie gibt es nicht (mehr).')); + } + $this->poll = $poll; + $this->slide = $slide; + } + + /** + * Like admin pages: never leak the key as referrer, never index or cache. + * Unlike everything else, framing by other sites is allowed. + * + * @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event + * @return void + */ + public function beforeRender(EventInterface $event): void + { + parent::beforeRender($event); + $this->response = $this->protect($this->response) + ->withoutHeader('X-Frame-Options') + ->withHeader('Content-Security-Policy', 'frame-ancestors ' . $this->frameAncestors()); + } + + /** + * @return void + */ + public function view(): void + { + $urls = []; + foreach (['state', 'activate', 'heartbeat', 'pause', 'control'] as $name) { + $urls[$name] = Router::url($this->embedUrl('embed:' . $name)); + } + $this->viewBuilder()->setLayout('present'); + $this->set('poll', $this->poll); + $this->set('slide', $this->slide); + $this->set('urls', $urls); + $this->set('joinBaseUrl', Router::url(['_name' => 'join:short'], true)); + $this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000)); + $this->set('heartbeatMs', max(1, (int)Configure::read('Plenario.embed.heartbeatSeconds', 5)) * 1000); + } + + /** + * @return \Cake\Http\Response + */ + public function state(): Response + { + return $this->stateResponse(); + } + + /** + * The embed became visible: this slide goes live. Idempotent. + * + * @return \Cake\Http\Response + */ + public function activate(): Response + { + $this->request->allowMethod(['post']); + if ($this->poll->is_active) { + $this->poll->showEmbeddedSlide($this->slide->id); + $this->Polls->saveOrFail($this->poll); + } + + return $this->stateResponse(); + } + + /** + * Still visible: keeps the slide live – but never takes it back when the + * presenter has switched to another slide in Plenario in the meantime. + * + * @return \Cake\Http\Response + */ + public function heartbeat(): Response + { + $this->request->allowMethod(['post']); + if ($this->poll->current_slide_id === $this->slide->id && $this->poll->embed_seen_at !== null) { + $this->poll->showEmbeddedSlide($this->slide->id); + $this->Polls->saveOrFail($this->poll); + } + + return $this->stateResponse(); + } + + /** + * The embed disappeared: pause, but only if this slide is still the live one + * (the next embedded slide may already have taken over). Idempotent. + * + * @return \Cake\Http\Response + */ + public function pause(): Response + { + $this->request->allowMethod(['post']); + if ($this->poll->current_slide_id === $this->slide->id) { + $this->poll->pause(); + $this->Polls->saveOrFail($this->poll); + } + + return $this->stateResponse(); + } + + /** + * Voting / quiz / Q&A controls of this slide (see SlideControlService). + * + * @return \Cake\Http\Response + */ + public function control(): Response + { + $this->request->allowMethod(['post']); + $action = (string)$this->request->getData('action'); + if (!in_array($action, SlideControlService::ACTIONS, true)) { + throw new BadRequestException('Unknown action'); + } + (new SlideControlService())->apply($this->slide, $action, (array)$this->request->getData()); + + return $this->stateResponse(); + } + + /** + * @return \Cake\Http\Response + */ + protected function stateResponse(): Response + { + return $this->protect($this->json((new PollStateService())->forEmbed($this->poll, $this->slide))); + } + + /** + * @param \Cake\Http\Response $response Response + * @return \Cake\Http\Response + */ + protected function protect(Response $response): Response + { + return $response + ->withHeader('Referrer-Policy', 'no-referrer') + ->withHeader('X-Robots-Tag', 'noindex, nofollow') + ->withHeader('Cache-Control', 'no-store, private'); + } + + /** + * @param string $name Route name + * @return array + */ + protected function embedUrl(string $name): array + { + return ['_name' => $name, 'key' => (string)$this->poll->embed_key, 'id' => $this->slide->id]; + } + + /** + * @return string CSP source list; falls back to 'self' for anything unexpected + */ + protected function frameAncestors(): string + { + $value = trim((string)Configure::read('Plenario.embed.frameAncestors', '*')); + + return preg_match('#^[A-Za-z0-9*:/.\' -]+$#', $value) ? $value : "'self'"; + } +} diff --git a/src/Model/Entity/Poll.php b/src/Model/Entity/Poll.php index 76e7eb6..e7bfc81 100644 --- a/src/Model/Entity/Poll.php +++ b/src/Model/Entity/Poll.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace App\Model\Entity; +use Cake\I18n\DateTime; use Cake\ORM\Entity; /** @@ -12,7 +13,10 @@ use Cake\ORM\Entity; * @property string $admin_token_hash * @property string $admin_token_encrypted * @property string $join_code + * @property string|null $embed_key * @property int|null $current_slide_id + * @property \Cake\I18n\DateTime|null $embed_seen_at + * @property int|null $paused_slide_id * @property bool $is_active * @property bool $show_results_to_participants * @property \Cake\I18n\DateTime|null $last_admin_access @@ -44,6 +48,7 @@ class Poll extends Entity 'admin_token_hash', 'admin_token_encrypted', 'email', + 'embed_key', ]; /** @@ -55,4 +60,52 @@ class Poll extends Entity { return trim(chunk_split($this->join_code, 3, ' ')); } + + /** + * Shows a slide to the participants (from Plenario itself: no embed timeout). + * + * @param int $slideId Slide id (must belong to this poll, checked by the caller) + * @return void + */ + public function showSlide(int $slideId): void + { + $this->current_slide_id = $slideId; + $this->paused_slide_id = null; + $this->embed_seen_at = null; + } + + /** + * Shows a slide because its embedded page (e.g. in Canva) became visible. + * It stays live only as long as the page keeps sending heartbeats. + * + * @param int $slideId Slide id + * @return void + */ + public function showEmbeddedSlide(int $slideId): void + { + $this->showSlide($slideId); + $this->embed_seen_at = DateTime::now(); + } + + /** + * No slide live: participants see the pause page. Idempotent. + * + * @return void + */ + public function pause(): void + { + if ($this->current_slide_id !== null) { + $this->paused_slide_id = $this->current_slide_id; + } + $this->current_slide_id = null; + $this->embed_seen_at = null; + } + + /** + * @return bool Paused after a slide had been live (not: not started yet) + */ + public function isPaused(): bool + { + return $this->current_slide_id === null && $this->paused_slide_id !== null; + } } diff --git a/src/Model/Table/PollsTable.php b/src/Model/Table/PollsTable.php index f460308..d51485a 100644 --- a/src/Model/Table/PollsTable.php +++ b/src/Model/Table/PollsTable.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Model\Table; use App\Model\Entity\Poll; +use Cake\Core\Configure; use Cake\ORM\Query\SelectQuery; use Cake\ORM\RulesChecker; use Cake\ORM\Table; @@ -230,4 +231,82 @@ class PollsTable extends Table { return $query->where(['Polls.join_code' => static::normalizeJoinCode($code)]); } + + /** + * @param \Cake\ORM\Query\SelectQuery $query Query + * @param string $key Embed key + * @return \Cake\ORM\Query\SelectQuery + */ + public function findByEmbedKey(SelectQuery $query, string $key): SelectQuery + { + // Never match polls without key (null) and never compare against an empty string. + return $query->where(['Polls.embed_key' => $key === '' ? '-' : $key]); + } + + /** + * Creates the embed key on first use; keeps an existing one (idempotent). + * + * @param \App\Model\Entity\Poll $poll Poll + * @return string + */ + public function ensureEmbedKey(Poll $poll): string + { + if ($poll->embed_key === null || $poll->embed_key === '') { + return $this->rotateEmbedKey($poll); + } + + return $poll->embed_key; + } + + /** + * New embed key, all previous embed URLs stop working. + * + * @param \App\Model\Entity\Poll $poll Poll + * @return string + */ + public function rotateEmbedKey(Poll $poll): string + { + // Only the key column, so the rest of the entity (e.g. live slide) is not overwritten. + $key = static::generateToken(); + $this->updateAll(['embed_key' => $key], ['id' => $poll->id]); + $poll->embed_key = $key; + $poll->setDirty('embed_key', false); + + return $key; + } + + /** + * Pauses the poll when the embedded slide that made itself live has stopped reporting + * (presentation moved on to a non-Plenario slide, or was closed without a pause beacon). + * Called lazily whenever the state is read, like SlidesTable::closeIfExpired(). + * + * @param \App\Model\Entity\Poll $poll Poll + * @return \App\Model\Entity\Poll + */ + public function pauseIfEmbedStale(Poll $poll): Poll + { + $timeout = max(1, (int)Configure::read('Plenario.embed.timeoutSeconds', 20)); + if ( + $poll->embed_seen_at === null + || $poll->current_slide_id === null + || $poll->embed_seen_at->wasWithinLast($timeout . ' seconds') + ) { + return $poll; + } + + // Conditional update: a concurrent heartbeat or slide change wins. + $this->updateAll( + ['current_slide_id' => null, 'paused_slide_id' => $poll->current_slide_id, 'embed_seen_at' => null], + ['id' => $poll->id, 'current_slide_id' => $poll->current_slide_id, 'embed_seen_at' => $poll->embed_seen_at], + ); + + /** @var \App\Model\Entity\Poll $fresh */ + $fresh = $this->get($poll->id); + foreach (['current_slide_id', 'paused_slide_id', 'embed_seen_at'] as $field) { + $poll->set($field, $fresh->get($field)); + $poll->setDirty($field, false); + } + + return $poll; + } } diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index d3a8f3b..3f183f6 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -5,6 +5,7 @@ namespace App\Service; use App\Model\Entity\Poll; use App\Model\Entity\Slide; +use App\Model\Table\PollsTable; use App\Model\Table\ResponsesTable; use App\Model\Table\SlidesTable; use Cake\ORM\Locator\LocatorAwareTrait; @@ -33,6 +34,8 @@ class PollStateService protected ResponsesTable $Responses; + protected PollsTable $Polls; + protected ResultsService $results; /** @@ -46,6 +49,9 @@ class PollStateService /** @var \App\Model\Table\ResponsesTable $responses */ $responses = $this->fetchTable('Responses'); $this->Responses = $responses; + /** @var \App\Model\Table\PollsTable $polls */ + $polls = $this->fetchTable('Polls'); + $this->Polls = $polls; $this->results = new ResultsService(); } @@ -55,6 +61,7 @@ class PollStateService */ public function currentSlide(Poll $poll): ?Slide { + $this->Polls->pauseIfEmbedStale($poll); if ($poll->current_slide_id === null) { return null; } @@ -74,6 +81,7 @@ class PollStateService */ public function forPresenter(Poll $poll): array { + $this->Polls->pauseIfEmbedStale($poll); $slides = $this->Slides->listForPoll($poll->id); $current = null; $index = null; @@ -90,6 +98,7 @@ class PollStateService 'joinCode' => $poll->join_code, 'joinCodeFormatted' => $poll->formattedJoinCode(), 'isActive' => $poll->is_active, + 'isPaused' => $poll->isPaused(), ], 'slides' => array_map(fn(Slide $s) => [ 'id' => $s->id, @@ -103,6 +112,35 @@ class PollStateService ]; } + /** + * State of one embedded slide (/e/{key}/{slide}/state). Same shape as forPresenter(), + * but always for this slide, live or not, plus `isLive`. Never contains the slide list. + * + * @param \App\Model\Entity\Poll $poll Poll + * @param \App\Model\Entity\Slide $slide Slide of this poll incl. slide_options + * @return array + */ + public function forEmbed(Poll $poll, Slide $slide): array + { + $this->Polls->pauseIfEmbedStale($poll); + $slide = $this->Slides->closeIfExpired($slide); + + return [ + 'poll' => [ + 'title' => $poll->title, + 'joinCode' => $poll->join_code, + 'joinCodeFormatted' => $poll->formattedJoinCode(), + 'isActive' => $poll->is_active, + 'isPaused' => $poll->isPaused(), + ], + 'isLive' => $poll->current_slide_id === $slide->id, + 'index' => null, + 'count' => null, + 'slide' => $this->slidePayload($slide), + 'results' => $this->results->forSlide($slide), + ]; + } + /** * @param \App\Model\Entity\Poll $poll Poll * @param string $participantHash Participant hash @@ -131,6 +169,7 @@ class PollStateService return [ 'isActive' => $poll->is_active, + 'isPaused' => $slide === null && $poll->isPaused(), 'slideId' => $slide?->id, 'isVotingOpen' => $isVotingOpen, 'hasResponded' => $hasResponded, diff --git a/src/Service/SlideControlService.php b/src/Service/SlideControlService.php new file mode 100644 index 0000000..5123858 --- /dev/null +++ b/src/Service/SlideControlService.php @@ -0,0 +1,90 @@ +fetchTable('Slides'); + $this->Slides = $slides; + } + + /** + * @param \App\Model\Entity\Slide $slide Slide (belongs to the poll, checked by the caller) + * @param string $action One of self::ACTIONS + * @param array $data Request data (stage, step) + * @return void + * @throws \Cake\Http\Exception\BadRequestException + */ + public function apply(Slide $slide, string $action, array $data = []): void + { + $qa = new QaService(); + switch ($action) { + case 'stage': + case 'question': + if (!$slide->isQa()) { + throw new BadRequestException('Not a Q&A slide'); + } + if ($action === 'question') { + $qa->moveFocus($slide, (int)($data['step'] ?? 1) < 0 ? -1 : 1); + break; + } + $stage = (string)($data['stage'] ?? ''); + if (!in_array($stage, Slide::QA_STAGES, true)) { + throw new BadRequestException('Unknown stage'); + } + $qa->setStage($slide, $stage); + break; + case 'toggle': + if ($slide->isQa()) { + $qa->advance($slide); + break; + } + $this->setVotingOpen($slide, !$slide->isVotingOpen()); + break; + case 'open': + case 'close': + $this->setVotingOpen($slide, $action === 'open'); + break; + default: + throw new BadRequestException('Unknown action'); + } + } + + /** + * Opening a quiz (re)starts its timer, see Slide::setVotingOpen(). + * + * @param \App\Model\Entity\Slide $slide Slide + * @param bool $open Open or close + * @return void + */ + protected function setVotingOpen(Slide $slide, bool $open): void + { + $slide->setVotingOpen($open); + $this->Slides->saveOrFail($slide); + } +} diff --git a/templates/Admin/index.php b/templates/Admin/index.php index 9bdbce0..d1672d6 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -10,6 +10,7 @@ * @var array $typeLabels * @var array $typeDescriptions * @var string $joinUrl + * @var string $embedKey */ $this->assign('title', $poll->title); $this->assign('noindex', '1'); @@ -25,12 +26,22 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad + isPaused()) : ?> + +

▶ + current_slide_id !== null) : ?> + Form->postLink('⏸ ' . __('Pause'), $url('admin:control'), [ + 'data' => ['action' => 'stop'], + 'class' => 'button', + 'title' => __('Keine Folie zeigen – Teilnehmende sehen eine Pause-Seite'), + ]) ?> +
@@ -97,6 +108,15 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad $slide->slide_options, ))) ?>

+
+ +
+ + +
+
@@ -145,6 +165,17 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad
+
+

+

+

+

+ Form->postLink(__('Neue Einbett-Links erzeugen'), $url('admin:rotate-embed'), [ + 'class' => 'button button--small', + 'confirm' => __('Neue Einbett-Links erzeugen? Alle bisher eingebetteten Folien funktionieren danach nicht mehr.'), + ]) ?> +
+

Form->create($poll, ['url' => $url('admin:settings'), 'type' => 'post']) ?> diff --git a/templates/Admin/present.php b/templates/Admin/present.php index 13a6be5..1ad65c2 100644 --- a/templates/Admin/present.php +++ b/templates/Admin/present.php @@ -3,7 +3,7 @@ * Presenter screen. Rendered empty and filled by webroot/js/plenario.js * (Plenario.presenter) from /admin/{token}/state. * - * Keyboard: ←/→ slides, V voting on/off, H hide results, F fullscreen, Q QR code, T light/dark. + * Keyboard: ←/→ slides, P pause (→ resumes), V voting on/off, H hide results, F fullscreen, Q QR code, T light/dark. * Q&A slides: V switches to the next stage; while discussing ←/→ step through the questions first. * * @var \App\View\AppView $this @@ -50,6 +50,10 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl); + diff --git a/templates/Embed/view.php b/templates/Embed/view.php new file mode 100644 index 0000000..385a430 --- /dev/null +++ b/templates/Embed/view.php @@ -0,0 +1,66 @@ + $urls state, activate, heartbeat, pause, control + * @var string $joinBaseUrl + * @var int $pollIntervalMs + * @var int $heartbeatMs + */ +$this->assign('title', $slide->question); +$host = preg_replace('#^https?://#', '', $joinBaseUrl); +?> +
+ +
+
+ + formattedJoinCode()) ?> +
+ +
+ +
+

+

question) ?>

+

+ +
+
+ +
+ + + + + element('theme_switch', [ + 'key' => 'plenario-theme-present', + 'modes' => 'dark,light', + 'class' => 'ctrl ctrl--wide', + 'shortcut' => 'T', + ]) ?> +
+
diff --git a/templates/Participate/view.php b/templates/Participate/view.php index 5e31cac..4f21cb7 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -41,6 +41,13 @@ $countdown = function (?int $remaining): string {

+ isPaused()) : ?> +
+ +

+

+
+
diff --git a/tests/TestCase/Controller/EmbedTest.php b/tests/TestCase/Controller/EmbedTest.php new file mode 100644 index 0000000..cebf60c --- /dev/null +++ b/tests/TestCase/Controller/EmbedTest.php @@ -0,0 +1,271 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + /** + * @return array{0: \App\Model\Entity\Poll, 1: string, 2: string} poll, admin token, embed key + */ + protected function embeddedPoll(): array + { + [$poll, $token] = $this->createPoll(); + $key = $this->pollsTable()->ensureEmbedKey($poll); + + return [$poll, $token, $key]; + } + + /** + * POST without CSRF token, like the beacon / fetch from a third-party iframe. + * + * @return array + */ + protected function embedPost(string $key, Slide $slide, string $action, array $data = []): array + { + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/e/$key/{$slide->id}/$action", $data); + $this->assertResponseOk(); + + return json_decode((string)$this->_response->getBody(), true); + } + + protected function reload(Poll $poll): Poll + { + return $this->pollsTable()->get($poll->id); + } + + public function testEnsureEmbedKeyIsIdempotent(): void + { + [$poll] = $this->createPoll(); + $key = $this->pollsTable()->ensureEmbedKey($poll); + + $this->assertSame($key, $this->pollsTable()->ensureEmbedKey($this->reload($poll))); + $this->assertNotSame($key, $this->pollsTable()->rotateEmbedKey($poll)); + } + + public function testUnknownKeyOrForeignSlideIs404(): void + { + [$poll, , $key] = $this->embeddedPoll(); + [$other] = $this->createPoll('Andere'); + $foreign = $this->createSlide($other); + $this->createSlide($poll); + + $this->get('/e/' . str_repeat('x', 43) . '/' . $foreign->id); + $this->assertResponseCode(404); + $this->get("/e/$key/{$foreign->id}"); + $this->assertResponseCode(404); + } + + public function testViewMayBeFramedAndHidesAdminToken(): void + { + [$poll, $token, $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_CHOICE, ['question' => 'Wie es?']); + + $this->get("/e/$key/{$slide->id}"); + + $this->assertResponseOk(); + $this->assertResponseContains('Wie <geht> es?'); + $this->assertResponseContains('data-embed'); + $this->assertResponseNotContains($token); + $this->assertHeader('Content-Security-Policy', 'frame-ancestors *'); + $this->assertNull($this->_response->getHeaderLine('X-Frame-Options') ?: null); + $this->assertHeader('Referrer-Policy', 'no-referrer'); + $this->assertNull($this->reload($poll)->current_slide_id, 'viewing alone does not go live'); + } + + public function testActivateWorksWithoutCsrfAndIsIdempotent(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + + $state = $this->embedPost($key, $slide, 'activate'); + $this->embedPost($key, $slide, 'activate'); + + $this->assertTrue($state['isLive']); + $this->assertSame($slide->id, $state['slide']['id']); + $this->assertArrayNotHasKey('slides', $state); + $poll = $this->reload($poll); + $this->assertSame($slide->id, $poll->current_slide_id); + $this->assertNotNull($poll->embed_seen_at); + } + + public function testCsrfIsStillCheckedOutsideEmbedRoutes(): void + { + [$poll, $token] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + + $this->post("/admin/$token/control", ['action' => 'goto', 'slide_id' => $slide->id]); + $this->assertResponseCode(403); + $this->post('/p/' . $poll->join_code . '/vote', ['slide_id' => $slide->id]); + $this->assertResponseCode(403); + } + + public function testActivateDoesNothingWhenPollIsClosed(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + $this->pollsTable()->updateAll(['is_active' => false], ['id' => $poll->id]); + + $state = $this->embedPost($key, $slide, 'activate'); + + $this->assertFalse($state['isLive']); + $this->assertNull($this->reload($poll)->current_slide_id); + } + + public function testPauseOnlyWhenOwnSlideIsLive(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $first = $this->createSlide($poll); + $second = $this->createSlide($poll, Slide::TYPE_OPEN); + + // Canva moves from embed 1 to embed 2: the late pause beacon of 1 must not stop 2. + $this->embedPost($key, $first, 'activate'); + $this->embedPost($key, $second, 'activate'); + $this->embedPost($key, $first, 'pause'); + $this->assertSame($second->id, $this->reload($poll)->current_slide_id); + + $this->embedPost($key, $second, 'pause'); + $this->embedPost($key, $second, 'pause'); + $poll = $this->reload($poll); + $this->assertNull($poll->current_slide_id); + $this->assertSame($second->id, $poll->paused_slide_id); + $this->assertTrue($poll->isPaused()); + + $this->get('/p/' . $poll->join_code); + $this->assertResponseContains('Kurze Pause'); + $this->get('/p/' . $poll->join_code . '/state'); + $this->assertTrue(json_decode((string)$this->_response->getBody(), true)['isPaused']); + } + + public function testHeartbeatDoesNotTakeBackManuallyChosenSlide(): void + { + [$poll, $token, $key] = $this->embeddedPoll(); + $embedded = $this->createSlide($poll); + $other = $this->createSlide($poll, Slide::TYPE_OPEN); + $this->embedPost($key, $embedded, 'activate'); + + $this->enableCsrfToken(); + $this->post("/admin/$token/control", ['action' => 'goto', 'slide_id' => $other->id]); + $this->assertNull($this->reload($poll)->embed_seen_at, 'manual choice has no embed timeout'); + + $state = $this->embedPost($key, $embedded, 'heartbeat'); + $this->assertFalse($state['isLive']); + $this->assertSame($other->id, $this->reload($poll)->current_slide_id); + } + + public function testPollPausesWhenHeartbeatsStop(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + $this->embedPost($key, $slide, 'activate'); + $this->pollsTable()->updateAll(['embed_seen_at' => DateTime::now()->subMinutes(5)], ['id' => $poll->id]); + + $this->get('/p/' . $poll->join_code . '/state'); + $state = json_decode((string)$this->_response->getBody(), true); + + $this->assertNull($state['slideId']); + $this->assertTrue($state['isPaused']); + $poll = $this->reload($poll); + $this->assertNull($poll->current_slide_id); + $this->assertSame($slide->id, $poll->paused_slide_id); + } + + public function testFreshHeartbeatKeepsSlideLive(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + $this->embedPost($key, $slide, 'activate'); + $this->pollsTable()->updateAll(['embed_seen_at' => DateTime::now()->subMinutes(5)], ['id' => $poll->id]); + + $this->post("/e/$key/{$slide->id}/heartbeat"); + $this->get('/p/' . $poll->join_code . '/state'); + + $this->assertSame($slide->id, json_decode((string)$this->_response->getBody(), true)['slideId']); + } + + public function testControlStartsQuizButRejectsNavigation(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $quiz = $this->createSlide($poll, Slide::TYPE_QUIZ, ['is_voting_open' => false], ['Richtig', 'Falsch']); + $this->embedPost($key, $quiz, 'activate'); + + $state = $this->embedPost($key, $quiz, 'control', ['action' => 'toggle']); + $this->assertSame('running', $state['results']['phase']); + $this->assertStringNotContainsString('correct', (string)$this->_response->getBody()); + + foreach (['next', 'goto', 'stop', 'delete'] as $action) { + $this->post("/e/$key/{$quiz->id}/control", ['action' => $action]); + $this->assertResponseCode(400, $action); + } + } + + public function testQaStageCanBeSwitchedFromEmbed(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $qa = $this->createSlide($poll, Slide::TYPE_QA); + + $state = $this->embedPost($key, $qa, 'control', ['action' => 'stage', 'stage' => Slide::QA_VOTE]); + + $this->assertSame(Slide::QA_VOTE, $state['results']['stage']); + } + + public function testAdminPauseAndResume(): void + { + [$poll, $token] = $this->createPoll(); + $first = $this->createSlide($poll); + $second = $this->createSlide($poll, Slide::TYPE_OPEN); + $this->goLive($poll, $second); + $this->enableCsrfToken(); + + $this->post("/admin/$token/control", ['action' => 'stop']); + $this->assertTrue($this->reload($poll)->isPaused()); + + // Opening the presenter while paused keeps the pause. + $this->get("/admin/$token/present"); + $this->assertTrue($this->reload($poll)->isPaused()); + + // → resumes the slide that was live, not the next one / the first one. + $this->post("/admin/$token/control", ['action' => 'next']); + $poll = $this->reload($poll); + $this->assertSame($second->id, $poll->current_slide_id); + $this->assertNull($poll->paused_slide_id); + $this->assertNotSame($first->id, $poll->current_slide_id); + } + + public function testDashboardListsEmbedLinksAndRotationInvalidatesThem(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll); + + $this->get("/admin/$token"); + $key = (string)$this->reload($poll)->embed_key; + $this->assertNotSame('', $key); + $this->assertResponseContains("/e/$key/{$slide->id}"); + + $this->enableCsrfToken(); + $this->post("/admin/$token/rotate-embed-key"); + $this->assertRedirectContains("/admin/$token"); + + $this->get("/e/$key/{$slide->id}"); + $this->assertResponseCode(404); + } +} diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 041f8ca..85e6654 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -238,6 +238,11 @@ textarea { resize: vertical; } .slide-item__meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: .85rem; margin-bottom: 4px; } .slide-item__title { font-weight: 600; color: var(--text); text-decoration: none; word-break: break-word; } .slide-item__options { margin: 4px 0 0; font-size: .85rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.slide-embed { margin-top: 6px; font-size: .85rem; } +.slide-embed summary { cursor: pointer; color: var(--muted); width: max-content; } +.slide-embed summary:hover { color: var(--text); } +.slide-embed .copy-field { margin-top: 6px; } +.slide-embed input { min-width: 0; flex: 1; } .slide-item__actions { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; } @media (max-width: 700px) { .slide-item { grid-template-columns: auto minmax(0, 1fr); } @@ -530,6 +535,10 @@ body.present { @media (hover: none) and (pointer: coarse) { .ctrl__key { display: none; } /* touch devices usually have no keyboard */ } +.live-indicator { font-size: .8em; color: var(--muted); white-space: nowrap; } +.live-indicator.is-live { color: var(--c1); font-weight: 700; } +/* Embedded slides are smaller than a beamer: keep the controls visible, they are the only ones. */ +.stage--embed .stage__controls { opacity: .7; } .ctrl-counter { color: var(--muted); min-width: 64px; text-align: center; font-variant-numeric: tabular-nums; } .qr-overlay { position: fixed; inset: 0; background: var(--overlay-bg); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 16px; cursor: zoom-out; z-index: 10; } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index 2541d72..f0b1289 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -5,7 +5,8 @@ * - [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; + * with [data-embed]: one embedded slide (/e/{key}/{id}), goes live while visible * - [data-participant] participant page, polls /p/{code}/state * - [data-countdown] quiz timer (data-remaining = seconds), fires `plenario:timeup` on document * - [data-quiz-options] slide form: "add answer" button for quiz slides @@ -761,6 +762,13 @@ var controlUrl = root.getAttribute('data-control-url'); var interval = parseInt(root.getAttribute('data-interval'), 10) || 2000; var q = function (selector) { return root.querySelector(selector); }; + var embedded = root.hasAttribute('data-embed'); + var setText = function (selector, text) { + var node = q(selector); + if (node) { + node.textContent = text; + } + }; var last = ''; var hideResults = false; var state = null; @@ -791,23 +799,32 @@ state = newState; var slide = state.slide; - q('[data-counter]').textContent = state.count === 0 + setText('[data-counter]', state.count === 0 ? '0 / 0' - : (state.index === null ? '–' : state.index + 1) + ' / ' + state.count; + : (state.index === null ? (state.poll.isPaused ? '⏸' : '–') : state.index + 1) + ' / ' + state.count); + var pauseButton = q('[data-action="stop"]'); + if (pauseButton) { + pauseButton.hidden = !slide; + } + if (embedded) { + renderLive(); + } if (!slide) { - q('[data-type]').textContent = ''; + q('[data-type]').textContent = state.poll.isPaused ? 'Pause' : ''; q('[data-question]').textContent = state.count === 0 ? 'Noch keine Folien angelegt' : state.poll.title; q('[data-description]').textContent = state.count === 0 ? 'Lege in der Verwaltung Fragen an.' - : 'Drücke → um zu starten.'; + : (state.poll.isPaused + ? 'Teilnehmende sehen gerade eine Pause-Seite. Drücke → zum Fortsetzen.' + : 'Drücke → um zu starten.'); q('[data-results]').innerHTML = ''; renderMedia(null); root.classList.remove('stage--video'); q('[data-voting]').hidden = true; - q('[data-participants]').textContent = ''; + setText('[data-participants]', ''); return; } @@ -834,9 +851,9 @@ : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen')); var count = qaStage ? state.results.questions.length : (slide.isInteractive ? state.results.participants : 0); - q('[data-participants]').textContent = !slide.isInteractive ? '' : (qaStage + setText('[data-participants]', !slide.isInteractive ? '' : (qaStage ? count + (count === 1 ? ' Frage' : ' Fragen') - : count + ' ' + (count === 1 ? 'Antwort' : 'Antworten')); + : count + ' ' + (count === 1 ? 'Antwort' : 'Antworten'))); var container = q('[data-results]'); container.classList.toggle('is-hidden', hideResults); @@ -865,10 +882,70 @@ function toggleHide() { hideResults = !hideResults; q('[data-results]').classList.toggle('is-hidden', hideResults); - q('[data-hide-results] [data-label]').textContent = hideResults ? 'Ergebnisse zeigen' : 'Ergebnisse verbergen'; + setText('[data-hide-results] [data-label]', hideResults ? 'Ergebnisse zeigen' : 'Ergebnisse verbergen'); } q('[data-hide-results]').addEventListener('click', toggleHide); + /* + * Embed mode: the slide goes live while the embed is really on screen (tab visible and + * at least half of it in the viewport - IntersectionObserver also sees through the + * iframes of the surrounding presentation), stays live with heartbeats, pauses when gone. + */ + var live = false; + function renderLive() { + var isLive = !!state.isLive; + var indicator = q('[data-live]'); + indicator.textContent = !state.poll.isActive + ? 'Umfrage geschlossen' + : (isLive ? '● live' : 'nicht live'); + indicator.classList.toggle('is-live', isLive); + q('[data-go-live]').hidden = isLive || !state.poll.isActive; + } + function goLive() { + live = true; + postJson(root.getAttribute('data-activate-url'), {}).then(render).catch(function () {}); + } + function leave() { + if (!live) { + return; + } + live = false; + var url = root.getAttribute('data-pause-url'); + // sendBeacon survives page unload; embed routes need no CSRF token. + if (!(navigator.sendBeacon && navigator.sendBeacon(url, new FormData()))) { + postJson(url, {}).catch(function () {}); + } + } + if (embedded) { + var inView = false; + var check = function () { + if (inView && document.visibilityState === 'visible') { + if (!live) { + goLive(); + } + } else { + leave(); + } + }; + if ('IntersectionObserver' in window) { + new IntersectionObserver(function (entries) { + inView = entries[entries.length - 1].intersectionRatio >= 0.5; + check(); + }, { threshold: [0, 0.5, 1] }).observe(root); + } else { + inView = true; + check(); + } + document.addEventListener('visibilitychange', check); + window.addEventListener('pagehide', leave); + q('[data-go-live]').addEventListener('click', goLive); + setInterval(function () { + if (live) { + postJson(root.getAttribute('data-heartbeat-url'), {}).then(render).catch(function () {}); + } + }, parseInt(root.getAttribute('data-heartbeat'), 10) || 5000); + } + function toggleFullscreen() { if (!document.fullscreenElement) { (document.documentElement.requestFullscreen || function () {}).call(document.documentElement); @@ -876,20 +953,33 @@ document.exitFullscreen(); } } - q('[data-fullscreen]').addEventListener('click', toggleFullscreen); + if (q('[data-fullscreen]')) { + q('[data-fullscreen]').addEventListener('click', toggleFullscreen); + } var overlay = q('[data-qr-overlay]'); function toggleQr() { - overlay.hidden = !overlay.hidden; + if (overlay) { + overlay.hidden = !overlay.hidden; + } + } + if (overlay) { + q('[data-qr-toggle]').addEventListener('click', toggleQr); + overlay.addEventListener('click', toggleQr); } - q('[data-qr-toggle]').addEventListener('click', toggleQr); - overlay.addEventListener('click', toggleQr); document.addEventListener('keydown', function (event) { if (event.target.closest('input, textarea, select')) { return; } + if (embedded && ['ArrowRight', 'ArrowLeft', 'PageUp', 'PageDown', ' ', 'p', 'P', 'f', 'F', 'q', 'Q'].indexOf(event.key) >= 0) { + return; // slide navigation belongs to the surrounding presentation + } switch (event.key) { + case 'p': + case 'P': + control('stop'); + break; case 'ArrowRight': case 'PageDown': case ' ': @@ -926,7 +1016,9 @@ } break; case 'Escape': - overlay.hidden = true; + if (overlay) { + overlay.hidden = true; + } break; } });