Add embeddable slides and pause mode
Every slide gets an embed URL /e/{key}/{id} for presentation software
like Canva. The page goes live while it is visible, keeps itself live
with heartbeats and pauses when it disappears; stale embeds are paused
lazily. The embed key is separate from the admin token and only allows
showing, activating, pausing and voting controls of that slide.
Participants see a pause page while no slide is live. The presenter
can pause (P) and resume the paused slide with the arrow keys; the
dashboard has a pause button.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
58145e9753
commit
07a292d109
19 files changed
+1116
-68
No files matched your search
+9
-2
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\PollsTable;
|
||||
use App\Model\Table\SlidesTable;
|
||||
use App\Service\PollStateService;
|
||||
use App\Service\SlideControlService;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Event\EventInterface;
|
||||
use Cake\Http\Exception\BadRequestException;
|
||||
use Cake\Http\Exception\NotFoundException;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Routing\Router;
|
||||
|
||||
/**
|
||||
* One slide embedded in other presentation software (e.g. Canva): /e/{key}/{id}.
|
||||
*
|
||||
* The embed key only allows showing this slide, making it live, pausing and the
|
||||
* slide actions of SlideControlService – never editing or the admin dashboard.
|
||||
* The page makes its slide live while it is visible (`activate`), keeps it live
|
||||
* with `heartbeat`s and pauses when it disappears (`pause`, sendBeacon). If the
|
||||
* heartbeats stop, PollsTable::pauseIfEmbedStale() pauses the poll.
|
||||
*
|
||||
* Runs in third-party iframes: no CSRF check (see Application::middleware()),
|
||||
* framing allowed via CSP frame-ancestors (Plenario.embed.frameAncestors).
|
||||
*/
|
||||
class EmbedController extends AppController
|
||||
{
|
||||
protected PollsTable $Polls;
|
||||
|
||||
protected SlidesTable $Slides;
|
||||
|
||||
protected Poll $poll;
|
||||
|
||||
protected Slide $slide;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
/** @var \App\Model\Table\PollsTable $polls */
|
||||
$polls = $this->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<string, mixed>
|
||||
*/
|
||||
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'";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, mixed>
|
||||
*/
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\SlidesTable;
|
||||
use Cake\Http\Exception\BadRequestException;
|
||||
use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
|
||||
/**
|
||||
* Presenter actions on a single slide, shared by the presenter screen
|
||||
* (AdminController::control) and embedded slides (EmbedController::control).
|
||||
*
|
||||
* Actions: open, close, toggle, Q&A: stage (+ stage: collect|vote|discuss), question (+ step: 1|-1).
|
||||
* On Q&A slides `toggle` switches to the next stage (no-op while discussing).
|
||||
*/
|
||||
class SlideControlService
|
||||
{
|
||||
use LocatorAwareTrait;
|
||||
|
||||
public const ACTIONS = ['open', 'close', 'toggle', 'stage', 'question'];
|
||||
|
||||
protected SlidesTable $Slides;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
/** @var \App\Model\Table\SlidesTable $slides */
|
||||
$slides = $this->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<string, mixed> $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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user