Add countdown audio per presentation
CI / Deploy / PHP 8.4 (push) Failing after 1m18s
CI / Deploy / PHP 8.5 (push) Failing after 2m4s
CI / Deploy / test (push) Failing after 1s
CI / Deploy / deploy (push) Skipped

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 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Sonnet 5.5 committed 2026-11-21 11:36:01 +01:00
1 parent cad09163d9
commit 2f7a401522
16 files changed
+648 -11

No files matched your search

+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.
*
* @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,
];
}