text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```php <?php declare(strict_types=1); namespace App\Media\Metadata\Reader; use App\Event\Media\ReadMetadata; use App\Media\Metadata; use App\Media\MetadataInterface; use App\Media\MimeType; use App\Utilities\File; use App\Utilities\Time; use App\Utilities\Types; use FFMpeg\FFMpeg; use FFMpeg\FFProbe; use FFMpeg\FFProbe\DataMapping\Stream; use Psr\Log\LoggerInterface; use Throwable; final class FfprobeReader extends AbstractReader { private readonly FFProbe $ffprobe; private readonly FFMpeg $ffmpeg; public function __construct( LoggerInterface $logger ) { $this->ffprobe = FFProbe::create([], $logger); $this->ffmpeg = FFMpeg::create([], $logger, $this->ffprobe); } public function __invoke(ReadMetadata $event): void { $path = $event->getPath(); $format = $this->ffprobe->format($path); $streams = $this->ffprobe->streams($path); $metadata = new Metadata(); $metadata->setMimeType(MimeType::getMimeTypeFromFile($path)); $duration = $this->getDuration($format, $streams); if (null !== $duration) { $metadata->setDuration($duration); } $this->aggregateFFProbeMetaTags( $metadata, $format, $streams ); $metadata->setArtwork( $this->getAlbumArt( $streams, $path ) ); $event->setMetadata($metadata); } private function getDuration( FFProbe\DataMapping\Format $format, FFProbe\DataMapping\StreamCollection $streams ): ?float { $formatDuration = $format->get('duration'); if (is_numeric($formatDuration)) { return Time::displayTimeToSeconds($formatDuration); } /** @var Stream $stream */ foreach ($streams->audios() as $stream) { $duration = $stream->get('duration'); if (is_numeric($duration)) { return Time::displayTimeToSeconds($duration); } } return null; } private function aggregateFFProbeMetaTags( MetadataInterface $metadata, FFProbe\DataMapping\Format $format, FFProbe\DataMapping\StreamCollection $streams ): void { $toProcess = [ Types::array($format->get('comments')), Types::array($format->get('tags')), ]; /** @var Stream $stream */ foreach ($streams->audios() as $stream) { $toProcess[] = Types::array($stream->get('comments')); $toProcess[] = Types::array($stream->get('tags')); } $this->aggregateMetaTags($metadata, $toProcess); } private function getAlbumArt( FFProbe\DataMapping\StreamCollection $streams, string $path ): ?string { // Pull album art directly from relevant streams. try { /** @var Stream $videoStream */ foreach ($streams->videos() as $videoStream) { $streamDisposition = $videoStream->get('disposition'); if (!isset($streamDisposition['attached_pic']) || 1 !== $streamDisposition['attached_pic']) { continue; } $artOutput = File::generateTempPath('artwork.jpg'); @unlink($artOutput); // Ffmpeg won't overwrite the empty file. $this->ffmpeg->getFFMpegDriver()->command([ '-i', $path, '-an', '-vcodec', 'copy', $artOutput, ]); $artContent = file_get_contents($artOutput) ?: null; @unlink($artOutput); return $artContent; } } catch (Throwable) { } return null; } } ```
/content/code_sandbox/backend/src/Media/Metadata/Reader/FfprobeReader.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
860
```php <?php declare(strict_types=1); namespace App\Media\Metadata\Reader; use App\Container\LoggerAwareTrait; use App\Event\Media\ReadMetadata; use App\Media\Metadata; use App\Utilities\Time; use JamesHeinrich\GetID3\GetID3; use RuntimeException; use Throwable; use const JSON_THROW_ON_ERROR; final class PhpReader extends AbstractReader { use LoggerAwareTrait; public function __invoke(ReadMetadata $event): void { $path = $event->getPath(); try { $getid3 = new GetID3(); $getid3->option_md5_data = true; $getid3->option_md5_data_source = true; $getid3->encoding = 'UTF-8'; $info = $getid3->analyze($path); $getid3->CopyTagsToComments($info); if (!empty($info['error'])) { throw new RuntimeException( json_encode($info['error'], JSON_THROW_ON_ERROR) ); } $metadata = new Metadata(); if (is_numeric($info['playtime_seconds'])) { $metadata->setDuration( Time::displayTimeToSeconds($info['playtime_seconds']) ?? 0.0 ); } // ID3v2 should always supersede ID3v1. if (isset($info['tags']['id3v2'])) { unset($info['tags']['id3v1']); } if (!empty($info['tags'])) { $toProcess = $info['tags']; } else { $toProcess = [ $info['comments'] ?? [], ]; } $toProcess[] = $this->convertReplayGainBackIntoText($info['replay_gain'] ?? []); $this->aggregateMetaTags($metadata, $toProcess); $metadata->setMimeType($info['mime_type']); $artwork = null; if (!empty($info['attached_picture'][0])) { $artwork = $info['attached_picture'][0]['data']; } elseif (!empty($info['comments']['picture'][0])) { $artwork = $info['comments']['picture'][0]['data']; } elseif (!empty($info['id3v2']['APIC'][0]['data'])) { $artwork = $info['id3v2']['APIC'][0]['data']; } elseif (!empty($info['id3v2']['PIC'][0]['data'])) { $artwork = $info['id3v2']['PIC'][0]['data']; } if (!empty($artwork)) { $metadata->setArtwork($artwork); } $event->setMetadata($metadata); $event->stopPropagation(); } catch (Throwable $e) { $this->logger->info( sprintf( 'getid3 failed for file %s: %s', $path, $e->getMessage() ), [ 'exception' => $e, ] ); } } protected function convertReplayGainBackIntoText(array $row): array { $return = []; if (isset($row['track']['peak'])) { $return['replaygain_track_peak'] = $row['track']['peak']; } if (isset($row['track']['originator'])) { $return['replaygain_track_originator'] = $row['track']['originator']; } if (isset($row['track']['adjustment'])) { $return['replaygain_track_gain'] = $row['track']['adjustment'] . ' dB'; } if (isset($row['album']['peak'])) { $return['replaygain_album_peak'] = $row['album']['peak']; } if (isset($row['album']['originator'])) { $return['replaygain_album_originator'] = $row['album']['originator']; } if (isset($row['album']['adjustment'])) { $return['replaygain_album_gain'] = $row['album']['adjustment'] . ' dB'; } if (isset($row['reference_volume'])) { $return['replaygain_reference_loudness'] = $row['reference_volume'] . ' LUFS'; } return $return; } } ```
/content/code_sandbox/backend/src/Media/Metadata/Reader/PhpReader.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
944
```php <?php declare(strict_types=1); namespace App\Media\Metadata\Reader; use App\Media\Enums\MetadataTags; use App\Media\Metadata; use App\Media\MetadataInterface; use App\Utilities\Arrays; use App\Utilities\Strings; abstract class AbstractReader { protected function aggregateMetaTags(MetadataInterface $metadata, array $toProcessRaw): void { $toProcess = []; // Restructure the incoming array to handle nested hashmaps. foreach ($toProcessRaw as $tagSet) { if (empty($tagSet)) { continue; } foreach ($tagSet as $tagName => $tagContents) { $tagContents = (array)$tagContents; if (empty($tagContents)) { continue; } // Skip pictures if (isset($tagContents[0]['data'])) { continue; } if (array_is_list($tagContents)) { $toProcess[$tagName][] = $tagContents; } else { foreach ($tagContents as $tagSubKey => $tagSubValue) { if (empty($tagSubValue)) { continue; } $toProcess[$tagSubKey][] = $tagSubValue; } } } } $knownTags = []; $extraTags = []; foreach ($toProcess as $tagName => $tagContents) { $tagName = mb_strtolower((string)$tagName); $tagEnum = MetadataTags::getTag($tagName); $newTagValues = $this->aggregateValues($tagContents); if (null !== $tagEnum) { $knownTags[$tagEnum->value] = $newTagValues; } else { $extraTags[$tagName] = $newTagValues; } } $metadata->setKnownTags($knownTags); $metadata->setExtraTags($extraTags); } protected function aggregateValues(array $values): string { $newValues = []; foreach (Arrays::flattenArray($values) as $valueRow) { if (str_contains($valueRow, Metadata::MULTI_VALUE_SEPARATOR)) { foreach (explode(Metadata::MULTI_VALUE_SEPARATOR, $valueRow) as $valueSubRow) { $newValues[] = trim($valueSubRow); } } else { $newValues[] = $valueRow; } } return Strings::stringToUtf8( implode(Metadata::MULTI_VALUE_SEPARATOR . ' ', array_unique($newValues)) ); } } ```
/content/code_sandbox/backend/src/Media/Metadata/Reader/AbstractReader.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
552
```php <?php declare(strict_types=1); namespace App\Media\AlbumArtHandler; use App\Entity\Interfaces\SongInterface; use App\Service\MusicBrainz; final class MusicBrainzAlbumArtHandler extends AbstractAlbumArtHandler { public function __construct( private readonly MusicBrainz $musicBrainz ) { } protected function getServiceName(): string { return 'MusicBrainz'; } public function getAlbumArt(SongInterface $song): ?string { $releaseGroupIds = []; foreach ($this->musicBrainz->findRecordingsForSong($song) as $recording) { if (empty($recording['releases'])) { continue; } foreach ($recording['releases'] as $release) { if (isset($release['release-group']['id'])) { $releaseGroupId = $release['release-group']['id']; if (isset($releaseGroupIds[$releaseGroupId])) { continue; // Already been checked. } $releaseGroupIds[$releaseGroupId] = $releaseGroupId; $groupAlbumArt = $this->musicBrainz->getCoverArt('release-group', $releaseGroupId); if (!empty($groupAlbumArt)) { return $groupAlbumArt; } } } } return null; } } ```
/content/code_sandbox/backend/src/Media/AlbumArtHandler/MusicBrainzAlbumArtHandler.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
289
```php <?php declare(strict_types=1); namespace App\Media\AlbumArtHandler; use App\Container\LoggerAwareTrait; use App\Entity\Interfaces\SongInterface; use App\Event\Media\GetAlbumArt; use App\Exception\Http\RateLimitExceededException; use RuntimeException; use Throwable; abstract class AbstractAlbumArtHandler { use LoggerAwareTrait; public function __invoke(GetAlbumArt $event): void { $serviceName = $this->getServiceName(); if (!$this->isSupported()) { $this->logger->info( sprintf( 'Service %f is not currently supported; skipping album art check.', $serviceName ) ); return; } $song = $event->getSong(); try { $albumArt = $this->getAlbumArt($song); if (!empty($albumArt)) { $event->setAlbumArt($albumArt); } } catch (Throwable $e) { $this->logger->error( sprintf('%s Album Art Error: %s', $serviceName, $e->getMessage()), [ 'exception' => $e, 'song' => $song->getText(), 'songId' => $song->getSongId(), ] ); if ( $e instanceof RateLimitExceededException || false !== stripos($e->getMessage(), 'rate limit') ) { return; } throw new RuntimeException( sprintf('%s Album Art Error: %s', $serviceName, $e->getMessage()), $e->getCode(), $e ); } } protected function isSupported(): bool { return true; } abstract protected function getServiceName(): string; abstract protected function getAlbumArt(SongInterface $song): ?string; } ```
/content/code_sandbox/backend/src/Media/AlbumArtHandler/AbstractAlbumArtHandler.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
390
```php <?php declare(strict_types=1); namespace App\Media\AlbumArtHandler; use App\Entity\Interfaces\SongInterface; use App\Entity\StationMedia; use App\Service\LastFm; final class LastFmAlbumArtHandler extends AbstractAlbumArtHandler { public function __construct( private readonly LastFm $lastFm, ) { } protected function getServiceName(): string { return 'LastFm'; } protected function getAlbumArt(SongInterface $song): ?string { if ($song instanceof StationMedia && !empty($song->getAlbum())) { $response = $this->lastFm->makeRequest( 'album.getInfo', [ 'artist' => $song->getArtist(), 'album' => $song->getAlbum(), ] ); if (isset($response['album'])) { return $this->getImageFromArray($response['album']['image'] ?? []); } } $response = $this->lastFm->makeRequest( 'track.getInfo', [ 'artist' => $song->getArtist(), 'track' => $song->getTitle(), ] ); if (isset($response['album'])) { return $this->getImageFromArray($response['album']['image'] ?? []); } return null; } private function getImageFromArray(array $images): ?string { $imagesBySize = []; foreach ($images as $image) { $size = ('' === $image['size']) ? 'default' : $image['size']; $imagesBySize[$size] = $image['#text']; } return $imagesBySize['large'] ?? $imagesBySize['extralarge'] ?? $imagesBySize['default'] ?? null; } } ```
/content/code_sandbox/backend/src/Media/AlbumArtHandler/LastFmAlbumArtHandler.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
395
```php <?php declare(strict_types=1); namespace App\Notification\Check; use App\Container\SettingsAwareTrait; use App\Entity\Api\Notification; use App\Enums\GlobalPermissions; use App\Enums\ReleaseChannel; use App\Event\GetNotifications; use App\Session\FlashLevels; use App\Version; final class UpdateCheck { use SettingsAwareTrait; public function __construct( private readonly Version $version, ) { } public function __invoke(GetNotifications $event): void { // This notification is for full administrators only. $acl = $event->getRequest()->getAcl(); if (!$acl->isAllowed(GlobalPermissions::All)) { return; } $settings = $this->readSettings(); if (!$settings->getCheckForUpdates()) { return; } $updateData = $settings->getUpdateResults(); if (empty($updateData)) { return; } $router = $event->getRequest()->getRouter(); $actionLabel = __('Update AzuraCast'); $actionUrl = $router->named('admin:updates:index'); $releaseChannel = $this->version->getReleaseChannelEnum(); if ( ReleaseChannel::Stable === $releaseChannel && ($updateData['needs_release_update'] ?? false) ) { $notification = new Notification(); $notification->title = __( 'New AzuraCast Stable Release Available', ); $notification->body = sprintf( __( 'Version %s is now available. You are currently running version %s. Updating is recommended.' ), $updateData['latest_release'], $updateData['current_release'] ); $notification->type = FlashLevels::Info->value; $notification->actionLabel = $actionLabel; $notification->actionUrl = $actionUrl; $event->addNotification($notification); return; } if (ReleaseChannel::RollingRelease === $releaseChannel) { if ($updateData['needs_rolling_update'] ?? false) { $notification = new Notification(); $notification->title = __( 'New AzuraCast Rolling Release Available' ); $notification->body = sprintf( __( 'Your installation is currently %d update(s) behind the latest version. Updating is recommended.' ), $updateData['rolling_updates_available'] ); $notification->type = FlashLevels::Info->value; $notification->actionLabel = $actionLabel; $notification->actionUrl = $actionUrl; $event->addNotification($notification); } if ($updateData['can_switch_to_stable'] ?? false) { $notification = new Notification(); $notification->title = __( 'Switch to Stable Channel Available' ); $notification->body = __( 'Your Rolling Release installation is currently older than the latest Stable release. This means you can switch releases to the "Stable" release channel if desired.' ); $notification->type = FlashLevels::Info->value; $notification->actionLabel = __('About Release Channels'); $notification->actionUrl = '/docs/getting-started/updates/release-channels/'; $event->addNotification($notification); } } } } ```
/content/code_sandbox/backend/src/Notification/Check/UpdateCheck.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
705
```php <?php declare(strict_types=1); namespace App\Notification\Check; use App\Container\EnvironmentAwareTrait; use App\Entity\Api\Notification; use App\Event\GetNotifications; use App\Exception\Http\RateLimitExceededException; use App\Session\FlashLevels; final class DonateAdvisorCheck { use EnvironmentAwareTrait; public function __invoke(GetNotifications $event): void { if (!$this->environment->isProduction()) { return; } $request = $event->getRequest(); $rateLimit = $request->getRateLimit(); try { $rateLimit->checkRequestRateLimit($request, 'notification:donate', 600, 1); } catch (RateLimitExceededException) { return; } $notification = new Notification(); $notification->title = __('AzuraCast is free and open-source software.'); $notification->body = __( 'If you are enjoying AzuraCast, please consider donating to support our work. We depend ' . 'on donations to build new features, fix bugs, and keep AzuraCast modern, accessible and free.', ); $notification->type = FlashLevels::Info->value; $notification->actionLabel = __('Donate to AzuraCast'); $notification->actionUrl = 'path_to_url $event->addNotification($notification); } } ```
/content/code_sandbox/backend/src/Notification/Check/DonateAdvisorCheck.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
294
```php <?php declare(strict_types=1); namespace App\Notification\Check; use App\Entity\Api\Notification; use App\Enums\GlobalPermissions; use App\Event\GetNotifications; use App\Service\ServiceControl; use App\Session\FlashLevels; final class ServiceCheck { public function __construct( private readonly ServiceControl $serviceControl ) { } public function __invoke(GetNotifications $event): void { // This notification is for full administrators only. $request = $event->getRequest(); $acl = $request->getAcl(); if (!$acl->isAllowed(GlobalPermissions::View)) { return; } $services = $this->serviceControl->getServices(); foreach ($services as $service) { if (!$service->running) { // phpcs:disable Generic.Files.LineLength $notification = new Notification(); $notification->title = sprintf(__('Service Not Running: %s'), $service->name); $notification->body = __( 'One of the essential services on this installation is not currently running. Visit the system administration and check the system logs to find the cause of this issue.' ); $notification->type = FlashLevels::Error->value; $router = $request->getRouter(); $notification->actionLabel = __('Administration'); $notification->actionUrl = $router->named('admin:index:index'); // phpcs:enable $event->addNotification($notification); } } } } ```
/content/code_sandbox/backend/src/Notification/Check/ServiceCheck.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
321
```php <?php declare(strict_types=1); namespace App\Notification\Check; use App\Container\SettingsAwareTrait; use App\Entity\Api\Notification; use App\Enums\GlobalPermissions; use App\Event\GetNotifications; use App\Session\FlashLevels; final class BaseUrlCheck { use SettingsAwareTrait; public function __invoke(GetNotifications $event): void { // This notification is for full administrators only. $request = $event->getRequest(); $router = $request->getRouter(); $acl = $request->getAcl(); if (!$acl->isAllowed(GlobalPermissions::Settings)) { return; } $settings = $this->readSettings(); // Base URL mismatch doesn't happen if this setting is enabled. if ($settings->getPreferBrowserUrl()) { return; } $baseUriWithRequest = $router->buildBaseUrl(true); $baseUriWithoutRequest = $router->buildBaseUrl(false); if ((string)$baseUriWithoutRequest !== (string)$baseUriWithRequest) { // phpcs:disable Generic.Files.LineLength $notificationBodyParts = []; $notificationBodyParts[] = __( 'You may want to update your base URL to ensure it is correct.' ); $notificationBodyParts[] = __( 'If you regularly use different URLs to access AzuraCast, you should enable the "Prefer Browser URL" setting.' ); // phpcs:enable Generic.Files.LineLength $notification = new Notification(); $notification->title = sprintf( __('Your "Base URL" setting (%s) does not match the URL you are currently using (%s).'), (string)$baseUriWithoutRequest, (string)$baseUriWithRequest ); $notification->body = implode(' ', $notificationBodyParts); $notification->type = FlashLevels::Warning->value; $notification->actionLabel = __('System Settings'); $notification->actionUrl = $router->named('admin:settings:index'); $event->addNotification($notification); } } } ```
/content/code_sandbox/backend/src/Notification/Check/BaseUrlCheck.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
447
```php <?php declare(strict_types=1); namespace App\Notification\Check; use App\Container\SettingsAwareTrait; use App\Entity\Api\Notification; use App\Enums\GlobalPermissions; use App\Event\GetNotifications; use App\Session\FlashLevels; final class SyncTaskCheck { use SettingsAwareTrait; public function __invoke(GetNotifications $event): void { // This notification is for full administrators only. $request = $event->getRequest(); $acl = $request->getAcl(); if (!$acl->isAllowed(GlobalPermissions::All)) { return; } $settings = $this->readSettings(); $setupComplete = $settings->getSetupCompleteTime(); if ($setupComplete > (time() - 60 * 60 * 2)) { return; } if ($settings->getSyncDisabled()) { // phpcs:disable Generic.Files.LineLength $notification = new Notification(); $notification->title = __('Synchronization Disabled'); $notification->body = __( 'Routine synchronization is currently disabled. Make sure to re-enable it to resume routine maintenance tasks.' ); $notification->type = FlashLevels::Error->value; // phpcs:enable $event->addNotification($notification); return; } $syncLastRun = $settings->getSyncLastRun(); if ($syncLastRun < (time() - 60 * 5)) { // phpcs:disable Generic.Files.LineLength $notification = new Notification(); $notification->title = __('Synchronization Not Recently Run'); $notification->body = __( 'The routine synchronization task has not run recently. This may indicate an error with your installation.' ); $notification->type = FlashLevels::Error->value; $router = $request->getRouter(); $notification->actionLabel = __('System Debugger'); $notification->actionUrl = $router->named('admin:debug:index'); // phpcs:enable $event->addNotification($notification); } } } ```
/content/code_sandbox/backend/src/Notification/Check/SyncTaskCheck.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
443
```php <?php declare(strict_types=1); namespace App\Notification\Check; use App\Container\EnvironmentAwareTrait; use App\Entity\Api\Notification; use App\Enums\GlobalPermissions; use App\Event\GetNotifications; use App\Session\FlashLevels; final class ProfilerAdvisorCheck { use EnvironmentAwareTrait; public function __invoke(GetNotifications $event): void { // This notification is for full administrators only. $acl = $event->getRequest()->getAcl(); if (!$acl->isAllowed(GlobalPermissions::All)) { return; } if (!$this->environment->isDocker() || !$this->environment->isDevelopment()) { return; } if (!$this->environment->isProfilingExtensionEnabled()) { return; } $notification = new Notification(); $notification->title = __('The performance profiling extension is currently enabled on this installation.'); $notification->body = __( 'You can track the execution time and memory usage of any AzuraCast page or application ' . 'from the profiler page.', ); $notification->type = FlashLevels::Info->value; $notification->actionLabel = __('Profiler Control Panel'); $notification->actionUrl = '/?' . http_build_query( [ 'SPX_UI_URI' => '/', 'SPX_KEY' => $this->environment->getProfilingExtensionHttpKey(), ] ); $event->addNotification($notification); if ($this->environment->isProfilingExtensionAlwaysOn()) { $notification = new Notification(); $notification->title = __('Performance profiling is currently enabled for all requests.'); $notification->body = __( 'This can have an adverse impact on system performance. ' . 'You should disable this when possible.' ); $notification->type = FlashLevels::Warning->value; $event->addNotification($notification); } } } ```
/content/code_sandbox/backend/src/Notification/Check/ProfilerAdvisorCheck.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
411
```php <?php declare(strict_types=1); namespace App\Notification\Check; use App\Container\EnvironmentAwareTrait; use App\Container\SettingsAwareTrait; use App\Entity\Api\Notification; use App\Enums\GlobalPermissions; use App\Event\GetNotifications; use App\Session\FlashLevels; use Carbon\CarbonImmutable; final class RecentBackupCheck { use EnvironmentAwareTrait; use SettingsAwareTrait; public function __invoke(GetNotifications $event): void { // This notification is for backup administrators only. $request = $event->getRequest(); $acl = $request->getAcl(); if (!$acl->isAllowed(GlobalPermissions::Backups)) { return; } if (!$this->environment->isProduction()) { return; } $threshold = CarbonImmutable::now()->subWeeks(2)->getTimestamp(); // Don't show backup warning for freshly created installations. $settings = $this->readSettings(); $setupComplete = $settings->getSetupCompleteTime(); if ($setupComplete >= $threshold) { return; } $backupLastRun = $settings->getBackupLastRun(); if ($backupLastRun < $threshold) { $notification = new Notification(); $notification->title = __('Installation Not Recently Backed Up'); $notification->body = __('This installation has not been backed up in the last two weeks.'); $notification->type = FlashLevels::Info->value; $router = $request->getRouter(); $notification->actionLabel = __('Backups'); $notification->actionUrl = $router->named('admin:backups:index'); $event->addNotification($notification); } } } ```
/content/code_sandbox/backend/src/Notification/Check/RecentBackupCheck.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
365
```php <?php declare(strict_types=1); namespace App\View; use ArrayAccess; use League\Plates\Template\Template; use LogicException; /** * A global section container for templates. * * @implements ArrayAccess<string, string> */ final class GlobalSections implements ArrayAccess { private int $sectionMode = Template::SECTION_MODE_REWRITE; private array $sections = []; private ?string $sectionName = null; public function has(string $section): bool { return !empty($this->sections[$section]); } public function offsetExists(mixed $offset): bool { return $this->has((string)$offset); } public function get(string $section, ?string $default = null): ?string { return $this->sections[$section] ?? $default; } public function offsetGet(mixed $offset): mixed { return $this->get((string)$offset); } public function unset(string $section): void { unset($this->sections[$section]); } public function offsetUnset(mixed $offset): void { $this->unset((string)$offset); } public function set( string $section, ?string $value, int $mode = Template::SECTION_MODE_REWRITE ): void { $initialValue = $this->sections[$section] ?? ''; $this->sections[$section] = match ($mode) { Template::SECTION_MODE_PREPEND => $value . $initialValue, Template::SECTION_MODE_APPEND => $initialValue . $value, default => $value }; } public function offsetSet(mixed $offset, mixed $value): void { $this->set((string)$offset, (string)$value); } public function prepend(string $section, ?string $value): void { $this->set($section, $value, Template::SECTION_MODE_PREPEND); } public function append(string $section, ?string $value): void { $this->set($section, $value, Template::SECTION_MODE_APPEND); } public function start(string $name): void { if ($this->sectionName) { throw new LogicException('You cannot nest sections within other sections.'); } $this->sectionName = $name; ob_start(); } public function appendStart(string $name): void { $this->sectionMode = Template::SECTION_MODE_APPEND; $this->start($name); } public function prependStart(string $name): void { $this->sectionMode = Template::SECTION_MODE_PREPEND; $this->start($name); } public function end(): void { if (is_null($this->sectionName)) { throw new LogicException( 'You must start a section before you can stop it.' ); } $this->set($this->sectionName, ob_get_clean() ?: null, $this->sectionMode); $this->sectionName = null; $this->sectionMode = Template::SECTION_MODE_REWRITE; } } ```
/content/code_sandbox/backend/src/View/GlobalSections.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
681
```php <?php declare(strict_types=1); namespace App\Nginx; use App\Entity\Station; use App\Event\Nginx\WriteNginxConfiguration; use Psr\EventDispatcher\EventDispatcherInterface; use Supervisor\SupervisorInterface; use Symfony\Component\Filesystem\Filesystem; final class Nginx { private const string PROCESS_NAME = 'nginx'; public function __construct( private readonly SupervisorInterface $supervisor, private readonly EventDispatcherInterface $eventDispatcher ) { } public function writeConfiguration( Station $station, bool $reloadIfChanged = true, ): void { $configPath = $this->getConfigPath($station); $currentConfig = (is_file($configPath)) ? file_get_contents($configPath) : null; $newConfig = $this->getConfiguration($station, true); if ($currentConfig === $newConfig) { return; } (new Filesystem())->dumpFile($configPath, $newConfig); if ($reloadIfChanged) { $this->reload(); } } public function getConfiguration( Station $station, bool $writeToDisk = false ): string { $event = new WriteNginxConfiguration( $station, $writeToDisk ); $this->eventDispatcher->dispatch($event); return $event->buildConfiguration(); } public function reload(): void { $this->supervisor->signalProcess(self::PROCESS_NAME, 'HUP'); } public function reopenLogs(): void { $this->supervisor->signalProcess(self::PROCESS_NAME, 'USR1'); } private function getConfigPath(Station $station): string { return $station->getRadioConfigDir() . '/nginx.conf'; } } ```
/content/code_sandbox/backend/src/Nginx/Nginx.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
393
```php <?php declare(strict_types=1); namespace App\Nginx; use App\Container\EntityManagerAwareTrait; use App\Container\LoggerAwareTrait; use App\Entity\Station; use JsonException; use NowPlaying\Result\Client; use NowPlaying\Result\Result; final class HlsListeners { use LoggerAwareTrait; use EntityManagerAwareTrait; public function updateNowPlaying( Result $np, Station $station, bool $includeClients = false ): Result { if (!$station->getEnableHls()) { return $np; } $hlsStreams = $station->getHlsStreams(); if (0 === $hlsStreams->count()) { $this->logger->error('No HLS streams.'); return $np; } $thresholdSecs = $station->getBackendConfig()->getHlsSegmentLength() * 2; $timestamp = time() - $thresholdSecs; $hlsLogFile = ConfigWriter::getHlsLogFile($station); $hlsLogBackup = $hlsLogFile . '.1'; if (!is_file($hlsLogFile)) { $this->logger->error('No HLS log file available.'); return $np; } $streamsByName = []; $clientsByStream = []; foreach ($hlsStreams as $hlsStream) { $streamsByName[$hlsStream->getName()] = $hlsStream->getIdRequired(); $clientsByStream[$hlsStream->getName()] = 0; } $allClients = []; $i = 1; $logContents = file($hlsLogFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; if (is_file($hlsLogBackup) && filemtime($hlsLogBackup) >= $timestamp) { $logContents = array_merge( $logContents, file($hlsLogBackup, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] ); } $logContents = array_reverse($logContents); foreach ($logContents as $logRow) { $client = $this->parseRow($logRow, $timestamp); if ( null !== $client && isset($clientsByStream[$client->mount]) && !isset($allClients[$client->uid]) ) { $clientsByStream[$client->mount]++; $clientHash = $client->uid; $client->uid = (string)$i; $client->mount = 'hls_' . $streamsByName[$client->mount]; $allClients[$clientHash] = $client; $i++; } } foreach ($hlsStreams as $hlsStream) { $numClients = (int)$clientsByStream[$hlsStream->getName()]; $hlsStream->setListeners($numClients); $this->em->persist($hlsStream); } $this->em->flush(); $result = Result::blank(); $result->listeners->total = $result->listeners->unique = count($allClients); $result->clients = ($includeClients) ? array_values($allClients) : []; $this->logger->debug('HLS response', ['response' => $result]); return $np->merge($result); } private function parseRow( string $row, int $threshold ): ?Client { if (empty(trim($row))) { return null; } try { /** @var array<array-key, string> $rowJson */ $rowJson = json_decode($row, true, 512, JSON_THROW_ON_ERROR); } catch (JsonException) { return null; } /* * Structure: * { * "msec": "1656205963.806", * "ua": "Mozilla/5.0 (Windows NT 10.0;...Chrome/102.0.0.0 Safari/537.36", * "ip": "192.168.48.1", * "ip_xff": "", * "uri": "/hls/azuratest_radio/aac_hifi.m3u8" * } */ $timestamp = (int)(explode('.', $rowJson['msec'], 2)[0]); if ($timestamp < $threshold) { return null; } $ip = (!empty($rowJson['ip_xff'])) ? $rowJson['ip_xff'] : $rowJson['ip']; $ua = $rowJson['ua']; return new Client( uid: md5($ip . '_' . $ua), ip: $ip, userAgent: $ua, connectedSeconds: 1, mount: basename($rowJson['uri'], '.m3u8') ); } } ```
/content/code_sandbox/backend/src/Nginx/HlsListeners.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,053
```php <?php declare(strict_types=1); namespace App\Nginx; use App\Entity\Station; use App\Event\Nginx\WriteNginxConfiguration; use App\Radio\Enums\BackendAdapters; use App\Radio\Enums\FrontendAdapters; use Symfony\Component\EventDispatcher\EventSubscriberInterface; final class ConfigWriter implements EventSubscriberInterface { /** * @return mixed[] */ public static function getSubscribedEvents(): array { return [ WriteNginxConfiguration::class => [ ['writeRadioSection', 35], ['writeWebDjSection', 30], ['writeHlsSection', 25], ], ]; } public function writeRadioSection(WriteNginxConfiguration $event): void { $station = $event->getStation(); // Only forward local radio if (FrontendAdapters::Remote === $station->getFrontendType()) { return; } $listenBaseUrl = CustomUrls::getListenUrl($station); $listenBaseUrlForRegex = preg_quote($listenBaseUrl, null); $port = $station->getFrontendConfig()->getPort(); $event->appendBlock( <<<NGINX location ~ ^({$listenBaseUrlForRegex}|/radio/{$port})\$ { return 302 \$uri/; } location ~ ^({$listenBaseUrlForRegex}|/radio/{$port})/(.*)\$ { include proxy_params; proxy_intercept_errors on; proxy_next_upstream error timeout invalid_header; proxy_redirect off; proxy_connect_timeout 60; proxy_set_header Host \$host/{$listenBaseUrl}; set \$args \$args&_ic2=1; proxy_pass path_to_url{$port}/\$2?\$args; } NGINX ); } public function writeWebDjSection(WriteNginxConfiguration $event): void { $station = $event->getStation(); // Only forward Liquidsoap if (BackendAdapters::Liquidsoap !== $station->getBackendType()) { return; } $webDjBaseUrl = preg_quote(CustomUrls::getWebDjUrl($station), null); $autoDjPort = $station->getBackendConfig()->getDjPort(); $event->appendBlock( <<<NGINX # Reverse proxy the WebDJ connection. location ~ ^({$webDjBaseUrl}|/radio/{$autoDjPort})(/?)(.*)\$ { include proxy_params; proxy_pass path_to_url{$autoDjPort}/$3; } NGINX ); } public function writeHlsSection(WriteNginxConfiguration $event): void { $station = $event->getStation(); if (!$station->getEnableHls()) { return; } $hlsBaseUrl = CustomUrls::getHlsUrl($station); $hlsFolder = $station->getRadioHlsDir(); $hlsLogPath = self::getHlsLogFile($station); $event->appendBlock( <<<NGINX # Reverse proxy the frontend broadcast. location {$hlsBaseUrl} { location ~ \.m3u8$ { access_log {$hlsLogPath} hls_json; } add_header 'Access-Control-Allow-Origin' '*'; add_header 'Cache-Control' 'no-cache'; alias {$hlsFolder}; try_files \$uri =404; } NGINX ); } public static function getHlsLogFile(Station $station): string { return $station->getRadioConfigDir() . '/hls.log'; } } ```
/content/code_sandbox/backend/src/Nginx/ConfigWriter.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
814
```php <?php declare(strict_types=1); namespace App\Nginx; use App\Entity\Station; final class CustomUrls { public static function getListenUrl(Station $station): string { return '/listen/' . $station->getShortName(); } public static function getWebDjUrl(Station $station): string { return '/webdj/' . $station->getShortName(); } public static function getHlsUrl(Station $station): string { return '/hls/' . $station->getShortName(); } /** * Returns a custom path if X-Accel-Redirect is configured for the path provided. */ public static function getXAccelPath(string $path): ?string { $specialPaths = [ '/var/azuracast/stations' => '/internal/stations', '/var/azuracast/storage' => '/internal/storage', '/var/azuracast/backups' => '/internal/backups', ]; foreach ($specialPaths as $diskPath => $nginxPath) { if (str_starts_with($path, $diskPath)) { return str_replace($diskPath, $nginxPath, $path); } } return null; } } ```
/content/code_sandbox/backend/src/Nginx/CustomUrls.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
280
```php <?php declare(strict_types=1); namespace App\Installer\Command; use App\Container\EnvironmentAwareTrait; use App\Enums\SupportedLocales; use App\Environment; use App\Installer\EnvFiles\AbstractEnvFile; use App\Installer\EnvFiles\AzuraCastEnvFile; use App\Installer\EnvFiles\EnvFile; use App\Radio\Configuration; use App\Utilities\Strings; use App\Utilities\Types; use InvalidArgumentException; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Yaml\Yaml; #[AsCommand( name: 'install' )] final class InstallCommand extends Command { use EnvironmentAwareTrait; public const string DEFAULT_BASE_DIRECTORY = '/installer'; protected function configure(): void { $this->addArgument('base-dir', InputArgument::OPTIONAL) ->addOption('update', null, InputOption::VALUE_NONE) ->addOption('defaults', null, InputOption::VALUE_NONE) ->addOption('http-port', null, InputOption::VALUE_OPTIONAL) ->addOption('https-port', null, InputOption::VALUE_OPTIONAL) ->addOption('release-channel', null, InputOption::VALUE_OPTIONAL); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $baseDir = Types::string($input->getArgument('base-dir'), self::DEFAULT_BASE_DIRECTORY); $update = Types::bool($input->getOption('update')); $defaults = Types::bool($input->getOption('defaults')); $httpPort = Types::intOrNull($input->getOption('http-port')); $httpsPort = Types::intOrNull($input->getOption('https-port')); $releaseChannel = Types::stringOrNull($input->getOption('release-channel')); $devMode = ($baseDir !== self::DEFAULT_BASE_DIRECTORY); // Initialize all the environment variables. $envPath = EnvFile::buildPathFromBase($baseDir); $azuracastEnvPath = AzuraCastEnvFile::buildPathFromBase($baseDir); // Fail early if permissions aren't present. if (!is_writable($envPath)) { $io->error( 'Permissions error: cannot write to work directory. Exiting installer and using defaults instead.' ); return 1; } $isNewInstall = !$update; try { $env = EnvFile::fromEnvFile($envPath); } catch (InvalidArgumentException $e) { $io->error($e->getMessage()); $env = new EnvFile($envPath); } try { $azuracastEnv = AzuraCastEnvFile::fromEnvFile($azuracastEnvPath); } catch (InvalidArgumentException $e) { $io->error($e->getMessage()); $azuracastEnv = new AzuraCastEnvFile($envPath); } // Podman support $isPodman = $env->getAsBool('AZURACAST_PODMAN_MODE', false); if ($isPodman) { $azuracastEnv[Environment::ENABLE_WEB_UPDATER] = 'false'; } // Initialize locale for translated installer/updater. if (!$defaults && ($isNewInstall || empty($azuracastEnv[Environment::LANG]))) { $langOptions = []; foreach (SupportedLocales::cases() as $supportedLocale) { $langOptions[$supportedLocale->getLocaleWithoutEncoding()] = $supportedLocale->getLocalName(); } $azuracastEnv[Environment::LANG] = $io->choice( 'Select Language', $langOptions, SupportedLocales::default()->getLocaleWithoutEncoding() ); } $locale = SupportedLocales::getValidLocale($azuracastEnv[Environment::LANG] ?? null); $locale->register($this->environment); $envConfig = EnvFile::getConfiguration($this->environment); $env->setFromDefaults($this->environment); $azuracastEnvConfig = AzuraCastEnvFile::getConfiguration($this->environment); $azuracastEnv->setFromDefaults($this->environment); // Apply values passed via flags if (null !== $releaseChannel) { $env['AZURACAST_VERSION'] = $releaseChannel; } if (null !== $httpPort) { $env['AZURACAST_HTTP_PORT'] = (string)$httpPort; } if (null !== $httpsPort) { $env['AZURACAST_HTTPS_PORT'] = (string)$httpsPort; } // Migrate legacy config values. if (isset($azuracastEnv['PREFER_RELEASE_BUILDS'])) { $env['AZURACAST_VERSION'] = ('true' === $azuracastEnv['PREFER_RELEASE_BUILDS']) ? 'stable' : 'latest'; unset($azuracastEnv['PREFER_RELEASE_BUILDS']); } unset($azuracastEnv['ENABLE_ADVANCED_FEATURES']); // Randomize the MariaDB root password for new installs. if ($isNewInstall) { if ($devMode) { if (empty($azuracastEnv['MYSQL_ROOT_PASSWORD'])) { $azuracastEnv['MYSQL_ROOT_PASSWORD'] = 'azur4c457_root'; } } else { if ( empty($azuracastEnv[Environment::DB_PASSWORD]) || 'azur4c457' === $azuracastEnv[Environment::DB_PASSWORD] ) { $azuracastEnv[Environment::DB_PASSWORD] = Strings::generatePassword(12); } if (empty($azuracastEnv['MYSQL_ROOT_PASSWORD'])) { $azuracastEnv['MYSQL_ROOT_PASSWORD'] = Strings::generatePassword(20); } } } if (!empty($azuracastEnv['MYSQL_ROOT_PASSWORD'])) { unset($azuracastEnv['MYSQL_RANDOM_ROOT_PASSWORD']); } else { $azuracastEnv['MYSQL_RANDOM_ROOT_PASSWORD'] = 'yes'; } // Special fixes for transitioning to standalone installations. if ($this->environment->isDocker()) { if ('mariadb' === $azuracastEnv['MYSQL_HOST']) { unset($azuracastEnv['MYSQL_HOST']); } if ('redis' === $azuracastEnv['REDIS_HOST']) { unset($azuracastEnv['REDIS_HOST']); } } // Display header messages if ($isNewInstall) { $io->title( __('AzuraCast Installer') ); $io->block( __('Welcome to AzuraCast! Complete the initial server setup by answering a few questions.') ); $customize = !$defaults; } else { $io->title( __('AzuraCast Updater') ); if ($defaults) { $customize = false; } else { $customize = $io->confirm( __('Change installation settings?'), false ); } } if ($customize) { // Port customization $io->writeln( __('AzuraCast is currently configured to listen on the following ports:'), ); $io->listing( [ sprintf(__('HTTP Port: %d'), $env['AZURACAST_HTTP_PORT']), sprintf(__('HTTPS Port: %d'), $env['AZURACAST_HTTPS_PORT']), sprintf(__('SFTP Port: %d'), $env['AZURACAST_SFTP_PORT']), sprintf(__('Radio Ports: %s'), $env['AZURACAST_STATION_PORTS']), ], ); $customizePorts = $io->confirm( __('Customize ports used for AzuraCast?'), false ); if ($customizePorts) { $simplePorts = [ 'AZURACAST_HTTP_PORT', 'AZURACAST_HTTPS_PORT', 'AZURACAST_SFTP_PORT', ]; foreach ($simplePorts as $port) { $env[$port] = $io->ask( sprintf( '%s - %s', $envConfig[$port]['name'], $envConfig[$port]['description'] ?? '' ), Types::stringOrNull($env[$port]) ); } $azuracastEnv[Environment::AUTO_ASSIGN_PORT_MIN] = $io->ask( $azuracastEnvConfig[Environment::AUTO_ASSIGN_PORT_MIN]['name'], Types::stringOrNull($azuracastEnv[Environment::AUTO_ASSIGN_PORT_MIN]) ); $azuracastEnv[Environment::AUTO_ASSIGN_PORT_MAX] = $io->ask( $azuracastEnvConfig[Environment::AUTO_ASSIGN_PORT_MAX]['name'], Types::stringOrNull($azuracastEnv[Environment::AUTO_ASSIGN_PORT_MAX]) ); $stationPorts = Configuration::enumerateDefaultPorts( rangeMin: Types::int($azuracastEnv[Environment::AUTO_ASSIGN_PORT_MIN]), rangeMax: Types::int($azuracastEnv[Environment::AUTO_ASSIGN_PORT_MAX]) ); $env['AZURACAST_STATION_PORTS'] = implode(',', $stationPorts); } $azuracastEnv['COMPOSER_PLUGIN_MODE'] = $io->confirm( $azuracastEnvConfig['COMPOSER_PLUGIN_MODE']['name'], $azuracastEnv->getAsBool('COMPOSER_PLUGIN_MODE', false) ) ? 'true' : 'false'; if (!$isPodman) { $azuracastEnv[Environment::ENABLE_WEB_UPDATER] = $io->confirm( $azuracastEnvConfig[Environment::ENABLE_WEB_UPDATER]['name'], $azuracastEnv->getAsBool(Environment::ENABLE_WEB_UPDATER, true) ) ? 'true' : 'false'; } } $io->writeln( __('Writing configuration files...') ); $envStr = $env->writeToFile($this->environment); $azuracastEnvStr = $azuracastEnv->writeToFile($this->environment); if ($io->isVerbose()) { $io->section($env->getBasename()); $io->block($envStr); $io->section($azuracastEnv->getBasename()); $io->block($azuracastEnvStr); } $dockerComposePath = ($devMode) ? $baseDir . '/docker-compose.yml' : $baseDir . '/docker-compose.new.yml'; $dockerComposeStr = $this->updateDockerCompose($dockerComposePath, $env, $azuracastEnv); if ($io->isVerbose()) { $io->section(basename($dockerComposePath)); $io->block($dockerComposeStr); } $io->success( __('Server configuration complete!') ); return 0; } private function updateDockerCompose( string $dockerComposePath, AbstractEnvFile $env, AbstractEnvFile $azuracastEnv ): string { // Attempt to parse Docker Compose YAML file $sampleFile = $this->environment->getBaseDirectory() . '/docker-compose.sample.yml'; /** @var array $yaml */ $yaml = Yaml::parseFile($sampleFile); // Parse port listing and convert into YAML format. $ports = $env['AZURACAST_STATION_PORTS'] ?? ''; $envConfig = $env::getConfiguration($this->environment); $defaultPorts = $envConfig['AZURACAST_STATION_PORTS']['default'] ?? ''; if (!empty($ports) && 0 !== strcmp($ports, $defaultPorts)) { $yamlPorts = []; $nginxRadioPorts = []; $nginxWebDjPorts = []; foreach (explode(',', $ports) as $port) { $port = (int)$port; if ($port <= 0) { continue; } $yamlPorts[] = $port . ':' . $port; if (0 === $port % 10) { $nginxRadioPorts[] = $port; } elseif (5 === $port % 10) { $nginxWebDjPorts[] = $port; } } if (!empty($yamlPorts)) { $existingPorts = []; foreach ($yaml['services']['web']['ports'] as $port) { if (str_starts_with($port, '$')) { $existingPorts[] = $port; } } $yaml['services']['web']['ports'] = array_merge($existingPorts, $yamlPorts); } if (!empty($nginxRadioPorts)) { $yaml['services']['web']['environment']['NGINX_RADIO_PORTS'] = '(' . implode( '|', $nginxRadioPorts ) . ')'; } if (!empty($nginxWebDjPorts)) { $yaml['services']['web']['environment']['NGINX_WEBDJ_PORTS'] = '(' . implode( '|', $nginxWebDjPorts ) . ')'; } } // Add plugin mode if it's selected. if ($azuracastEnv->getAsBool('COMPOSER_PLUGIN_MODE', false)) { $yaml['services']['web']['volumes'][] = 'www_vendor:/var/azuracast/www/vendor'; $yaml['volumes']['www_vendor'] = []; } // Remove privileged-mode settings if not enabled. if (!$env->getAsBool('AZURACAST_COMPOSE_PRIVILEGED', true)) { foreach ($yaml['services'] as &$service) { unset( $service['ulimits'], $service['sysctls'] ); } unset($service); } // Remove web updater if disabled. if (!$azuracastEnv->getAsBool(Environment::ENABLE_WEB_UPDATER, true)) { unset($yaml['services']['updater']); } // Podman privileged mode explicit specification. if ($env->getAsBool('AZURACAST_PODMAN_MODE', false)) { $yaml['services']['web']['privileged'] = 'true'; } $yamlRaw = Yaml::dump($yaml, PHP_INT_MAX); file_put_contents($dockerComposePath, $yamlRaw); return $yamlRaw; } } ```
/content/code_sandbox/backend/src/Installer/Command/InstallCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
3,180
```php <?php declare(strict_types=1); namespace App\Installer\EnvFiles; use App\Environment; use App\Utilities\Strings; use App\Utilities\Types; use ArrayAccess; use DateTimeImmutable; use DateTimeZone; use Dotenv\Dotenv; use Dotenv\Exception\ExceptionInterface; use InvalidArgumentException; /** * @implements ArrayAccess<string, string> */ abstract class AbstractEnvFile implements ArrayAccess { final public function __construct( protected string $path, protected array $data = [] ) { } public function getPath(): string { return $this->path; } public function getBasename(): string { return basename($this->path); } public function setFromDefaults(Environment $environment): void { $currentVars = array_filter($this->data); $defaults = []; foreach (static::getConfiguration($environment) as $key => $keyInfo) { if (isset($keyInfo['default'])) { $defaults[$key] = $keyInfo['default']; } } $this->data = array_merge($defaults, $currentVars); } /** * @return array<string,mixed> */ public function toArray(): array { return $this->data; } public function getAsBool(string $key, bool $default): bool { return Types::bool($this->data[$key] ?? null, $default, true); } public function offsetExists(mixed $offset): bool { return isset($this->data[$offset]); } public function offsetGet(mixed $offset): mixed { return $this->data[$offset] ?? null; } public function offsetSet(mixed $offset, mixed $value): void { $this->data[$offset] = $value; } public function offsetUnset(mixed $offset): void { unset($this->data[$offset]); } public function writeToFile(Environment $environment): string { $values = array_filter($this->data); $envFile = [ '# ' . __('This file was automatically generated by AzuraCast.'), '# ' . __('You can modify it as necessary. To apply changes, restart the Docker containers.'), '# ' . __('Remove the leading "#" symbol from lines to uncomment them.'), '', ]; foreach (static::getConfiguration($environment) as $key => $keyInfo) { $envFile[] = sprintf('# %s', $keyInfo['name']); if (!empty($keyInfo['description'])) { $desc = Strings::mbWordwrap($keyInfo['description']); foreach (explode("\n", $desc) as $descPart) { $envFile[] = '# ' . $descPart; } } if (!empty($keyInfo['options'])) { $options = array_map( fn($val) => $this->getEnvValue($val), $keyInfo['options'], ); $envFile[] = '# ' . sprintf(__('Valid options: %s'), implode(', ', $options)); } if (isset($values[$key])) { $value = $this->getEnvValue($values[$key]); unset($values[$key]); } else { $value = null; } if (!empty($keyInfo['default'])) { $default = $this->getEnvValue($keyInfo['default']); $envFile[] = '# ' . sprintf(__('Default: %s'), $default); } else { $default = ''; } $isRequired = (bool)($keyInfo['required'] ?? false); if (null === $value || ($default === $value && !$isRequired)) { $value ??= $default; $envFile[] = '# ' . $key . '=' . $value; } else { $envFile[] = $key . '=' . $value; } $envFile[] = ''; } // Add in other environment vars that were missed or previously present. if (!empty($values)) { $envFile[] = '# ' . __('Additional Environment Variables'); foreach ($values as $key => $value) { $envFile[] = $key . '=' . $this->getEnvValue($value); } } $envFileStr = implode("\n", $envFile); if (is_file($this->path)) { $existingFile = file_get_contents($this->path) ?: ''; if ($envFileStr !== $existingFile) { $currentTimeUtc = new DateTimeImmutable('now', new DateTimeZone('UTC')); $backupPath = $this->path . '_backup_' . $currentTimeUtc->format('Ymd-his') . '.bak'; copy($this->path, $backupPath); } } file_put_contents($this->path, $envFileStr); return $envFileStr; } protected function getEnvValue( mixed $value ): string { if (is_array($value)) { return implode(',', $value); } $value = Types::string($value); if (str_contains($value, ' ')) { $value = '"' . $value . '"'; } return $value; } /** * @return array<string, array{ * name: string, * description?: string, * options?: array, * default?: string, * required?: bool * }> */ abstract public static function getConfiguration(Environment $environment): array; abstract public static function buildPathFromBase(string $baseDir): string; public static function fromEnvFile(string $path): static { $data = []; if (is_file($path)) { $fileContents = file_get_contents($path); if (!empty($fileContents)) { try { $data = array_filter(Dotenv::parse($fileContents)); } catch (ExceptionInterface $e) { throw new InvalidArgumentException( sprintf( 'Encountered an error parsing %s: "%s". Resetting to default configuration.', basename($path), $e->getMessage() ) ); } } } return new static($path, $data); } } ```
/content/code_sandbox/backend/src/Installer/EnvFiles/AbstractEnvFile.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,367
```php <?php declare(strict_types=1); namespace App\Installer\EnvFiles; use App\Enums\ApplicationEnvironment; use App\Enums\SupportedLocales; use App\Environment; use Psr\Log\LogLevel; use function __; final class AzuraCastEnvFile extends AbstractEnvFile { /** @inheritDoc */ public static function getConfiguration(Environment $environment): array { static $config = null; if (null === $config) { $emptyEnv = Environment::getDefaultsForEnvironment($environment); $defaults = $emptyEnv->toArray(); $langOptions = []; foreach (SupportedLocales::cases() as $supportedLocale) { $langOptions[] = $supportedLocale->getLocaleWithoutEncoding(); } $dbSettings = $emptyEnv->getDatabaseSettings(); $redisSettings = $emptyEnv->getRedisSettings(); $config = [ Environment::LANG => [ 'name' => __('The locale to use for CLI commands.'), 'options' => $langOptions, 'default' => SupportedLocales::default()->getLocaleWithoutEncoding(), 'required' => true, ], Environment::APP_ENV => [ 'name' => __('The application environment.'), 'options' => ApplicationEnvironment::toSelect(), 'required' => true, ], Environment::LOG_LEVEL => [ 'name' => __('Manually modify the logging level.'), 'description' => __( 'This allows you to log debug-level errors temporarily (for problem-solving) or reduce the volume of logs that are produced by your installation, without needing to modify whether your installation is a production or development instance.' ), 'options' => [ LogLevel::DEBUG, LogLevel::INFO, LogLevel::NOTICE, LogLevel::WARNING, LogLevel::ERROR, LogLevel::CRITICAL, LogLevel::ALERT, LogLevel::EMERGENCY, ], ], 'COMPOSER_PLUGIN_MODE' => [ 'name' => __('Enable Custom Code Plugins'), 'description' => __( 'Enable the composer "merge" functionality to combine the main application\'s composer.json file with any plugin composer files. This can have performance implications, so you should only use it if you use one or more plugins with their own Composer dependencies.', ), 'options' => [true, false], 'default' => false, ], Environment::AUTO_ASSIGN_PORT_MIN => [ 'name' => __('Minimum Port for Station Port Assignment'), 'description' => __( 'Modify this if your stations are listening on nonstandard ports.', ), ], Environment::AUTO_ASSIGN_PORT_MAX => [ 'name' => __('Maximum Port for Station Port Assignment'), 'description' => __( 'Modify this if your stations are listening on nonstandard ports.', ), ], Environment::SHOW_DETAILED_ERRORS => [ 'name' => __('Show Detailed Slim Application Errors'), 'description' => __( 'This allows you to debug Slim Application Errors you may encounter. Please report any Slim Application Error logs to the development team on GitHub.' ), 'options' => [true, false], 'default' => false, ], Environment::DB_HOST => [ 'name' => __('MariaDB Host'), 'description' => __( 'Do not modify this after installation.', ), 'default' => $dbSettings['host'], 'required' => true, ], Environment::DB_PORT => [ 'name' => __('MariaDB Port'), 'description' => __( 'Do not modify this after installation.', ), 'default' => $dbSettings['port'], 'required' => true, ], Environment::DB_USER => [ 'name' => __('MariaDB Username'), 'description' => __( 'Do not modify this after installation.', ), 'default' => $dbSettings['user'], 'required' => true, ], Environment::DB_PASSWORD => [ 'name' => __('MariaDB Password'), 'description' => __( 'Do not modify this after installation.', ), 'default' => $dbSettings['password'], 'required' => true, ], Environment::DB_NAME => [ 'name' => __('MariaDB Database Name'), 'description' => __( 'Do not modify this after installation.', ), 'default' => $dbSettings['dbname'], 'required' => true, ], 'MYSQL_RANDOM_ROOT_PASSWORD' => [ 'name' => __('Auto-generate Random MariaDB Root Password'), 'description' => __( 'Do not modify this after installation.', ), ], 'MYSQL_ROOT_PASSWORD' => [ 'name' => __('MariaDB Root Password'), 'description' => __( 'Do not modify this after installation.', ), ], 'MYSQL_SLOW_QUERY_LOG' => [ 'name' => __('Enable MariaDB Slow Query Log'), 'description' => __( 'Log slower queries to diagnose possible database issues. Only turn this on if needed.', ), 'default' => 0, ], 'MYSQL_MAX_CONNECTIONS' => [ 'name' => __('MariaDB Maximum Connections'), 'description' => __( 'Set the amount of allowed connections to the database. This value should be increased if you are seeing the "Too many connections" error in the logs.', ), 'default' => 100, ], 'MYSQL_INNODB_BUFFER_POOL_SIZE' => [ 'name' => __('MariaDB InnoDB Buffer Pool Size'), 'description' => __( 'The InnoDB buffer pool size controls how much data & indexes are kept in memory. Making sure that this value is as large as possible reduces the amount of disk IO.', ), 'default' => '128M', ], 'MYSQL_INNODB_LOG_FILE_SIZE' => [ 'name' => __('MariaDB InnoDB Log File Size'), 'description' => __( 'The InnoDB log file is used to achieve data durability in case of crashes or unexpected shutoffs and to allow the DB to better optimize IO for write operations.', ), 'default' => '16M', ], Environment::ENABLE_REDIS => [ 'name' => __('Enable Redis'), 'description' => __( 'Disable to use a flatfile cache instead of Redis.', ), ], Environment::REDIS_HOST => [ 'name' => __('Redis Host'), 'default' => $redisSettings['host'], 'required' => true, ], Environment::REDIS_PORT => [ 'name' => __('Redis Port'), 'default' => $redisSettings['port'], 'required' => true, ], 'PHP_MAX_FILE_SIZE' => [ 'name' => __('PHP Maximum POST File Size'), 'default' => '25M', ], 'PHP_MEMORY_LIMIT' => [ 'name' => __('PHP Memory Limit'), 'default' => '128M', ], 'PHP_MAX_EXECUTION_TIME' => [ 'name' => __('PHP Script Maximum Execution Time (Seconds)'), 'default' => 30, ], Environment::SYNC_SHORT_EXECUTION_TIME => [ 'name' => __('Short Sync Task Execution Time (Seconds)'), 'description' => __( 'The maximum execution time (and lock timeout) for the 15-second, 1-minute and 5-minute synchronization tasks.' ), ], Environment::SYNC_LONG_EXECUTION_TIME => [ 'name' => __('Long Sync Task Execution Time (Seconds)'), 'description' => __( 'The maximum execution time (and lock timeout) for the 1-hour synchronization task.', ), ], Environment::NOW_PLAYING_DELAY_TIME => [ 'name' => __('Now Playing Delay Time (Seconds)'), 'description' => __( 'The delay between Now Playing checks for every station. Decrease for more frequent checks at the expense of performance; increase for less frequent checks but better performance (for large installations).' ), ], Environment::NOW_PLAYING_MAX_CONCURRENT_PROCESSES => [ 'name' => __('Now Playing Max Concurrent Processes'), 'description' => __( 'The maximum number of concurrent processes for now playing updates. Increasing this can help reduce the latency between updates now playing updates on large installations.' ), ], 'PHP_FPM_MAX_CHILDREN' => [ 'name' => __('Maximum PHP-FPM Worker Processes'), 'default' => 5, ], Environment::PROFILING_EXTENSION_ENABLED => [ 'name' => __('Enable Performance Profiling Extension'), 'description' => sprintf( __('Profiling data can be viewed by visiting %s.'), 'path_to_url ), ], Environment::PROFILING_EXTENSION_ALWAYS_ON => [ 'name' => __('Profile Performance on All Requests'), 'description' => __( 'This will have a significant performance impact on your installation.', ), ], Environment::PROFILING_EXTENSION_HTTP_KEY => [ 'name' => __('Profiling Extension HTTP Key'), 'description' => __( 'The value for the "SPX_KEY" parameter for viewing profiling pages.', ), ], 'PROFILING_EXTENSION_HTTP_IP_WHITELIST' => [ 'name' => __('Profiling Extension IP Allow List'), 'options' => ['127.0.0.1', '*'], 'default' => '*', ], 'NGINX_CLIENT_MAX_BODY_SIZE' => [ 'name' => __('Nginx Max Client Body Size'), 'description' => __( 'This is the total size any single request body can be. AzuraCast chunks its uploads into smaller file sizes, so this only applies when doing custom uploads via the API. Sizes should be listed in a format like "100K", "128M", "1G" for kilobytes, megabytes, and gigabytes respectively.' ), 'default' => '50M', ], Environment::ENABLE_WEB_UPDATER => [ 'name' => __('Enable web-based Docker image updates'), 'default' => true, ], 'INSTALL_PACKAGES_ON_STARTUP' => [ 'name' => __('Extra Ubuntu packages to install upon startup'), 'default' => __( 'Separate package names with a space. Packages will be installed during container startup.' ), ], ]; foreach ($config as $key => &$keyInfo) { $keyInfo['default'] ??= $defaults[$key] ?? null; } } return $config; } public static function buildPathFromBase(string $baseDir): string { return $baseDir . DIRECTORY_SEPARATOR . 'azuracast.env'; } } ```
/content/code_sandbox/backend/src/Installer/EnvFiles/AzuraCastEnvFile.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,310
```php <?php declare(strict_types=1); namespace App\Installer\EnvFiles; use App\Environment; use App\Radio\Configuration; use function __; final class EnvFile extends AbstractEnvFile { /** @inheritDoc */ public static function getConfiguration(Environment $environment): array { static $config = null; if (null === $config) { $config = [ 'COMPOSE_PROJECT_NAME' => [ 'name' => __( '(Docker Compose) All Docker containers are prefixed by this name. Do not change this after installation.' ), 'default' => 'azuracast', 'required' => true, ], 'COMPOSE_HTTP_TIMEOUT' => [ 'name' => __( '(Docker Compose) The amount of time to wait before a Docker Compose operation fails. Increase this on lower performance computers.' ), 'default' => 300, 'required' => true, ], 'AZURACAST_VERSION' => [ 'name' => __('Release Channel'), 'options' => ['latest', 'stable'], 'default' => 'latest', 'required' => true, ], 'AZURACAST_HTTP_PORT' => [ 'name' => __('HTTP Port'), 'description' => __( 'The main port AzuraCast listens to for insecure HTTP connections.', ), 'default' => 80, ], 'AZURACAST_HTTPS_PORT' => [ 'name' => __('HTTPS Port'), 'description' => __( 'The main port AzuraCast listens to for secure HTTPS connections.', ), 'default' => 443, ], 'AZURACAST_SFTP_PORT' => [ 'name' => __('SFTP Port'), 'description' => __( 'The port AzuraCast listens to for SFTP file management connections.', ), 'default' => 2022, ], 'AZURACAST_STATION_PORTS' => [ 'name' => __('Station Ports'), 'description' => __( 'The ports AzuraCast should listen to for station broadcasts and incoming DJ connections.', ), 'default' => implode(',', Configuration::enumerateDefaultPorts()), ], 'AZURACAST_PUID' => [ 'name' => __('Docker User UID'), 'description' => __( 'Set the UID of the user running inside the Docker containers. Matching this with your host UID can fix permission issues.', ), 'default' => 1000, ], 'AZURACAST_PGID' => [ 'name' => __('Docker User GID'), 'description' => __( 'Set the GID of the user running inside the Docker containers. Matching this with your host GID can fix permission issues.' ), 'default' => 1000, ], 'AZURACAST_PODMAN_MODE' => [ 'name' => __('Use Podman instead of Docker.'), 'default' => false, ], 'AZURACAST_COMPOSE_PRIVILEGED' => [ 'name' => __('Advanced: Use Privileged Docker Settings'), 'default' => true, ], ]; } return $config; } public static function buildPathFromBase(string $baseDir): string { return $baseDir . DIRECTORY_SEPARATOR . '.env'; } } ```
/content/code_sandbox/backend/src/Installer/EnvFiles/EnvFile.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
736
```php <?php declare(strict_types=1); namespace App\MessageQueue; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Messenger\Event\WorkerMessageReceivedEvent; use Symfony\Contracts\Cache\CacheInterface; final class ResetArrayCacheSubscriber implements EventSubscriberInterface { public function __construct( private readonly CacheInterface $cache ) { } /** * @inheritDoc */ public static function getSubscribedEvents(): array { return [ WorkerMessageReceivedEvent::class => [ ['resetArrayCache', -100], ], ]; } public function resetArrayCache(): void { if ($this->cache instanceof ArrayAdapter) { $this->cache->reset(); } } } ```
/content/code_sandbox/backend/src/MessageQueue/ResetArrayCacheSubscriber.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
166
```php <?php declare(strict_types=1); namespace App\MessageQueue; enum QueueNames: string { case HighPriority = 'high_priority'; case NormalPriority = 'normal_priority'; case LowPriority = 'low_priority'; case SearchIndex = 'search_index'; case Media = 'media'; case PodcastMedia = 'podcast_media'; } ```
/content/code_sandbox/backend/src/MessageQueue/QueueNames.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
76
```php <?php declare(strict_types=1); namespace App\MessageQueue; use App\Service\RedisFactory; use Symfony\Component\Messenger\Bridge\Redis\Transport\Connection; use Symfony\Component\Messenger\Bridge\Redis\Transport\RedisTransport; use Symfony\Component\Messenger\Exception\TransportException; final class QueueManager extends AbstractQueueManager { /** @var Connection[] */ private array $connections = []; public function __construct( private readonly RedisFactory $redisFactory ) { } public function clearQueue(QueueNames $queue): void { $connection = $this->getConnection($queue); $connection->cleanup(); $connection->setup(); } public function getTransport(QueueNames $queue): RedisTransport { return new RedisTransport($this->getConnection($queue)); } /** * @return RedisTransport[] */ public function getTransports(): array { $transports = []; foreach (QueueNames::cases() as $queue) { $transports[$queue->value] = $this->getTransport($queue); } return $transports; } private function getConnection(QueueNames $queue): Connection { $queueName = $queue->value; if (!isset($this->connections[$queueName])) { $this->connections[$queueName] = new Connection( [ 'lazy' => true, 'stream' => 'messages.' . $queueName, 'delete_after_ack' => true, 'redeliver_timeout' => 43200, 'claim_interval' => 86400, ], $this->redisFactory->getInstance() ); } return $this->connections[$queueName]; } public function getQueueCount(QueueNames $queue): int { try { return $this->getConnection($queue)->getMessageCount(); } catch (TransportException) { return 0; } } } ```
/content/code_sandbox/backend/src/MessageQueue/QueueManager.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
421
```php <?php declare(strict_types=1); namespace App\MessageQueue; use App\Lock\LockFactory; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException; use Symfony\Component\Messenger\Middleware\MiddlewareInterface; use Symfony\Component\Messenger\Middleware\StackInterface; use Symfony\Component\Messenger\Stamp\ConsumedByWorkerStamp; final class HandleUniqueMiddleware implements MiddlewareInterface { public function __construct( protected LockFactory $lockFactory ) { } public function handle(Envelope $envelope, StackInterface $stack): Envelope { if ( $envelope->last(ConsumedByWorkerStamp::class) === null || !($envelope->getMessage() instanceof UniqueMessageInterface) ) { return $stack->next()->handle($envelope, $stack); } /** @var UniqueMessageInterface $message */ $message = $envelope->getMessage(); $lock = $this->lockFactory->createLock('message_queue_' . $message->getIdentifier(), $message->getTtl()); if (!$lock->acquire()) { throw new UnrecoverableMessageHandlingException( 'A queued message matching this one is already being handled.' ); } try { return $stack->next()->handle($envelope, $stack); } finally { $lock->release(); } } } ```
/content/code_sandbox/backend/src/MessageQueue/HandleUniqueMiddleware.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
299
```php <?php declare(strict_types=1); namespace App\MessageQueue; use App\Container\LoggerAwareTrait; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent; final class LogWorkerExceptionSubscriber implements EventSubscriberInterface { use LoggerAwareTrait; /** * @inheritDoc */ public static function getSubscribedEvents(): array { return [ WorkerMessageFailedEvent::class => 'logError', ]; } public function logError(WorkerMessageFailedEvent $event): void { $exception = $event->getThrowable(); $this->logger->error($exception->getMessage(), [ 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'code' => $exception->getCode(), ]); } } ```
/content/code_sandbox/backend/src/MessageQueue/LogWorkerExceptionSubscriber.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
179
```php <?php declare(strict_types=1); namespace App\MessageQueue; use App\Message\AbstractMessage; use Symfony\Component\Messenger\Envelope; abstract class AbstractQueueManager implements QueueManagerInterface { protected string $workerName = 'app'; public function setWorkerName(string $workerName): void { $this->workerName = $workerName; } public function clearAllQueues(): void { foreach (QueueNames::cases() as $queue) { $this->clearQueue($queue); } } /** * @inheritDoc */ public function getSenders(Envelope $envelope): iterable { $message = $envelope->getMessage(); if (!$message instanceof AbstractMessage) { return [ QueueNames::NormalPriority->value => $this->getTransport(QueueNames::NormalPriority), ]; } $queue = $message->getQueue(); return [ $queue->value => $this->getTransport($queue), ]; } public function getTransports(): array { $transports = []; foreach (QueueNames::cases() as $queue) { $transports[$queue->value] = $this->getTransport($queue); } return $transports; } } ```
/content/code_sandbox/backend/src/MessageQueue/AbstractQueueManager.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
277
```php <?php declare(strict_types=1); namespace App\MessageQueue; use Symfony\Component\Messenger\Transport\InMemory\InMemoryTransport; use Symfony\Component\Messenger\Transport\TransportInterface; final class TestQueueManager extends AbstractQueueManager { public function clearQueue(QueueNames $queue): void { // Noop } public function getTransport(QueueNames $queue): TransportInterface { return new InMemoryTransport(); } public function getQueueCount(QueueNames $queue): int { return 0; } } ```
/content/code_sandbox/backend/src/MessageQueue/TestQueueManager.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
123
```php <?php declare(strict_types=1); namespace App\MessageQueue; interface UniqueMessageInterface { public function getIdentifier(): string; public function getTtl(): ?float; } ```
/content/code_sandbox/backend/src/MessageQueue/UniqueMessageInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
40
```php <?php declare(strict_types=1); namespace App\MessageQueue; use Symfony\Component\Messenger\Transport\Sender\SendersLocatorInterface; use Symfony\Component\Messenger\Transport\TransportInterface; interface QueueManagerInterface extends SendersLocatorInterface { public function setWorkerName(string $workerName): void; public function clearAllQueues(): void; public function clearQueue(QueueNames $queue): void; public function getTransport(QueueNames $queue): TransportInterface; /** * @return TransportInterface[] */ public function getTransports(): array; public function getQueueCount(QueueNames $queue): int; } ```
/content/code_sandbox/backend/src/MessageQueue/QueueManagerInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
136
```php <?php /** * Based on Herloct's Slim 3.0 Connector * path_to_url */ declare(strict_types=1); namespace App\Tests; use App\AppFactory; use App\Doctrine\ReloadableEntityManagerInterface; use App\Enums\ApplicationEnvironment; use App\Environment; use Codeception\Lib\Framework; use Codeception\Lib\Interfaces\DoctrineProvider; use Codeception\Lib\ModuleContainer; use Codeception\TestInterface; use Doctrine\ORM\EntityManagerInterface; use Psr\Container\ContainerInterface; use Slim\App; /** * @phpstan-import-type AppWithContainer from AppFactory * phpcs:disable PSR2.Methods.MethodDeclaration.Underscore */ class Module extends Framework implements DoctrineProvider { public ContainerInterface $container; /** * @var AppWithContainer */ public App $app; public ReloadableEntityManagerInterface $em; public function __construct(ModuleContainer $moduleContainer, ?array $config = null) { parent::__construct($moduleContainer, $config); $this->requiredFields = ['container']; } public function _initialize(): void { $this->app = AppFactory::createApp( [ Environment::APP_ENV => ApplicationEnvironment::Testing->value, ] ); $container = $this->app->getContainer(); $this->container = $container; /** @var ReloadableEntityManagerInterface $em */ $em = $this->container->get(ReloadableEntityManagerInterface::class); $this->em = $em; parent::_initialize(); } public function _before(TestInterface $test): void { $this->client = new Connector(); $this->client->setApp($this->app); parent::_before($test); } public function _after(TestInterface $test): void { $_GET = []; $_POST = []; $_COOKIE = []; parent::_after($test); } public function _getEntityManager(): EntityManagerInterface { return $this->em; } } ```
/content/code_sandbox/backend/src/Tests/Module.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
434
```php <?php declare(strict_types=1); namespace App\Tests; use App\AppFactory; use App\Http\HttpFactory; use Codeception\Lib\Connector\Shared\PhpSuperGlobalsConverter; use Slim\App; use Symfony\Component\BrowserKit\AbstractBrowser; use Symfony\Component\BrowserKit\Request as BrowserKitRequest; use Symfony\Component\BrowserKit\Response as BrowserKitResponse; /** * @phpstan-import-type AppWithContainer from AppFactory */ class Connector extends AbstractBrowser { use PhpSuperGlobalsConverter; /** * @var AppWithContainer */ protected App $app; /** * @param AppWithContainer $app */ public function setApp(App $app): void { $this->app = $app; } /** * Makes a request. * * @param BrowserKitRequest $request An origin request instance * * @return BrowserKitResponse An origin response instance */ public function doRequest($request): BrowserKitResponse { $_COOKIE = $request->getCookies(); $_SERVER = $request->getServer(); $_FILES = $this->remapFiles($request->getFiles()); // Temporary fix, see path_to_url $_SERVER['PHP_SELF'] = __FILE__; $uri = str_replace('path_to_url '', $request->getUri()); $_REQUEST = $this->remapRequestParameters($request->getParameters()); if (strtoupper($request->getMethod()) === 'GET') { $_GET = $_REQUEST; $_POST = []; } else { $_GET = []; $_POST = $_REQUEST; } $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; $_SERVER['REQUEST_METHOD'] = strtoupper($request->getMethod()); $_SERVER['REQUEST_URI'] = $uri; $request = (new HttpFactory())->createServerRequestFromGlobals(); $slimResponse = $this->app->handle($request); return new BrowserKitResponse( (string)$slimResponse->getBody(), $slimResponse->getStatusCode(), $slimResponse->getHeaders() ); } } ```
/content/code_sandbox/backend/src/Tests/Connector.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
462
```php <?php declare(strict_types=1); namespace App\Traits; trait LoadFromParentObject { /** * @param object|array<mixed> $obj */ public function fromParentObject(object|array $obj): void { if (is_object($obj)) { foreach (get_object_vars($obj) as $key => $value) { if (property_exists($this, $key)) { $this->$key = $value; } } } elseif (is_array($obj)) { foreach ($obj as $key => $value) { if (property_exists($this, $key)) { $this->$key = $value; } } } } } ```
/content/code_sandbox/backend/src/Traits/LoadFromParentObject.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
155
```php <?php declare(strict_types=1); namespace App\Traits; use App\Http\ServerRequest; trait RequestAwareTrait { protected ?ServerRequest $request = null; public function setRequest(?ServerRequest $request): void { $this->request = $request; } public function withRequest(?ServerRequest $request): self { $newInstance = clone $this; $newInstance->setRequest($request); return $newInstance; } } ```
/content/code_sandbox/backend/src/Traits/RequestAwareTrait.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
103
```php <?php declare(strict_types=1); namespace App\Console; use App\Container\LoggerAwareTrait; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\Console\Event\ConsoleErrorEvent; use Symfony\Component\Console\Event\ConsoleTerminateEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; final class ErrorHandler implements EventSubscriberInterface { use LoggerAwareTrait; /** * @return mixed[] */ public static function getSubscribedEvents(): array { return [ ConsoleEvents::TERMINATE => [ 'onTerminate', ], ConsoleEvents::ERROR => [ 'onError', ], ]; } public function onTerminate(ConsoleTerminateEvent $event): void { $command = $event->getCommand(); $commandName = (null !== $command) ? $command->getName() : 'Unknown'; $exitCode = $event->getExitCode(); if (0 === $exitCode) { return; } $message = sprintf( 'Console command `%s` exited with error code %d.', $commandName, $exitCode ); $this->logger->warning($message); } public function onError(ConsoleErrorEvent $event): void { $command = $event->getCommand(); $commandName = (null !== $command) ? $command->getName() : 'Unknown'; $exception = $event->getError(); $message = sprintf( '%s: %s (uncaught exception) at %s line %s while running console command `%s`', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine(), $commandName ); $this->logger->error($message, ['exception' => $exception]); } } ```
/content/code_sandbox/backend/src/Console/ErrorHandler.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
385
```php <?php declare(strict_types=1); namespace App\Console; use RuntimeException; use Symfony\Component\Console\Application as SymfonyApplication; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\StreamOutput; final class Application extends SymfonyApplication { /** * Run a one-off command from elsewhere in the application, and pass through the results. * * @param string $command * @param array $args * @param string $outputFile * * @return mixed[] [int $return_code, string $return_output] */ public function runCommandWithArgs(string $command, array $args = [], string $outputFile = 'php://temp'): array { $input = new ArrayInput(array_merge(['command' => $command], $args)); $input->setInteractive(false); $tempStream = fopen($outputFile, 'wb+'); if (false === $tempStream) { throw new RuntimeException(sprintf('Could not open output file: "%s"', $outputFile)); } $output = new StreamOutput($tempStream); $resultCode = $this->find($command)->run($input, $output); rewind($tempStream); $resultOutput = stream_get_contents($tempStream); fclose($tempStream); $resultOutput = trim((string)$resultOutput); return [ $resultCode, $resultOutput, ]; } } ```
/content/code_sandbox/backend/src/Console/Application.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
305
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Container\SettingsAwareTrait; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:cache:clear', description: 'Clear all application caches.', aliases: ['cache:clear'] )] final class ClearCacheCommand extends CommandAbstract { use SettingsAwareTrait; public function __construct( private readonly AdapterInterface $cache ) { parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); // Flush all Redis entries. $this->cache->clear(); // Clear cached system settings. $settings = $this->readSettings(); $settings->updateUpdateLastRun(); $settings->setUpdateResults(null); if ('127.0.0.1' !== $settings->getExternalIp()) { $settings->setExternalIp(null); } $this->writeSettings($settings); $io->success('Local cache flushed.'); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/ClearCacheCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
285
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Entity\Repository\StationRepository; use App\Entity\Station; use App\Nginx\Nginx; use App\Radio\Configuration; use App\Utilities\Types; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Throwable; #[AsCommand( name: 'azuracast:radio:restart', description: 'Restart all radio stations, or a single one if specified.', )] final class RestartRadioCommand extends CommandAbstract { public function __construct( private readonly StationRepository $stationRepo, private readonly Configuration $configuration, private readonly Nginx $nginx, ) { parent::__construct(); } protected function configure(): void { $this->addArgument('station-name', InputArgument::OPTIONAL) ->addOption( 'no-supervisor-restart', null, InputOption::VALUE_NONE, 'Do not reload Supervisord immediately with changes.' ); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $stationName = Types::stringOrNull($input->getArgument('station-name')); $noSupervisorRestart = Types::bool($input->getOption('no-supervisor-restart')); if (!empty($stationName)) { $station = $this->stationRepo->findByIdentifier($stationName); if (!$station instanceof Station) { $io->error('Station not found.'); return 1; } $stations = [$station]; } else { $io->section('Restarting all radio stations...'); $stations = $this->stationRepo->fetchAll(); } $io->progressStart(count($stations)); foreach ($stations as $station) { try { $this->configuration->writeConfiguration( station: $station, reloadSupervisor: !$noSupervisorRestart, forceRestart: true ); $this->nginx->writeConfiguration( station: $station, reloadIfChanged: false ); } catch (Throwable $e) { $io->warning([ $station . ': ' . $e->getMessage(), ]); } $io->progressAdvance(); } if (!$noSupervisorRestart) { $this->nginx->reload(); } $io->progressFinish(); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/RestartRadioCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
571
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Container\ContainerAwareTrait; use App\Container\EnvironmentAwareTrait; use App\Entity\Attributes\StableMigration; use App\Utilities\Types; use Exception; use FilesystemIterator; use InvalidArgumentException; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use ReflectionClass; use SplFileInfo; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Filesystem\Filesystem; use Throwable; #[AsCommand( name: 'azuracast:setup:rollback', description: 'Roll back the database to the state associated with a certain stable release.', )] final class RollbackDbCommand extends AbstractDatabaseCommand { use ContainerAwareTrait; use EnvironmentAwareTrait; protected function configure(): void { $this->addArgument('version', InputArgument::REQUIRED); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title(__('Roll Back Database')); // Pull migration corresponding to the stable version specified. try { $version = Types::string($input->getArgument('version')); $migrationVersion = $this->findMigration($version); } catch (Throwable $e) { $io->error($e->getMessage()); return 1; } $this->runCommand( $output, 'migrations:sync-metadata-storage' ); // Attempt DB migration. $io->section(__('Running database migrations...')); // Back up current DB state. try { $dbDumpPath = $this->saveOrRestoreDatabase($io); } catch (Exception $e) { $io->error($e->getMessage()); return 1; } try { $io->info($migrationVersion); $this->runCommand( $output, 'migrations:migrate', [ '--allow-no-migration' => true, 'version' => $migrationVersion, ] ); } catch (Exception $e) { // Rollback to the DB dump from earlier. $io->error( sprintf( __('Database migration failed: %s'), $e->getMessage() ) ); return $this->tryEmergencyRestore($io, $dbDumpPath); } finally { (new Filesystem())->remove($dbDumpPath); } $io->newLine(); $io->success( sprintf( __('Database rolled back to stable release version "%s".'), $version ) ); return 0; } protected function findMigration(string $version): string { $version = trim($version); if (empty($version)) { throw new InvalidArgumentException('No version specified.'); } $versionParts = explode('.', $version); if (3 !== count($versionParts)) { throw new InvalidArgumentException( 'Invalid version specified. Version must be in the form of x.x.x, i.e. 0.19.0.' ); } $migrationsDir = $this->environment->getBackendDirectory() . '/src/Entity/Migration'; $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($migrationsDir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY ); $migrationFiles = []; /** @var SplFileInfo $file */ foreach ($iterator as $file) { // Skip dotfiles $fileName = $file->getBasename('.php'); if ($fileName == $file->getBasename()) { continue; } $className = 'App\\Entity\\Migration\\' . $fileName; $migrationFiles[$fileName] = $className; } $migrationFiles = array_reverse($migrationFiles); /** @var class-string $migrationClassName */ foreach ($migrationFiles as $migrationClassName) { $reflClass = new ReflectionClass($migrationClassName); $reflAttrs = $reflClass->getAttributes(StableMigration::class); foreach ($reflAttrs as $reflAttrInfo) { /** @var StableMigration $reflAttr */ $reflAttr = $reflAttrInfo->newInstance(); if ($version === $reflAttr->version) { return $migrationClassName; } } } throw new InvalidArgumentException( 'No migration found for the specified version. Make sure to specify a version after 0.17.0.' ); } } ```
/content/code_sandbox/backend/src/Console/Command/RollbackDbCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,012
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Container\EnvironmentAwareTrait; use App\Container\SettingsAwareTrait; use App\Entity\Repository\StorageLocationRepository; use App\Service\AzuraCastCentral; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:setup', description: 'Run all general AzuraCast setup steps.', )] final class SetupCommand extends CommandAbstract { use EnvironmentAwareTrait; use SettingsAwareTrait; public function __construct( private readonly AzuraCastCentral $acCentral, private readonly StorageLocationRepository $storageLocationRepo ) { parent::__construct(); } protected function configure(): void { $this->addOption('update', null, InputOption::VALUE_NONE) ->addOption('load-fixtures', null, InputOption::VALUE_NONE) ->addOption('release', null, InputOption::VALUE_NONE) ->addOption('init', null, InputOption::VALUE_NONE); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $update = (bool)$input->getOption('update'); $loadFixtures = (bool)$input->getOption('load-fixtures'); $isInit = (bool)$input->getOption('init'); if ($isInit) { $update = true; $loadFixtures = false; } if (!$update && !$this->environment->isProduction()) { $loadFixtures = true; } // Header display if ($isInit) { $io->title(__('AzuraCast Initializing...')); } else { $io->title(__('AzuraCast Setup')); $io->writeln( __('Welcome to AzuraCast. Please wait while some key dependencies of AzuraCast are set up...') ); $io->newLine(); } $io->section(__('Running Database Migrations')); $this->runCommand( $output, 'azuracast:setup:migrate' ); $io->newLine(); $io->section(__('Generating Database Proxy Classes')); $this->runCommand($output, 'orm:generate-proxies'); $io->newLine(); $io->section(__('Reload System Data')); $this->runCommand($output, 'cache:clear'); // Ensure default storage locations exist. $this->storageLocationRepo->createDefaultStorageLocations(); $io->newLine(); if ($loadFixtures) { $io->section(__('Installing Data Fixtures')); $this->runCommand($output, 'azuracast:setup:fixtures'); $io->newLine(); } $io->section(__('Refreshing All Stations')); $this->runCommand($output, 'azuracast:station-queues:clear'); $restartArgs = []; if ($this->environment->isDocker()) { $restartArgs['--no-supervisor-restart'] = true; } $this->runCommand( $output, 'azuracast:radio:restart', $restartArgs ); if ($isInit) { return 0; } // Update system setting logging when updates were last run. $settings = $this->readSettings(); $settings->updateUpdateLastRun(); $this->writeSettings($settings); if ($update) { $io->success( [ __('AzuraCast is now updated to the latest version!'), ] ); } else { $publicIp = $this->acCentral->getIp(false); /** @noinspection HttpUrlsUsage */ $io->success( [ __('AzuraCast installation complete!'), sprintf( __('Visit %s to complete setup.'), 'path_to_url . $publicIp ), ] ); } return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/SetupCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
895
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Container\EnvironmentAwareTrait; use App\Container\LoggerAwareTrait; use App\Utilities\Types; use App\Version; use OpenApi\Annotations\OpenApi; use OpenApi\Generator; use OpenApi\Util; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:api:docs', description: 'Trigger regeneration of AzuraCast API documentation.', )] final class GenerateApiDocsCommand extends CommandAbstract { use LoggerAwareTrait; use EnvironmentAwareTrait; protected function configure(): void { $this->addOption( 'api-version', null, InputOption::VALUE_REQUIRED, 'The version to tag, if different from the default.' ); } protected function execute(InputInterface $input, OutputInterface $output): int { $version = Types::stringOrNull($input->getOption('api-version')); $io = new SymfonyStyle($input, $output); $yaml = $this->generate($version)?->toYaml(); $yamlPath = $this->environment->getBaseDirectory() . '/web/static/openapi.yml'; file_put_contents($yamlPath, $yaml); $io->writeln('API documentation updated!'); return 0; } public function generate( string $version = null, string $apiBaseUrl = 'path_to_url ): ?OpenApi { define('AZURACAST_API_URL', $apiBaseUrl); define('AZURACAST_API_NAME', 'AzuraCast Public Demo Server'); define('AZURACAST_VERSION', $version ?? Version::STABLE_VERSION); $finder = Util::finder( [ $this->environment->getBackendDirectory() . '/src/OpenApi.php', $this->environment->getBackendDirectory() . '/src/Entity', $this->environment->getBackendDirectory() . '/src/Controller/Api', ], [ 'bootstrap', 'locale', 'templates', ] ); return Generator::scan($finder, [ 'logger' => $this->logger, ]); } } ```
/content/code_sandbox/backend/src/Console/Command/GenerateApiDocsCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
509
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Entity\Repository\StationQueueRepository; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:station-queues:clear', description: 'Clear all unplayed station queues.' )] final class ClearQueuesCommand extends CommandAbstract { public function __construct( private readonly StationQueueRepository $queueRepo, ) { parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); // Clear all station queues. $this->queueRepo->clearUnplayed(); $io->success('Unplayed station queues cleared.'); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/ClearQueuesCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
199
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Container\EnvironmentAwareTrait; use App\Entity\Attributes\StableMigration; use App\Utilities\Types; use DirectoryIterator; use LogicException; use Nette\PhpGenerator\ClassType; use Nette\PhpGenerator\PhpFile; use Nette\PhpGenerator\PsrPrinter; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Filesystem\Filesystem; #[AsCommand( name: 'azuracast:new-version', description: 'Update the codebase in preparation for a new stable release version.', )] final class NewVersionCommand extends CommandAbstract { use EnvironmentAwareTrait; protected function configure(): void { $this->addArgument('version', InputArgument::REQUIRED, 'The new version string.'); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $version = Types::string($input->getArgument('version')); $io->title(sprintf('Preparing codebase for release of stable version "%s"...', $version)); $io->section('Update Version file and API docs.'); $this->updateVersionFile($io, $version); $this->runCommand( $output, 'azuracast:api:docs', [ '--api-version' => $version, ] ); $io->section('Add attribute to latest DB migration.'); $this->addAttributeToLatestMigration($io, $version); $io->section('Update changelog.'); $this->updateChangelog($io, $version); $io->success( 'New version tagged successfully! Merge this branch with "stable", then push a new lightweight tag onto ' . 'the "stable" branch. Remember to switch back to the "main" branch for development!' ); return 0; } private function updateVersionFile(SymfonyStyle $io, string $version): void { $versionFile = $this->environment->getBackendDirectory() . '/src/Version.php'; $fsUtils = new Filesystem(); $fileObj = PhpFile::fromCode($fsUtils->readFile($versionFile)); $classObj = $this->getFirstClassInFile($fileObj); $classObj->getConstant('STABLE_VERSION')->setValue($version); $fsUtils->dumpFile($versionFile, (new PsrPrinter())->printFile($fileObj)); } private function addAttributeToLatestMigration(SymfonyStyle $io, string $version): void { $migrationPath = $this->getLatestMigration(); $fsUtils = new Filesystem(); $fileObj = PhpFile::fromCode($fsUtils->readFile($migrationPath)); $classObj = $this->getFirstClassInFile($fileObj); $classObj->addAttribute( StableMigration::class, [$version] ); $fsUtils->dumpFile($migrationPath, (new PsrPrinter())->printFile($fileObj)); } private function getFirstClassInFile(PhpFile $fileObj): ClassType { foreach ($fileObj->getClasses() as $class) { if ($class instanceof ClassType) { return $class; } } throw new LogicException('No class detected in file.'); } private function getLatestMigration(): string { $migrationsDir = $this->environment->getBackendDirectory() . '/src/Entity/Migration'; $migrationsByPath = []; foreach (new DirectoryIterator($migrationsDir) as $file) { if ($file->isDot() || !$file->isFile()) { continue; } $pathBase = $file->getBasename('.php'); if (str_starts_with($pathBase, 'Version')) { $pathBase = str_replace('Version', '', $pathBase); $migrationsByPath[$pathBase] = $file->getPathname(); } } krsort($migrationsByPath); $latestMigration = reset($migrationsByPath); if (false === $latestMigration) { throw new LogicException('Cannot find latest migration!'); } return $latestMigration; } private function updateChangelog(SymfonyStyle $io, string $version): void { $changelogPath = $this->environment->getBaseDirectory() . '/CHANGELOG.md'; $fsUtils = new Filesystem(); $changelog = $fsUtils->readFile($changelogPath); $hasNewHeader = false; $newChangelogLines = []; foreach (explode("\n", $changelog) as $changelogLine) { // Insert new version before first subheading. if (!$hasNewHeader && str_starts_with($changelogLine, '##')) { $newChangelogLines[] = '## New Features/Changes'; $newChangelogLines[] = ''; $newChangelogLines[] = '## Code Quality/Technical Changes'; $newChangelogLines[] = ''; $newChangelogLines[] = '## Bug Fixes'; $newChangelogLines[] = ''; $newChangelogLines[] = '---'; $newChangelogLines[] = ''; $newChangelogLines[] = '# AzuraCast ' . $version . ' (' . date('M j, Y') . ')'; $newChangelogLines[] = ''; $hasNewHeader = true; } $newChangelogLines[] = $changelogLine; } $fsUtils->dumpFile($changelogPath, implode("\n", $newChangelogLines)); } } ```
/content/code_sandbox/backend/src/Console/Command/NewVersionCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,273
```php <?php declare(strict_types=1); namespace App\Console\Command; use Exception; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\NullOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Filesystem\Filesystem; #[AsCommand( name: 'azuracast:setup:migrate', description: 'Migrate the database to the latest revision.', )] final class MigrateDbCommand extends AbstractDatabaseCommand { protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title(__('Database Migrations')); $this->runCommand( $output, 'migrations:sync-metadata-storage' ); if ( 0 === $this->runCommand( new NullOutput(), 'migrations:up-to-date' ) ) { $io->success(__('Database is already up to date!')); return 0; } // Back up current DB state. try { $dbDumpPath = $this->saveOrRestoreDatabase($io); } catch (Exception $e) { $io->error($e->getMessage()); return 1; } // Attempt DB migration. $io->section(__('Running database migrations...')); try { $this->runCommand( $output, 'migrations:migrate', [ '--allow-no-migration' => true, ] ); } catch (Exception $e) { // Rollback to the DB dump from earlier. $io->error( sprintf( __('Database migration failed: %s'), $e->getMessage() ) ); return $this->tryEmergencyRestore($io, $dbDumpPath); } finally { (new Filesystem())->remove($dbDumpPath); } $io->newLine(); $io->success( __('Database migration completed!') ); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/MigrateDbCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
451
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Console\Command\Traits\PassThruProcess; use App\Container\EntityManagerAwareTrait; use App\Container\EnvironmentAwareTrait; use App\Entity\StorageLocation; use Exception; use RuntimeException; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Filesystem\Filesystem; abstract class AbstractDatabaseCommand extends CommandAbstract { use PassThruProcess; use EntityManagerAwareTrait; use EnvironmentAwareTrait; protected function getDatabaseSettingsAsCliFlags(): array { $connSettings = $this->environment->getDatabaseSettings(); $commandEnvVars = [ 'DB_DATABASE' => $connSettings['dbname'], 'DB_USERNAME' => $connSettings['user'], 'DB_PASSWORD' => $connSettings['password'], ]; $commandFlags = [ '--user=$DB_USERNAME', '--password=$DB_PASSWORD', ]; if (isset($connSettings['unix_socket'])) { $commandFlags[] = '--socket=$DB_SOCKET'; $commandEnvVars['DB_SOCKET'] = $connSettings['unix_socket']; } else { $commandFlags[] = '--host=$DB_HOST'; $commandFlags[] = '--port=$DB_PORT'; $commandEnvVars['DB_HOST'] = $connSettings['host']; $commandEnvVars['DB_PORT'] = $connSettings['port']; } return [$commandFlags, $commandEnvVars]; } protected function dumpDatabase( OutputInterface $output, string $path ): void { [$commandFlags, $commandEnvVars] = $this->getDatabaseSettingsAsCliFlags(); $commandFlags[] = '--add-drop-table'; $commandFlags[] = '--default-character-set=UTF8MB4'; $commandEnvVars['DB_DEST'] = $path; $this->passThruProcess( $output, 'mariadb-dump ' . implode(' ', $commandFlags) . ' $DB_DATABASE > $DB_DEST', dirname($path), $commandEnvVars ); } protected function restoreDatabaseDump( SymfonyStyle $io, string $path ): void { if (!file_exists($path)) { throw new RuntimeException('Database backup file not found!'); } $conn = $this->em->getConnection(); // Drop all preloaded tables prior to running a DB dump backup. $conn->executeQuery('SET FOREIGN_KEY_CHECKS = 0'); /** @var string $table */ foreach ($conn->fetchFirstColumn('SHOW TABLES') as $table) { $conn->executeQuery('DROP TABLE IF EXISTS ' . $conn->quoteIdentifier($table)); } $conn->executeQuery('SET FOREIGN_KEY_CHECKS = 1'); [$commandFlags, $commandEnvVars] = $this->getDatabaseSettingsAsCliFlags(); $commandEnvVars['DB_DUMP'] = $path; $this->passThruProcess( $io, 'mariadb ' . implode(' ', $commandFlags) . ' $DB_DATABASE < $DB_DUMP', dirname($path), $commandEnvVars ); } protected function saveOrRestoreDatabase( SymfonyStyle $io, ): string { $io->section(__('Backing up initial database state...')); $tempDir = StorageLocation::DEFAULT_BACKUPS_PATH; $dbDumpPath = $tempDir . '/pre_migration_db.sql'; $fs = new Filesystem(); if ($fs->exists($dbDumpPath)) { $io->info([ __('We detected a database restore file from a previous (possibly failed) migration.'), __('Attempting to restore that now...'), ]); $this->restoreDatabaseDump($io, $dbDumpPath); } else { $this->dumpDatabase($io, $dbDumpPath); } return $dbDumpPath; } protected function tryEmergencyRestore( SymfonyStyle $io, string $dbDumpPath ): int { $io->section(__('Attempting to roll back to previous database state...')); try { $this->restoreDatabaseDump($io, $dbDumpPath); $io->warning([ __('Your database was restored due to a failed migration.'), __('Please report this bug to our developers.'), ]); return 0; } catch (Exception $e) { $io->error( sprintf( __('Restore failed: %s'), $e->getMessage() ) ); return 1; } } } ```
/content/code_sandbox/backend/src/Console/Command/AbstractDatabaseCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
991
```php <?php declare(strict_types=1); namespace App\Console\Command; use RuntimeException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\OutputInterface; abstract class CommandAbstract extends Command { protected function runCommand(OutputInterface $output, string $commandName, array $commandArgs = []): int { $command = $this->getApplication()?->find($commandName); if (null === $command) { throw new RuntimeException(sprintf('Command %s not found.', $commandName)); } $input = new ArrayInput(['command' => $commandName] + $commandArgs); $input->setInteractive(false); return $command->run($input, $output); } } ```
/content/code_sandbox/backend/src/Console/Command/CommandAbstract.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
162
```php <?php declare(strict_types=1); namespace App\Console\Command; use App\Container\ContainerAwareTrait; use App\Container\EntityManagerAwareTrait; use App\Container\EnvironmentAwareTrait; use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\Loader; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use SplFileInfo; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:setup:fixtures', description: 'Install fixtures for demo / local development.', )] final class SetupFixturesCommand extends CommandAbstract { use ContainerAwareTrait; use EntityManagerAwareTrait; use EnvironmentAwareTrait; protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $loader = new Loader(); // Dependency-inject the fixtures and load them. $fixturesDir = $this->environment->getBackendDirectory() . '/src/Entity/Fixture'; $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($fixturesDir), RecursiveIteratorIterator::LEAVES_ONLY ); /** @var SplFileInfo $file */ foreach ($iterator as $file) { // Skip dotfiles if (($fileName = $file->getBasename('.php')) == $file->getBasename()) { continue; } /** @var class-string $className */ $className = 'App\\Entity\\Fixture\\' . $fileName; /** @var FixtureInterface $fixture */ $fixture = $this->di->get($className); $loader->addFixture($fixture); } $purger = new ORMPurger($this->em); $executor = new ORMExecutor($this->em, $purger); $executor->execute($loader->getFixtures()); $io->success(__('Fixtures loaded.')); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/SetupFixturesCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
463
```php <?php declare(strict_types=1); namespace App\Console\Command\Debug; use App\Console\Command\CommandAbstract; use Doctrine\DBAL\Connection; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:debug:optimize-tables', description: 'Optimize all tables in the database.', )] final class OptimizeTablesCommand extends CommandAbstract { public function __construct( private readonly Connection $db ) { parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title('Optimizing Database Tables...'); foreach ($this->db->fetchAllAssociative('SHOW TABLES') as $tableRow) { /** @var string $table */ $table = reset($tableRow); $io->listing([$table]); $this->db->executeQuery('OPTIMIZE TABLE ' . $this->db->quoteIdentifier($table)); } $io->success('All tables optimized.'); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Debug/OptimizeTablesCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
269
```php <?php declare(strict_types=1); namespace App\Console\Command\Media; use App\Console\Command\CommandAbstract; use App\Container\EntityManagerAwareTrait; use App\Entity\Repository\StationRepository; use App\Entity\Station; use App\Utilities\Types; use InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; abstract class AbstractBatchMediaCommand extends CommandAbstract { use EntityManagerAwareTrait; public function __construct( private readonly StationRepository $stationRepo, ) { parent::__construct(); } protected function configure(): void { $this->addArgument( 'station-name', InputArgument::OPTIONAL, 'The shortcode for the station (i.e. "my_station_name") to only apply to one station.' ); $this->addArgument( 'path', InputArgument::OPTIONAL, 'Optionally specify a path (of either a file or a directory) to only apply to that item.' ); } protected function getStation(InputInterface $input): ?Station { $stationName = Types::stringOrNull($input->getArgument('station-name'), true); if (null === $stationName) { return null; } $station = $this->stationRepo->findByIdentifier($stationName); if (!$station instanceof Station) { throw new InvalidArgumentException('Station not found.'); } return $station; } protected function getPath(InputInterface $input): ?string { return Types::stringOrNull($input->getArgument('path'), true); } } ```
/content/code_sandbox/backend/src/Console/Command/Media/AbstractBatchMediaCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
338
```php <?php declare(strict_types=1); namespace App\Console\Command\Media; use App\Entity\StationMedia; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:media:reprocess', description: 'Manually reload all media metadata from file.', )] final class ReprocessCommand extends AbstractBatchMediaCommand { protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $station = $this->getStation($input); $path = $this->getPath($input); $io->title('Manually Reprocess Media'); $reprocessMediaQueue = $this->em->createQueryBuilder() ->update(StationMedia::class, 'sm') ->set('sm.mtime', 0); if (null === $station) { $io->section('Reprocessing media for all stations...'); } else { $io->writeln(sprintf('Reprocessing media for station: %s', $station->getName())); $reprocessMediaQueue = $reprocessMediaQueue->andWhere('sm.storage_location = :storageLocation') ->setParameter('storageLocation', $station->getMediaStorageLocation()); } if (null !== $path) { $reprocessMediaQueue = $reprocessMediaQueue->andWhere('sm.path LIKE :path') ->setParameter('path', $path . '%'); } $recordsAffected = $reprocessMediaQueue->getQuery()->getSingleScalarResult(); $io->writeln(sprintf('Marked %d record(s) for reprocessing.', $recordsAffected)); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Media/ReprocessCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
387
```php <?php declare(strict_types=1); namespace App\Console\Command\Media; use App\Entity\StationMedia; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:media:clear-extra', description: 'Clear all extra metadata from the specified media.', )] final class ClearExtraMetadataCommand extends AbstractBatchMediaCommand { protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $station = $this->getStation($input); $path = $this->getPath($input); $io->title('Clear Extra Metadata'); $reprocessMediaQueue = $this->em->createQueryBuilder() ->update(StationMedia::class, 'sm') ->set('sm.mtime', 0) ->set('sm.extra_metadata', 'null'); if (null === $station) { $io->section('Clearing extra metadata for all stations...'); } else { $io->writeln(sprintf('Clearing extra metadata for station: %s', $station->getName())); $reprocessMediaQueue = $reprocessMediaQueue->andWhere('sm.storage_location = :storageLocation') ->setParameter('storageLocation', $station->getMediaStorageLocation()); } if (null !== $path) { $reprocessMediaQueue = $reprocessMediaQueue->andWhere('sm.path LIKE :path') ->setParameter('path', $path . '%'); } $recordsAffected = $reprocessMediaQueue->getQuery()->getSingleScalarResult(); $io->writeln(sprintf('Cleared extra metadata for %d record(s).', $recordsAffected)); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Media/ClearExtraMetadataCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
399
```php <?php declare(strict_types=1); namespace App\Console\Command\Acme; use App\Console\Command\CommandAbstract; use App\Service\Acme; use Exception; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:acme:get-certificate', description: 'Get a new or updated ACME (LetsEncrypt) certificate.', aliases: ['acme:cert'] )] final class GetCertificateCommand extends CommandAbstract { public function __construct( private readonly Acme $acme ) { parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); try { $this->acme->getCertificate(); } catch (Exception $e) { $io->error($e->getMessage()); return 1; } return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Acme/GetCertificateCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
232
```php <?php declare(strict_types=1); namespace App\Console\Command\MessageQueue; use App\CallableEventDispatcherInterface; use App\Console\Command\Sync\AbstractSyncCommand; use App\Container\EnvironmentAwareTrait; use App\Container\LoggerAwareTrait; use App\Doctrine\Messenger\ClearEntityManagerSubscriber; use App\MessageQueue\LogWorkerExceptionSubscriber; use App\MessageQueue\QueueManagerInterface; use App\MessageQueue\ResetArrayCacheSubscriber; use App\Utilities\Types; use Psr\Log\LogLevel; use Psr\Log\NullLogger; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Messenger\EventListener\StopWorkerOnFailureLimitListener; use Symfony\Component\Messenger\EventListener\StopWorkerOnTimeLimitListener; use Symfony\Component\Messenger\MessageBus; use Symfony\Component\Messenger\Worker; use Throwable; #[AsCommand( name: 'azuracast:queue:process', description: 'Process the message queue.', aliases: ['queue:process'] )] final class ProcessCommand extends AbstractSyncCommand { use LoggerAwareTrait; use EnvironmentAwareTrait; public function __construct( private readonly MessageBus $messageBus, private readonly CallableEventDispatcherInterface $eventDispatcher, private readonly QueueManagerInterface $queueManager ) { parent::__construct(); } protected function configure(): void { $this->addArgument('runtime', InputArgument::OPTIONAL) ->addOption('worker-name', null, InputOption::VALUE_OPTIONAL); } protected function execute(InputInterface $input, OutputInterface $output): int { $this->logToExtraFile('app_worker.log'); $runtime = Types::int($input->getArgument('runtime')); $workerName = Types::stringOrNull($input->getOption('worker-name'), true); $this->logger->notice( 'Starting new Message Queue worker process.', [ 'runtime' => $runtime, 'workerName' => $workerName, ] ); if (null !== $workerName) { $this->queueManager->setWorkerName($workerName); } $receivers = $this->queueManager->getTransports(); $this->eventDispatcher->addServiceSubscriber(ClearEntityManagerSubscriber::class); $this->eventDispatcher->addServiceSubscriber(LogWorkerExceptionSubscriber::class); $this->eventDispatcher->addServiceSubscriber(ResetArrayCacheSubscriber::class); if ($runtime <= 0) { $runtime = $this->environment->isProduction() ? 300 : 30; } $busLogger = (LogLevel::DEBUG === $this->environment->getLogLevel()) ? $this->logger : new NullLogger(); $this->eventDispatcher->addSubscriber( new StopWorkerOnTimeLimitListener($runtime, $busLogger) ); $this->eventDispatcher->addSubscriber( new StopWorkerOnFailureLimitListener(5, $busLogger) ); try { $worker = new Worker($receivers, $this->messageBus, $this->eventDispatcher, $busLogger); $worker->run(); } catch (Throwable $e) { $this->logger->error( sprintf('Message queue error: %s', $e->getMessage()), [ 'workerName' => $workerName, 'exception' => $e, ] ); return 1; } return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/MessageQueue/ProcessCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
768
```php <?php declare(strict_types=1); namespace App\Console\Command\MessageQueue; use App\Console\Command\CommandAbstract; use App\MessageQueue\QueueManagerInterface; use App\MessageQueue\QueueNames; use App\Utilities\Types; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:queue:clear', description: 'Clear the contents of the message queue.', aliases: ['queue:clear'] )] final class ClearCommand extends CommandAbstract { public function __construct( private readonly QueueManagerInterface $queueManager, ) { parent::__construct(); } protected function configure(): void { $this->addArgument('queue', InputArgument::OPTIONAL); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $queueName = Types::stringOrNull($input->getArgument('queue'), true); if (null !== $queueName) { $queue = QueueNames::tryFrom($queueName); if (null !== $queue) { $this->queueManager->clearQueue($queue); $io->success(sprintf('Message queue "%s" cleared.', $queue->value)); } else { $io->error(sprintf('Message queue "%s" does not exist.', $queueName)); return 1; } } else { $this->queueManager->clearAllQueues(); $io->success('All message queues cleared.'); } return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/MessageQueue/ClearCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
370
```php <?php declare(strict_types=1); namespace App\Console\Command\Traits; use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Process\Process; trait PassThruProcess { protected function passThruProcess( OutputInterface $output, string|array $cmd, ?string $cwd = null, array $env = [], int $timeout = 14400 ): Process { set_time_limit($timeout); if (is_array($cmd)) { $process = new Process($cmd, $cwd); } else { $process = Process::fromShellCommandline($cmd, $cwd); } $process->setTimeout($timeout - 60); $process->setIdleTimeout(null); $stderr = match (true) { $output instanceof SymfonyStyle => $output->getErrorStyle(), $output instanceof ConsoleOutputInterface => $output->getErrorOutput(), default => $output }; $process->mustRun(function ($type, $data) use ($process, $output, $stderr): void { if ($process::ERR === $type) { $stderr->write($data); } else { $output->write($data); } }, $env); return $process; } } ```
/content/code_sandbox/backend/src/Console/Command/Traits/PassThruProcess.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
293
```php <?php declare(strict_types=1); namespace App\Console\Command\Backup; use App\Console\Command\AbstractDatabaseCommand; use App\Entity\Enums\StorageLocationTypes; use App\Entity\Repository\StorageLocationRepository; use App\Entity\Station; use App\Entity\StorageLocation; use App\Utilities\Types; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Path; use Throwable; use const PATHINFO_EXTENSION; #[AsCommand( name: 'azuracast:backup', description: 'Back up the AzuraCast database and statistics (and optionally media).', )] final class BackupCommand extends AbstractDatabaseCommand { public function __construct( private readonly StorageLocationRepository $storageLocationRepo ) { parent::__construct(); } protected function configure(): void { $this->addArgument('path', InputArgument::REQUIRED) ->addOption('storage-location-id', null, InputOption::VALUE_OPTIONAL) ->addOption('exclude-media', null, InputOption::VALUE_NONE); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $fsUtils = new Filesystem(); $path = Types::stringOrNull($input->getArgument('path'), true) ?? 'manual_backup_' . gmdate('Ymd_Hi') . '.zip'; $excludeMedia = Types::bool($input->getOption('exclude-media')); $storageLocationId = Types::intOrNull($input->getOption('storage-location-id')); $startTime = microtime(true); $fileExt = strtolower(pathinfo($path, PATHINFO_EXTENSION)); if (Path::isAbsolute($path)) { $tmpPath = $path; $storageLocation = null; } else { $tmpPath = $fsUtils->tempnam( sys_get_temp_dir(), 'backup_', '.' . $fileExt ); // Zip command cannot handle an existing file (even an empty one) @unlink($tmpPath); if (null === $storageLocationId) { $io->error('You must specify a storage location when providing a relative path.'); return 1; } $storageLocation = $this->storageLocationRepo->findByType( StorageLocationTypes::Backup, $storageLocationId ); if (!($storageLocation instanceof StorageLocation)) { $io->error('Invalid storage location specified.'); return 1; } if ($storageLocation->isStorageFull()) { $io->error('Storage location is full.'); return 1; } } $includeMedia = !$excludeMedia; $filesToBackup = []; $io->title(__('AzuraCast Backup')); $io->writeln(__('Please wait while a backup is generated...')); // Create temp directories $io->section(__('Creating temporary directories...')); $tmpDirMariadb = '/tmp/azuracast_backup_mariadb'; try { $fsUtils->mkdir($tmpDirMariadb); } catch (Throwable $e) { $io->error($e->getMessage()); return 1; } $io->newLine(); // Back up MariaDB $io->section(__('Backing up MariaDB...')); $pathDbDump = $tmpDirMariadb . '/db.sql'; $this->dumpDatabase($io, $pathDbDump); $filesToBackup[] = $pathDbDump; $io->newLine(); // Backup uploaded custom assets $filesToBackup[] = $this->environment->getUploadsDirectory(); // Include station media if specified. if ($includeMedia) { $stations = $this->em->createQuery( <<<'DQL' SELECT s FROM App\Entity\Station s DQL )->execute(); foreach ($stations as $station) { /** @var Station $station */ $mediaAdapter = $station->getMediaStorageLocation(); if ($mediaAdapter->isLocal()) { $filesToBackup[] = $mediaAdapter->getPath(); } $podcastsAdapter = $station->getPodcastsStorageLocation(); if ($podcastsAdapter->isLocal()) { $filesToBackup[] = $podcastsAdapter->getPath(); } $recordingsAdapter = $station->getRecordingsStorageLocation(); if ($recordingsAdapter->isLocal()) { $filesToBackup[] = $recordingsAdapter->getPath(); } } } // Compress backup files. $io->section(__('Creating backup archive...')); // Strip leading slashes from backup paths. $filesToBackup = array_map( static function (string $val) { if (str_starts_with($val, '/')) { return substr($val, 1); } return $val; }, $filesToBackup ); switch ($fileExt) { case 'tzst': $this->passThruProcess( $output, array_merge( [ 'tar', '-I', 'zstd', '-cvf', $tmpPath, ], $filesToBackup ), '/' ); break; case 'gz': case 'tgz': $this->passThruProcess( $output, array_merge( [ 'tar', 'zcvf', $tmpPath, ], $filesToBackup ), '/' ); break; case 'zip': default: $dontCompress = ['.tar.gz', '.zip', '.jpg', '.mp3', '.ogg', '.flac', '.aac', '.wav']; $this->passThruProcess( $output, array_merge( [ 'zip', '-r', '-n', implode(':', $dontCompress), $tmpPath, ], $filesToBackup ), '/' ); break; } if (null !== $storageLocation) { $fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $fs->uploadAndDeleteOriginal($tmpPath, $path); } $io->newLine(); // Cleanup $io->section(__('Cleaning up temporary files...')); $fsUtils->remove($tmpDirMariadb); $io->newLine(); $endTime = microtime(true); $timeDiff = $endTime - $startTime; $io->success( [ sprintf( __('Backup complete in %.2f seconds.'), $timeDiff ), ] ); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Backup/BackupCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,493
```php <?php declare(strict_types=1); namespace App\Console\Command\Backup; use App\Console\Command\AbstractDatabaseCommand; use App\Entity\StorageLocation; use App\Utilities\Types; use Exception; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Filesystem\Filesystem; use const PATHINFO_EXTENSION; #[AsCommand( name: 'azuracast:restore', description: 'Restore a backup previously generated by AzuraCast.', )] final class RestoreCommand extends AbstractDatabaseCommand { protected function configure(): void { $this->addArgument('path', InputArgument::OPTIONAL) ->addOption('restore', null, InputOption::VALUE_NONE) ->addOption('release', null, InputOption::VALUE_NONE); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $path = Types::stringOrNull($input->getArgument('path'), true); $startTime = microtime(true); $io->title('AzuraCast Restore'); if (null === $path) { $filesRaw = glob(StorageLocation::DEFAULT_BACKUPS_PATH . '/*', GLOB_NOSORT) ?: []; usort( $filesRaw, static fn($a, $b) => filemtime($b) <=> filemtime($a) ); if (0 === count($filesRaw)) { $io->getErrorStyle() ->error('Backups directory has no available files. You must explicitly specify a backup file.'); return 1; } $files = []; $i = 1; foreach ($filesRaw as $filePath) { $files[$i] = basename($filePath); if (10 === $i) { break; } $i++; } $path = Types::string($io->choice('Select backup file to restore:', $files, 1)); } if ('/' !== $path[0]) { $path = StorageLocation::DEFAULT_BACKUPS_PATH . '/' . $path; } if (!file_exists($path)) { $io->getErrorStyle()->error( sprintf( __('Backup path %s not found!'), $path ) ); return 1; } $io->writeln('Please wait while the backup is restored...'); // Extract tar.gz archive $io->section('Extracting backup file...'); $fileExt = strtolower(pathinfo($path, PATHINFO_EXTENSION)); switch ($fileExt) { case 'tzst': $this->passThruProcess( $output, [ 'tar', '-I', 'unzstd', '-xvf', $path, ], '/' ); break; case 'gz': case 'tgz': $this->passThruProcess( $output, [ 'tar', 'zxvf', $path, ], '/' ); break; case 'zip': default: $this->passThruProcess( $output, [ 'unzip', '-o', $path, ], '/' ); break; } $io->newLine(); // Handle DB dump $io->section('Importing database...'); $tmpDirMariadb = '/tmp/azuracast_backup_mariadb'; try { $pathDbDump = $tmpDirMariadb . '/db.sql'; $this->restoreDatabaseDump($io, $pathDbDump); } catch (Exception $e) { $io->getErrorStyle()->error($e->getMessage()); return 1; } (new Filesystem())->remove($tmpDirMariadb); $io->newLine(); // Update from current version to latest. $io->section('Running standard updates...'); $this->runCommand($output, 'azuracast:setup', ['--update' => true]); $endTime = microtime(true); $timeDiff = $endTime - $startTime; $io->success( [ 'Restore complete in ' . round($timeDiff, 3) . ' seconds.', ] ); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Backup/RestoreCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
970
```php <?php declare(strict_types=1); namespace App\Console\Command\Users; use App\Console\Command\CommandAbstract; use App\Container\EntityManagerAwareTrait; use App\Entity\User; use App\Utilities; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:account:reset-password', description: 'Reset the password of the specified account.', )] final class ResetPasswordCommand extends CommandAbstract { use EntityManagerAwareTrait; protected function configure(): void { $this->addArgument('email', InputArgument::REQUIRED); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $email = Utilities\Types::string($input->getArgument('email')); $io->title('Reset Account Password'); $user = $this->em->getRepository(User::class) ->findOneBy(['email' => $email]); if ($user instanceof User) { $tempPw = Utilities\Strings::generatePassword(15); $user->setNewPassword($tempPw); $user->setTwoFactorSecret(); $this->em->persist($user); $this->em->flush(); $io->text([ 'The account password has been reset. The new temporary password is:', '', ' ' . $tempPw, '', 'Log in using this temporary password and set a new password using the web interface.', '', ]); return 0; } $io->error('Account not found.'); return 1; } } ```
/content/code_sandbox/backend/src/Console/Command/Users/ResetPasswordCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
387
```php <?php declare(strict_types=1); namespace App\Console\Command\Users; use App\Console\Command\CommandAbstract; use App\Container\EntityManagerAwareTrait; use App\Entity\User; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:account:list', description: 'List all accounts in the system.', )] final class ListCommand extends CommandAbstract { use EntityManagerAwareTrait; protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title('AzuraCast User Accounts'); $usersRaw = $this->em->getRepository(User::class) ->findAll(); $headers = [ 'E-mail Address', 'Name', 'Roles', 'Created', ]; $users = []; foreach ($usersRaw as $row) { /** @var User $row */ $roles = []; foreach ($row->getRoles() as $role) { $roles[] = $role->getName(); } $users[] = [ $row->getEmail(), $row->getName(), implode(', ', $roles), gmdate('Y-m-d g:ia', $row->getCreatedAt()), ]; } $io->table($headers, $users); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Users/ListCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
323
```php <?php declare(strict_types=1); namespace App\Console\Command\Users; use App\Console\Command\CommandAbstract; use App\Container\EntityManagerAwareTrait; use App\Entity\Repository\UserLoginTokenRepository; use App\Entity\User; use App\Http\RouterInterface; use App\Utilities\Types; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:account:login-token', description: 'Create a unique login recovery URL for the specified account.', )] final class LoginTokenCommand extends CommandAbstract { use EntityManagerAwareTrait; public function __construct( private readonly UserLoginTokenRepository $loginTokenRepo, private readonly RouterInterface $router, ) { parent::__construct(); } protected function configure(): void { $this->addArgument('email', InputArgument::REQUIRED); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $email = Types::string($input->getArgument('email')); $io->title('Generate Account Login Recovery URL'); $user = $this->em->getRepository(User::class) ->findOneBy(['email' => $email]); if ($user instanceof User) { $loginToken = $this->loginTokenRepo->createToken($user); $url = $this->router->named( routeName: 'account:recover', routeParams: ['token' => $loginToken], absolute: true ); $io->text([ 'The account recovery URL is:', '', ' ' . $url, '', 'Log in using this temporary URL and set a new password using the web interface.', '', ]); return 0; } $io->error('Account not found.'); return 1; } } ```
/content/code_sandbox/backend/src/Console/Command/Users/LoginTokenCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
437
```php <?php declare(strict_types=1); namespace App\Console\Command\Users; use App\Console\Command\CommandAbstract; use App\Container\EntityManagerAwareTrait; use App\Entity\Repository\RolePermissionRepository; use App\Entity\User; use App\Utilities\Types; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:account:set-administrator', description: 'Set the account specified as a global administrator.', )] final class SetAdministratorCommand extends CommandAbstract { use EntityManagerAwareTrait; public function __construct( private readonly RolePermissionRepository $permsRepo, ) { parent::__construct(); } protected function configure(): void { $this->addArgument('email', InputArgument::REQUIRED); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $email = Types::string($input->getArgument('email')); $io->title('Set Administrator'); $user = $this->em->getRepository(User::class) ->findOneBy(['email' => $email]); if ($user instanceof User) { $adminRole = $this->permsRepo->ensureSuperAdministratorRole(); $userRoles = $user->getRoles(); if (!$userRoles->contains($adminRole)) { $userRoles->add($adminRole); } $this->em->persist($user); $this->em->flush(); $io->text( sprintf( __('The account associated with e-mail address "%s" has been set as an administrator'), $user->getEmail() ) ); $io->newLine(); return 0; } $io->error(__('Account not found.')); $io->newLine(); return 1; } } ```
/content/code_sandbox/backend/src/Console/Command/Users/SetAdministratorCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
432
```php <?php declare(strict_types=1); namespace App\Console\Command\Sync; use App\Cache\NowPlayingCache; use App\Container\EntityManagerAwareTrait; use App\Container\SettingsAwareTrait; use App\Lock\LockFactory; use App\Utilities\Types; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:sync:nowplaying', description: 'Task to run the Now Playing worker task.' )] final class NowPlayingCommand extends AbstractSyncRunnerCommand { use EntityManagerAwareTrait; use SettingsAwareTrait; public function __construct( private readonly NowPlayingCache $nowPlayingCache, LockFactory $lockFactory, ) { parent::__construct($lockFactory); } protected function configure(): void { $this->addOption( 'timeout', 't', InputOption::VALUE_OPTIONAL, 'Amount of time (in seconds) to run the worker process.', 600 ); } protected function execute(InputInterface $input, OutputInterface $output): int { $this->logToExtraFile('app_nowplaying.log'); $io = new SymfonyStyle($input, $output); $settings = $this->readSettings(); if ($settings->getSyncDisabled()) { $this->logger->error('Automated synchronization is temporarily disabled.'); return 1; } $timeout = Types::int($input->getOption('timeout')); $this->loop($io, $timeout); return 0; } private function loop(OutputInterface $output, int $timeout): void { $threshold = time() + $timeout; // If max current processes isn't specified, make it 1/3 of all stations, rounded up. $npMaxCurrentProcesses = $this->environment->getNowPlayingMaxConcurrentProcesses(); if (null === $npMaxCurrentProcesses) { $npMaxCurrentProcesses = ceil(count($this->getStationsToRun($threshold)) / 3); } // Gate the Now Playing delay time between a reasonable minimum and maximum. $npDelayTime = max( min( $this->environment->getNowPlayingDelayTime() ?? 10, 60 ), 5 ); while (time() < $threshold || !empty($this->processes)) { // Check existing processes. $this->checkRunningProcesses(); // Only spawn new processes if we're before the timeout threshold and there are not too many processes. $numProcesses = count($this->processes); if ( $numProcesses < $npMaxCurrentProcesses && time() < $threshold - 5 ) { // Ensure a process is running for every active station. $npThreshold = time() - $npDelayTime - rand(0, 5); foreach ($this->getStationsToRun($npThreshold) as $shortName) { if (count($this->processes) >= $npMaxCurrentProcesses) { break; } if (isset($this->processes[$shortName])) { continue; } $this->logger->debug('Starting NP process for station: ' . $shortName); if ($this->start($output, $shortName)) { usleep(100000); } } } $this->em->clear(); gc_collect_cycles(); usleep(1000000); } } private function getStationsToRun( int $threshold ): array { $lookupRaw = $this->nowPlayingCache->getLookup(); $lookup = []; foreach ($lookupRaw as $stationRow) { $lookup[$stationRow['short_name']] = $stationRow['updated_at']; } $allStations = $this->em->createQuery( <<<'DQL' SELECT s.short_name FROM App\Entity\Station s WHERE s.is_enabled = 1 AND s.has_started = 1 DQL )->getSingleColumnResult(); $stationsByUpdated = []; foreach ($allStations as $shortName) { $stationsByUpdated[$shortName] = $lookup[$shortName] ?? 0; } asort($stationsByUpdated, SORT_NUMERIC); return array_keys( array_filter( $stationsByUpdated, fn($timestamp) => $timestamp < $threshold ) ); } private function start( OutputInterface $output, string $shortName ): bool { return $this->lockAndRunConsoleCommand( $output, $shortName, 'nowplaying', [ 'azuracast:sync:nowplaying:station', $shortName, ] ); } } ```
/content/code_sandbox/backend/src/Console/Command/Sync/NowPlayingCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,076
```php <?php declare(strict_types=1); namespace App\Console\Command\Sync; use App\Container\ContainerAwareTrait; use App\Container\LoggerAwareTrait; use App\Sync\Task\AbstractTask; use App\Utilities\Types; use InvalidArgumentException; use Monolog\LogRecord; use Psr\Cache\CacheItemPoolInterface; use ReflectionClass; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:sync:task', description: 'Task to run a specific scheduled task.', )] final class SingleTaskCommand extends AbstractSyncCommand { use ContainerAwareTrait; use LoggerAwareTrait; public function __construct( private readonly CacheItemPoolInterface $cache ) { parent::__construct(); } protected function configure(): void { $this->addArgument('task', InputArgument::REQUIRED); } protected function execute(InputInterface $input, OutputInterface $output): int { $this->logToExtraFile('app_sync.log'); /** @var class-string $task */ $task = Types::string($input->getArgument('task')); try { $this->runTask($task); } catch (InvalidArgumentException $e) { $io = new SymfonyStyle($input, $output); $io->error($e->getMessage()); return 1; } return 0; } /** * @param class-string $task * @param bool $force */ public function runTask( string $task, bool $force = false ): void { if (!$this->di->has($task)) { throw new InvalidArgumentException('Task not found.'); } $taskClass = $this->di->get($task); if (!($taskClass instanceof AbstractTask)) { throw new InvalidArgumentException('Specified class is not a synchronized task.'); } $taskShortName = self::getClassShortName($task); $cacheKey = self::getCacheKey($task); $startTime = microtime(true); $this->logger->pushProcessor( function (LogRecord $record) use ($taskShortName) { $record->extra['task'] = $taskShortName; return $record; } ); $this->logger->info('Starting sync task.'); $taskClass->run($force); $this->logger->info('Sync task completed.', [ 'time' => microtime(true) - $startTime, ]); $this->logger->popProcessor(); $cacheItem = $this->cache->getItem($cacheKey) ->set(time()) ->expiresAfter(86400); $this->cache->save($cacheItem); } /** * @param class-string $taskClass * @return string */ public static function getCacheKey(string $taskClass): string { return urlencode('sync_last_run.' . self::getClassShortName($taskClass)); } /** * @param class-string $taskClass * @return string */ public static function getClassShortName(string $taskClass): string { return (new ReflectionClass($taskClass))->getShortName(); } } ```
/content/code_sandbox/backend/src/Console/Command/Sync/SingleTaskCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
727
```php <?php declare(strict_types=1); namespace App\Console\Command\Sync; use App\Console\Command\CommandAbstract; use App\Container\EnvironmentAwareTrait; use App\Container\LoggerAwareTrait; use Monolog\Handler\RotatingFileHandler; abstract class AbstractSyncCommand extends CommandAbstract { use LoggerAwareTrait; use EnvironmentAwareTrait; protected function logToExtraFile(string $extraFilePath): void { $logExtraFile = new RotatingFileHandler( $this->environment->getTempDirectory() . '/' . $extraFilePath, 5, $this->environment->getLogLevel(), true ); $this->logger->pushHandler($logExtraFile); } } ```
/content/code_sandbox/backend/src/Console/Command/Sync/AbstractSyncCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
152
```php <?php declare(strict_types=1); namespace App\Console\Command\Sync; use App\Container\EnvironmentAwareTrait; use App\Container\LoggerAwareTrait; use App\Lock\LockFactory; use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Lock\Lock; use Symfony\Component\Process\Process; abstract class AbstractSyncRunnerCommand extends AbstractSyncCommand { use LoggerAwareTrait; use EnvironmentAwareTrait; protected array $processes = []; public function __construct( protected LockFactory $lockFactory, ) { parent::__construct(); } protected function checkRunningProcesses(): void { foreach ($this->processes as $processName => $processGroup) { /** @var Lock $lock */ $lock = $processGroup['lock']; /** @var Process $process */ $process = $processGroup['process']; // 10% chance that refresh will be called if (rand(1, 100) <= 10) { $lock->refresh(); } if ($process->isRunning()) { continue; } $this->logger->debug(sprintf( 'Sync process %s ended with status code %d.', $processName, $process->getExitCode() )); $lock->release(); unset($this->processes[$processName]); } } protected function lockAndRunConsoleCommand( OutputInterface $output, string $processKey, string $lockPrefix, array $consoleCommand, int $timeout = 60 ): bool { $lockName = $lockPrefix . '_' . $processKey; $lock = $this->lockFactory->createAndAcquireLock($lockName, $timeout); if (false === $lock) { $this->logger->error( sprintf('Could not obtain lock for task "%s"; skipping it.', $processKey) ); return false; } $process = new Process( array_merge( [ 'php', $this->environment->getBackendDirectory() . '/bin/console', ], $consoleCommand ), $this->environment->getBaseDirectory() ); $process->setTimeout($timeout); $process->setIdleTimeout($timeout); $stderr = match (true) { $output instanceof SymfonyStyle => $output->getErrorStyle(), $output instanceof ConsoleOutputInterface => $output->getErrorOutput(), default => $output }; $process->start(function ($type, $data) use ($output, $stderr): void { if (Process::ERR === $type) { $stderr->write($data); } else { $output->write($data); } }, getenv()); $this->processes[$processKey] = [ 'process' => $process, 'lock' => $lock, ]; return true; } } ```
/content/code_sandbox/backend/src/Console/Command/Sync/AbstractSyncRunnerCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
650
```php <?php declare(strict_types=1); namespace App\Console\Command\Sync; use App\Container\SettingsAwareTrait; use App\Event\GetSyncTasks; use App\Lock\LockFactory; use Carbon\CarbonImmutable; use DateTimeZone; use Psr\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use function usleep; /** * @phpstan-import-type TaskClass from GetSyncTasks */ #[AsCommand( name: 'azuracast:sync:run', description: 'Task to run the minute\'s synchronized tasks.' )] final class RunnerCommand extends AbstractSyncRunnerCommand { use SettingsAwareTrait; public function __construct( private readonly EventDispatcherInterface $dispatcher, LockFactory $lockFactory ) { parent::__construct($lockFactory); } protected function execute(InputInterface $input, OutputInterface $output): int { $this->logToExtraFile('app_sync.log'); $settings = $this->readSettings(); if ($settings->getSyncDisabled()) { $io = new SymfonyStyle($input, $output); $io->error('Automated synchronization is temporarily disabled.'); return 1; } $syncTasksEvent = new GetSyncTasks(); $this->dispatcher->dispatch($syncTasksEvent); $now = CarbonImmutable::now(new DateTimeZone('UTC')); foreach ($syncTasksEvent->getTasks() as $taskClass) { if ($taskClass::isDue($now, $this->environment, $settings)) { $this->start($output, $taskClass); } } $this->manageStartedEvents(); $settings->updateSyncLastRun(); $this->writeSettings($settings); return 0; } private function manageStartedEvents(): void { while ($this->processes) { $this->checkRunningProcesses(); } usleep(250000); } /** * @param OutputInterface $output * @param TaskClass $taskClass */ private function start( OutputInterface $output, string $taskClass, ): void { $taskShortName = SingleTaskCommand::getClassShortName($taskClass); $isLongTask = $taskClass::isLongTask(); $timeout = ($isLongTask) ? $this->environment->getSyncLongExecutionTime() : $this->environment->getSyncShortExecutionTime(); $this->lockAndRunConsoleCommand( $output, $taskShortName, 'sync_task', [ 'azuracast:sync:task', $taskClass, ], $timeout ); } } ```
/content/code_sandbox/backend/src/Console/Command/Sync/RunnerCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
607
```php <?php declare(strict_types=1); namespace App\Console\Command\Sync; use App\Container\LoggerAwareTrait; use App\Entity\Repository\StationRepository; use App\Entity\Station; use App\Sync\NowPlaying\Task\BuildQueueTask; use App\Sync\NowPlaying\Task\NowPlayingTask; use App\Utilities\Types; use Monolog\LogRecord; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Throwable; #[AsCommand( name: 'azuracast:sync:nowplaying:station', description: 'Task to run the Now Playing worker task for a specific station.', )] final class NowPlayingPerStationCommand extends AbstractSyncCommand { use LoggerAwareTrait; public function __construct( private readonly StationRepository $stationRepo, private readonly BuildQueueTask $buildQueueTask, private readonly NowPlayingTask $nowPlayingTask ) { parent::__construct(); } protected function configure(): void { $this->addArgument('station', InputArgument::REQUIRED); } protected function execute(InputInterface $input, OutputInterface $output): int { $this->logToExtraFile('app_nowplaying.log'); $stationName = Types::string($input->getArgument('station')); $station = $this->stationRepo->findByIdentifier($stationName); if (!($station instanceof Station)) { $io = new SymfonyStyle($input, $output); $io->error('Station not found.'); return 1; } $this->logger->pushProcessor( function (LogRecord $record) use ($station) { $record->extra['station'] = [ 'id' => $station->getId(), 'name' => $station->getName(), ]; return $record; } ); $this->logger->info('Starting Now Playing sync task.'); try { $this->buildQueueTask->run($station); } catch (Throwable $e) { $this->logger->error( 'Queue builder error: ' . $e->getMessage(), ['exception' => $e] ); } try { $this->nowPlayingTask->run($station); } catch (Throwable $e) { $this->logger->error( 'Now Playing error: ' . $e->getMessage(), ['exception' => $e] ); } $this->logger->info('Now Playing sync task complete.'); $this->logger->popProcessor(); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Sync/NowPlayingPerStationCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
583
```php <?php declare(strict_types=1); namespace App\Console\Command\Internal; use App\Console\Command\CommandAbstract; use App\Container\EnvironmentAwareTrait; use App\Utilities\Spinner; use App\Utilities\Types; use Doctrine\DBAL\Driver\PDO\MySQL\Driver; use GuzzleHttp\Client; use GuzzleHttp\RequestOptions; use InvalidArgumentException; use Psr\Log\LogLevel; use Redis; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Throwable; #[AsCommand( name: 'azuracast:internal:uptime-wait', description: 'Wait for a service to become available, or exit if it times out.', )] final class UptimeWaitCommand extends CommandAbstract { use EnvironmentAwareTrait; protected function configure(): void { $this->addOption( 'timeout', 't', InputOption::VALUE_OPTIONAL, 'The timeout (in seconds) to wait for the service.', 180 ); $this->addOption( 'interval', 'i', InputOption::VALUE_OPTIONAL, 'The delay (in seconds) between retries.', 1 ); $this->addArgument( 'service', InputArgument::OPTIONAL, 'The service to wait for (redis, db, php-fpm, nginx)', 'db', ); } protected function execute(InputInterface $input, OutputInterface $output): int { $spinner = new Spinner($output); $io = new SymfonyStyle($input, $output); $logLevel = $this->environment->getLogLevel(); $debugMode = (LogLevel::DEBUG === $logLevel); $service = Types::string($input->getArgument('service')); $timeout = Types::int($input->getOption('timeout')); $interval = Types::int($input->getOption('interval')); $title = match ($service) { 'redis' => 'cache service (Redis)', 'db' => 'database (MariaDB)', 'nginx' => 'web server (nginx)', default => throw new InvalidArgumentException('Invalid service name!') }; $io->title(sprintf('Waiting for %s to become available...', $title)); $elapsed = 0; while ($elapsed <= $timeout) { try { $checkReturn = match ($service) { 'redis' => $this->checkRedis(), 'db' => $this->checkDatabase(), 'nginx' => $this->checkNginx() }; if ($checkReturn) { $io->success('Services started up and ready!'); return 0; } } catch (Throwable $e) { if ($debugMode) { $io->writeln($e->getMessage()); } } sleep($interval); $elapsed += $interval; if (!$debugMode) { $spinner->tick('Waiting...'); } } $io->error('Timed out waiting for services to start.'); return 1; } private function checkDatabase(): bool { $dbSettings = $this->environment->getDatabaseSettings(); if (isset($dbSettings['unix_socket'])) { unset($dbSettings['host'], $dbSettings['port']); } $connection = (new Driver())->connect($dbSettings); $connection->exec('SELECT 1'); return true; } private function checkRedis(): bool { // Redis disabled; skipping Redis check... if (!$this->environment->enableRedis()) { return true; } $settings = $this->environment->getRedisSettings(); $redis = new Redis(); if (isset($settings['socket'])) { $redis->connect($settings['socket']); } else { $redis->connect($settings['host'], $settings['port'], 15); } $redis->ping(); return true; } private function checkNginx(): bool { $guzzle = new Client(); $response = $guzzle->get( 'path_to_url [ RequestOptions::ALLOW_REDIRECTS => false, RequestOptions::HTTP_ERRORS => true, ] ); return 200 === $response->getStatusCode(); } } ```
/content/code_sandbox/backend/src/Console/Command/Internal/UptimeWaitCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
954
```php <?php declare(strict_types=1); namespace App\Console\Command\Internal; use App\Console\Command\CommandAbstract; use App\Container\EntityManagerAwareTrait; use App\Entity\Station; use App\Radio\Adapters; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; #[AsCommand( name: 'azuracast:internal:on-ssl-renewal', description: 'Reload broadcast frontends when an SSL certificate changes.', )] final class OnSslRenewal extends CommandAbstract { use EntityManagerAwareTrait; public function __construct( private readonly Adapters $adapters, ) { parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { $stations = $this->em->createQuery( <<<'DQL' SELECT s FROM App\Entity\Station s DQL )->toIterable(); /** @var Station $station */ foreach ($stations as $station) { if ($station->getFrontendType()->supportsReload()) { $frontend = $this->adapters->getFrontendAdapter($station); if (null !== $frontend) { $frontend->write($station); $frontend->reload($station); } } } return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Internal/OnSslRenewal.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
295
```php <?php declare(strict_types=1); namespace App\Console\Command\Internal; use App\Console\Command\CommandAbstract; use App\Service\AzuraCastCentral; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:internal:ip', description: 'Get the external IP address for this instance.', )] final class GetIpCommand extends CommandAbstract { public function __construct( private readonly AzuraCastCentral $acCentral, ) { parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->write($this->acCentral->getIp() ?? 'Unknown'); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Internal/GetIpCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
196
```php <?php declare(strict_types=1); namespace App\Console\Command\Settings; use App\Console\Command\CommandAbstract; use App\Container\SettingsAwareTrait; use App\Utilities; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:settings:list', description: 'List all settings in the AzuraCast settings database.', )] final class ListCommand extends CommandAbstract { use SettingsAwareTrait; protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title(__('AzuraCast Settings')); $headers = [ __('Setting Key'), __('Setting Value'), ]; $rows = []; $settings = $this->readSettings(); foreach ($this->settingsRepo->toArray($settings) as $settingKey => $settingValue) { $value = print_r($settingValue, true); $value = Utilities\Strings::truncateText($value, 600); $rows[] = [$settingKey, $value]; } $io->table($headers, $rows); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Settings/ListCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
279
```php <?php declare(strict_types=1); namespace App\Console\Command\Settings; use App\Console\Command\CommandAbstract; use App\Container\SettingsAwareTrait; use App\Utilities\Types; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:settings:set', description: 'Set the value of a setting in the AzuraCast settings database.', )] final class SetCommand extends CommandAbstract { use SettingsAwareTrait; protected function configure(): void { $this->addArgument('setting-key', InputArgument::REQUIRED) ->addArgument('setting-value', InputArgument::REQUIRED); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $settingKey = Types::string($input->getArgument('setting-key')); $settingValue = Types::string($input->getArgument('setting-value')); $io->title('AzuraCast Settings'); if (strtolower($settingValue) === 'null') { $this->writeSettings([$settingKey => null]); $io->success(sprintf('Setting "%s" removed.', $settingKey)); return 0; } if (str_starts_with($settingValue, '{')) { $settingValue = json_decode($settingValue, true, 512, JSON_THROW_ON_ERROR); } $this->writeSettings([$settingKey => $settingValue]); $io->success(sprintf('Setting "%s" updated.', $settingKey)); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Settings/SetCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
374
```php <?php declare(strict_types=1); namespace App\Console\Command\Locale; use App\Console\Command\CommandAbstract; use App\Container\EnvironmentAwareTrait; use App\Enums\SupportedLocales; use App\Translations\JsonGenerator; use Gettext\Generator\ArrayGenerator; use Gettext\Loader\PoLoader; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:locale:import', description: 'Convert translated locale files into PHP arrays.', aliases: ['locale:import'] )] final class ImportCommand extends CommandAbstract { use EnvironmentAwareTrait; protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title('Import Locales'); $localesBase = $this->environment->getBaseDirectory() . '/translations'; $supportedLocales = SupportedLocales::cases(); $defaultLocale = SupportedLocales::default(); $poLoader = new PoLoader(); $arrayGenerator = new ArrayGenerator(); foreach ($supportedLocales as $supportedLocale) { if ($supportedLocale === $defaultLocale) { continue; } $localeFolder = $localesBase . '/' . $supportedLocale->value; $localeSource = $localeFolder . '/LC_MESSAGES/default.po'; $localeDest = $localeFolder . '/LC_MESSAGES/default.php'; $jsonDest = $localeFolder . '/translations.json'; if (is_file($localeSource)) { $translations = $poLoader->loadFile($localeSource); $arrayGenerator->generateFile($translations, $localeDest); (new JsonGenerator($supportedLocale))->generateFile($translations, $jsonDest); $io->writeln( sprintf( __('Imported locale: %s'), $supportedLocale->value . ' (' . $supportedLocale->getLocalName() . ')' ) ); } } $io->success('Locales imported.'); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Locale/ImportCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
465
```php <?php declare(strict_types=1); namespace App\Console\Command\Locale; use App\Console\Command\CommandAbstract; use App\Console\Command\Traits\PassThruProcess; use App\Container\EnvironmentAwareTrait; use App\Enums\SupportedLocales; use Gettext\Generator\PoGenerator; use Gettext\Loader\PoLoader; use Gettext\Scanner\PhpScanner; use Gettext\Translations; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use RegexIterator; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; #[AsCommand( name: 'azuracast:locale:generate', description: 'Generate the translation locale file.', aliases: ['locale:generate'] )] final class GenerateCommand extends CommandAbstract { use EnvironmentAwareTrait; use PassThruProcess; protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title('Generate Locales'); $exportDir = $this->environment->getBaseDirectory() . '/translations'; $translations = Translations::create('default'); $destFile = $exportDir . '/default.pot'; // Run the JS generator $this->passThruProcess( $output, ['npm', 'run', 'generate-locales'], $this->environment->getBaseDirectory() ); // Import the JS-generated files if they exist $frontendJsFile = $exportDir . '/frontend.pot'; if (is_file($frontendJsFile)) { $translations = (new PoLoader())->loadFile($frontendJsFile, $translations); @unlink($frontendJsFile); } // Find all PHP/PHTML files in the application's code. $translatableFolders = [ dirname(__DIR__, 4) . '/src', dirname(__DIR__, 4) . '/config', dirname(__DIR__, 4) . '/templates', ]; $phpScanner = new PhpScanner($translations); $phpScanner->setDefaultDomain('default'); foreach ($translatableFolders as $folder) { $directory = new RecursiveDirectoryIterator($folder); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\.(phtml|php)$/i', RegexIterator::GET_MATCH); foreach ($regex as $pathMatch) { $path = $pathMatch[0]; $phpScanner->scanFile($path); } } @unlink($destFile); $poGenerator = new PoGenerator(); $poGenerator->generateFile( $translations, $destFile ); // Create locale folders if they don't exist already. $supportedLocales = SupportedLocales::cases(); $defaultLocale = SupportedLocales::default(); foreach ($supportedLocales as $supportedLocale) { if ($supportedLocale === $defaultLocale) { continue; } $localeDir = $exportDir . '/' . $supportedLocale->value . '/LC_MESSAGES'; if (!is_dir($localeDir)) { /** @noinspection MkdirRaceConditionInspection */ mkdir($localeDir, 0777, true); } } $io->success('Locales generated.'); return 0; } } ```
/content/code_sandbox/backend/src/Console/Command/Locale/GenerateCommand.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
736
```php <?php declare(strict_types=1); /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Lock; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerAwareTrait; use Psr\Log\NullLogger; use Symfony\Component\Lock\BlockingStoreInterface; use Symfony\Component\Lock\Exception\LockConflictedException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\PersistingStoreInterface; use const PHP_INT_MAX; /** * Copied from Symfony 5.x as it was deprecated in 6.x with no suitable replacement. * * RetryTillSaveStore is a PersistingStoreInterface implementation which decorate a non blocking * PersistingStoreInterface to provide a blocking storage. * * @author Jrmy Deruss <jeremy@derusse.com> */ final class RetryTillSaveStore implements BlockingStoreInterface, LoggerAwareInterface { use LoggerAwareTrait; /** * @param int $retrySleep Duration in ms between 2 retry * @param int $retryCount Maximum amount of retry */ public function __construct( private readonly PersistingStoreInterface $decorated, private readonly int $retrySleep = 100, private readonly int $retryCount = PHP_INT_MAX ) { $this->logger = new NullLogger(); } /** * {@inheritdoc} */ public function save(Key $key): void { $this->decorated->save($key); } /** * {@inheritdoc} */ public function waitAndSave(Key $key): void { $retry = 0; $sleepRandomness = (int)($this->retrySleep / 10); do { try { $this->decorated->save($key); return; } catch (LockConflictedException) { usleep(($this->retrySleep + random_int(-$sleepRandomness, $sleepRandomness)) * 1000); } } while (++$retry < $this->retryCount); $this->logger?->warning( 'Failed to store the "{resource}" lock. Abort after {retry} retry.', ['resource' => $key, 'retry' => $retry] ); throw new LockConflictedException(); } /** * {@inheritdoc} */ public function putOffExpiration(Key $key, float $ttl): void { $this->decorated->putOffExpiration($key, $ttl); } /** * {@inheritdoc} */ public function delete(Key $key): void { $this->decorated->delete($key); } /** * {@inheritdoc} */ public function exists(Key $key): bool { return $this->decorated->exists($key); } } ```
/content/code_sandbox/backend/src/Lock/RetryTillSaveStore.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
644
```php <?php declare(strict_types=1); namespace App\Lock; use Exception; use Psr\Log\LoggerInterface; use Symfony\Component\Lock\BlockingStoreInterface; use Symfony\Component\Lock\LockFactory as SymfonyLockFactory; use Symfony\Component\Lock\PersistingStoreInterface; use Symfony\Component\Lock\SharedLockInterface; final class LockFactory extends SymfonyLockFactory { public function __construct( PersistingStoreInterface $lockStore, LoggerInterface $logger ) { if (!$lockStore instanceof BlockingStoreInterface) { $lockStore = new RetryTillSaveStore($lockStore, 30, 1000); $lockStore->setLogger($logger); } parent::__construct($lockStore); $this->setLogger($logger); } public function createLock(string $resource, ?float $ttl = 300.0, bool $autoRelease = true): SharedLockInterface { return parent::createLock($this->getPrefixedResourceName($resource), $ttl, $autoRelease); } public function createAndAcquireLock( string $resource, ?float $ttl = 300.0, bool $autoRelease = true, bool $force = false ): SharedLockInterface|false { $lock = $this->createLock($resource, $ttl, $autoRelease); if ($force) { try { $lock->release(); $lock->acquire(true); } catch (Exception) { return false; } } elseif (!$lock->acquire()) { return false; } return $lock; } private function getPrefixedResourceName(string $resource): string { return 'lock_' . $resource; } } ```
/content/code_sandbox/backend/src/Lock/LockFactory.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
379
```php <?php declare(strict_types=1); namespace App\Security; use InvalidArgumentException; use SensitiveParameter; final class SplitToken { public const string SEPARATOR = ':'; public string $identifier; public string $verifier; public function hashVerifier(): string { return hash('sha512', $this->verifier); } public function verify( #[SensitiveParameter] string $hashedVerifier ): bool { return hash_equals($hashedVerifier, $this->hashVerifier()); } public function __toString(): string { return $this->identifier . self::SEPARATOR . $this->verifier; } public static function fromKeyString( #[SensitiveParameter] string $key ): self { [$identifier, $verifier] = explode(self::SEPARATOR, $key, 2); if (empty($identifier) || empty($verifier)) { throw new InvalidArgumentException('Token is not in a valid format.'); } $token = new self(); $token->identifier = $identifier; $token->verifier = $verifier; return $token; } public static function isValidKeyString( #[SensitiveParameter] string $key ): bool { return str_contains($key, self::SEPARATOR); } public static function generate(): self { $randomStr = hash('sha256', random_bytes(32)); $token = new self(); $token->identifier = substr($randomStr, 0, 16); $token->verifier = substr($randomStr, 16, 32); return $token; } } ```
/content/code_sandbox/backend/src/Security/SplitToken.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
355
```php <?php declare(strict_types=1); namespace App\Security; use stdClass; final class WebAuthnPasskey { public function __construct( protected readonly string $id, protected readonly string $publicKeyPem ) { } public function getId(): string { return $this->id; } public function getHashedId(): string { return self::hashIdentifier($this->id); } public function getPublicKeyPem(): string { return $this->publicKeyPem; } public static function hashIdentifier(string $id): string { return hash('sha256', $id); } public static function fromWebAuthnObject(stdClass $data): self { return new self( $data->credentialId, $data->credentialPublicKey ); } } ```
/content/code_sandbox/backend/src/Security/WebAuthnPasskey.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
189
```php <?php /** * A customized implementation of the Zend/Laminas Config XML reader. */ declare(strict_types=1); namespace App\Xml; use RuntimeException; use XMLReader; use const LIBXML_XINCLUDE; /** * XML config reader. */ final class Reader { /** * Nodes to handle as plain text. */ private static array $textNodes = [ XMLReader::TEXT, XMLReader::CDATA, XMLReader::WHITESPACE, XMLReader::SIGNIFICANT_WHITESPACE, ]; public static function fromString(string $string): array|string|bool { if (empty($string)) { return []; } /** @var XMLReader|false $reader */ $reader = XMLReader::XML($string, null, LIBXML_XINCLUDE); if (false === $reader) { return false; } set_error_handler( static function ($error, $message = '') { throw new RuntimeException( sprintf('Error reading XML string: %s', $message), $error ); }, E_WARNING ); $return = self::processNextElement($reader); restore_error_handler(); $reader->close(); return $return; } private static function processNextElement(XMLReader $reader): string|array { $children = []; $text = ''; while ($reader->read()) { if ($reader->nodeType === XMLReader::ELEMENT) { if ($reader->depth === 0) { return self::processNextElement($reader); } $attributes = self::getAttributes($reader); $name = $reader->name; if ($reader->isEmptyElement) { $child = []; } else { $child = self::processNextElement($reader); } if ($attributes) { if (is_string($child)) { $child = ['_' => $child]; } if (!is_array($child)) { $child = []; } $child = array_merge($child, $attributes); } if (isset($children[$name])) { if (!is_array($children[$name]) || !array_key_exists(0, $children[$name])) { $children[$name] = [$children[$name]]; } $children[$name][] = $child; } else { $children[$name] = $child; } } elseif ($reader->nodeType === XMLReader::END_ELEMENT) { break; } elseif (in_array($reader->nodeType, self::$textNodes)) { $text .= $reader->value; } } return $children ?: $text; } /** * Get all attributes on the current node. * * @return string[] */ private static function getAttributes(XMLReader $reader): array { $attributes = []; if ($reader->hasAttributes) { while ($reader->moveToNextAttribute()) { $attributes['@' . $reader->localName] = $reader->value; } $reader->moveToElement(); } return $attributes; } } ```
/content/code_sandbox/backend/src/Xml/Reader.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
681
```php <?php /** * Customized implementation of the Zend/Laminas Config XML Writer object. */ declare(strict_types=1); namespace App\Xml; use XMLWriter; final class Writer { public static function toString( array $config, string $baseElement = 'xml-config', bool $includeOpeningTag = true ): string { $writer = new XMLWriter(); $writer->openMemory(); $writer->setIndent(true); $writer->setIndentString(str_repeat(' ', 4)); if ($includeOpeningTag) { $writer->startDocument('1.0', 'UTF-8'); } $writer->startElement($baseElement); foreach ($config as $sectionName => $data) { if (!is_array($data)) { if (str_starts_with($sectionName, '@')) { $writer->writeAttribute(substr($sectionName, 1), (string)$data); } else { $writer->writeElement($sectionName, (string)$data); } } else { self::addBranch($sectionName, $data, $writer); } } $writer->endElement(); $writer->endDocument(); return $writer->outputMemory(); } private static function addBranch( mixed $branchName, array $config, XMLWriter $writer ): void { $attributes = []; $innerText = null; foreach ($config as $key => $value) { if (str_starts_with((string)$key, '@')) { $attributes[substr($key, 1)] = (string)$value; unset($config[$key]); } else { if ('_' === $key) { $innerText = (string)$value; unset($config[$key]); } } } if (0 !== count($config) && array_is_list($config)) { foreach ($config as $value) { if (is_array($value)) { self::addBranch($branchName, $value, $writer); } else { $writer->writeElement($branchName, (string)$value); } } } else { $writer->startElement($branchName); foreach ($attributes as $attrKey => $attrVal) { $writer->writeAttribute($attrKey, $attrVal); } if (null !== $innerText) { $writer->text($innerText); } foreach ($config as $key => $value) { /** @var string $key */ if (is_array($value)) { self::addBranch($key, $value, $writer); } else { $writer->writeElement($key, (string)$value); } } $writer->endElement(); } } } ```
/content/code_sandbox/backend/src/Xml/Writer.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
607
```php <?php declare(strict_types=1); namespace App\Session; use App\Environment; use App\Exception\Http\CsrfValidationException; use App\Utilities\Types; use Mezzio\Session\SessionInterface; use Psr\Http\Message\ServerRequestInterface; final class Csrf { public const int CODE_LENGTH = 10; public const string DEFAULT_NAMESPACE = 'general'; public function __construct( private readonly ServerRequestInterface $request, private readonly SessionInterface $session, private readonly Environment $environment ) { } /** * Generate a Cross-Site Request Forgery (CSRF) protection token. * The "namespace" allows distinct CSRF tokens for different site functions, * while not crowding the session namespace with one token for each action. * If not renewed (with another "generate" call to the same namespace), * a CSRF token will last the time specified in $this->_csrf_lifetime. * * @param string $namespace */ public function generate(string $namespace = self::DEFAULT_NAMESPACE): string { $sessionKey = $this->getSessionIdentifier($namespace); if ($this->session->has($sessionKey)) { $csrf = Types::stringOrNull($this->session->get($sessionKey), true); if (null !== $csrf) { return $csrf; } } $key = $this->randomString(); $this->session->set($sessionKey, $key); return $key; } /** * Verify a supplied CSRF token against the tokens stored in the session. * * @param string $key * @param string $namespace * * @throws CsrfValidationException */ public function verify(string $key, string $namespace = self::DEFAULT_NAMESPACE): void { if ($this->environment->isTesting()) { return; } if (empty($key)) { throw new CsrfValidationException( $this->request, 'A CSRF token is required for this request.' ); } if (strlen($key) !== self::CODE_LENGTH) { throw new CsrfValidationException( $this->request, 'Malformed CSRF token supplied.' ); } $sessionIdentifier = $this->getSessionIdentifier($namespace); if (!$this->session->has($sessionIdentifier)) { throw new CsrfValidationException( $this->request, 'No CSRF token supplied for this namespace.' ); } $sessionKey = Types::string($this->session->get($sessionIdentifier)); if (0 !== strcmp($key, $sessionKey)) { throw new CsrfValidationException( $this->request, 'Invalid CSRF token supplied.' ); } } /** * Generates a random string of given $length. * * @return string The randomly generated string. */ private function randomString(): string { $seed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijqlmnopqrtsuvwxyz0123456789'; $max = strlen($seed) - 1; $string = ''; for ($i = 0; $i < self::CODE_LENGTH; ++$i) { $string .= $seed[random_int(0, $max)]; } return $string; } private function getSessionIdentifier(string $namespace): string { return 'csrf_' . $namespace; } } ```
/content/code_sandbox/backend/src/Session/Csrf.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
737
```php <?php declare(strict_types=1); namespace App\Session; enum FlashLevels: string { case Success = 'success'; case Warning = 'warning'; case Error = 'danger'; case Info = 'info'; } ```
/content/code_sandbox/backend/src/Session/FlashLevels.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
50
```php <?php declare(strict_types=1); namespace App\Session; use Mezzio\Session\SessionInterface; /** * Quick message queue service. */ final class Flash { public const string SESSION_KEY = 'flash'; private ?array $messages = null; public function __construct( private readonly SessionInterface $session ) { } public function success( string $message, bool $saveInSession = true ): void { $this->addMessage($message, FlashLevels::Success, $saveInSession); } public function warning( string $message, bool $saveInSession = true ): void { $this->addMessage($message, FlashLevels::Warning, $saveInSession); } public function error( string $message, bool $saveInSession = true ): void { $this->addMessage($message, FlashLevels::Error, $saveInSession); } public function info( string $message, bool $saveInSession = true ): void { $this->addMessage($message, FlashLevels::Info, $saveInSession); } public function addMessage( string $message, FlashLevels $level = FlashLevels::Info, bool $saveInSession = true ): void { $messageRow = [ 'text' => $message, 'color' => $level->value, ]; $this->getMessages(); $this->messages[] = $messageRow; if ($saveInSession) { $messages = (array)$this->session->get(self::SESSION_KEY); $messages[] = $messageRow; $this->session->set(self::SESSION_KEY, $messages); } } /** * Indicate whether messages are currently pending display. */ public function hasMessages(): bool { $messages = $this->getMessages(); return (count($messages) > 0); } /** * Return all messages, removing them from the internal storage in the process. * * @return mixed[] */ public function getMessages(): array { if (null === $this->messages) { if ($this->session->has(self::SESSION_KEY)) { $this->messages = (array)$this->session->get(self::SESSION_KEY); $this->session->unset(self::SESSION_KEY); } else { $this->messages = []; } } return $this->messages; } } ```
/content/code_sandbox/backend/src/Session/Flash.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
548
```php <?php declare(strict_types=1); namespace App\Enums; enum ReleaseChannel: string { case RollingRelease = 'latest'; case Stable = 'stable'; public static function default(): self { return self::RollingRelease; } } ```
/content/code_sandbox/backend/src/Enums/ReleaseChannel.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
58
```php <?php declare(strict_types=1); namespace App\Enums; use App\Entity\Station; use App\Exception\StationUnsupportedException; enum StationFeatures { case CustomLiquidsoapConfig; case Media; case Sftp; case MountPoints; case RemoteRelays; case HlsStreams; case Streamers; case Webhooks; case Podcasts; case OnDemand; case Requests; public function supportedForStation(Station $station): bool { $backendEnabled = $station->getBackendType()->isEnabled(); return match ($this) { self::Media, self::CustomLiquidsoapConfig => $backendEnabled, self::Streamers => $backendEnabled && $station->getEnableStreamers(), self::Sftp => $backendEnabled && $station->getMediaStorageLocation()->isLocal(), self::MountPoints => $station->getFrontendType()->supportsMounts(), self::HlsStreams => $backendEnabled && $station->getEnableHls(), self::Requests => $backendEnabled && $station->getEnableRequests(), self::OnDemand => $station->getEnableOnDemand(), self::Webhooks, self::Podcasts, self::RemoteRelays => true, }; } /** * @param Station $station * @return void * @throws StationUnsupportedException */ public function assertSupportedForStation(Station $station): void { if (!$this->supportedForStation($station)) { throw match ($this) { self::Requests => StationUnsupportedException::requests(), self::OnDemand => StationUnsupportedException::onDemand(), default => StationUnsupportedException::generic(), }; } } } ```
/content/code_sandbox/backend/src/Enums/StationFeatures.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
373
```php <?php declare(strict_types=1); namespace App\Enums; interface PermissionInterface { public function getValue(): string; public function needsStation(): bool; } ```
/content/code_sandbox/backend/src/Enums/PermissionInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
36
```php <?php declare(strict_types=1); namespace App\Enums; use App\Environment; use App\Exception\Http\InvalidRequestAttribute; use App\Http\ServerRequest; use Gettext\Translator; use Gettext\TranslatorFunctions; use Locale; enum SupportedLocales: string { case English = 'en_US.UTF-8'; case Czech = 'cs_CZ.UTF-8'; case Dutch = 'nl_NL.UTF-8'; case French = 'fr_FR.UTF-8'; case German = 'de_DE.UTF-8'; case Greek = 'el_GR.UTF-8'; case Italian = 'it_IT.UTF-8'; case Japanese = 'ja_JP.UTF-8'; case Korean = 'ko_KR.UTF-8'; case Norwegian = 'nb_NO.UTF-8'; case Polish = 'pl_PL.UTF-8'; case Portuguese = 'pt_PT.UTF-8'; case PortugueseBrazilian = 'pt_BR.UTF-8'; case Russian = 'ru_RU.UTF-8'; case SimplifiedChinese = 'zh_CN.UTF-8'; case Spanish = 'es_ES.UTF-8'; case Swedish = 'sv_SE.UTF-8'; case Turkish = 'tr_TR.UTF-8'; case Ukrainian = 'uk_UA.UTF-8'; public function getLocalName(): string { return match ($this) { self::English => 'English (Default)', self::Czech => 'etina', self::Dutch => 'Nederlands', self::French => 'Franais', self::German => 'Deutsch', self::Greek => '', self::Italian => 'Italiano', self::Japanese => '', self::Korean => '', self::Norwegian => 'norsk', self::Polish => 'Polski', self::Portuguese => 'Portugus', self::PortugueseBrazilian => 'Portugus do Brasil', self::Russian => ' ', self::SimplifiedChinese => '', self::Spanish => 'Espaol', self::Swedish => 'Svenska', self::Turkish => 'Trke', self::Ukrainian => ' ', }; } /** * @return string A shortened locale (minus .UTF-8). */ public function getLocaleWithoutEncoding(): string { return self::stripLocaleEncoding($this); } /** * @return string The first two characters of the locale (for HTML `lang` attribute). */ public function getHtmlLang(): string { return strtolower(substr($this->value, 0, 2)); } public function register(Environment $environment): void { $t = new Translator(); // Skip translation file reading for default locale. if ($this !== self::default()) { $translationsFile = $environment->getBaseDirectory() . '/translations/' . $this->value . '/LC_MESSAGES/default.php'; if (file_exists($translationsFile)) { $t->loadTranslations($translationsFile); } } TranslatorFunctions::register($t); } public static function default(): self { return self::English; } public static function getValidLocale(array|string|null $possibleLocales): self { if (null !== $possibleLocales) { if (is_string($possibleLocales)) { $possibleLocales = [$possibleLocales]; } foreach ($possibleLocales as $locale) { $locale = self::ensureLocaleEncoding($locale); // Prefer exact match. $exactLocale = self::tryFrom($locale); if (null !== $exactLocale) { return $exactLocale; } // Use approximate match if available. foreach (self::cases() as $supportedLocale) { if (str_starts_with($locale, substr($supportedLocale->value, 0, 2))) { return $supportedLocale; } } } } return self::default(); } public static function createFromRequest( Environment $environment, ServerRequest $request ): self { $possibleLocales = []; // Prefer user-based profile locale. try { $user = $request->getUser(); if (!empty($user->getLocale()) && 'default' !== $user->getLocale()) { $possibleLocales[] = $user->getLocale(); } } catch (InvalidRequestAttribute) { } $serverParams = $request->getServerParams(); $browserLocale = Locale::acceptFromHttp($serverParams['HTTP_ACCEPT_LANGUAGE'] ?? ''); if (!empty($browserLocale)) { if (2 === strlen($browserLocale)) { $browserLocale = strtolower($browserLocale) . '_' . strtoupper($browserLocale); } $possibleLocales[] = substr($browserLocale, 0, 5) . '.UTF-8'; } // Attempt to load from environment variable. $envLang = $environment->getLang(); if (null !== $envLang) { $possibleLocales[] = $envLang; } $locale = self::getValidLocale($possibleLocales); $locale->register($environment); return $locale; } public static function createForCli( Environment $environment ): self { $locale = self::getValidLocale($environment->getLang()); $locale->register($environment); return $locale; } public static function stripLocaleEncoding(string|self $locale): string { if ($locale instanceof self) { $locale = $locale->value; } if (str_contains($locale, '.')) { return explode('.', $locale, 2)[0]; } return $locale; } public static function ensureLocaleEncoding(string|self $locale): string { return self::stripLocaleEncoding($locale) . '.UTF-8'; } } ```
/content/code_sandbox/backend/src/Enums/SupportedLocales.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,293
```php <?php declare(strict_types=1); namespace App\Enums; enum StationPermissions: string implements PermissionInterface { case All = 'administer all'; case View = 'view station management'; case Reports = 'view station reports'; case Logs = 'view station logs'; case Profile = 'manage station profile'; case Broadcasting = 'manage station broadcasting'; case Streamers = 'manage station streamers'; case MountPoints = 'manage station mounts'; case RemoteRelays = 'manage station remotes'; case Media = 'manage station media'; case Automation = 'manage station automation'; case WebHooks = 'manage station web hooks'; case Podcasts = 'manage station podcasts'; public function getName(): string { return match ($this) { self::All => __('All Permissions'), self::View => __('View Station Page'), self::Reports => __('View Station Reports'), self::Logs => __('View Station Logs'), self::Profile => __('Manage Station Profile'), self::Broadcasting => __('Manage Station Broadcasting'), self::Streamers => __('Manage Station Streamers'), self::MountPoints => __('Manage Station Mount Points'), self::RemoteRelays => __('Manage Station Remote Relays'), self::Media => __('Manage Station Media'), self::Automation => __('Manage Station Automation'), self::WebHooks => __('Manage Station Web Hooks'), self::Podcasts => __('Manage Station Podcasts'), }; } public function getValue(): string { return $this->value; } public function needsStation(): bool { return true; } } ```
/content/code_sandbox/backend/src/Enums/StationPermissions.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
348
```php <?php declare(strict_types=1); namespace App\Enums; enum SupportedThemes: string { case Browser = 'browser'; case Light = 'light'; case Dark = 'dark'; public static function default(): self { return self::Browser; } } ```
/content/code_sandbox/backend/src/Enums/SupportedThemes.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
62
```php <?php declare(strict_types=1); namespace App\Enums; enum ApplicationEnvironment: string { case Production = 'production'; case Testing = 'testing'; case Development = 'development'; public function getName(): string { return ucfirst($this->value); } public static function default(): self { return self::Production; } public static function toSelect(): array { $values = []; foreach (self::cases() as $case) { $values[$case->value] = $case->getName(); } return $values; } } ```
/content/code_sandbox/backend/src/Enums/ApplicationEnvironment.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
132
```php <?php declare(strict_types=1); namespace App\Enums; enum GlobalPermissions: string implements PermissionInterface { case All = 'administer all'; case View = 'view administration'; case Logs = 'view system logs'; case Settings = 'administer settings'; case ApiKeys = 'administer api keys'; case Stations = 'administer stations'; case CustomFields = 'administer custom fields'; case Backups = 'administer backups'; case StorageLocations = 'administer storage locations'; public function getName(): string { return match ($this) { self::All => __('All Permissions'), self::View => __('View Administration Page'), self::Logs => __('View System Logs'), self::Settings => __('Administer Settings'), self::ApiKeys => __('Administer API Keys'), self::Stations => __('Administer Stations'), self::CustomFields => __('Administer Custom Fields'), self::Backups => __('Administer Backups'), self::StorageLocations => __('Administer Storage Locations'), }; } public function getValue(): string { return $this->value; } public function needsStation(): bool { return false; } } ```
/content/code_sandbox/backend/src/Enums/GlobalPermissions.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
265
```php <?php declare(strict_types=1); namespace App\Sync\Task; use App\Entity\Enums\StorageLocationTypes; use App\Entity\Repository\StationStreamerBroadcastRepository; use App\Entity\Repository\StorageLocationRepository; use App\Entity\StationStreamerBroadcast; use App\Entity\StorageLocation; use Symfony\Component\Finder\Finder; use Throwable; final class MoveBroadcastsTask extends AbstractTask { public static function getSchedulePattern(): string { return self::SCHEDULE_EVERY_MINUTE; } public function __construct( private readonly StationStreamerBroadcastRepository $broadcastRepo, private readonly StorageLocationRepository $storageLocationRepo ) { } public function run(bool $force = false): void { foreach ( $this->iterateStorageLocations( StorageLocationTypes::StationRecordings ) as $storageLocation ) { try { /** @var StorageLocation $storageLocation */ $this->processForStorageLocation($storageLocation); } catch (Throwable $e) { $this->logger->error($e->getMessage(), [ 'storageLocation' => (string)$storageLocation, ]); } } } private function processForStorageLocation(StorageLocation $storageLocation): void { if ($storageLocation->isStorageFull()) { $this->logger->error('Storage location is full; skipping broadcasts.', [ 'storageLocation' => (string)$storageLocation, ]); return; } $fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $stations = $this->storageLocationRepo->getStationsUsingLocation($storageLocation); foreach ($stations as $station) { $finder = (new Finder()) ->files() ->in($station->getRadioTempDir()) ->name(StationStreamerBroadcast::PATH_PREFIX . '_*') ->notName('*.tmp') ->depth(1); $this->logger->debug('Files', ['files', iterator_to_array($finder, false)]); foreach ($finder as $file) { $this->logger->debug('File', ['file' => $file]); $recordingPath = $file->getRelativePathname(); if (!$storageLocation->canHoldFile($file->getSize())) { $this->logger->error( 'Storage location full; broadcast not moved to storage location. ' . 'Check temporary directory at path to recover file.', [ 'storageLocation' => (string)$storageLocation, 'path' => $recordingPath, ] ); break; } $broadcast = $this->broadcastRepo->getOrCreateFromPath($station, $recordingPath); if (null !== $broadcast) { if (0 === $broadcast->getTimestampEnd()) { $broadcast->setTimestampEnd($file->getMTime() ?: time()); } $this->em->persist($broadcast); $this->em->flush(); $tempPath = $file->getPathname(); $fs->uploadAndDeleteOriginal($tempPath, $recordingPath); $this->logger->info( 'Uploaded broadcast to storage location.', [ 'storageLocation' => (string)$storageLocation, 'path' => $recordingPath, ] ); } else { @unlink($file->getPathname()); $this->logger->info( 'Could not find a corresponding broadcast.', [ 'path' => $recordingPath, ] ); } } } } } ```
/content/code_sandbox/backend/src/Sync/Task/MoveBroadcastsTask.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
766
```php <?php declare(strict_types=1); namespace App\Sync\Task; use App\Container\EnvironmentAwareTrait; use App\Container\SettingsAwareTrait; use App\Entity\Settings; use App\Environment; use App\Service\AzuraCastCentral; use DateTimeInterface; use GuzzleHttp\Exception\TransferException; final class CheckUpdatesTask extends AbstractTask { use EnvironmentAwareTrait; use SettingsAwareTrait; // 3 hours + ~3 minutes to force irregularity in update checks. private const int|float UPDATE_THRESHOLD = (60 * 60 * 3) + 150; public function __construct( private readonly AzuraCastCentral $azuracastCentral ) { } public static function isDue( DateTimeInterface $now, Environment $environment, Settings $settings ): bool { if ($environment->isTesting()) { return false; } $nextRun = self::getNextRun($now, $environment, $settings); return $now->getTimestamp() > $nextRun; } public static function getNextRun( DateTimeInterface $now, Environment $environment, Settings $settings ): int { $updateLastRun = $settings->getUpdateLastRun(); return ($updateLastRun !== 0) ? $updateLastRun + self::UPDATE_THRESHOLD : $now->getTimestamp(); } public function run(bool $force = false): void { $settings = $this->readSettings(); $settings->updateUpdateLastRun(); $this->writeSettings($settings); try { $updates = $this->azuracastCentral->checkForUpdates(); if (!empty($updates)) { $settings->setUpdateResults($updates); $this->writeSettings($settings); $this->logger->info('Successfully checked for updates.', ['results' => $updates]); } else { $this->logger->error('Error parsing update data response from AzuraCast central.'); } } catch (TransferException $e) { $this->logger->error(sprintf('Error from AzuraCast Central (%d): %s', $e->getCode(), $e->getMessage())); return; } } } ```
/content/code_sandbox/backend/src/Sync/Task/CheckUpdatesTask.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
482
```php <?php declare(strict_types=1); namespace App\Sync\Task; use App\Entity\Enums\PlaylistSources; use App\Entity\Repository\StationPlaylistMediaRepository; use App\Entity\Station; use App\Entity\StationMedia; use App\Entity\StationPlaylist; use App\Flysystem\ExtendedFilesystemInterface; use App\Flysystem\StationFilesystems; use Doctrine\ORM\Query; final class CheckFolderPlaylistsTask extends AbstractTask { public function __construct( private readonly StationPlaylistMediaRepository $spmRepo, private readonly StationFilesystems $stationFilesystems ) { } public static function getSchedulePattern(): string { return '*/5 * * * *'; } public function run(bool $force = false): void { foreach ($this->iterateStations() as $station) { $this->syncPlaylistFolders($station); } } public function syncPlaylistFolders(Station $station): void { $this->logger->info( 'Processing auto-assigning folders for station...', [ 'station' => $station->getName(), ] ); $fsMedia = $this->stationFilesystems->getMediaFilesystem($station); $mediaInPlaylistQuery = $this->em->createQuery( <<<'DQL' SELECT spm.media_id FROM App\Entity\StationPlaylistMedia spm WHERE spm.playlist_id = :playlist_id DQL ); $mediaInFolderQuery = $this->em->createQuery( <<<'DQL' SELECT sm.id FROM App\Entity\StationMedia sm WHERE sm.storage_location = :storageLocation AND sm.path LIKE :path DQL )->setParameter('storageLocation', $station->getMediaStorageLocation()); foreach ($station->getPlaylists() as $playlist) { if (PlaylistSources::Songs !== $playlist->getSource()) { continue; } $this->em->wrapInTransaction( fn() => $this->processPlaylist( $playlist, $fsMedia, $mediaInPlaylistQuery, $mediaInFolderQuery ) ); } } private function processPlaylist( StationPlaylist $playlist, ExtendedFilesystemInterface $fsMedia, Query $mediaInPlaylistQuery, Query $mediaInFolderQuery ): void { $folders = $playlist->getFolders(); if (0 === $folders->count()) { return; } // Get all media IDs that are already in the playlist. $mediaInPlaylistRaw = $mediaInPlaylistQuery->setParameter('playlist_id', $playlist->getId()) ->getArrayResult(); $mediaInPlaylist = array_column($mediaInPlaylistRaw, 'media_id', 'media_id'); foreach ($folders as $folder) { $path = $folder->getPath(); // Verify the folder still exists. if (!$fsMedia->isDir($path)) { $this->em->remove($folder); continue; } $mediaInFolderRaw = $mediaInFolderQuery->setParameter('path', $path . '/%') ->getArrayResult(); $addedRecords = 0; $weight = $this->spmRepo->getHighestSongWeight($playlist); foreach ($mediaInFolderRaw as $row) { $mediaId = $row['id']; if (!isset($mediaInPlaylist[$mediaId])) { $media = $this->em->find(StationMedia::class, $mediaId); if ($media instanceof StationMedia) { $this->spmRepo->addMediaToPlaylist($media, $playlist, $weight); $weight++; $mediaInPlaylist[$mediaId] = $mediaId; $addedRecords++; } } } $logMessage = (0 === $addedRecords) ? 'No changes detected in folder.' : sprintf('%d media records added from folder.', $addedRecords); $this->logger->debug( $logMessage, [ 'playlist' => $playlist->getName(), 'folder' => $folder->getPath(), ] ); } } } ```
/content/code_sandbox/backend/src/Sync/Task/CheckFolderPlaylistsTask.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
903
```php <?php declare(strict_types=1); namespace App\Sync\Task; use App\Radio\Adapters; use App\Radio\AutoDJ\Scheduler; use App\Radio\Backend\Liquidsoap; use App\Radio\Enums\BackendAdapters; final class EnforceBroadcastTimesTask extends AbstractTask { public function __construct( private readonly Scheduler $scheduler, private readonly Adapters $adapters, ) { } public static function getSchedulePattern(): string { return self::SCHEDULE_EVERY_MINUTE; } public function run(bool $force = false): void { foreach ($this->iterateStations() as $station) { if (BackendAdapters::Liquidsoap !== $station->getBackendType()) { continue; } $currentStreamer = $station->getCurrentStreamer(); if (null === $currentStreamer) { continue; } if (!$this->scheduler->canStreamerStreamNow($currentStreamer)) { /** @var Liquidsoap $adapter */ $adapter = $this->adapters->getBackendAdapter($station); $adapter->disconnectStreamer($station); } } } } ```
/content/code_sandbox/backend/src/Sync/Task/EnforceBroadcastTimesTask.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
252
```php <?php declare(strict_types=1); namespace App\Sync\Task; use App\Entity\Enums\StorageLocationTypes; use App\Entity\Repository\StorageLocationRepository; use App\Entity\Station; use App\Entity\StorageLocation; use App\Flysystem\StationFilesystems; use Exception; use League\Flysystem\StorageAttributes; use Symfony\Component\Finder\Finder; use Throwable; final class CleanupStorageTask extends AbstractTask { public function __construct( private readonly StorageLocationRepository $storageLocationRepo, ) { } public static function getSchedulePattern(): string { return '24 * * * *'; } public function run(bool $force = false): void { foreach ($this->iterateStations() as $station) { try { /** @var Station $station */ $this->cleanStationTempFiles($station); } catch (Throwable $e) { $this->logger->error($e->getMessage(), [ 'station' => (string)$station, ]); } } $storageLocations = $this->iterateStorageLocations(StorageLocationTypes::StationMedia); foreach ($storageLocations as $storageLocation) { try { /** @var StorageLocation $storageLocation */ $this->cleanMediaStorageLocation($storageLocation); } catch (Throwable $e) { $this->logger->error($e->getMessage(), [ 'storageLocation' => (string)$storageLocation, ]); } } } private function cleanStationTempFiles(Station $station): void { $tempDir = $station->getRadioTempDir(); $finder = new Finder(); $finder ->files() ->in($tempDir) ->date('before 2 days ago'); foreach ($finder as $file) { $filePath = $file->getRealPath(); if (false !== $filePath) { @unlink($filePath); } } } private function cleanMediaStorageLocation(StorageLocation $storageLocation): void { $fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $allUniqueIdsRaw = $this->em->createQuery( <<<'DQL' SELECT sm.unique_id FROM App\Entity\StationMedia sm WHERE sm.storage_location = :storageLocation DQL )->setParameter('storageLocation', $storageLocation) ->getArrayResult(); $allUniqueIds = []; foreach ($allUniqueIdsRaw as $row) { $allUniqueIds[$row['unique_id']] = $row['unique_id']; } if (0 === count($allUniqueIds)) { $this->logger->notice( sprintf('Skipping storage location %s: no media found.', $storageLocation) ); return; } $removed = [ 'albumart' => 0, 'waveform' => 0, ]; $cleanupDirs = [ 'albumart' => StationFilesystems::DIR_ALBUM_ART, 'waveform' => StationFilesystems::DIR_WAVEFORMS, ]; foreach ($cleanupDirs as $key => $dirBase) { try { /** @var StorageAttributes $row */ foreach ($fs->listContents($dirBase, true) as $row) { $path = $row->path(); $filename = pathinfo($path, PATHINFO_FILENAME); if (!isset($allUniqueIds[$filename])) { $fs->delete($path); $removed[$key]++; } } } catch (Exception $e) { $this->logger->error( sprintf('Filesystem error: %s', $e->getMessage()), [ 'exception' => $e, ] ); } } $this->logger->info('Storage directory cleanup completed.', $removed); } } ```
/content/code_sandbox/backend/src/Sync/Task/CleanupStorageTask.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
836
```php <?php declare(strict_types=1); namespace App\Sync\Task; use App\Entity\Enums\StorageLocationTypes; use App\Entity\Repository\StationMediaRepository; use App\Entity\Repository\StorageLocationRepository; use App\Entity\Repository\UnprocessableMediaRepository; use App\Entity\StationMedia; use App\Entity\StorageLocation; use App\Entity\UnprocessableMedia; use App\Flysystem\Attributes\FileAttributes; use App\Flysystem\ExtendedFilesystemInterface; use App\Flysystem\StationFilesystems; use App\Media\MimeType; use App\Message\AddNewMediaMessage; use App\Message\ProcessCoverArtMessage; use App\Message\ReprocessMediaMessage; use App\MessageQueue\QueueManagerInterface; use App\MessageQueue\QueueNames; use App\Radio\Quota; use App\Utilities\Types; use Brick\Math\BigInteger; use Doctrine\ORM\AbstractQuery; use League\Flysystem\FilesystemException; use League\Flysystem\StorageAttributes; use League\Flysystem\UnableToRetrieveMetadata; use Symfony\Component\Filesystem\Path; use Symfony\Component\Messenger\MessageBus; final class CheckMediaTask extends AbstractTask { public function __construct( private readonly StationMediaRepository $mediaRepo, private readonly UnprocessableMediaRepository $unprocessableMediaRepo, private readonly StorageLocationRepository $storageLocationRepo, private readonly MessageBus $messageBus, private readonly QueueManagerInterface $queueManager ) { } public static function getSchedulePattern(): string { return '1-59/5 * * * *'; } public static function isLongTask(): bool { return true; } public function run(bool $force = false): void { // Clear existing media queue. $this->queueManager->clearQueue(QueueNames::Media); // Process for each storage location. $storageLocations = $this->iterateStorageLocations(StorageLocationTypes::StationMedia); foreach ($storageLocations as $storageLocation) { $this->logger->info( sprintf( 'Processing media for storage location %s...', $storageLocation ) ); $this->importMusic( $storageLocation ); } } public function importMusic( StorageLocation $storageLocation ): void { $fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $stats = [ 'total_size' => '0', 'total_files' => 0, 'unchanged' => 0, 'updated' => 0, 'created' => 0, 'deleted' => 0, 'cover_art' => 0, 'not_processable' => 0, ]; $totalSize = BigInteger::zero(); try { $fsIterator = $fs->listContents('/', true)->filter( fn(StorageAttributes $attrs) => $attrs->isFile() && !StationFilesystems::isDotFile($attrs->path()) ); } catch (FilesystemException $e) { $this->logger->error( sprintf('Flysystem Error for Storage Space %s', $storageLocation), [ 'exception' => $e, ] ); return; } $musicFiles = []; $coverFiles = []; /** @var FileAttributes $file */ foreach ($fsIterator as $file) { try { $size = $file->fileSize(); if (null !== $size) { $totalSize = $totalSize->plus($size); } } catch (UnableToRetrieveMetadata) { continue; } if ($size === 0) { continue; } if (MimeType::isPathProcessable($file->path())) { $pathHash = md5($file->path()); $musicFiles[$pathHash] = [ StorageAttributes::ATTRIBUTE_PATH => $file->path(), StorageAttributes::ATTRIBUTE_LAST_MODIFIED => $file->lastModified(), ]; } elseif (MimeType::isPathImage($file->path())) { $stats['cover_art']++; $dirHash = StationMedia::getFolderHashForPath($file->path()); $coverFiles[$dirHash] = [ StorageAttributes::ATTRIBUTE_PATH => $file->path(), StorageAttributes::ATTRIBUTE_LAST_MODIFIED => $file->lastModified(), ]; } else { $stats['not_processable']++; } } $storageLocation->setStorageUsed($totalSize); $this->em->persist($storageLocation); $this->em->flush(); $stats['total_size'] = $totalSize . ' (' . Quota::getReadableSize($totalSize) . ')'; $stats['total_files'] = count($musicFiles); // Process cover art. $this->processCoverArt($storageLocation, $fs, $coverFiles); // Check queue for existing pending processing entries. $this->processExistingMediaRows($storageLocation, $musicFiles, $stats); $storageLocation = $this->em->refetch($storageLocation); // Loop through currently unprocessable media. $this->processUnprocessableMediaRows($storageLocation, $musicFiles, $stats); $storageLocation = $this->em->refetch($storageLocation); $this->processNewFiles($storageLocation, $musicFiles, $stats); $this->logger->debug(sprintf('Media processed for "%s".', $storageLocation), $stats); } private function processCoverArt( StorageLocation $storageLocation, ExtendedFilesystemInterface $fs, array $coverFiles ): void { $fsIterator = $fs->listContents(StationFilesystems::DIR_FOLDER_COVERS, true)->filter( fn(StorageAttributes $attrs) => $attrs->isFile() ); /** @var FileAttributes $file */ foreach ($fsIterator as $file) { $basename = Path::getFilenameWithoutExtension($file->path(), '.jpg'); if (!isset($coverFiles[$basename])) { $fs->delete($file->path()); } elseif ($file->lastModified() > $coverFiles[$basename][StorageAttributes::ATTRIBUTE_LAST_MODIFIED]) { unset($coverFiles[$basename]); } } foreach ($coverFiles as $folderHash => $coverFile) { $message = new ProcessCoverArtMessage(); $message->storage_location_id = $storageLocation->getIdRequired(); $message->path = $coverFile[StorageAttributes::ATTRIBUTE_PATH]; $message->folder_hash = $folderHash; $this->messageBus->dispatch($message); } } private function processExistingMediaRows( StorageLocation $storageLocation, array &$musicFiles, array &$stats ): void { $existingMediaQuery = $this->em->createQuery( <<<'DQL' SELECT sm.id, sm.path, sm.mtime, sm.unique_id FROM App\Entity\StationMedia sm WHERE sm.storage_location = :storageLocation DQL )->setParameter('storageLocation', $storageLocation); /** @var array<array-key, int|string> $mediaRow */ foreach ($existingMediaQuery->toIterable([], AbstractQuery::HYDRATE_ARRAY) as $mediaRow) { // Check if media file still exists. $path = (string)$mediaRow['path']; $pathHash = md5($path); if (isset($musicFiles[$pathHash])) { $fileInfo = $musicFiles[$pathHash]; $mtime = $fileInfo[StorageAttributes::ATTRIBUTE_LAST_MODIFIED] ?? 0; if (StationMedia::needsReprocessing($mtime, Types::int($mediaRow['mtime']))) { $message = new ReprocessMediaMessage(); $message->storage_location_id = $storageLocation->getIdRequired(); $message->media_id = (int)$mediaRow['id']; $this->messageBus->dispatch($message); $stats['updated']++; } else { $stats['unchanged']++; } unset($musicFiles[$pathHash]); } else { $media = $this->em->find(StationMedia::class, $mediaRow['id']); if ($media instanceof StationMedia) { $this->mediaRepo->remove($media); } $stats['deleted']++; } } $this->em->clear(); } private function processUnprocessableMediaRows( StorageLocation $storageLocation, array &$musicFiles, array &$stats ): void { $unprocessableMediaQuery = $this->em->createQuery( <<<'DQL' SELECT upm.id, upm.path, upm.mtime FROM App\Entity\UnprocessableMedia upm WHERE upm.storage_location = :storageLocation DQL )->setParameter('storageLocation', $storageLocation); $unprocessableRecords = $unprocessableMediaQuery->toIterable([], AbstractQuery::HYDRATE_ARRAY); foreach ($unprocessableRecords as $unprocessableRow) { $pathHash = md5($unprocessableRow['path']); if (isset($musicFiles[$pathHash])) { $fileInfo = $musicFiles[$pathHash]; $mtime = $fileInfo[StorageAttributes::ATTRIBUTE_LAST_MODIFIED] ?? 0; if (UnprocessableMedia::needsReprocessing($mtime, Types::int($unprocessableRow['mtime']))) { $message = new AddNewMediaMessage(); $message->storage_location_id = $storageLocation->getIdRequired(); $message->path = $unprocessableRow['path']; $this->messageBus->dispatch($message); $stats['updated']++; } else { $stats['not_processable']++; } unset($musicFiles[$pathHash]); } else { $this->unprocessableMediaRepo->clearForPath($storageLocation, $unprocessableRow['path']); } } $this->em->clear(); } private function processNewFiles( StorageLocation $storageLocation, array $musicFiles, array &$stats ): void { foreach ($musicFiles as $newMusicFile) { $path = $newMusicFile[StorageAttributes::ATTRIBUTE_PATH]; $message = new AddNewMediaMessage(); $message->storage_location_id = $storageLocation->getIdRequired(); $message->path = $path; $this->messageBus->dispatch($message); $stats['created']++; } } } ```
/content/code_sandbox/backend/src/Sync/Task/CheckMediaTask.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,256
```php <?php declare(strict_types=1); namespace App\Sync\Task; use App\Container\SettingsAwareTrait; use App\Entity\Enums\StorageLocationTypes; use App\Entity\Repository\StorageLocationRepository; use App\Entity\Station; use App\Entity\StorageLocation; use App\Nginx\ConfigWriter; use App\Nginx\Nginx; use League\Flysystem\StorageAttributes; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Throwable; final class RotateLogsTask extends AbstractTask { use SettingsAwareTrait; public function __construct( private readonly StorageLocationRepository $storageLocationRepo, private readonly Nginx $nginx, ) { } public static function getSchedulePattern(): string { return '34 * * * *'; } public function run(bool $force = false): void { // Rotate logs for individual stations. $hlsRotated = false; foreach ($this->iterateStations() as $station) { $this->logger->info( 'Rotating logs for station.', ['station' => (string)$station] ); try { $this->cleanUpIcecastLog($station); if ($station->getEnableHls() && $this->rotateHlsLog($station)) { $hlsRotated = true; } } catch (Throwable $e) { $this->logger->error($e->getMessage(), [ 'station' => (string)$station, ]); } } if ($hlsRotated) { $this->nginx->reopenLogs(); } // Rotate the automated backups. $settings = $this->readSettings(); $copiesToKeep = $settings->getBackupKeepCopies(); if ($copiesToKeep > 0) { $backupStorageId = (int)$settings->getBackupStorageLocation(); if ($backupStorageId > 0) { $storageLocation = $this->storageLocationRepo->findByType( StorageLocationTypes::Backup, $backupStorageId ); if ($storageLocation instanceof StorageLocation) { $this->rotateBackupStorage($storageLocation, $copiesToKeep); } } } } private function rotateBackupStorage( StorageLocation $storageLocation, int $copiesToKeep ): void { $fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $iterator = $fs->listContents('', false)->filter( function (StorageAttributes $attrs) { return 0 === stripos($attrs->path(), 'automatic_backup'); } ); $backupsByTime = []; foreach ($iterator as $backup) { /** @var StorageAttributes $backup */ $backupsByTime[$backup->lastModified()] = $backup->path(); } if (count($backupsByTime) <= $copiesToKeep) { return; } krsort($backupsByTime); foreach (array_slice($backupsByTime, $copiesToKeep) as $backupToDelete) { $fs->delete($backupToDelete); $this->logger->info(sprintf('Deleted automated backup: "%s"', $backupToDelete)); } } private function cleanUpIcecastLog(Station $station): void { $configPath = $station->getRadioConfigDir(); $finder = new Finder(); $finder ->files() ->in($configPath) ->name('icecast_*.log.*') ->date('before 1 month ago'); foreach ($finder as $file) { $filePath = $file->getRealPath(); if ($filePath) { @unlink($filePath); } } } private function rotateHlsLog(Station $station): bool { $hlsLogFile = ConfigWriter::getHlsLogFile($station); $hlsLogBackup = $hlsLogFile . '.1'; if (!file_exists($hlsLogFile)) { return false; } $fsUtils = new Filesystem(); if (file_exists($hlsLogBackup)) { $fsUtils->remove([$hlsLogBackup]); } $fsUtils->rename($hlsLogFile, $hlsLogBackup); return true; } } ```
/content/code_sandbox/backend/src/Sync/Task/RotateLogsTask.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
939
```php <?php declare(strict_types=1); namespace App\Sync\Task; use App\Entity\Repository\StationRequestRepository; use App\Entity\Station; use App\Entity\StationQueue; use App\Entity\StationRequest; use App\Event\Radio\AnnotateNextSong; use App\Radio\Adapters; use App\Radio\Backend\Liquidsoap; use App\Radio\Enums\LiquidsoapQueues; use Psr\EventDispatcher\EventDispatcherInterface; final class CheckRequestsTask extends AbstractTask { public function __construct( private readonly StationRequestRepository $requestRepo, private readonly Adapters $adapters, private readonly EventDispatcherInterface $dispatcher ) { } public static function getSchedulePattern(): string { return self::SCHEDULE_EVERY_MINUTE; } /** * Manually process any requests for stations that use "Manual AutoDJ" mode. * * @param bool $force */ public function run(bool $force = false): void { foreach ($this->iterateStations() as $station) { if (!$station->useManualAutoDJ()) { continue; } $request = $this->requestRepo->getNextPlayableRequest($station); if (null === $request) { continue; } $this->submitRequest($station, $request); } } private function submitRequest(Station $station, StationRequest $request): void { // Send request to the station to play the request. $backend = $this->adapters->getBackendAdapter($station); if (!($backend instanceof Liquidsoap)) { return; } // Check for an existing SongHistory record and skip if one exists. $sq = $this->em->getRepository(StationQueue::class)->findOneBy( [ 'station' => $station, 'request' => $request, ] ); if (!$sq instanceof StationQueue) { // Log the item in SongHistory. $sq = StationQueue::fromRequest($request); $sq->setSentToAutodj(); $sq->setTimestampCued(time()); $this->em->persist($sq); $this->em->flush(); } // Generate full Liquidsoap annotations $event = AnnotateNextSong::fromStationQueue($sq, true); $this->dispatcher->dispatch($event); $track = $event->buildAnnotations(); // Queue request with Liquidsoap. $queue = LiquidsoapQueues::Requests; if (!$backend->isQueueEmpty($station, $queue)) { $this->logger->error('Skipping submitting request to Liquidsoap; current queue is occupied.'); return; } $this->logger->debug('Submitting request to AutoDJ.', ['track' => $track]); $response = $backend->enqueue($station, $queue, $track); $this->logger->debug('AutoDJ request response', ['response' => $response]); // Log the request as played. $request->setPlayedAt(time()); $this->em->persist($request); $this->em->flush(); } } ```
/content/code_sandbox/backend/src/Sync/Task/CheckRequestsTask.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
681