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 <noreply@anthropic.com>
This commit is contained in:
1 parent
cad09163d9
commit
2f7a401522
16 files changed
+648
-11
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
|
||||
@@ -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.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user