Add countdown audio per presentation #117

Merged
gnilebein merged 2 commits from feature/quiz-audio into main 2026-11-21 11:46:29 +01:00
16 changed files with 642 additions and 5 deletions

No files matched your search

+2
View File
@@ -52,6 +52,8 @@ POLL_INTERVAL_MS=2000
# UPLOADS_PATH=/var/www/plenario-uploads # UPLOADS_PATH=/var/www/plenario-uploads
IMAGE_MAX_UPLOAD_MB=10 IMAGE_MAX_UPLOAD_MB=10
IMAGE_MAX_PER_POLL=20 IMAGE_MAX_PER_POLL=20
# Countdown music of a presentation: largest upload in MB (PHP's upload_max_filesize and post_max_size must allow it)
AUDIO_MAX_UPLOAD_MB=10
# Embedded slides (/e/{key}/{slide}, e.g. Canva): heartbeat interval and timeout until pause (s) # Embedded slides (/e/{key}/{slide}, e.g. Canva): heartbeat interval and timeout until pause (s)
EMBED_HEARTBEAT_SECONDS=5 EMBED_HEARTBEAT_SECONDS=5
EMBED_TIMEOUT_SECONDS=20 EMBED_TIMEOUT_SECONDS=20
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
use Migrations\BaseMigration;
/**
* Optional audio file per presentation, played in the presenter view while a quiz countdown runs.
* The file lives in the upload directory, see \App\Service\AudioService; the table only holds its
* random file name.
*/
class AddAudioToPolls extends BaseMigration
{
/**
* @return void
*/
public function up(): void
{
$table = $this->table('polls');
if (!$table->hasColumn('audio')) {
$table->addColumn('audio', 'string', ['null' => true, 'default' => null, 'limit' => 40])->update();
}
}
/**
* @return void
*/
public function down(): void
{
$table = $this->table('polls');
if ($table->hasColumn('audio')) {
$table->removeColumn('audio')->update();
}
}
}
+5
View File
@@ -69,6 +69,11 @@ return [
// Slides with an image per poll. // Slides with an image per poll.
'maxPerPoll' => (int)env('IMAGE_MAX_PER_POLL', 20), 'maxPerPoll' => (int)env('IMAGE_MAX_PER_POLL', 20),
], ],
// Countdown audio of a presentation (see \App\Service\AudioService): stored as uploaded next to the images.
'audio' => [
// Largest accepted upload. PHP's upload_max_filesize/post_max_size must allow it.
'maxUploadBytes' => (int)env('AUDIO_MAX_UPLOAD_MB', 10) * 1024 * 1024,
],
// Slides embedded in other presentation software (/e/{key}/{slide}, e.g. Canva). // Slides embedded in other presentation software (/e/{key}/{slide}, e.g. Canva).
'embed' => [ 'embed' => [
// A visible embedded slide reports every N seconds that it is still on screen ... // A visible embedded slide reports every N seconds that it is still on screen ...
+7 -1
View File
@@ -37,7 +37,11 @@ return function (RouteBuilder $routes): void {
$builder->connect('/p/{code}/img/{file}', 'Participate::image', ['_name' => 'participate:image']) $builder->connect('/p/{code}/img/{file}', 'Participate::image', ['_name' => 'participate:image'])
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}', 'file' => '[a-f0-9]{24}\.webp']) ->setPatterns(['code' => '[A-Za-z0-9-]{4,16}', 'file' => '[a-f0-9]{24}\.webp'])
->setPass(['code', 'file']); ->setPass(['code', 'file']);
$builder->connect('/p/{code}/vote', 'Participate::vote', ['_name' => 'participate:vote']) // Countdown audio of a poll (played by the presenter view): random file name, only files of this poll.
$builder->connect('/p/{code}/audio/{file}', 'Participate::audio', ['_name' => 'participate:audio'])
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}', 'file' => '[a-f0-9]{24}\.(mp3|ogg|wav|m4a)'])
->setPass(['code', 'file']);
$builder->connect('/p/{code}/vote','Participate::vote', ['_name' => 'participate:vote'])
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}']) ->setPatterns(['code' => '[A-Za-z0-9-]{4,16}'])
->setPass(['code']) ->setPass(['code'])
->setMethods(['POST']); ->setMethods(['POST']);
@@ -67,6 +71,8 @@ return function (RouteBuilder $routes): void {
$admin->connect('/', 'Admin::index', ['_name' => 'admin'])->setPatterns($token); $admin->connect('/', 'Admin::index', ['_name' => 'admin'])->setPatterns($token);
$admin->connect('/settings', 'Admin::settings', ['_name' => 'admin:settings']) $admin->connect('/settings', 'Admin::settings', ['_name' => 'admin:settings'])
->setPatterns($token)->setMethods(['POST']); ->setPatterns($token)->setMethods(['POST']);
$admin->connect('/audio', 'Admin::audio', ['_name' => 'admin:audio'])
->setPatterns($token)->setMethods(['POST']);
$admin->connect('/rotate-token', 'Admin::rotateToken', ['_name' => 'admin:rotate']) $admin->connect('/rotate-token', 'Admin::rotateToken', ['_name' => 'admin:rotate'])
->setPatterns($token)->setMethods(['POST']); ->setPatterns($token)->setMethods(['POST']);
$admin->connect('/rotate-embed-key', 'Admin::rotateEmbedKey', ['_name' => 'admin:rotate-embed']) $admin->connect('/rotate-embed-key', 'Admin::rotateEmbedKey', ['_name' => 'admin:rotate-embed'])
+2
View File
@@ -113,6 +113,8 @@ Folienbilder landen in `data/uploads` (anderer Ort: `UPLOADS_PATH`), nie unter `
Datensicherung. Voraussetzungen: PHP-Erweiterung `gd` mit WebP sowie `upload_max_filesize` und `post_max_size` passend zu Datensicherung. Voraussetzungen: PHP-Erweiterung `gd` mit WebP sowie `upload_max_filesize` und `post_max_size` passend zu
`IMAGE_MAX_UPLOAD_MB` (Standard 10 MB, PHP-Standard sind nur 2 MB bzw. 8 MB). Dateien ohne Folie (z. B. nach einem Absturz) `IMAGE_MAX_UPLOAD_MB` (Standard 10 MB, PHP-Standard sind nur 2 MB bzw. 8 MB). Dateien ohne Folie (z. B. nach einem Absturz)
entfernt `bin/cake images_cleanup` (`--dry-run` zeigt sie nur an). entfernt `bin/cake images_cleanup` (`--dry-run` zeigt sie nur an).
Die Quiz-Musik (eine Audiodatei je Präsentation) liegt im selben Verzeichnis; ihre Obergrenze steht in `AUDIO_MAX_UPLOAD_MB`
(Standard 10 MB), auch dafür müssen `upload_max_filesize` und `post_max_size` reichen.
Bei Updates: Code aktualisieren, `composer install --no-dev`, Migrationen und `cache clear_all` wiederholen. Bei Updates: Code aktualisieren, `composer install --no-dev`, Migrationen und `cache clear_all` wiederholen.
+8
View File
@@ -28,6 +28,14 @@ geändert wird es nur über die Presenter-Steuerung (`SlideControlService`) bzw.
`SlidesTable::closeIfExpired()` beim State-Abruf. **Zählungen und `is_correct` dürfen vor `finished` nie im `SlidesTable::closeIfExpired()` beim State-Abruf. **Zählungen und `is_correct` dürfen vor `finished` nie im
JSON/HTML landen** (weder Presenter noch Teilnehmende); danach sehen Teilnehmende die Lösung und ob sie JSON/HTML landen** (weder Presenter noch Teilnehmende); danach sehen Teilnehmende die Lösung und ob sie
richtig lagen (ohne Verteilung). Zurücksetzen setzt das Quiz wieder auf `ready`. richtig lagen (ohne Verteilung). Zurücksetzen setzt das Quiz wieder auf `ready`.
- **Quiz-Musik:** je **Präsentation** (nicht je Folie) eine Audiodatei (`polls.audio`), hochgeladen im Menü unter „Einstellungen →
Musik zum Quiz-Countdown“ (`Admin::audio`, Route `admin:audio`; Entfernen = Feld `remove`). Gespeichert wird die Datei unverändert
(`AudioService`: Format nur an den ersten Bytes erkannt – MP3, M4A, OGG, WAV –, Zufallsname mit fester Endung, Obergrenze
`Plenario.audio.maxUploadBytes`) im Upload-Verzeichnis der Umfrage, ausgeliefert über `participate:audio` (`/p/{code}/audio/{file}`,
nur die Datei dieser Umfrage, feste Content-Type, Range-Anfragen). Im State steht `poll.audioUrl`. Abgespielt wird nur in der
Referentenansicht/Einbettung (`StageAudio` in `plenario.js`): als Schleife, solange irgendein Quiz `running` ist, Stopp bei
Ende/Folienwechsel/Pause. Teilnehmende hören nichts. Blockiert der Browser den Start (keine Nutzeraktion), wird er beim
nächsten Klick/Tastendruck wiederholt. „Umfrage kopieren“ kopiert die Datei, Löschen der Umfrage und `images_cleanup` räumen sie mit auf.
**Klicker/Presenter-Stick** (sendet nur →/← bzw. Bild↑/↓): `AdminController::control` behandelt `next` auf einem Quiz als **Klicker/Presenter-Stick** (sendet nur →/← bzw. Bild↑/↓): `AdminController::control` behandelt `next` auf einem Quiz als
Schritt – `ready` → starten, `running` → beenden (Lösung), erst `finished` → nächste Folie. `prev` geht immer zur vorigen Folie Schritt – `ready` → starten, `running` → beenden (Lösung), erst `finished` → nächste Folie. `prev` geht immer zur vorigen Folie
und startet nie ein Quiz. Tests: `QuizClickerTest.php`. und startet nie ein Quiz. Tests: `QuizClickerTest.php`.
+10 -1
View File
@@ -32,7 +32,7 @@ class ImagesCleanupCommand extends Command
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
{ {
return $parser return $parser
->setDescription(__('Löscht Bilddateien, die zu keiner Folie mehr gehören.')) ->setDescription(__('Löscht Bild- und Audiodateien, die zu keiner Folie mehr gehören.'))
->addOption('dry-run', [ ->addOption('dry-run', [
'help' => __('Nur anzeigen, nichts löschen.'), 'help' => __('Nur anzeigen, nichts löschen.'),
'boolean' => true, 'boolean' => true,
@@ -57,6 +57,15 @@ class ImagesCleanupCommand extends Command
foreach ($rows as $row) { foreach ($rows as $row) {
$referenced[(int)$row['poll_id']][] = (string)$row['image']; $referenced[(int)$row['poll_id']][] = (string)$row['image'];
} }
// The countdown audio of a poll shares the upload directory with its images.
$audio = $this->fetchTable('Polls')->find()
->select(['id', 'audio'])
->where(['audio IS NOT' => null])
->disableHydration()
->all();
foreach ($audio as $row) {
$referenced[(int)$row['id']][] = (string)$row['audio'];
}
$dryRun = (bool)$args->getOption('dry-run'); $dryRun = (bool)$args->getOption('dry-run');
$removed = (new ImageService())->cleanup($referenced, $dryRun); $removed = (new ImageService())->cleanup($referenced, $dryRun);
+50
View File
@@ -7,6 +7,8 @@ use App\Mailer\PollMailer;
use App\Model\Entity\Slide; use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable; use App\Model\Table\ResponsesTable;
use App\Model\Table\SlidesTable; use App\Model\Table\SlidesTable;
use App\Service\AudioService;
use App\Service\ImageException;
use App\Service\PollStateService; use App\Service\PollStateService;
use App\Service\QaService; use App\Service\QaService;
use App\Service\ReportService; use App\Service\ReportService;
@@ -20,6 +22,7 @@ use Cake\Routing\Router;
use chillerlan\QRCode\Output\QRMarkupSVG; use chillerlan\QRCode\Output\QRMarkupSVG;
use chillerlan\QRCode\QRCode; use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions; use chillerlan\QRCode\QROptions;
use Psr\Http\Message\UploadedFileInterface;
use Throwable; use Throwable;
/** /**
@@ -89,6 +92,53 @@ class AdminController extends AdminAppController
return $this->redirect($this->adminUrl()); return $this->redirect($this->adminUrl());
} }
/**
* Countdown music of the presentation: uploads a new file (replaces the old one) or, with
* `remove` = 1, deletes it. Old files are deleted after saving, never before.
*
* @return \Cake\Http\Response|null
*/
public function audio(): ?Response
{
$this->request->allowMethod(['post']);
$service = new AudioService();
$old = $this->poll->audio;
$upload = $this->request->getUploadedFile('audio');
$hasUpload = $upload instanceof UploadedFileInterface && $upload->getError() !== UPLOAD_ERR_NO_FILE;
$back = $this->adminUrl() + ['#' => 'audio'];
if ($hasUpload) {
try {
$new = $service->store($upload, $this->poll->id);
} catch (ImageException $e) {
$this->Flash->error($e->getMessage());
return $this->redirect($back);
}
} elseif (filter_var($this->request->getData('remove'), FILTER_VALIDATE_BOOLEAN)) {
$new = null;
} else {
$this->Flash->error(__('Bitte wähle eine Audiodatei aus.'));
return $this->redirect($back);
}
$this->poll->set('audio', $new);
try {
$this->Polls->saveOrFail($this->poll);
} catch (Throwable $e) {
$service->delete($this->poll->id, $new);
throw $e;
}
if ($old !== null && $old !== $new) {
$service->delete($this->poll->id, $old);
}
$this->Flash->success($new === null ? __('Audiodatei entfernt.') : __('Audiodatei gespeichert.'));
return $this->redirect($back);
}
/** /**
* Invalidates the current admin link and mails a new one. * Invalidates the current admin link and mails a new one.
* *
+25 -1
View File
@@ -6,6 +6,7 @@ namespace App\Controller;
use App\Model\Entity\Poll; use App\Model\Entity\Poll;
use App\Model\Entity\Slide; use App\Model\Entity\Slide;
use App\Model\Table\PollsTable; use App\Model\Table\PollsTable;
use App\Service\AudioService;
use App\Service\ImageService; use App\Service\ImageService;
use App\Service\PollStateService; use App\Service\PollStateService;
use App\Service\VoteException; use App\Service\VoteException;
@@ -50,7 +51,7 @@ class ParticipateController extends AppController
public function beforeFilter(EventInterface $event): void public function beforeFilter(EventInterface $event): void
{ {
parent::beforeFilter($event); parent::beforeFilter($event);
if ($this->request->getParam('action') === 'image') { if (in_array($this->request->getParam('action'), ['image', 'audio'], true)) {
// Cacheable static content: no participant id, no cookie. // Cacheable static content: no participant id, no cookie.
return; return;
} }
@@ -124,6 +125,29 @@ class ParticipateController extends AppController
->withHeader('Cache-Control', 'private, max-age=31536000, immutable'); ->withHeader('Cache-Control', 'private, max-age=31536000, immutable');
} }
/**
* Serves the countdown audio of this poll (random file name, cached for good, supports range
* requests so browsers can loop and seek). Content type is fixed by the extension, never sniffed.
*
* @param string $code Join code
* @param string $file Stored file name
* @return \Cake\Http\Response
*/
public function audio(string $code, string $file): Response
{
$poll = $this->loadPoll($code);
$path = $poll->audio === $file ? (new AudioService())->path($poll->id, $file) : null;
if ($path === null) {
throw new NotFoundException(__('Audiodatei nicht gefunden.'));
}
return $this->response
->withFile($path)
->withHeader('Content-Type', AudioService::contentType($file))
->withHeader('X-Content-Type-Options', 'nosniff')
->withHeader('Cache-Control', 'private, max-age=31536000, immutable');
}
/** /**
* @param string $code Join code * @param string $code Join code
* @return \Cake\Http\Response * @return \Cake\Http\Response
+9
View File
@@ -20,6 +20,7 @@ use Cake\ORM\Entity;
* @property int|null $paused_slide_id * @property int|null $paused_slide_id
* @property bool $is_active * @property bool $is_active
* @property int $comment_speed Speed of rotating scale comments in percent, see COMMENT_SPEEDS * @property int $comment_speed Speed of rotating scale comments in percent, see COMMENT_SPEEDS
* @property string|null $audio File name of the audio played during quiz countdowns (see AudioService)
* @property \Cake\I18n\DateTime|null $last_admin_access * @property \Cake\I18n\DateTime|null $last_admin_access
* @property \Cake\I18n\DateTime|null $expiry_reminded_at When the reminder before the expiry was mailed * @property \Cake\I18n\DateTime|null $expiry_reminded_at When the reminder before the expiry was mailed
* @property \Cake\I18n\DateTime $created * @property \Cake\I18n\DateTime $created
@@ -36,6 +37,14 @@ class Poll extends Entity
*/ */
public const COMMENT_SPEEDS = [50, 75, 100, 125, 150, 200]; public const COMMENT_SPEEDS = [50, 75, 100, 125, 150, 200];
/**
* @return bool
*/
public function hasAudio(): bool
{
return $this->audio !== null && $this->audio !== '';
}
/** /**
* Only harmless fields are mass assignable. Tokens, join code and the * Only harmless fields are mass assignable. Tokens, join code and the
* current slide are always set explicitly in code. * current slide are always set explicitly in code.
+17 -1
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Model\Table; namespace App\Model\Table;
use App\Model\Entity\Poll; use App\Model\Entity\Poll;
use App\Service\AudioService;
use App\Service\ImageService; use App\Service\ImageService;
use ArrayObject; use ArrayObject;
use Cake\Core\Configure; use Cake\Core\Configure;
@@ -16,6 +17,7 @@ use Cake\ORM\Table;
use Cake\Utility\Security; use Cake\Utility\Security;
use Cake\Validation\Validator; use Cake\Validation\Validator;
use RuntimeException; use RuntimeException;
use Throwable;
/** /**
* Polls ("presentations"). Access control works exclusively via the secret * Polls ("presentations"). Access control works exclusively via the secret
@@ -277,13 +279,27 @@ class PollsTable extends Table
$copy->set('comment_speed', $poll->comment_speed); $copy->set('comment_speed', $poll->comment_speed);
$token = null; $token = null;
$this->getConnection()->transactional(function () use ($copy, $slides, &$token): void { $audio = new AudioService();
$audioCopy = null;
try {
$this->getConnection()->transactional(function () use ($poll, $copy, $slides, $audio, &$token, &$audioCopy): void {
[, $token] = $this->insertPoll($copy); [, $token] = $this->insertPoll($copy);
if ($token === null) { if ($token === null) {
throw new RuntimeException('Poll could not be saved'); throw new RuntimeException('Poll could not be saved');
} }
$this->Slides->copyAllToPoll($slides, $copy->id); $this->Slides->copyAllToPoll($slides, $copy->id);
// The copy gets its own audio file: deleting one poll never takes the music of the other.
$audioCopy = $poll->hasAudio() ? $audio->copy($copy->id, (string)$poll->audio, $poll->id) : null;
if ($audioCopy !== null) {
$copy->set('audio', $audioCopy);
$this->saveOrFail($copy);
}
}); });
} catch (Throwable $e) {
$audio->delete((int)$copy->id, $audioCopy);
throw $e;
}
return [$copy, $token]; return [$copy, $token];
} }
+210
View File
@@ -0,0 +1,210 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Cake\Core\Configure;
use Psr\Http\Message\UploadedFileInterface;
/**
* Stores the audio file of a presentation (played in the presenter view while a quiz countdown runs).
*
* Audio is not re-encoded: the format is recognised by its leading bytes (never by the client-sent
* name or type), the file is stored under a random name with a fixed extension, and served with a
* fixed content type by ParticipateController::audio(). Files live next to the slide images in
* `{Plenario.images.path}/{poll id}/`, so deleting a poll removes them as well; `bin/cake images_cleanup`
* sweeps leftovers of both kinds.
*
* Deleting is idempotent: a missing file is fine.
*/
class AudioService
{
/**
* Accepted formats: extension => content type.
*
* @var array<string, string>
*/
public const FORMATS = [
'mp3' => 'audio/mpeg',
'ogg' => 'audio/ogg',
'wav' => 'audio/wav',
'm4a' => 'audio/mp4',
];
/**
* Whether a stored name has the shape generated by store() (guards file system access).
*
* @param string $name File name
* @return bool
*/
public static function isValidName(string $name): bool
{
return (bool)preg_match('/^[a-f0-9]{24}\.(mp3|ogg|wav|m4a)$/', $name);
}
/**
* Content type for a stored name.
*
* @param string $name File name
* @return string
*/
public static function contentType(string $name): string
{
return self::FORMATS[pathinfo($name, PATHINFO_EXTENSION)] ?? 'application/octet-stream';
}
/**
* Recognises MP3 (ID3 tag or frame sync), Ogg, WAV and MPEG-4 audio by the first bytes.
*
* @param string $bytes File content
* @return string|null Extension (a key of FORMATS) or null for anything else
*/
public static function detectFormat(string $bytes): ?string
{
if (strlen($bytes) < 12) {
return null;
}
if (str_starts_with($bytes, 'OggS')) {
return 'ogg';
}
if (str_starts_with($bytes, 'RIFF') && substr($bytes, 8, 4) === 'WAVE') {
return 'wav';
}
if (substr($bytes, 4, 4) === 'ftyp') {
return 'm4a';
}
if (str_starts_with($bytes, 'ID3')) {
return 'mp3';
}
// Frame sync: 11 set bits, then a valid version and layer (not reserved).
$second = ord($bytes[1]);
if (ord($bytes[0]) === 0xFF && ($second & 0xE0) === 0xE0 && ($second & 0x18) !== 0x08 && ($second & 0x06) !== 0x00) {
return 'mp3';
}
return null;
}
/**
* Validates and stores an upload.
*
* @param \Psr\Http\Message\UploadedFileInterface $file Uploaded file
* @param int $pollId Poll the audio belongs to
* @return string Stored file name
* @throws \App\Service\ImageException If the file cannot be used
*/
public function store(UploadedFileInterface $file, int $pollId): string
{
$this->assertUploaded($file);
$bytes = (string)$file->getStream();
$extension = self::detectFormat($bytes);
if ($extension === null) {
throw new ImageException(__('Bitte wähle eine Audiodatei im Format MP3, M4A, OGG oder WAV aus.'));
}
$name = bin2hex(random_bytes(12)) . '.' . $extension;
$directory = $this->directory($pollId);
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) {
throw new ImageException(__('Die Audiodatei konnte nicht gespeichert werden (Upload-Verzeichnis nicht beschreibbar).'));
}
// Write under a temporary name first: a half written file must never be served.
$temporary = $directory . DS . $name . '.tmp';
if (@file_put_contents($temporary, $bytes) !== strlen($bytes) || !@rename($temporary, $directory . DS . $name)) {
@unlink($temporary);
throw new ImageException(__('Die Audiodatei konnte nicht gespeichert werden.'));
}
return $name;
}
/**
* Copies a stored file (duplicated slides get their own file).
*
* @param int $pollId Poll id that receives the copy
* @param string $name Source file name
* @param int|null $sourcePollId Poll id of the source file (default: the same poll)
* @return string|null Name of the copy, null if the source is gone or the copy failed
*/
public function copy(int $pollId, string $name, ?int $sourcePollId = null): ?string
{
$source = $this->path($sourcePollId ?? $pollId, $name);
if ($source === null) {
return null;
}
$directory = $this->directory($pollId);
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) {
return null;
}
$copy = bin2hex(random_bytes(12)) . '.' . pathinfo($name, PATHINFO_EXTENSION);
return @copy($source, $directory . DS . $copy) ? $copy : null;
}
/**
* Absolute path of a stored file, null if the name is invalid or the file does not exist.
*
* @param int $pollId Poll id
* @param string $name File name
* @return string|null
*/
public function path(int $pollId, string $name): ?string
{
if (!self::isValidName($name)) {
return null;
}
$path = $this->directory($pollId) . DS . $name;
return is_file($path) ? $path : null;
}
/**
* Deletes one file. Idempotent, ignores unknown names and missing files.
*
* @param int $pollId Poll id
* @param string|null $name File name
* @return void
*/
public function delete(int $pollId, ?string $name): void
{
if ($name === null || !self::isValidName($name)) {
return;
}
@unlink($this->directory($pollId) . DS . $name);
}
/**
* @param int $pollId Poll id
* @return string
*/
protected function directory(int $pollId): string
{
return rtrim((string)Configure::read('Plenario.images.path'), '/\\') . DS . $pollId;
}
/**
* @param \Psr\Http\Message\UploadedFileInterface $file Uploaded file
* @return void
*/
protected function assertUploaded(UploadedFileInterface $file): void
{
switch ($file->getError()) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new ImageException(__(
'Die Datei ist größer, als der Server erlaubt ({0}). Bitte wähle eine kleinere Audiodatei.',
(string)ini_get('upload_max_filesize'),
));
default:
throw new ImageException(__('Die Audiodatei konnte nicht hochgeladen werden. Bitte versuche es noch einmal.'));
}
$max = (int)Configure::read('Plenario.audio.maxUploadBytes', 10 * 1024 * 1024);
if (($file->getSize() ?? 0) > $max) {
throw new ImageException(__('Die Audiodatei ist zu groß (höchstens {0} MB).', (int)round($max / 1024 / 1024)));
}
if (($file->getSize() ?? 0) === 0) {
throw new ImageException(__('Die Datei ist leer.'));
}
}
}
+5 -1
View File
@@ -422,7 +422,7 @@ class PollStateService
* Poll part of the presenter and embed state. * Poll part of the presenter and embed state.
* *
* @param \App\Model\Entity\Poll $poll Poll * @param \App\Model\Entity\Poll $poll Poll
* @return array{title: string, joinCode: string, joinCodeFormatted: string, isActive: bool, isPaused: bool} * @return array{title: string, joinCode: string, joinCodeFormatted: string, isActive: bool, isPaused: bool, commentSpeed: float|int, audioUrl: string|null}
*/ */
protected function pollPayload(Poll $poll): array protected function pollPayload(Poll $poll): array
{ {
@@ -434,6 +434,10 @@ class PollStateService
'isPaused' => $poll->isPaused(), 'isPaused' => $poll->isPaused(),
// Factor for the rotating scale comments on stage (1 = normal, 2 = twice as fast) // Factor for the rotating scale comments on stage (1 = normal, 2 = twice as fast)
'commentSpeed' => ($poll->comment_speed ?? 100) / 100, 'commentSpeed' => ($poll->comment_speed ?? 100) / 100,
// Music for quiz countdowns: looped by the presenter view while a quiz runs (participants never play it)
'audioUrl' => $poll->hasAudio()
? Router::url(['_name' => 'participate:audio', 'code' => $poll->join_code, 'file' => $poll->audio])
: null,
]; ];
} }
+23
View File
@@ -280,6 +280,29 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
<p class="hint" id="comment-speed-hint"><?= __('Gilt für die Kommentare von Skala-Folien, die nacheinander durchlaufen. Die Anzeigedauer richtet sich weiter nach der Textlänge und wird mit diesem Faktor verkürzt oder verlängert.') ?></p> <p class="hint" id="comment-speed-hint"><?= __('Gilt für die Kommentare von Skala-Folien, die nacheinander durchlaufen. Die Anzeigedauer richtet sich weiter nach der Textlänge und wird mit diesem Faktor verkürzt oder verlängert.') ?></p>
<?= $this->Form->button(__('Speichern'), ['class' => 'button']) ?> <?= $this->Form->button(__('Speichern'), ['class' => 'button']) ?>
<?= $this->Form->end() ?> <?= $this->Form->end() ?>
<section class="card-section">
<h3 id="audio"><?= __('Musik zum Quiz-Countdown') ?></h3>
<?php $audioMb = (int)round((int)\Cake\Core\Configure::read('Plenario.audio.maxUploadBytes', 10 * 1024 * 1024) / 1024 / 1024); ?>
<p class="hint"><?= __('Eine Audiodatei für die ganze Präsentation (MP3, M4A, OGG oder WAV, bis {0} MB). Sie läuft in der Präsentationsansicht, solange ein Quiz läuft, und wiederholt sich, wenn sie kürzer ist als der Countdown. Teilnehmende hören nichts davon.', $audioMb) ?></p>
<?php if ($poll->hasAudio()) : ?>
<audio controls preload="none" class="audio-player"
src="<?= h($this->Url->build(['_name' => 'participate:audio', 'code' => $poll->join_code, 'file' => $poll->audio])) ?>"></audio>
<?php endif; ?>
<?= $this->Form->create(null, ['url' => $url('admin:audio'), 'type' => 'file']) ?>
<div class="input file">
<label for="audio-file"><?= $poll->hasAudio() ? __('Durch andere Datei ersetzen') : __('Audiodatei auswählen') ?></label>
<input type="file" id="audio-file" name="audio" accept="audio/mpeg,audio/mp4,audio/ogg,audio/wav,.mp3,.m4a,.ogg,.wav" required>
</div>
<?= $this->Form->button(__('Hochladen'), ['class' => 'button button--small']) ?>
<?= $this->Form->end() ?>
<?php if ($poll->hasAudio()) : ?>
<?= $this->Form->postButton(__('Audiodatei entfernen'), $url('admin:audio'), [
'class' => 'button button--small button--danger',
'data' => ['remove' => '1'],
'data-confirm' => __('Die Audiodatei entfernen?'),
]) ?>
<?php endif; ?>
</section>
<section class="card-section"> <section class="card-section">
<h3 id="embed"><?= __('In Präsentation einbetten') ?></h3> <h3 id="embed"><?= __('In Präsentation einbetten') ?></h3>
<p class="hint"><?= __('Jede Folie hat einen eigenen Einbett-Link (unter „Einbett-Link“ in der Folienliste). Füge ihn z. B. in Canva als Einbettung auf einer Folie ein.') ?></p> <p class="hint"><?= __('Jede Folie hat einen eigenen Einbett-Link (unter „Einbett-Link“ in der Folienliste). Füge ihn z. B. in Canva als Einbettung auf einer Folie ein.') ?></p>
+169
View File
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Controller;
use App\Command\ImagesCleanupCommand;
use App\Service\AudioService;
use App\Service\PollStateService;
use App\Test\TestCase\ImageTestTrait;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\TestSuite\StubConsoleOutput;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
use Laminas\Diactoros\UploadedFile;
/**
* Countdown music of a presentation: upload, replace, remove, delivery, state and copying.
*/
class PollAudioTest extends TestCase
{
use ImageTestTrait;
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 tearDown(): void
{
$this->clearImages();
parent::tearDown();
}
/**
* Writes a small file with the given leading bytes.
*
* @param string $head First bytes
* @return string Path
*/
protected function makeAudio(string $head = "ID3\x03\x00\x00\x00\x00\x00\x00"): string
{
$path = tempnam(sys_get_temp_dir(), 'plen');
file_put_contents($path, $head . str_repeat("\x00", 2000));
$this->imageFiles[] = $path;
return $path;
}
protected function upload(string $token, ?string $path, array $data = []): void
{
$this->_request['files'] = $path === null ? [] : [
'audio' => new UploadedFile($path, (int)filesize($path), UPLOAD_ERR_OK, 'musik.mp3', 'audio/mpeg'),
];
try {
$this->post("/admin/$token/audio", $data);
} finally {
$this->_request['files'] = [];
}
}
public function testUploadServeReplaceAndRemove(): void
{
[$poll, $token] = $this->createPoll();
$this->upload($token, $this->makeAudio());
$this->assertRedirect(['_name' => 'admin', 'token' => $token, '#' => 'audio']);
$first = (string)$this->pollsTable()->get($poll->id)->audio;
$this->assertMatchesRegularExpression('/^[a-f0-9]{24}\.mp3$/', $first);
$this->assertSame([$first], $this->storedImages($poll->id));
$this->get("/admin/$token");
$this->assertResponseOk();
$this->assertResponseContains('<audio controls');
$this->assertResponseContains('Audiodatei entfernen');
// The presenter state carries the URL, the participant page never plays it but the file is served.
$fresh = $this->pollsTable()->get($poll->id);
$state = (new PollStateService())->forPresenter($fresh);
$this->assertStringContainsString("/p/{$poll->join_code}/audio/$first", (string)$state['poll']['audioUrl']);
$this->get("/p/{$poll->join_code}/audio/$first");
$this->assertResponseOk();
$this->assertContentType('audio/mpeg');
$this->assertHeader('X-Content-Type-Options', 'nosniff');
// Replacing: new random name, the old file is gone and no longer served.
$this->upload($token, $this->makeAudio("RIFF\x00\x00\x00\x00WAVE"));
$second = (string)$this->pollsTable()->get($poll->id)->audio;
$this->assertMatchesRegularExpression('/^[a-f0-9]{24}\.wav$/', $second);
$this->assertSame([$second], $this->storedImages($poll->id));
$this->get("/p/{$poll->join_code}/audio/$first");
$this->assertResponseCode(404);
// Removing is explicit and repeatable.
foreach ([1, 2] as $ignored) {
$this->post("/admin/$token/audio", ['remove' => '1']);
$this->assertRedirect();
$this->assertNull($this->pollsTable()->get($poll->id)->audio);
$this->assertSame([], $this->storedImages($poll->id));
}
}
public function testRejectsOtherFilesAndEmptyRequests(): void
{
[$poll, $token] = $this->createPoll();
$this->upload($token, $this->makeAudio('<html><script>alert(1)</script>'));
$this->assertRedirect();
$this->assertNull($this->pollsTable()->get($poll->id)->audio);
$this->assertSame([], $this->storedImages($poll->id));
$this->upload($token, null);
$this->assertRedirect();
$this->assertNull($this->pollsTable()->get($poll->id)->audio);
}
public function testFileOfAnotherPollIsNotServed(): void
{
[$poll, $token] = $this->createPoll();
[$other] = $this->createPoll();
$this->upload($token, $this->makeAudio());
$file = (string)$this->pollsTable()->get($poll->id)->audio;
$this->get("/p/{$other->join_code}/audio/$file");
$this->assertResponseCode(404);
}
public function testFormatDetection(): void
{
$this->assertSame('mp3', AudioService::detectFormat("\xFF\xFB\x90\x00" . str_repeat("\x00", 20)));
$this->assertSame('mp3', AudioService::detectFormat("ID3\x04" . str_repeat("\x00", 20)));
$this->assertSame('ogg', AudioService::detectFormat('OggS' . str_repeat("\x00", 20)));
$this->assertSame('m4a', AudioService::detectFormat("\x00\x00\x00\x20ftypM4A " . str_repeat("\x00", 20)));
$this->assertNull(AudioService::detectFormat('GIF89a' . str_repeat("\x00", 20)));
$this->assertNull(AudioService::detectFormat("\xFF\xE1\x00\x00" . str_repeat("\x00", 20)), 'reserved layer');
$this->assertNull(AudioService::detectFormat('short'));
}
public function testCloneCopiesTheFileAndCleanupKeepsIt(): void
{
[$poll, $token] = $this->createPoll();
$this->createSlide($poll, 'quiz');
$this->upload($token, $this->makeAudio());
$original = (string)$this->pollsTable()->get($poll->id)->audio;
$slides = $this->slidesTable()->listForPoll($poll->id);
[$copy] = $this->pollsTable()->clonePoll($this->pollsTable()->get($poll->id), $slides);
$copied = (string)$this->pollsTable()->get($copy->id)->audio;
$this->assertNotSame($original, $copied, 'own file per poll');
$this->assertSame([$copied], $this->storedImages($copy->id));
$this->assertSame([$original], $this->storedImages($poll->id));
// The sweep for leftovers must not take the music.
$command = new ImagesCleanupCommand();
$command->execute(new Arguments([], ['dry-run' => false], []), new ConsoleIo(new StubConsoleOutput(), new StubConsoleOutput()));
$this->assertSame([$original], $this->storedImages($poll->id));
$this->assertSame([$copied], $this->storedImages($copy->id));
}
}
+66
View File
@@ -204,6 +204,70 @@
} }
}; };
// ------------------------------------------------------------------ stage audio
/**
* Music of the presentation (presenter view only): plays in a loop while a quiz runs, so it also covers a
* countdown that is longer than the file, and stops when the quiz ends or the slide changes.
* Browsers may refuse to start audio without a previous click or key press; the presenter has
* always pressed something to start the quiz, and a refused start is retried on the next one.
*/
var StageAudio = {
element: null,
url: null,
wanted: false,
/** @param {string|null} url audio URL of the poll, only passed while a quiz is running */
sync: function (url) {
StageAudio.wanted = !!url;
if (!url) {
StageAudio.stop();
return;
}
if (!StageAudio.element) {
StageAudio.element = new Audio();
StageAudio.element.loop = true;
StageAudio.element.preload = 'auto';
}
var audio = StageAudio.element;
if (StageAudio.url !== url) {
StageAudio.url = url;
audio.src = url;
}
if (audio.paused) {
StageAudio.play();
}
},
play: function () {
var attempt = StageAudio.element && StageAudio.element.play();
if (attempt && attempt.catch) {
attempt.catch(function () {
// Blocked (no user activation yet): try again on the next click or key press.
var retry = function () {
document.removeEventListener('click', retry, true);
document.removeEventListener('keydown', retry, true);
if (StageAudio.wanted && StageAudio.element && StageAudio.element.paused) {
StageAudio.play();
}
};
document.addEventListener('click', retry, true);
document.addEventListener('keydown', retry, true);
});
}
},
stop: function () {
StageAudio.wanted = false;
if (StageAudio.element && !StageAudio.element.paused) {
StageAudio.element.pause();
}
if (StageAudio.element && StageAudio.element.currentTime) {
StageAudio.element.currentTime = 0;
}
}
};
// ------------------------------------------------------------------ word matching // ------------------------------------------------------------------ word matching
/** /**
@@ -1454,6 +1518,7 @@
root.classList.remove('stage--video'); root.classList.remove('stage--video');
q('[data-voting]').hidden = true; q('[data-voting]').hidden = true;
setText('[data-participants]', ''); setText('[data-participants]', '');
StageAudio.stop();
return; return;
} }
@@ -1498,6 +1563,7 @@
} }
renderResults(); renderResults();
Countdown.start(); Countdown.start();
StageAudio.sync(quizPhase === 'running' ? state.poll.audioUrl : null);
} }
function isPrivate() { function isPrivate() {