From 2f7a401522afa6630004ced1a3f19bd86e782078 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sat, 21 Nov 2026 11:36:01 +0100 Subject: [PATCH] Add countdown audio per presentation One audio file per poll (MP3, M4A, OGG, WAV) is uploaded in the admin settings and looped in the presenter view while a quiz runs. Format is detected by magic bytes, files are served with a fixed content type, copied with the poll and swept by images_cleanup. Co-Authored-By: Claude Sonnet 5.5 --- config/.env.example | 2 + .../20261121120000_AddAudioToPolls.php | 34 +++ config/app.php | 5 + config/routes.php | 8 +- docs/deployment.md | 2 + docs/slide-types.md | 8 + src/Command/ImagesCleanupCommand.php | 11 +- src/Controller/AdminController.php | 50 +++++ src/Controller/ParticipateController.php | 26 ++- src/Model/Entity/Poll.php | 9 + src/Model/Table/PollsTable.php | 30 ++- src/Service/AudioService.php | 210 ++++++++++++++++++ src/Service/PollStateService.php | 6 +- templates/Admin/index.php | 23 ++ tests/TestCase/Controller/PollAudioTest.php | 169 ++++++++++++++ webroot/js/plenario.js | 66 ++++++ 16 files changed, 648 insertions(+), 11 deletions(-) create mode 100644 config/Migrations/20261121120000_AddAudioToPolls.php create mode 100644 src/Service/AudioService.php create mode 100644 tests/TestCase/Controller/PollAudioTest.php diff --git a/config/.env.example b/config/.env.example index 63171be..3da91da 100644 --- a/config/.env.example +++ b/config/.env.example @@ -52,6 +52,8 @@ POLL_INTERVAL_MS=2000 # UPLOADS_PATH=/var/www/plenario-uploads IMAGE_MAX_UPLOAD_MB=10 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) EMBED_HEARTBEAT_SECONDS=5 EMBED_TIMEOUT_SECONDS=20 diff --git a/config/Migrations/20261121120000_AddAudioToPolls.php b/config/Migrations/20261121120000_AddAudioToPolls.php new file mode 100644 index 0000000..b9c9c51 --- /dev/null +++ b/config/Migrations/20261121120000_AddAudioToPolls.php @@ -0,0 +1,34 @@ +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(); + } + } +} diff --git a/config/app.php b/config/app.php index 538ea53..537e888 100644 --- a/config/app.php +++ b/config/app.php @@ -69,6 +69,11 @@ return [ // Slides with an image per poll. '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). 'embed' => [ // A visible embedded slide reports every N seconds that it is still on screen ... diff --git a/config/routes.php b/config/routes.php index 92d106e..139cfeb 100644 --- a/config/routes.php +++ b/config/routes.php @@ -37,7 +37,11 @@ return function (RouteBuilder $routes): void { $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']) ->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}']) ->setPass(['code']) ->setMethods(['POST']); @@ -67,6 +71,8 @@ return function (RouteBuilder $routes): void { $admin->connect('/', 'Admin::index', ['_name' => 'admin'])->setPatterns($token); $admin->connect('/settings', 'Admin::settings', ['_name' => 'admin:settings']) ->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']) ->setPatterns($token)->setMethods(['POST']); $admin->connect('/rotate-embed-key', 'Admin::rotateEmbedKey', ['_name' => 'admin:rotate-embed']) diff --git a/docs/deployment.md b/docs/deployment.md index ecc0b8e..9a27e89 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -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 `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). +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. diff --git a/docs/slide-types.md b/docs/slide-types.md index 8d641dd..05c8b9f 100644 --- a/docs/slide-types.md +++ b/docs/slide-types.md @@ -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 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`. +- **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 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`. diff --git a/src/Command/ImagesCleanupCommand.php b/src/Command/ImagesCleanupCommand.php index 1da39a0..9b588b7 100644 --- a/src/Command/ImagesCleanupCommand.php +++ b/src/Command/ImagesCleanupCommand.php @@ -32,7 +32,7 @@ class ImagesCleanupCommand extends Command protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser { 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', [ 'help' => __('Nur anzeigen, nichts löschen.'), 'boolean' => true, @@ -57,6 +57,15 @@ class ImagesCleanupCommand extends Command foreach ($rows as $row) { $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'); $removed = (new ImageService())->cleanup($referenced, $dryRun); diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 6bc0746..396d25b 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -7,6 +7,8 @@ use App\Mailer\PollMailer; use App\Model\Entity\Slide; use App\Model\Table\ResponsesTable; use App\Model\Table\SlidesTable; +use App\Service\AudioService; +use App\Service\ImageException; use App\Service\PollStateService; use App\Service\QaService; use App\Service\ReportService; @@ -17,6 +19,7 @@ use Cake\Http\Exception\BadRequestException; use Cake\Http\Response; use Cake\I18n\DateTime; use Cake\Routing\Router; +use Psr\Http\Message\UploadedFileInterface; use chillerlan\QRCode\Output\QRMarkupSVG; use chillerlan\QRCode\QRCode; use chillerlan\QRCode\QROptions; @@ -89,6 +92,53 @@ class AdminController extends AdminAppController 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. * diff --git a/src/Controller/ParticipateController.php b/src/Controller/ParticipateController.php index 704b390..458ee28 100644 --- a/src/Controller/ParticipateController.php +++ b/src/Controller/ParticipateController.php @@ -6,6 +6,7 @@ namespace App\Controller; use App\Model\Entity\Poll; use App\Model\Entity\Slide; use App\Model\Table\PollsTable; +use App\Service\AudioService; use App\Service\ImageService; use App\Service\PollStateService; use App\Service\VoteException; @@ -50,7 +51,7 @@ class ParticipateController extends AppController public function beforeFilter(EventInterface $event): void { 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. return; } @@ -124,6 +125,29 @@ class ParticipateController extends AppController ->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 * @return \Cake\Http\Response diff --git a/src/Model/Entity/Poll.php b/src/Model/Entity/Poll.php index 8bb56f1..b32dad0 100644 --- a/src/Model/Entity/Poll.php +++ b/src/Model/Entity/Poll.php @@ -20,6 +20,7 @@ use Cake\ORM\Entity; * @property int|null $paused_slide_id * @property bool $is_active * @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 $expiry_reminded_at When the reminder before the expiry was mailed * @property \Cake\I18n\DateTime $created @@ -36,6 +37,14 @@ class Poll extends Entity */ 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 * current slide are always set explicitly in code. diff --git a/src/Model/Table/PollsTable.php b/src/Model/Table/PollsTable.php index ca26da9..705704d 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 App\Service\AudioService; use App\Service\ImageService; use ArrayObject; use Cake\Core\Configure; @@ -16,6 +17,7 @@ use Cake\ORM\Table; use Cake\Utility\Security; use Cake\Validation\Validator; use RuntimeException; +use Throwable; /** * Polls ("presentations"). Access control works exclusively via the secret @@ -277,13 +279,27 @@ class PollsTable extends Table $copy->set('comment_speed', $poll->comment_speed); $token = null; - $this->getConnection()->transactional(function () use ($copy, $slides, &$token): void { - [, $token] = $this->insertPoll($copy); - if ($token === null) { - throw new RuntimeException('Poll could not be saved'); - } - $this->Slides->copyAllToPoll($slides, $copy->id); - }); + $audio = new AudioService(); + $audioCopy = null; + try { + $this->getConnection()->transactional(function () use ($poll, $copy, $slides, $audio, &$token, &$audioCopy): void { + [, $token] = $this->insertPoll($copy); + if ($token === null) { + throw new RuntimeException('Poll could not be saved'); + } + $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]; } diff --git a/src/Service/AudioService.php b/src/Service/AudioService.php new file mode 100644 index 0000000..deab1f7 --- /dev/null +++ b/src/Service/AudioService.php @@ -0,0 +1,210 @@ + content type. + * + * @var array + */ + 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.')); + } + } +} diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index e7323cc..83a7598 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -422,7 +422,7 @@ class PollStateService * Poll part of the presenter and embed state. * * @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 { @@ -434,6 +434,10 @@ class PollStateService 'isPaused' => $poll->isPaused(), // Factor for the rotating scale comments on stage (1 = normal, 2 = twice as fast) '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, ]; } diff --git a/templates/Admin/index.php b/templates/Admin/index.php index 3c25292..b73cd4f 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -280,6 +280,29 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-

Form->button(__('Speichern'), ['class' => 'button']) ?> Form->end() ?> +
+

+ +

+ hasAudio()) : ?> + + + Form->create(null, ['url' => $url('admin:audio'), 'type' => 'file']) ?> +
+ + +
+ Form->button(__('Hochladen'), ['class' => 'button button--small']) ?> + Form->end() ?> + hasAudio()) : ?> + Form->postButton(__('Audiodatei entfernen'), $url('admin:audio'), [ + 'class' => 'button button--small button--danger', + 'data' => ['remove' => '1'], + 'data-confirm' => __('Die Audiodatei entfernen?'), + ]) ?> + +

diff --git a/tests/TestCase/Controller/PollAudioTest.php b/tests/TestCase/Controller/PollAudioTest.php new file mode 100644 index 0000000..1d3c70a --- /dev/null +++ b/tests/TestCase/Controller/PollAudioTest.php @@ -0,0 +1,169 @@ + + */ + 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('