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\Entity\Api\Admin; use App\Entity\Api\NowPlaying\StationMount; use App\Entity\Api\ResolvableUrlInterface; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; #[OA\Schema( schema: 'Api_Admin_Relay', type: 'object' )] final class Relay implements ResolvableUrlInterface { #[OA\Property( description: 'Station ID', example: 1 )] public int $id; #[OA\Property( description: 'Station name', example: 'AzuraTest Radio' )] public ?string $name = null; #[OA\Property( description: 'Station "short code", used for URL and folder paths', example: 'azuratest_radio' )] public ?string $shortcode = null; #[OA\Property( description: 'Station description', example: 'An AzuraCast station!' )] public ?string $description; #[OA\Property( description: 'Station homepage URL', example: 'path_to_url )] public ?string $url; #[OA\Property( description: 'The genre of the station', example: 'Variety' )] public ?string $genre; #[OA\Property( description: 'Which broadcasting software (frontend) the station uses', example: 'shoutcast2' )] public ?string $type = null; #[OA\Property( description: 'The port used by this station to serve its broadcasts.', example: 8000 )] public ?int $port = null; #[OA\Property( description: 'The relay password for the frontend (if applicable).', example: 'p4ssw0rd' )] public string $relay_pw; #[OA\Property( description: 'The administrator password for the frontend (if applicable).', example: 'p4ssw0rd' )] public string $admin_pw; /** @var StationMount[] */ #[OA\Property] public array $mounts = []; /** * Re-resolve any Uri instances to reflect base URL changes. * * @param UriInterface $base */ public function resolveUrls(UriInterface $base): void { foreach ($this->mounts as $mount) { if ($mount instanceof ResolvableUrlInterface) { $mount->resolveUrls($base); } } } } ```
/content/code_sandbox/backend/src/Entity/Api/Admin/Relay.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
545
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use App\Entity\Api\ResolvableUrlInterface; use App\Http\Router; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; #[OA\Schema( schema: 'Api_NowPlaying_Station', type: 'object' )] final class Station implements ResolvableUrlInterface { #[OA\Property( description: 'Station ID', example: 1 )] public int $id; #[OA\Property( description: 'Station name', example: 'AzuraTest Radio' )] public string $name; #[OA\Property( description: 'Station "short code", used for URL and folder paths', example: 'azuratest_radio' )] public string $shortcode = ''; #[OA\Property( description: 'Station description', example: 'An AzuraCast station!' )] public string $description = ''; #[OA\Property( description: 'Which broadcasting software (frontend) the station uses', example: 'shoutcast2' )] public string $frontend = ''; #[OA\Property( description: 'Which AutoDJ software (backend) the station uses', example: 'liquidsoap' )] public string $backend = ''; #[OA\Property( description: 'The station\'s IANA time zone', example: 'America/Chicago' )] public string $timezone = ''; #[OA\Property( description: 'The full URL to listen to the default mount of the station', example: 'path_to_url )] public string|UriInterface|null $listen_url; #[OA\Property( description: 'The public URL of the station.', example: 'path_to_url )] public ?string $url = null; #[OA\Property( description: 'The public player URL for the station.', example: 'path_to_url )] public string|UriInterface $public_player_url; #[OA\Property( description: 'The playlist download URL in PLS format.', example: 'path_to_url )] public string|UriInterface $playlist_pls_url; #[OA\Property( description: 'The playlist download URL in M3U format.', example: 'path_to_url )] public string|UriInterface $playlist_m3u_url; #[OA\Property( description: 'If the station is public (i.e. should be shown in listings of all stations)', example: true )] public bool $is_public = false; /** @var StationMount[] */ #[OA\Property] public array $mounts = []; /** @var StationRemote[] */ #[OA\Property] public array $remotes = []; #[OA\Property( description: 'If the station has HLS streaming enabled.', example: true )] public bool $hls_enabled = false; #[OA\Property( description: 'If the HLS stream should be the default one for the station.', example: true )] public bool $hls_is_default = false; #[OA\Property( description: 'The full URL to listen to the HLS stream for the station.', example: 'path_to_url nullable: true )] public string|UriInterface|null $hls_url = null; #[OA\Property( description: 'HLS Listeners', example: 1 )] public int $hls_listeners = 0; /** * Re-resolve any Uri instances to reflect base URL changes. * * @param UriInterface $base */ public function resolveUrls(UriInterface $base): void { $this->listen_url = (null !== $this->listen_url) ? (string)Router::resolveUri($base, $this->listen_url, true) : null; $this->public_player_url = (string)Router::resolveUri($base, $this->public_player_url, true); $this->playlist_pls_url = (string)Router::resolveUri($base, $this->playlist_pls_url, true); $this->playlist_m3u_url = (string)Router::resolveUri($base, $this->playlist_m3u_url, true); foreach ($this->mounts as $mount) { if ($mount instanceof ResolvableUrlInterface) { $mount->resolveUrls($base); } } $this->hls_url = (null !== $this->hls_url) ? (string)Router::resolveUri($base, $this->hls_url, true) : null; } } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/Station.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,028
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use OpenApi\Attributes as OA; #[OA\Schema( schema: 'Api_NowPlaying_Listeners', type: 'object' )] final class Listeners { #[OA\Property( description: 'Total non-unique current listeners', example: 20 )] public int $total = 0; #[OA\Property( description: 'Total unique current listeners', example: 15 )] public int $unique = 0; #[OA\Property( description: 'Total non-unique current listeners (Legacy field, may be retired in the future.)', example: 20 )] public int $current = 0; public function __construct( int $total = 0, ?int $unique = null ) { $this->total = $total; $this->current = $total; $this->unique = $unique ?? 0; } } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/Listeners.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
223
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use App\Entity\Api\ResolvableUrlInterface; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; #[OA\Schema(schema: 'Api_NowPlaying', type: 'object')] class NowPlaying implements ResolvableUrlInterface { #[OA\Property] public Station $station; #[OA\Property] public Listeners $listeners; #[OA\Property] public Live $live; #[OA\Property] public ?CurrentSong $now_playing = null; #[OA\Property] public ?StationQueue $playing_next = null; /** @var SongHistory[] */ #[OA\Property] public array $song_history = []; #[OA\Property( description: 'Whether the stream is currently online.', example: true )] public bool $is_online = false; #[OA\Property( description: 'Debugging information about where the now playing data comes from.', enum: ['hit', 'database', 'station'] )] public ?string $cache = null; /** * Update any variable items in the feed. */ public function update(): void { $this->now_playing?->recalculate(); } /** * Return an array representation of this object. * * @return mixed[] */ public function toArray(): array { return json_decode(json_encode($this, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); } /** * Iterate through sub-items and re-resolve any Uri instances to reflect base URL changes. * * @param UriInterface $base */ public function resolveUrls(UriInterface $base): void { $this->station->resolveUrls($base); $this->live->resolveUrls($base); if ($this->now_playing instanceof ResolvableUrlInterface) { $this->now_playing->resolveUrls($base); } if ($this->playing_next instanceof ResolvableUrlInterface) { $this->playing_next->resolveUrls($base); } foreach ($this->song_history as $historyObj) { if ($historyObj instanceof ResolvableUrlInterface) { $historyObj->resolveUrls($base); } } } } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/NowPlaying.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
502
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use App\Entity\Api\ResolvableUrlInterface; use App\Http\Router; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; #[OA\Schema( schema: 'Api_NowPlaying_StationMount', type: 'object' )] final class StationMount extends StationRemote implements ResolvableUrlInterface { #[OA\Property( description: 'The relative path that corresponds to this mount point', example: '/radio.mp3' )] public string $path; #[OA\Property( description: 'If the mount is the default mount for the parent station', example: true )] public bool $is_default; /** * Re-resolve any Uri instances to reflect base URL changes. * * @param UriInterface $base */ public function resolveUrls(UriInterface $base): void { $this->url = (string)Router::resolveUri($base, $this->url, true); } } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/StationMount.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
228
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use App\Entity\Api\ResolvableUrlInterface; use App\Entity\Api\Song; use App\OpenApi; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; #[OA\Schema( schema: 'Api_NowPlaying_StationQueue', type: 'object' )] class StationQueue implements ResolvableUrlInterface { #[OA\Property( description: 'UNIX timestamp when the AutoDJ is expected to queue the song for playback.', example: OpenApi::SAMPLE_TIMESTAMP )] public int $cued_at = 0; #[OA\Property( description: 'UNIX timestamp when playback is expected to start.', example: OpenApi::SAMPLE_TIMESTAMP )] public int $played_at = 0; #[OA\Property( description: 'Duration of the song in seconds', example: 180 )] public int $duration = 0; #[OA\Property( description: 'Indicates the playlist that the song was played from, if available, or empty string if not.', example: 'Top 100' )] public ?string $playlist = null; #[OA\Property( description: 'Indicates whether the song is a listener request.', )] public bool $is_request = false; #[OA\Property] public Song $song; /** * Re-resolve any Uri instances to reflect base URL changes. * * @param UriInterface $base */ public function resolveUrls(UriInterface $base): void { $this->song->resolveUrls($base); } } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/StationQueue.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
360
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use App\Entity\Api\ResolvableUrlInterface; use App\Entity\Api\Song; use App\OpenApi; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; #[OA\Schema( schema: 'Api_NowPlaying_SongHistory', type: 'object' )] class SongHistory implements ResolvableUrlInterface { #[OA\Property( description: 'Song history unique identifier' )] public int $sh_id; #[OA\Property( description: 'UNIX timestamp when playback started.', example: OpenApi::SAMPLE_TIMESTAMP )] public int $played_at = 0; #[OA\Property( description: 'Duration of the song in seconds', example: 180 )] public int $duration = 0; #[OA\Property( description: 'Indicates the playlist that the song was played from, if available, or empty string if not.', example: 'Top 100' )] public ?string $playlist = null; #[OA\Property( description: 'Indicates the current streamer that was connected, if available, or empty string if not.', example: 'Test DJ' )] public ?string $streamer = null; #[OA\Property( description: 'Indicates whether the song is a listener request.', )] public bool $is_request = false; #[OA\Property] public Song $song; /** * Re-resolve any Uri instances to reflect base URL changes. * * @param UriInterface $base */ public function resolveUrls(UriInterface $base): void { $this->song->resolveUrls($base); } } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/SongHistory.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
382
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use App\Entity\Api\ResolvableUrlInterface; use App\Http\Router; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; #[OA\Schema( schema: 'Api_NowPlaying_Live', type: 'object' )] final class Live implements ResolvableUrlInterface { #[OA\Property( description: 'Whether the stream is known to currently have a live DJ.', example: false )] public bool $is_live = false; #[OA\Property( description: 'The current active streamer/DJ, if one is available.', example: 'DJ Jazzy Jeff' )] public string $streamer_name = ''; #[OA\Property( description: 'The start timestamp of the current broadcast, if one is available.', example: '1591548318' )] public ?int $broadcast_start = null; #[OA\Property( description: 'URL to the streamer artwork (if available).', example: 'path_to_url nullable: true )] public string|UriInterface|null $art = null; public function resolveUrls(UriInterface $base): void { $this->art = (null !== $this->art) ? (string)Router::resolveUri($base, $this->art, true) : null; } } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/Live.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
310
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; #[OA\Schema( schema: 'Api_NowPlaying_StationRemote', type: 'object' )] class StationRemote { #[OA\Property( description: 'Mount/Remote ID number.', example: 1 )] public int $id; #[OA\Property( description: 'Mount point name/URL', example: '/radio.mp3' )] public string $name; #[OA\Property( description: 'Full listening URL specific to this mount', example: 'path_to_url )] public string|UriInterface $url; #[OA\Property( description: 'Bitrate (kbps) of the broadcasted audio (if known)', example: 128 )] public ?int $bitrate = null; #[OA\Property( description: 'Audio encoding format of broadcasted audio (if known)', example: 'mp3' )] public ?string $format = null; #[OA\Property] public Listeners $listeners; } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/StationRemote.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
257
```php <?php declare(strict_types=1); namespace App\Entity\Api\NowPlaying; use App\Entity\SongHistory as SongHistoryEntity; use App\Traits\LoadFromParentObject; use OpenApi\Attributes as OA; #[OA\Schema( schema: 'Api_NowPlaying_CurrentSong', type: 'object' )] final class CurrentSong extends SongHistory { use LoadFromParentObject; #[OA\Property( description: 'Elapsed time of the song\'s playback since it started.', example: 25 )] public int $elapsed = 0; #[OA\Property( description: 'Remaining time in the song, in seconds.', example: 155 )] public int $remaining = 0; /** * Update the "elapsed" and "remaining" timers based on the exact current second. */ public function recalculate(): void { $this->elapsed = time() + SongHistoryEntity::PLAYBACK_DELAY_SECONDS - $this->played_at; if ($this->elapsed < 0) { $this->elapsed = 0; } $this->remaining = 0; if ($this->duration !== 0) { if ($this->elapsed >= $this->duration) { $this->elapsed = $this->duration; } else { $this->remaining = $this->duration - $this->elapsed; } } } } ```
/content/code_sandbox/backend/src/Entity/Api/NowPlaying/CurrentSong.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
309
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Role; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Persistence\ObjectManager; final class RoleFixture extends AbstractFixture { public function load(ObjectManager $manager): void { $adminRole = new Role(); $adminRole->setName('Super Administrator'); $demoRole = new Role(); $demoRole->setName('Demo Account'); $manager->persist($adminRole); $manager->persist($demoRole); $manager->flush(); $this->addReference('admin_role', $adminRole); $this->addReference('demo_role', $demoRole); } } ```
/content/code_sandbox/backend/src/Entity/Fixture/RoleFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
150
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Station; use App\Radio\Enums\BackendAdapters; use App\Radio\Enums\FrontendAdapters; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Persistence\ObjectManager; final class StationFixture extends AbstractFixture { public function load(ObjectManager $manager): void { $station = new Station(); $station->setName('AzuraTest Radio'); $station->setDescription('A test radio station.'); $station->setEnableRequests(true); $station->setFrontendType(FrontendAdapters::Icecast); $station->setBackendType(BackendAdapters::Liquidsoap); $station->setEnableHls(true); $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio'); $station->setHasStarted(true); $station->ensureDirectoriesExist(); $mediaStorage = $station->getMediaStorageLocation(); $recordingsStorage = $station->getRecordingsStorageLocation(); $podcastsStorage = $station->getPodcastsStorageLocation(); $stationQuota = getenv('INIT_STATION_QUOTA'); if (!empty($stationQuota)) { $mediaStorage->setStorageQuota($stationQuota); $recordingsStorage->setStorageQuota($stationQuota); $podcastsStorage->setStorageQuota($stationQuota); } $manager->persist($station); $manager->persist($mediaStorage); $manager->persist($recordingsStorage); $manager->persist($podcastsStorage); $manager->flush(); $this->addReference('station', $station); } } ```
/content/code_sandbox/backend/src/Entity/Fixture/StationFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
372
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Station; use App\Entity\StationPlaylist; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; final class StationPlaylistFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { /** @var Station $station */ $station = $this->getReference('station'); $playlist = new StationPlaylist($station); $playlist->setName('default'); $manager->persist($playlist); $manager->flush(); $this->addReference('station_playlist', $playlist); } /** * @return string[] */ public function getDependencies(): array { return [ StationFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/StationPlaylistFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
184
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Station; use App\Entity\StationMount; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; final class StationMountFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { /** @var Station $station */ $station = $this->getReference('station'); $mountRadio = new StationMount($station); $mountRadio->setName('/radio.mp3'); $mountRadio->setIsDefault(true); $manager->persist($mountRadio); $mountMobile = new StationMount($station); $mountMobile->setName('/mobile.mp3'); $mountMobile->setAutodjBitrate(64); $manager->persist($mountMobile); $manager->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ StationFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/StationMountFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
231
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Analytics; use App\Entity\Enums\AnalyticsIntervals; use App\Entity\Station; use Carbon\CarbonImmutable; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; final class AnalyticsFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { $stations = $manager->getRepository(Station::class)->findAll(); $midnightUtc = CarbonImmutable::now('UTC')->setTime(0, 0); for ($i = 1; $i <= 14; $i++) { $day = $midnightUtc->subDays($i); $dayMin = 0; $dayMax = 0; $dayListeners = 0; $dayUnique = 0; foreach ($stations as $station) { /** @var Station $station */ $stationListeners = random_int(10, 50); $stationMin = random_int(1, $stationListeners); $stationMax = random_int($stationListeners, 150); $stationUnique = random_int(1, 250); $dayMin = min($dayMin, $stationMin); $dayMax = max($dayMax, $stationMax); $dayListeners += $stationListeners; $dayUnique += $stationUnique; $stationPoint = new Analytics( $day, $station, AnalyticsIntervals::Daily, $stationMin, $stationMax, $stationListeners, $stationUnique ); $manager->persist($stationPoint); } $totalPoint = new Analytics( $day, null, AnalyticsIntervals::Daily, $dayMin, $dayMax, $dayListeners, $dayUnique ); $manager->persist($totalPoint); } $manager->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ StationFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/AnalyticsFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
467
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\ApiKey; use App\Entity\User; use App\Security\SplitToken; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; final class ApiKeyFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { $demoApiKey = getenv('INIT_DEMO_API_KEY'); if (!empty($demoApiKey) && $this->hasReference('demo_user')) { /** @var User $demoUser */ $demoUser = $this->getReference('demo_user'); $apiKey = new ApiKey($demoUser, SplitToken::fromKeyString($demoApiKey)); $apiKey->setComment('Demo User'); $manager->persist($apiKey); } $adminApiKey = getenv('INIT_ADMIN_API_KEY'); if (!empty($adminApiKey) && $this->hasReference('admin_user')) { /** @var User $adminUser */ $adminUser = $this->getReference('admin_user'); $apiKey = new ApiKey($adminUser, SplitToken::fromKeyString($adminApiKey)); $apiKey->setComment('Administrator'); $manager->persist($apiKey); } $manager->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ UserFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/ApiKeyFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
319
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Station; use App\Entity\StationHlsStream; use App\Radio\Enums\StreamFormats; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; final class StationHlsStreamFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { /** @var Station $station */ $station = $this->getReference('station'); $mountLofi = new StationHlsStream($station); $mountLofi->setName('aac_lofi'); $mountLofi->setFormat(StreamFormats::Aac); $mountLofi->setBitrate(64); $manager->persist($mountLofi); $mountMidfi = new StationHlsStream($station); $mountMidfi->setName('aac_midfi'); $mountMidfi->setFormat(StreamFormats::Aac); $mountMidfi->setBitrate(128); $manager->persist($mountMidfi); $mountHifi = new StationHlsStream($station); $mountHifi->setName('aac_hifi'); $mountHifi->setFormat(StreamFormats::Aac); $mountHifi->setBitrate(256); $manager->persist($mountHifi); $manager->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ StationFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/StationHlsStreamFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
345
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Role; use App\Entity\User; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; final class UserFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { $adminEmail = getenv('INIT_ADMIN_EMAIL'); $adminPassword = getenv('INIT_ADMIN_PASSWORD'); if (!empty($adminEmail) && !empty($adminPassword)) { $demoUser = new User(); $demoUser->setEmail('demo@azuracast.com'); $demoUser->setNewPassword('demo'); $demoUser->setName('AzuraCast Demo User'); /** @var Role $demoRole */ $demoRole = $this->getReference('demo_role'); $demoUser->getRoles()->add($demoRole); $manager->persist($demoUser); $this->addReference('demo_user', $demoUser); $adminUser = new User(); $adminUser->setEmail($adminEmail); $adminUser->setName('System Administrator'); $adminUser->setNewPassword($adminPassword); /** @var Role $adminRole */ $adminRole = $this->getReference('admin_role'); $adminUser->getRoles()->add($adminRole); $admin2faSecret = getenv('INIT_ADMIN_2FA_SECRET'); if (!empty($admin2faSecret)) { $adminUser->setTwoFactorSecret($admin2faSecret); } $manager->persist($adminUser); $this->addReference('admin_user', $adminUser); } $manager->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ RoleFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/UserFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
412
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Role; use App\Entity\RolePermission; use App\Entity\Station; use App\Enums\GlobalPermissions; use App\Enums\StationPermissions; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; final class RolePermissionFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { /** @var Station $station */ $station = $this->getReference('station'); $permissions = [ 'admin_role' => [ [GlobalPermissions::All, null], ], 'demo_role' => [ [StationPermissions::View, $station], [StationPermissions::Reports, $station], [StationPermissions::Profile, $station], [StationPermissions::Streamers, $station], [StationPermissions::MountPoints, $station], [StationPermissions::RemoteRelays, $station], [StationPermissions::Media, $station], [StationPermissions::Automation, $station], ], ]; foreach ($permissions as $roleReference => $permNames) { /** @var Role $role */ $role = $this->getReference($roleReference); foreach ($permNames as $permName) { $rp = new RolePermission($role, $permName[1], $permName[0]); $manager->persist($rp); } } $manager->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ RoleFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/RolePermissionFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
364
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Podcast; use App\Entity\PodcastCategory; use App\Entity\Station; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; final class PodcastFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager): void { /** @var Station $station */ $station = $this->getReference('station'); $podcastStorage = $station->getPodcastsStorageLocation(); $podcast = new Podcast($podcastStorage); $podcast->setTitle('The AzuraTest Podcast'); $podcast->setLink('path_to_url $podcast->setLanguage('en'); $podcast->setDescription('The unofficial testing podcast for the AzuraCast development team.'); $podcast->setAuthor('AzuraCast'); $podcast->setEmail('demo@azuracast.com'); $manager->persist($podcast); $category = new PodcastCategory($podcast, 'Technology'); $manager->persist($category); $manager->flush(); $this->setReference('podcast', $podcast); } /** * @return string[] */ public function getDependencies(): array { return [ StationFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/PodcastFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
306
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Podcast; use App\Entity\PodcastEpisode; use App\Entity\Repository\PodcastEpisodeRepository; use App\Entity\Repository\StorageLocationRepository; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; use Symfony\Component\Finder\Finder; final class PodcastEpisodeFixture extends AbstractFixture implements DependentFixtureInterface { public function __construct( protected PodcastEpisodeRepository $episodeRepo, protected StorageLocationRepository $storageLocationRepo ) { } public function load(ObjectManager $manager): void { $podcastsSkeletonDir = getenv('INIT_PODCASTS_PATH'); if (empty($podcastsSkeletonDir) || !is_dir($podcastsSkeletonDir)) { return; } /** @var Podcast $podcast */ $podcast = $this->getReference('podcast'); $fs = $this->storageLocationRepo->getAdapter($podcast->getStorageLocation()) ->getFilesystem(); $finder = (new Finder()) ->files() ->in($podcastsSkeletonDir) ->name('/^.+\.(mp3|aac|ogg|flac)$/i'); $i = 1; $podcastNames = [ 'Attack of the %s', 'Introducing: %s!', 'Rants About %s', 'The %s Where Everyone Yells', '%s? It\'s AzuraCastastic!', ]; $podcastFillers = [ 'Content', 'Unicorn Login Screen', 'Default Error Message', ]; foreach ($finder as $file) { $filePath = $file->getPathname(); $fileBaseName = basename($filePath); $tempPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileBaseName; copy($filePath, $tempPath); // Create an episode and associate it with the podcast/media. $episode = new PodcastEpisode($podcast); /** @noinspection NonSecureArrayRandUsageInspection */ $podcastName = $podcastNames[array_rand($podcastNames)]; /** @noinspection NonSecureArrayRandUsageInspection */ $podcastFiller = $podcastFillers[array_rand($podcastFillers)]; $episode->setTitle('Episode ' . $i . ': ' . sprintf($podcastName, $podcastFiller)); $episode->setDescription('Another great episode!'); $episode->setExplicit(false); $manager->persist($episode); $manager->flush(); $this->episodeRepo->uploadMedia( $episode, $fileBaseName, $tempPath, $fs ); $i++; } } /** * @return string[] */ public function getDependencies(): array { return [ PodcastFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/PodcastEpisodeFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
635
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Repository\StorageLocationRepository; use App\Entity\Station; use App\Entity\StationPlaylist; use App\Entity\StationPlaylistMedia; use App\Media\MediaProcessor; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; use Symfony\Component\Finder\Finder; final class StationMediaFixture extends AbstractFixture implements DependentFixtureInterface { public function __construct( private readonly MediaProcessor $mediaProcessor, private readonly StorageLocationRepository $storageLocationRepo, ) { } public function load(ObjectManager $manager): void { $musicSkeletonDir = getenv('INIT_MUSIC_PATH'); if (empty($musicSkeletonDir) || !is_dir($musicSkeletonDir)) { return; } /** @var Station $station */ $station = $this->getReference('station'); $mediaStorage = $station->getMediaStorageLocation(); $fs = $this->storageLocationRepo->getAdapter($mediaStorage)->getFilesystem(); /** @var StationPlaylist $playlist */ $playlist = $this->getReference('station_playlist'); $finder = (new Finder()) ->files() ->in($musicSkeletonDir) ->name('/^.+\.(mp3|aac|ogg|flac)$/i'); foreach ($finder as $file) { $filePath = $file->getPathname(); $fileBaseName = basename($filePath); // Copy the file to the station media directory. $fs->upload($filePath, '/' . $fileBaseName); $mediaRow = $this->mediaProcessor->process($mediaStorage, $fileBaseName); if (null === $mediaRow) { continue; } $manager->persist($mediaRow); // Add the file to the playlist. $spmRow = new StationPlaylistMedia($playlist, $mediaRow); $spmRow->setWeight(1); $manager->persist($spmRow); } $manager->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ StationFixture::class, StationPlaylistFixture::class, ]; } } ```
/content/code_sandbox/backend/src/Entity/Fixture/StationMediaFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
491
```php <?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity\Enums\AnalyticsLevel; use App\Entity\Settings; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Persistence\ObjectManager; final class SettingsFixture extends AbstractFixture { public function load(ObjectManager $manager): void { foreach ($manager->getRepository(Settings::class)->findAll() as $row) { $manager->remove($row); } $settings = new Settings(); $settings->setBaseUrl((string)(getenv('INIT_BASE_URL') ?: 'path_to_url $settings->setInstanceName((string)(getenv('INIT_INSTANCE_NAME') ?: 'local test')); $settings->setSetupCompleteTime(time()); $settings->setPreferBrowserUrl(true); $settings->setUseRadioProxy(true); $settings->setCheckForUpdates(true); $settings->setExternalIp('127.0.0.1'); $settings->setEnableAdvancedFeatures(true); $settings->setEnableStaticNowPlaying(true); if (!empty(getenv('INIT_DEMO_API_KEY') ?: '')) { $settings->setAnalytics(AnalyticsLevel::NoIp); $settings->setCheckForUpdates(false); $settings->setPublicCustomJs( <<<'JS' (() => { document.addEventListener('vue-ready', () => { var form = document.getElementById('login-form'); if (form) { document.querySelector('input[name="username"]').value = 'demo@azuracast.com'; document.querySelector('input[name="password"]').value = 'demo'; } }); })(); JS ); } $manager->persist($settings); $manager->flush(); } } ```
/content/code_sandbox/backend/src/Entity/Fixture/SettingsFixture.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
372
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum PlaylistSources: string { case Songs = 'songs'; case RemoteUrl = 'remote_url'; } ```
/content/code_sandbox/backend/src/Entity/Enums/PlaylistSources.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\Entity\Enums; enum PlaylistOrders: string { case Random = 'random'; case Shuffle = 'shuffle'; case Sequential = 'sequential'; } ```
/content/code_sandbox/backend/src/Entity/Enums/PlaylistOrders.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
45
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum PlaylistRemoteTypes: string { case Stream = 'stream'; case Playlist = 'playlist'; case Other = 'other'; } ```
/content/code_sandbox/backend/src/Entity/Enums/PlaylistRemoteTypes.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
46
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum StorageLocationTypes: string { case Backup = 'backup'; case StationMedia = 'station_media'; case StationRecordings = 'station_recordings'; case StationPodcasts = 'station_podcasts'; } ```
/content/code_sandbox/backend/src/Entity/Enums/StorageLocationTypes.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
63
```php <?php declare(strict_types=1); namespace App\Entity\Enums; use OpenApi\Attributes as OA; #[OA\Schema(type: 'string')] enum FileTypes: string { case Directory = 'directory'; case Media = 'media'; case CoverArt = 'cover_art'; case UnprocessableFile = 'unprocessable_file'; case Other = 'other'; } ```
/content/code_sandbox/backend/src/Entity/Enums/FileTypes.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
80
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum AuditLogOperations: int { case Insert = 1; case Update = 2; case Delete = 3; public function getName(): string { return match ($this) { self::Update => 'update', self::Delete => 'delete', self::Insert => 'insert' }; } } ```
/content/code_sandbox/backend/src/Entity/Enums/AuditLogOperations.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
90
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum AnalyticsIntervals: string { case Daily = 'day'; case Hourly = 'hour'; } ```
/content/code_sandbox/backend/src/Entity/Enums/AnalyticsIntervals.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\Entity\Enums; use App\Entity\StorageLocationAdapter\DropboxStorageLocationAdapter; use App\Entity\StorageLocationAdapter\LocalStorageLocationAdapter; use App\Entity\StorageLocationAdapter\S3StorageLocationAdapter; use App\Entity\StorageLocationAdapter\SftpStorageLocationAdapter; use App\Entity\StorageLocationAdapter\StorageLocationAdapterInterface; enum StorageLocationAdapters: string { case Local = 'local'; case S3 = 's3'; case Dropbox = 'dropbox'; case Sftp = 'sftp'; public function isLocal(): bool { return self::Local === $this; } public function getName(): string { return match ($this) { self::Local => 'Local', self::S3 => 'S3', self::Dropbox => 'Dropbox', self::Sftp => 'SFTP', }; } /** * @return class-string<StorageLocationAdapterInterface> */ public function getAdapterClass(): string { return match ($this) { self::Local => LocalStorageLocationAdapter::class, self::S3 => S3StorageLocationAdapter::class, self::Dropbox => DropboxStorageLocationAdapter::class, self::Sftp => SftpStorageLocationAdapter::class }; } } ```
/content/code_sandbox/backend/src/Entity/Enums/StorageLocationAdapters.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
288
```php <?php declare(strict_types=1); namespace App\Entity\Enums; use Psr\Http\Message\ServerRequestInterface; use RuntimeException; enum IpSources: string { case Local = 'local'; case XForwardedFor = 'xff'; case Cloudflare = 'cloudflare'; public static function default(): self { return self::Local; } public function getIp(ServerRequestInterface $request): string { if (self::Cloudflare === $this) { $ip = $request->getHeaderLine('CF-Connecting-IP'); if (!empty($ip)) { return $this->parseIp($ip); } } if (self::XForwardedFor === $this) { $ip = $request->getHeaderLine('X-Forwarded-For'); if (!empty($ip)) { return $this->parseIp($ip); } } $serverParams = $request->getServerParams(); $ip = $serverParams['REMOTE_ADDR'] ?? null; if (empty($ip)) { throw new RuntimeException('No IP address attached to this request.'); } return $this->parseIp($ip); } private function parseIp(string $ip): string { // Handle the IP being separated by commas. if (str_contains($ip, ',')) { $ipParts = explode(',', $ip); $ip = array_shift($ipParts); } return trim($ip); } } ```
/content/code_sandbox/backend/src/Entity/Enums/IpSources.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
325
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum PlaylistTypes: string { case Standard = 'default'; case OncePerXSongs = 'once_per_x_songs'; case OncePerXMinutes = 'once_per_x_minutes'; case OncePerHour = 'once_per_hour'; case Advanced = 'custom'; public static function default(): self { return self::Standard; } } ```
/content/code_sandbox/backend/src/Entity/Enums/PlaylistTypes.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
94
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum StationBackendPerformanceModes: string { case LessMemory = 'less_memory'; case LessCpu = 'less_cpu'; case Balanced = 'balanced'; case Disabled = 'disabled'; public static function default(): self { return self::Disabled; } } ```
/content/code_sandbox/backend/src/Entity/Enums/StationBackendPerformanceModes.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
77
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum AnalyticsLevel: string { case All = 'all'; // Log all analytics data across the system. case NoIp = 'no_ip'; // Suppress any IP-based logging and use aggregate logging only. case None = 'none'; // No analytics data collected of any sort. public static function default(): self { return self::All; } } ```
/content/code_sandbox/backend/src/Entity/Enums/AnalyticsLevel.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
95
```php <?php declare(strict_types=1); namespace App\Entity\Enums; enum PodcastSources: string { case Manual = 'manual'; case Playlist = 'playlist'; } ```
/content/code_sandbox/backend/src/Entity/Enums/PodcastSources.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
38
```php <?php declare(strict_types=1); namespace App\Entity\StorageLocationAdapter; use App\Entity\Enums\StorageLocationAdapters; use App\Flysystem\Adapter\ExtendedAdapterInterface; use App\Flysystem\Adapter\SftpAdapter; use League\Flysystem\PhpseclibV3\SftpConnectionProvider; final class SftpStorageLocationAdapter extends AbstractStorageLocationLocationAdapter { public function getType(): StorageLocationAdapters { return StorageLocationAdapters::Sftp; } public function getStorageAdapter(): ExtendedAdapterInterface { $filteredPath = self::filterPath($this->storageLocation->getPath()); return new SftpAdapter($this->getSftpConnectionProvider(), $filteredPath); } private function getSftpConnectionProvider(): SftpConnectionProvider { return new SftpConnectionProvider( $this->storageLocation->getSftpHost() ?? '', $this->storageLocation->getSftpUsername() ?? '', $this->storageLocation->getSftpPassword(), $this->storageLocation->getSftpPrivateKey(), $this->storageLocation->getSftpPrivateKeyPassPhrase(), $this->storageLocation->getSftpPort() ?? 22 ); } } ```
/content/code_sandbox/backend/src/Entity/StorageLocationAdapter/SftpStorageLocationAdapter.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
266
```php <?php declare(strict_types=1); namespace App\Entity\StorageLocationAdapter; use App\Entity\Enums\StorageLocationAdapters; use App\Entity\StorageLocation; use App\Flysystem\Adapter\ExtendedAdapterInterface; use App\Flysystem\ExtendedFilesystemInterface; interface StorageLocationAdapterInterface { public function withStorageLocation(StorageLocation $storageLocation): static; public function getType(): StorageLocationAdapters; public function getStorageAdapter(): ExtendedAdapterInterface; public function getFilesystem(): ExtendedFilesystemInterface; public function validate(): void; public static function filterPath(string $path): string; public static function getUri(StorageLocation $storageLocation, ?string $suffix = null): string; } ```
/content/code_sandbox/backend/src/Entity/StorageLocationAdapter/StorageLocationAdapterInterface.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\Entity\StorageLocationAdapter; use App\Entity\Enums\StorageLocationAdapters; use App\Entity\StorageLocation; use App\Flysystem\Adapter\AwsS3Adapter; use App\Flysystem\Adapter\ExtendedAdapterInterface; use Aws\S3\S3Client; use RuntimeException; final class S3StorageLocationAdapter extends AbstractStorageLocationLocationAdapter { public function getType(): StorageLocationAdapters { return StorageLocationAdapters::S3; } public static function filterPath(string $path): string { return trim($path, '/'); } public function getStorageAdapter(): ExtendedAdapterInterface { $filteredPath = self::filterPath($this->storageLocation->getPath()); $bucket = $this->storageLocation->getS3Bucket(); if (null === $bucket) { throw new RuntimeException('Amazon S3 bucket is empty.'); } return new AwsS3Adapter($this->getClient(), $bucket, $filteredPath); } public function validate(): void { $client = $this->getClient(); $client->listObjectsV2( [ 'Bucket' => $this->storageLocation->getS3Bucket(), 'max-keys' => 1, ] ); parent::validate(); } private function getClient(): S3Client { $s3Options = array_filter( [ 'credentials' => [ 'key' => $this->storageLocation->getS3CredentialKey(), 'secret' => $this->storageLocation->getS3CredentialSecret(), ], 'region' => $this->storageLocation->getS3Region(), 'version' => $this->storageLocation->getS3Version(), 'endpoint' => $this->storageLocation->getS3Endpoint(), 'use_path_style_endpoint' => $this->storageLocation->getS3UsePathStyle(), 'options' => [ 'ACL' => '', ], ] ); return new S3Client($s3Options); } public static function getUri(StorageLocation $storageLocation, ?string $suffix = null): string { $path = self::applyPath($storageLocation->getPath(), $suffix); return 's3://' . $storageLocation->getS3Bucket() . '/' . ltrim($path, '/'); } } ```
/content/code_sandbox/backend/src/Entity/StorageLocationAdapter/S3StorageLocationAdapter.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
518
```php <?php declare(strict_types=1); namespace App\Entity\StorageLocationAdapter; use App\Container\EnvironmentAwareTrait; use App\Entity\Enums\StorageLocationAdapters; use App\Flysystem\Adapter\LocalAdapterInterface; use App\Flysystem\Adapter\LocalFilesystemAdapter; use App\Flysystem\ExtendedFilesystemInterface; use App\Flysystem\LocalFilesystem; use InvalidArgumentException; use Symfony\Component\Filesystem\Path; final class LocalStorageLocationAdapter extends AbstractStorageLocationLocationAdapter { use EnvironmentAwareTrait; public function getType(): StorageLocationAdapters { return StorageLocationAdapters::Local; } public function getStorageAdapter(): LocalAdapterInterface { $filteredPath = self::filterPath($this->storageLocation->getPath()); return new LocalFilesystemAdapter($filteredPath); } public function getFilesystem(): ExtendedFilesystemInterface { return new LocalFilesystem($this->getStorageAdapter()); } public function validate(): void { // Check that there is any overlap between the specified path and the docroot. $path = $this->storageLocation->getPath(); $baseDir = $this->environment->getBaseDirectory(); if (Path::isBasePath($baseDir, $path)) { throw new InvalidArgumentException('Directory is within the web root.'); } if (Path::isBasePath($path, $baseDir)) { throw new InvalidArgumentException('Directory is a parent directory of the web root.'); } parent::validate(); } } ```
/content/code_sandbox/backend/src/Entity/StorageLocationAdapter/LocalStorageLocationAdapter.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
329
```php <?php declare(strict_types=1); namespace App\Entity\StorageLocationAdapter; use App\Entity\StorageLocation; use App\Flysystem\ExtendedFilesystemInterface; use App\Flysystem\RemoteFilesystem; use InvalidArgumentException; abstract class AbstractStorageLocationLocationAdapter implements StorageLocationAdapterInterface { protected StorageLocation $storageLocation; public function withStorageLocation(StorageLocation $storageLocation): static { $clone = clone $this; $clone->setStorageLocation($storageLocation); return $clone; } protected function setStorageLocation(StorageLocation $storageLocation): void { if ($this->getType() !== $storageLocation->getAdapter()) { throw new InvalidArgumentException('This storage location is not using the specified adapter.'); } $this->storageLocation = $storageLocation; } public function getFilesystem(): ExtendedFilesystemInterface { return new RemoteFilesystem($this->getStorageAdapter()); } public function validate(): void { $adapter = $this->getStorageAdapter(); $adapter->fileExists('/test'); } public static function filterPath(string $path): string { return rtrim($path, '/'); } public static function getUri( StorageLocation $storageLocation, ?string $suffix = null ): string { return self::applyPath($storageLocation->getPath(), $suffix); } protected static function applyPath( string $path, ?string $suffix = null ): string { $suffix = (null !== $suffix) ? '/' . ltrim($suffix, '/') : ''; return $path . $suffix; } } ```
/content/code_sandbox/backend/src/Entity/StorageLocationAdapter/AbstractStorageLocationLocationAdapter.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
358
```php <?php declare(strict_types=1); namespace App\Entity\StorageLocationAdapter; use App\Entity\Enums\StorageLocationAdapters; use App\Entity\StorageLocation; use App\Flysystem\Adapter\DropboxAdapter; use App\Flysystem\Adapter\ExtendedAdapterInterface; use App\Service\Dropbox\OAuthAdapter; use Spatie\Dropbox\Client; final class DropboxStorageLocationAdapter extends AbstractStorageLocationLocationAdapter { public function __construct( private readonly OAuthAdapter $oauthAdapter ) { } public function getType(): StorageLocationAdapters { return StorageLocationAdapters::Dropbox; } public function getStorageAdapter(): ExtendedAdapterInterface { $filteredPath = self::filterPath($this->storageLocation->getPath()); return new DropboxAdapter($this->getClient(), $filteredPath); } private function getClient(): Client { return new Client($this->oauthAdapter->withStorageLocation($this->storageLocation)); } public function validate(): void { $adapter = $this->oauthAdapter->withStorageLocation($this->storageLocation); $adapter->setup(); parent::validate(); } public static function filterPath(string $path): string { return trim($path, '/'); } public static function getUri(StorageLocation $storageLocation, ?string $suffix = null): string { $path = self::applyPath($storageLocation->getPath(), $suffix); $token = (!empty($storageLocation->getDropboxAuthToken())) ? $storageLocation->getDropboxAuthToken() : $storageLocation->getDropboxRefreshToken(); $token = substr(md5($token ?? ''), 0, 10); return 'dropbox://' . $token . '/' . ltrim($path, '/'); } } ```
/content/code_sandbox/backend/src/Entity/StorageLocationAdapter/DropboxStorageLocationAdapter.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\Entity\Repository; use App\Doctrine\Repository; use App\Entity\CustomField; use App\Entity\Station; use App\Entity\StationMedia; use App\Entity\StationMediaCustomField; /** * @extends Repository<CustomField> */ final class CustomFieldRepository extends Repository { protected string $entityClass = CustomField::class; /** * @return CustomField[] */ public function getAutoAssignableFields(): array { $fields = []; foreach ($this->repository->findAll() as $field) { /** @var CustomField $field */ if (!$field->hasAutoAssign()) { continue; } $fields[$field->getAutoAssign()] = $field; } return $fields; } /** * @return string[] */ public function getFieldIds(): array { static $fields; if (!isset($fields)) { $fields = []; $fieldsRaw = $this->em->createQuery( <<<'DQL' SELECT cf.id, cf.name, cf.short_name FROM App\Entity\CustomField cf ORDER BY cf.name ASC DQL )->getArrayResult(); foreach ($fieldsRaw as $row) { $fields[$row['id']] = $row['short_name'] ?? Station::generateShortName($row['name']); } } return $fields; } /** * Retrieve a key-value representation of all custom metadata for the specified media. * * @param StationMedia $media * * @return mixed[] */ public function getCustomFields(StationMedia $media): array { $metadataRaw = $this->em->createQuery( <<<'DQL' SELECT cf.short_name, e.value FROM App\Entity\StationMediaCustomField e JOIN e.field cf WHERE e.media_id = :media_id DQL )->setParameter('media_id', $media->getId()) ->getArrayResult(); return array_column($metadataRaw, 'value', 'short_name'); } /** * Set the custom metadata for a specified station based on a provided key-value array. * * @param StationMedia $media * @param array $customFields */ public function setCustomFields(StationMedia $media, array $customFields): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationMediaCustomField e WHERE e.media_id = :media_id DQL )->setParameter('media_id', $media->getId()) ->execute(); foreach ($customFields as $fieldId => $fieldValue) { $field = is_numeric($fieldId) ? $this->em->find(CustomField::class, $fieldId) : $this->em->getRepository(CustomField::class)->findOneBy(['short_name' => $fieldId]); if ($field instanceof CustomField) { $record = new StationMediaCustomField($media, $field); $record->setValue($fieldValue); $this->em->persist($record); } } $this->em->flush(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/CustomFieldRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
699
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Station; use App\Entity\StationMount; use App\Flysystem\ExtendedFilesystemInterface; use App\Flysystem\StationFilesystems; use App\Service\Flow\UploadedFile; /** * @extends AbstractStationBasedRepository<StationMount> */ final class StationMountRepository extends AbstractStationBasedRepository { protected string $entityClass = StationMount::class; public function setIntro( StationMount $mount, UploadedFile $file, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= StationFilesystems::buildConfigFilesystem($mount->getStation()); if (!empty($mount->getIntroPath())) { $this->doDeleteIntro($mount, $fs); $mount->setIntroPath(null); } $originalPath = $file->getClientFilename(); $originalExt = pathinfo($originalPath, PATHINFO_EXTENSION); $introPath = 'mount_' . $mount->getIdRequired() . '_intro.' . $originalExt; $fs->uploadAndDeleteOriginal($file->getUploadedPath(), $introPath); $mount->setIntroPath($introPath); $this->em->persist($mount); $this->em->flush(); } private function doDeleteIntro( StationMount $mount, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= StationFilesystems::buildConfigFilesystem($mount->getStation()); $introPath = $mount->getIntroPath(); if (empty($introPath)) { return; } $fs->delete($introPath); } public function clearIntro( StationMount $mount, ?ExtendedFilesystemInterface $fs = null ): void { $this->doDeleteIntro($mount, $fs); $mount->setIntroPath(null); $this->em->persist($mount); $this->em->flush(); } public function destroy( StationMount $mount ): void { $this->doDeleteIntro($mount); $this->em->remove($mount); $this->em->flush(); } /** * @param Station $station * * @return mixed[] */ public function getDisplayNames(Station $station): array { $mounts = $this->repository->findBy(['station' => $station]); $displayNames = []; /** @var StationMount $mount */ foreach ($mounts as $mount) { $displayNames[$mount->getId()] = $mount->getDisplayName(); } return $displayNames; } public function getDefaultMount(Station $station): ?StationMount { $mount = $this->repository->findOneBy(['station_id' => $station->getId(), 'is_default' => true]); if ($mount instanceof StationMount) { return $mount; } // Use the first mount if none is specified as default. $mount = $station->getMounts()->first(); if ($mount instanceof StationMount) { $mount->setIsDefault(true); $this->em->persist($mount); $this->em->flush(); return $mount; } return null; } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationMountRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
721
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Container\LoggerAwareTrait; use App\Doctrine\Repository; use App\Entity\Song; use App\Entity\Station; use App\Entity\StationMedia; use App\Entity\StationMediaCustomField; use App\Entity\StorageLocation; use App\Exception\NotFoundException; use App\Flysystem\ExtendedFilesystemInterface; use App\Media\AlbumArt; use App\Media\MetadataManager; use App\Media\RemoteAlbumArt; use App\Service\AudioWaveform; use Exception; use Generator; use League\Flysystem\FilesystemException; use const JSON_PRETTY_PRINT; use const JSON_THROW_ON_ERROR; use const JSON_UNESCAPED_SLASHES; /** * @extends Repository<StationMedia> */ final class StationMediaRepository extends Repository { use LoggerAwareTrait; protected string $entityClass = StationMedia::class; public function __construct( private readonly MetadataManager $metadataManager, private readonly RemoteAlbumArt $remoteAlbumArt, private readonly CustomFieldRepository $customFieldRepo, private readonly StationPlaylistMediaRepository $spmRepo, private readonly StorageLocationRepository $storageLocationRepo, ) { } public function findForStation(int|string $id, Station $station): ?StationMedia { if (!is_numeric($id) && StationMedia::UNIQUE_ID_LENGTH === strlen($id)) { $media = $this->findByUniqueId($id, $station); if ($media instanceof StationMedia) { return $media; } } $storageLocation = $this->getStorageLocation($station); /** @var StationMedia|null $media */ $media = $this->repository->findOneBy( [ 'storage_location' => $storageLocation, 'id' => $id, ] ); return $media; } public function requireForStation(int|string $id, Station $station): StationMedia { $record = $this->findForStation($id, $station); if (null === $record) { throw NotFoundException::generic(); } return $record; } /** * @param string $path * @param Station|StorageLocation $source * */ public function findByPath( string $path, Station|StorageLocation $source ): ?StationMedia { $storageLocation = $this->getStorageLocation($source); /** @var StationMedia|null $media */ $media = $this->repository->findOneBy( [ 'storage_location' => $storageLocation, 'path' => $path, ] ); return $media; } public function iteratePaths(array $paths, Station|StorageLocation $source): Generator { $storageLocation = $this->getStorageLocation($source); foreach ($paths as $path) { $media = $this->findByPath($path, $storageLocation); if ($media instanceof StationMedia) { yield $path => $media; } } } /** * @param string $uniqueId * @param Station|StorageLocation $source * */ public function findByUniqueId( string $uniqueId, Station|StorageLocation $source ): ?StationMedia { $storageLocation = $this->getStorageLocation($source); /** @var StationMedia|null $media */ $media = $this->repository->findOneBy( [ 'storage_location' => $storageLocation, 'unique_id' => $uniqueId, ] ); return $media; } public function requireByUniqueId( string $uniqueId, Station|StorageLocation $source ): StationMedia { $record = $this->findByUniqueId($uniqueId, $source); if (null === $record) { throw NotFoundException::generic(); } return $record; } private function getStorageLocation(Station|StorageLocation $source): StorageLocation { if ($source instanceof Station) { return $source->getMediaStorageLocation(); } return $source; } /** * Process metadata information from media file. * * @param StationMedia $media * @param string $filePath * @param ExtendedFilesystemInterface|null $fs */ public function loadFromFile( StationMedia $media, string $filePath, ?ExtendedFilesystemInterface $fs = null ): void { // Load metadata from supported files. $metadata = $this->metadataManager->read($filePath); $media->fromMetadata($metadata); // Persist the media record for later custom field operations. $this->em->persist($media); // Clear existing auto-assigned custom fields. $fieldCollection = $media->getCustomFields(); foreach ($fieldCollection as $existingCustomField) { /** @var StationMediaCustomField $existingCustomField */ if ($existingCustomField->getField()->hasAutoAssign()) { $this->em->remove($existingCustomField); $fieldCollection->removeElement($existingCustomField); } } $customFieldsToSet = $this->customFieldRepo->getAutoAssignableFields(); $tags = $metadata->getKnownTags(); foreach ($customFieldsToSet as $tag => $customFieldKey) { if (!empty($tags[$tag])) { $customFieldRow = new StationMediaCustomField($media, $customFieldKey); $customFieldRow->setValue($tags[$tag]); $this->em->persist($customFieldRow); $fieldCollection->add($customFieldRow); } } $artwork = $metadata->getArtwork(); if (empty($artwork) && $this->remoteAlbumArt->enableForMedia()) { $artwork = $this->remoteAlbumArt->getArtwork($media); } if (!empty($artwork)) { try { $this->writeAlbumArt($media, $artwork, $fs); } catch (Exception $exception) { $this->logger->error( sprintf( 'Album Artwork for "%s" could not be processed: "%s"', $filePath, $exception->getMessage() ), $exception->getTrace() ); } } // Attempt to derive title and artist from filename. $artist = $media->getArtist(); $title = $media->getTitle(); if (null === $artist || null === $title) { $filename = pathinfo($media->getPath(), PATHINFO_FILENAME); $filename = str_replace('_', ' ', $filename); $songObj = Song::createFromText($filename); $media->setSong($songObj); } // Force a text property to auto-generate from artist/title $media->setText($media->getText()); // Generate a song_id hash based on the track $media->updateSongId(); } public function updateAlbumArt( StationMedia $media, string $rawArtString ): bool { $fs = $this->getFilesystem($media); $this->writeAlbumArt($media, $rawArtString, $fs); return $this->writeToFile($media, $fs); } public function writeAlbumArt( StationMedia $media, string $rawArtString, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= $this->getFilesystem($media); $media->setArtUpdatedAt(time()); $this->em->persist($media); $albumArtPath = StationMedia::getArtPath($media->getUniqueId()); $albumArtString = AlbumArt::resize($rawArtString); $fs->write($albumArtPath, $albumArtString); } public function removeAlbumArt( StationMedia $media, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= $this->getFilesystem($media); $currentAlbumArtPath = StationMedia::getArtPath($media->getUniqueId()); $fs->delete($currentAlbumArtPath); $media->setArtUpdatedAt(0); $this->em->persist($media); $this->em->flush(); $this->writeToFile($media, $fs); } public function writeToFile( StationMedia $media, ?ExtendedFilesystemInterface $fs = null ): bool { $fs ??= $this->getFilesystem($media); $metadata = $media->toMetadata(); $artPath = StationMedia::getArtPath($media->getUniqueId()); if ($fs->fileExists($artPath)) { $metadata->setArtwork($fs->read($artPath)); } // Write tags to the Media file. $media->setMtime(time() + 5); $media->updateSongId(); return $fs->withLocalFile( $media->getPath(), function ($path) use ($metadata) { $this->metadataManager->write($metadata, $path); return true; } ); } public function updateWaveform( StationMedia $media, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= $this->getFilesystem($media); $fs->withLocalFile( $media->getPath(), function ($path) use ($media, $fs): void { $this->writeWaveform($media, $path, $fs); } ); } public function writeWaveform( StationMedia $media, string $path, ?ExtendedFilesystemInterface $fs = null ): void { $waveformData = AudioWaveform::getWaveformFor($path); $this->saveWaveformData($media, $waveformData, $fs); } public function saveWaveformData( StationMedia $media, array $waveformData, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= $this->getFilesystem($media); $waveformPath = StationMedia::getWaveformPath($media->getUniqueId()); $fs->write( $waveformPath, json_encode( $waveformData, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR | JSON_PARTIAL_OUTPUT_ON_ERROR ) ); } /** * @param StationMedia $media * @param bool $deleteFile Whether to remove the media file itself (disabled for batch operations). * @param ExtendedFilesystemInterface|null $fs * * @return array<int, int> Affected playlist records (id => id) */ public function remove( StationMedia $media, bool $deleteFile = false, ?ExtendedFilesystemInterface $fs = null ): array { $fs ??= $this->getFilesystem($media); // Clear related media. foreach ($media->getRelatedFilePaths() as $relatedFilePath) { try { $fs->delete($relatedFilePath); } catch (FilesystemException) { // Skip } } if ($deleteFile) { try { $fs->delete($media->getPath()); } catch (FilesystemException) { // Skip } } $affectedPlaylists = $this->spmRepo->clearPlaylistsFromMedia($media); $this->em->remove($media); $this->em->flush(); return $affectedPlaylists; } private function getFilesystem(StationMedia $media): ExtendedFilesystemInterface { return $this->storageLocationRepo->getAdapter($media->getStorageLocation()) ->getFilesystem(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationMediaRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,551
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Station; use App\Entity\StationStreamer; use App\Entity\StationStreamerBroadcast; use App\Flysystem\StationFilesystems; use App\Media\AlbumArt; use App\Radio\AutoDJ\Scheduler; /** * @extends AbstractStationBasedRepository<StationStreamer> */ final class StationStreamerRepository extends AbstractStationBasedRepository { protected string $entityClass = StationStreamer::class; public function __construct( private readonly Scheduler $scheduler, private readonly StationStreamerBroadcastRepository $broadcastRepo ) { } /** * Attempt to authenticate a streamer. * * @param Station $station * @param string $username * @param string $password */ public function authenticate( Station $station, string $username = '', string $password = '' ): bool { // Extra safety check for the station's streamer status. if (!$station->getEnableStreamers()) { return false; } $streamer = $this->getStreamer($station, $username); if (!($streamer instanceof StationStreamer)) { return false; } return $streamer->authenticate($password) && $this->scheduler->canStreamerStreamNow($streamer); } /** * @param Station $station * @param string $username * */ public function onConnect(Station $station, string $username = ''): string|bool { // End all current streamer sessions. $this->broadcastRepo->endAllActiveBroadcasts($station); $streamer = $this->getStreamer($station, $username); if (!($streamer instanceof StationStreamer)) { return false; } $station->setIsStreamerLive(true); $station->setCurrentStreamer($streamer); $this->em->persist($station); $record = new StationStreamerBroadcast($streamer); $this->em->persist($record); $this->em->flush(); return true; } public function onDisconnect(Station $station): bool { foreach ($this->broadcastRepo->getActiveBroadcasts($station) as $broadcast) { $broadcast->setTimestampEnd(time()); $this->em->persist($broadcast); } $station->setIsStreamerLive(false); $station->setCurrentStreamer(null); $this->em->persist($station); $this->em->flush(); return true; } public function getStreamer( Station $station, string $username = '', bool $activeOnly = true ): ?StationStreamer { $criteria = [ 'station' => $station, 'streamer_username' => $username, ]; if ($activeOnly) { $criteria['is_active'] = 1; } /** @var StationStreamer|null $streamer */ $streamer = $this->repository->findOneBy($criteria); return $streamer; } public function writeArtwork( StationStreamer $streamer, string $rawArtworkString ): void { $artworkPath = StationStreamer::getArtworkPath($streamer->getIdRequired()); $artworkString = AlbumArt::resize($rawArtworkString); $fsConfig = StationFilesystems::buildConfigFilesystem($streamer->getStation()); $fsConfig->write($artworkPath, $artworkString); $streamer->setArtUpdatedAt(time()); $this->em->persist($streamer); } public function removeArtwork( StationStreamer $streamer ): void { $artworkPath = StationStreamer::getArtworkPath($streamer->getIdRequired()); $fsConfig = StationFilesystems::buildConfigFilesystem($streamer->getStation()); $fsConfig->delete($artworkPath); $streamer->setArtUpdatedAt(0); $this->em->persist($streamer); } public function delete( StationStreamer $streamer ): void { $this->removeArtwork($streamer); $this->em->remove($streamer); $this->em->flush(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationStreamerRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
921
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Container\LoggerAwareTrait; use App\Doctrine\ReloadableEntityManagerInterface; use App\Doctrine\Repository; use App\Entity\Listener; use App\Entity\Station; use App\Entity\Traits\TruncateStrings; use App\Service\DeviceDetector; use App\Service\IpGeolocation; use App\Utilities\File; use Carbon\CarbonImmutable; use DateTimeInterface; use DI\Attribute\Inject; use Doctrine\DBAL\Connection; use League\Csv\Writer; use NowPlaying\Result\Client; use Symfony\Component\Filesystem\Filesystem; use Throwable; /** * @extends Repository<Listener> */ final class ListenerRepository extends Repository { use LoggerAwareTrait; use TruncateStrings; protected string $entityClass = Listener::class; private string $tableName; private Connection $conn; public function __construct( private readonly DeviceDetector $deviceDetector, private readonly IpGeolocation $ipGeolocation ) { } #[Inject] public function setEntityManager(ReloadableEntityManagerInterface $em): void { parent::setEntityManager($em); $this->tableName = $this->em->getClassMetadata(Listener::class)->getTableName(); $this->conn = $this->em->getConnection(); } /** * Get the number of unique listeners for a station during a specified time period. * * @param Station $station * @param DateTimeInterface|int $start * @param DateTimeInterface|int $end */ public function getUniqueListeners( Station $station, DateTimeInterface|int $start, DateTimeInterface|int $end ): int { if ($start instanceof DateTimeInterface) { $start = $start->getTimestamp(); } if ($end instanceof DateTimeInterface) { $end = $end->getTimestamp(); } return (int)$this->em->createQuery( <<<'DQL' SELECT COUNT(DISTINCT l.listener_hash) FROM App\Entity\Listener l WHERE l.station_id = :station_id AND l.timestamp_start <= :time_end AND l.timestamp_end >= :time_start DQL )->setParameter('station_id', $station->getId()) ->setParameter('time_end', $end) ->setParameter('time_start', $start) ->getSingleScalarResult(); } public function iterateLiveListenersArray(Station $station): iterable { $query = $this->em->createQuery( <<<'DQL' SELECT l FROM App\Entity\Listener l WHERE l.station = :station AND l.timestamp_end = 0 ORDER BY l.timestamp_start ASC DQL )->setParameter('station', $station); return $query->toIterable([], $query::HYDRATE_ARRAY); } /** * Update listener data for a station. * * @param Station $station * @param Client[] $clients */ public function update(Station $station, array $clients): void { $this->em->wrapInTransaction( function () use ($station, $clients): void { $existingClientsRaw = $this->em->createQuery( <<<'DQL' SELECT l.id, l.listener_hash FROM App\Entity\Listener l WHERE l.station = :station AND l.timestamp_end = 0 DQL )->setParameter('station', $station); $existingClientsIterator = $existingClientsRaw->toIterable([], $existingClientsRaw::HYDRATE_ARRAY); $existingClients = []; foreach ($existingClientsIterator as $client) { $existingClients[$client['listener_hash']] = $client['id']; } $this->batchAddClients( $station, $clients, $existingClients ); // Mark the end of all other clients on this station. if (!empty($existingClients)) { $this->em->createQuery( <<<'DQL' UPDATE App\Entity\Listener l SET l.timestamp_end = :time WHERE l.id IN (:ids) DQL )->setParameter('time', time()) ->setParameter('ids', array_values($existingClients)) ->execute(); } } ); } private function batchAddClients( Station $station, array &$clients, array &$existingClients ): void { $tempCsvPath = File::generateTempPath('mariadb_listeners.csv'); (new Filesystem())->chmod($tempCsvPath, 0o777); $csv = Writer::createFromPath($tempCsvPath); $csv->setEscape(''); $csv->addFormatter(function ($row) { return array_map(function ($col) { if (null === $col) { return '\N'; } return is_string($col) ? str_replace('"', '""', $col) : $col; }, $row); }); $csvColumns = null; foreach ($clients as $client) { $identifier = Listener::calculateListenerHash($client); // Check for an existing record for this client. if (isset($existingClients[$identifier])) { unset($existingClients[$identifier]); } else { // Create a new record. $record = $this->batchAddRow($station, $client); if (null === $csvColumns) { $csvColumns = array_keys($record); } $csv->insertOne($record); } } if (null === $csvColumns) { @unlink($tempCsvPath); return; } // Use LOAD DATA INFILE for listener dumps $csvLoadQuery = sprintf( <<<'SQL' LOAD DATA LOCAL INFILE %s IGNORE INTO TABLE %s FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' (%s) SQL, $this->conn->quote($tempCsvPath), $this->conn->quoteIdentifier($this->tableName), implode( ',', array_map( fn($col) => $this->conn->quoteIdentifier($col), $csvColumns ) ) ); try { $this->conn->executeQuery($csvLoadQuery); } finally { @unlink($tempCsvPath); } $this->deviceDetector->saveCache(); $this->ipGeolocation->saveCache(); } private function batchAddRow(Station $station, Client $client): array { $record = [ 'station_id' => $station->getId(), 'timestamp_start' => time(), 'timestamp_end' => 0, 'listener_uid' => (int)$client->uid, 'listener_user_agent' => $this->truncateString($client->userAgent ?? ''), 'listener_ip' => $client->ip, 'listener_hash' => Listener::calculateListenerHash($client), 'mount_id' => null, 'remote_id' => null, 'hls_stream_id' => null, 'device_client' => null, 'device_is_browser' => null, 'device_is_mobile' => null, 'device_is_bot' => null, 'device_browser_family' => null, 'device_os_family' => null, 'location_description' => null, 'location_region' => null, 'location_city' => null, 'location_country' => null, 'location_lat' => null, 'location_lon' => null, ]; if (!empty($client->mount)) { [$mountType, $mountId] = explode('_', $client->mount, 2); if ('local' === $mountType) { $record['mount_id'] = (int)$mountId; } elseif ('remote' === $mountType) { $record['remote_id'] = (int)$mountId; } elseif ('hls' === $mountType) { $record['hls_stream_id'] = (int)$mountId; } } $this->batchAddDeviceDetails($record); $this->batchAddLocationDetails($record); return $record; } private function batchAddDeviceDetails(array &$record): void { $userAgent = $record['listener_user_agent']; try { $browserResult = $this->deviceDetector->parse($userAgent); $record['device_client'] = $this->truncateNullableString($browserResult->client); $record['device_is_browser'] = $browserResult->isBrowser ? 1 : 0; $record['device_is_mobile'] = $browserResult->isMobile ? 1 : 0; $record['device_is_bot'] = $browserResult->isBot ? 1 : 0; $record['device_browser_family'] = $this->truncateNullableString($browserResult->browserFamily, 150); $record['device_os_family'] = $this->truncateNullableString($browserResult->osFamily, 150); } catch (Throwable $e) { $this->logger->error('Device Detector error: ' . $e->getMessage(), [ 'user_agent' => $userAgent, 'exception' => $e, ]); } } private function batchAddLocationDetails(array &$record): void { $ip = $record['listener_ip']; try { $ipInfo = $this->ipGeolocation->getLocationInfo($ip); $record['location_description'] = $this->truncateString($ipInfo->description); $record['location_region'] = $this->truncateNullableString($ipInfo->region, 150); $record['location_city'] = $this->truncateNullableString($ipInfo->city, 150); $record['location_country'] = $this->truncateNullableString($ipInfo->country, 2); $record['location_lat'] = $ipInfo->lat; $record['location_lon'] = $ipInfo->lon; } catch (Throwable $e) { $this->logger->error('IP Geolocation error: ' . $e->getMessage(), [ 'ip' => $ip, 'exception' => $e, ]); $record['location_description'] = 'Unknown'; } } public function clearAll(): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\Listener l DQL )->execute(); } public function cleanup(int $daysToKeep): void { $threshold = CarbonImmutable::now() ->subDays($daysToKeep) ->getTimestamp(); $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\Listener sh WHERE sh.timestamp_start != 0 AND sh.timestamp_start <= :threshold DQL )->setParameter('threshold', $threshold) ->execute(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/ListenerRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,387
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Api\StationPlaylistQueue; use App\Entity\Station; use App\Entity\StationMedia; use App\Entity\StationRequest; use App\Radio\AutoDJ; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Exception as PhpException; /** * @extends AbstractStationBasedRepository<StationRequest> */ final class StationRequestRepository extends AbstractStationBasedRepository { protected string $entityClass = StationRequest::class; public function __construct( private readonly AutoDJ\DuplicatePrevention $duplicatePrevention, ) { } public function getPendingRequest(int|string $id, Station $station): ?StationRequest { return $this->repository->findOneBy( [ 'id' => $id, 'station' => $station, 'played_at' => 0, ] ); } public function clearPendingRequests(Station $station): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationRequest sr WHERE sr.station = :station AND sr.played_at = 0 DQL )->setParameter('station', $station) ->execute(); } /** * Check if the song is already enqueued as a request. */ public function isTrackPending(StationMedia $media, Station $station): bool { $pendingRequestThreshold = time() - (60 * 10); try { $pendingRequest = $this->em->createQuery( <<<'DQL' SELECT sr.timestamp FROM App\Entity\StationRequest sr WHERE sr.track_id = :track_id AND sr.station_id = :station_id AND (sr.timestamp >= :threshold OR sr.played_at = 0) ORDER BY sr.timestamp DESC DQL )->setParameter('track_id', $media->getId()) ->setParameter('station_id', $station->getId()) ->setParameter('threshold', $pendingRequestThreshold) ->setMaxResults(1) ->getSingleScalarResult(); } catch (PhpException) { return false; } return ($pendingRequest > 0); } public function getNextPlayableRequest( Station $station, ?CarbonInterface $now = null ): ?StationRequest { $now ??= CarbonImmutable::now($station->getTimezoneObject()); // Look up all requests that have at least waited as long as the threshold. $requests = $this->em->createQuery( <<<'DQL' SELECT sr, sm FROM App\Entity\StationRequest sr JOIN sr.track sm WHERE sr.played_at = 0 AND sr.station = :station ORDER BY sr.skip_delay DESC, sr.id ASC DQL )->setParameter('station', $station) ->execute(); foreach ($requests as $request) { /** @var StationRequest $request */ if ($request->shouldPlayNow($now) && !$this->hasPlayedRecently($request->getTrack(), $station)) { return $request; } } return null; } /** * Check the most recent song history. */ public function hasPlayedRecently(StationMedia $media, Station $station): bool { $lastPlayThresholdMins = ($station->getRequestThreshold() ?? 15); if (0 === $lastPlayThresholdMins) { return false; } $lastPlayThreshold = time() - ($lastPlayThresholdMins * 60); $recentTracks = $this->em->createQuery( <<<'DQL' SELECT sh FROM App\Entity\SongHistory sh WHERE sh.station = :station AND sh.timestamp_start >= :threshold ORDER BY sh.timestamp_start DESC DQL )->setParameter('station', $station) ->setParameter('threshold', $lastPlayThreshold) ->getArrayResult(); $eligibleTrack = new StationPlaylistQueue(); $eligibleTrack->media_id = $media->getIdRequired(); $eligibleTrack->song_id = $media->getSongId(); $eligibleTrack->title = $media->getTitle() ?? ''; $eligibleTrack->artist = $media->getArtist() ?? ''; return (null === $this->duplicatePrevention->getDistinctTrack([$eligibleTrack], $recentTracks)); } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationRequestRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
951
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Station; use App\Entity\StationRemote; /** * @extends AbstractStationBasedRepository<StationRemote> */ final class StationRemoteRepository extends AbstractStationBasedRepository { protected string $entityClass = StationRemote::class; /** * @param Station $station * * @return mixed[] */ public function getDisplayNames(Station $station): array { $remotes = $this->repository->findBy(['station' => $station]); $displayNames = []; foreach ($remotes as $remote) { /** @var StationRemote $remote */ $displayNames[$remote->getId()] = $remote->getDisplayName(); } return $displayNames; } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationRemoteRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
170
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Enums\PodcastSources; use App\Entity\Podcast; use App\Entity\PodcastEpisode; use App\Entity\PodcastMedia; use App\Entity\Station; use App\Entity\StorageLocation; use App\Exception\StorageLocationFullException; use App\Flysystem\ExtendedFilesystemInterface; use App\Media\AlbumArt; use App\Media\MetadataManager; use InvalidArgumentException; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToRetrieveMetadata; use LogicException; /** * @extends Repository<PodcastEpisode> */ final class PodcastEpisodeRepository extends Repository { protected string $entityClass = PodcastEpisode::class; public function __construct( private readonly MetadataManager $metadataManager, private readonly StorageLocationRepository $storageLocationRepo, ) { } public function fetchEpisodeForPodcast(Podcast $podcast, string $episodeId): ?PodcastEpisode { return $this->repository->findOneBy([ 'id' => $episodeId, 'podcast' => $podcast, ]); } public function fetchEpisodeForStation(Station $station, string $episodeId): ?PodcastEpisode { return $this->fetchEpisodeForStorageLocation( $station->getPodcastsStorageLocation(), $episodeId ); } public function fetchEpisodeForStorageLocation( StorageLocation $storageLocation, string $episodeId ): ?PodcastEpisode { return $this->em->createQuery( <<<'DQL' SELECT pe FROM App\Entity\PodcastEpisode pe JOIN pe.podcast p WHERE pe.id = :id AND p.storage_location = :storageLocation DQL )->setParameter('id', $episodeId) ->setParameter('storageLocation', $storageLocation) ->getOneOrNullResult(); } public function writeEpisodeArt( PodcastEpisode $episode, string $rawArtworkString ): void { $episodeArtworkString = AlbumArt::resize($rawArtworkString); $storageLocation = $episode->getPodcast()->getStorageLocation(); $fs = $this->storageLocationRepo->getAdapter($storageLocation) ->getFilesystem(); $episodeArtworkSize = strlen($episodeArtworkString); if (!$storageLocation->canHoldFile($episodeArtworkSize)) { throw new StorageLocationFullException(); } $episodeArtworkPath = PodcastEpisode::getArtPath($episode->getIdRequired()); $fs->write($episodeArtworkPath, $episodeArtworkString); $storageLocation->addStorageUsed($episodeArtworkSize); $this->em->persist($storageLocation); $episode->setArtUpdatedAt(time()); $this->em->persist($episode); } public function removeEpisodeArt( PodcastEpisode $episode, ?ExtendedFilesystemInterface $fs = null ): void { $artworkPath = PodcastEpisode::getArtPath($episode->getIdRequired()); $storageLocation = $episode->getPodcast()->getStorageLocation(); $fs ??= $this->storageLocationRepo->getAdapter($storageLocation) ->getFilesystem(); try { $size = $fs->fileSize($artworkPath); } catch (UnableToRetrieveMetadata) { $size = 0; } try { $fs->delete($artworkPath); } catch (UnableToDeleteFile) { } $storageLocation->removeStorageUsed($size); $this->em->persist($storageLocation); $episode->setArtUpdatedAt(0); $this->em->persist($episode); } public function uploadMedia( PodcastEpisode $episode, string $originalPath, string $uploadPath, ?ExtendedFilesystemInterface $fs = null ): void { $podcast = $episode->getPodcast(); if ($podcast->getSource() !== PodcastSources::Manual) { throw new LogicException('Cannot upload media to this podcast type.'); } $storageLocation = $podcast->getStorageLocation(); $fs ??= $this->storageLocationRepo->getAdapter($storageLocation) ->getFilesystem(); $size = filesize($uploadPath) ?: 0; if (!$storageLocation->canHoldFile($size)) { throw new StorageLocationFullException(); } // Do an early metadata check of the new media to avoid replacing a valid file with an invalid one. $metadata = $this->metadataManager->read($uploadPath); if (!in_array($metadata->getMimeType(), ['audio/x-m4a', 'audio/mpeg'])) { throw new InvalidArgumentException( sprintf('Invalid Podcast Media mime type: %s', $metadata->getMimeType()) ); } $existingMedia = $episode->getMedia(); if ($existingMedia instanceof PodcastMedia) { $this->deleteMedia($existingMedia, $fs); $episode->setMedia(null); } $ext = pathinfo($originalPath, PATHINFO_EXTENSION); $path = $podcast->getId() . '/' . $episode->getId() . '.' . $ext; $podcastMedia = new PodcastMedia($storageLocation); $podcastMedia->setPath($path); $podcastMedia->setOriginalName(basename($originalPath)); // Load metadata from local file while it's available. $podcastMedia->setLength($metadata->getDuration()); $podcastMedia->setMimeType($metadata->getMimeType()); // Upload local file remotely. $fs->uploadAndDeleteOriginal($uploadPath, $path); $podcastMedia->setEpisode($episode); $this->em->persist($podcastMedia); $storageLocation->addStorageUsed($size); $this->em->persist($storageLocation); $episode->setMedia($podcastMedia); $artwork = $metadata->getArtwork(); if (!empty($artwork) && 0 === $episode->getArtUpdatedAt()) { $this->writeEpisodeArt( $episode, $artwork ); } $this->em->persist($episode); $this->em->flush(); } public function deleteMedia( PodcastMedia $media, ?ExtendedFilesystemInterface $fs = null ): void { $storageLocation = $media->getStorageLocation(); $fs ??= $this->storageLocationRepo->getAdapter($storageLocation) ->getFilesystem(); $mediaPath = $media->getPath(); try { $size = $fs->fileSize($mediaPath); } catch (UnableToRetrieveMetadata) { $size = 0; } try { $fs->delete($mediaPath); } catch (UnableToDeleteFile) { } $storageLocation->removeStorageUsed($size); $this->em->persist($storageLocation); $this->em->remove($media); $this->em->flush(); } public function delete( PodcastEpisode $episode, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= $this->storageLocationRepo->getAdapter($episode->getPodcast()->getStorageLocation()) ->getFilesystem(); $media = $episode->getMedia(); if (null !== $media) { $this->deleteMedia($media, $fs); } $this->removeEpisodeArt($episode, $fs); $this->em->remove($episode); $this->em->flush(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/PodcastEpisodeRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,660
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Container\ContainerAwareTrait; use App\Doctrine\Repository; use App\Entity\Enums\StorageLocationAdapters; use App\Entity\Enums\StorageLocationTypes; use App\Entity\Station; use App\Entity\StorageLocation; use App\Entity\StorageLocationAdapter\StorageLocationAdapterInterface; use InvalidArgumentException; /** * @extends Repository<StorageLocation> */ final class StorageLocationRepository extends Repository { use ContainerAwareTrait; protected string $entityClass = StorageLocation::class; public function findByType( string|StorageLocationTypes $type, int $id ): ?StorageLocation { if ($type instanceof StorageLocationTypes) { $type = $type->value; } return $this->repository->findOneBy( [ 'type' => $type, 'id' => $id, ] ); } /** * @param string|StorageLocationTypes $type * * @return StorageLocation[] */ public function findAllByType(string|StorageLocationTypes $type): array { if ($type instanceof StorageLocationTypes) { $type = $type->value; } return $this->repository->findBy( [ 'type' => $type, ] ); } /** * @param string|StorageLocationTypes $type * @param bool $addBlank * @param string|null $emptyString * * @return string[] */ public function fetchSelectByType( string|StorageLocationTypes $type, bool $addBlank = false, ?string $emptyString = null ): array { $select = []; if ($addBlank) { $emptyString ??= __('None'); $select[''] = $emptyString; } foreach ($this->findAllByType($type) as $storageLocation) { $select[$storageLocation->getId()] = (string)$storageLocation; } return $select; } public function createDefaultStorageLocations(): void { $backupLocations = $this->findAllByType(StorageLocationTypes::Backup); if (0 === count($backupLocations)) { $record = new StorageLocation( StorageLocationTypes::Backup, StorageLocationAdapters::Local ); $record->setPath(StorageLocation::DEFAULT_BACKUPS_PATH); $this->em->persist($record); } $this->em->flush(); } /** * @param StorageLocation $storageLocation * * @return Station[] */ public function getStationsUsingLocation(StorageLocation $storageLocation): array { $qb = $this->em->createQueryBuilder() ->select('s') ->from(Station::class, 's'); switch ($storageLocation->getType()) { case StorageLocationTypes::StationMedia: $qb->where('s.media_storage_location = :storageLocation') ->setParameter('storageLocation', $storageLocation); break; case StorageLocationTypes::StationRecordings: $qb->where('s.recordings_storage_location = :storageLocation') ->setParameter('storageLocation', $storageLocation); break; case StorageLocationTypes::StationPodcasts: $qb->where('s.podcasts_storage_location = :storageLocation') ->setParameter('storageLocation', $storageLocation); break; case StorageLocationTypes::Backup: return []; } return $qb->getQuery()->execute(); } public function getAdapter(StorageLocation $storageLocation): StorageLocationAdapterInterface { $adapterClass = $storageLocation->getAdapter()->getAdapterClass(); if (!$this->di->has($adapterClass)) { throw new InvalidArgumentException(sprintf('Class not found: %s', $adapterClass)); } /** @var StorageLocationAdapterInterface $adapter */ $adapter = $this->di->get($adapterClass); return $adapter->withStorageLocation($storageLocation); } } ```
/content/code_sandbox/backend/src/Entity/Repository/StorageLocationRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
866
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Station; use App\Entity\StationStreamer; use App\Entity\StationStreamerBroadcast; use Carbon\CarbonImmutable; /** * @extends Repository<StationStreamerBroadcast> */ final class StationStreamerBroadcastRepository extends Repository { protected string $entityClass = StationStreamerBroadcast::class; public function getLatestBroadcast(Station $station): ?StationStreamerBroadcast { $currentStreamer = $station->getCurrentStreamer(); if (null === $currentStreamer) { return null; } /** @var StationStreamerBroadcast|null $latestBroadcast */ $latestBroadcast = $this->em->createQuery( <<<'DQL' SELECT ssb FROM App\Entity\StationStreamerBroadcast ssb WHERE ssb.station = :station AND ssb.streamer = :streamer ORDER BY ssb.timestampStart DESC DQL )->setParameter('station', $station) ->setParameter('streamer', $currentStreamer) ->setMaxResults(1) ->getSingleResult(); return $latestBroadcast; } public function endAllActiveBroadcasts(Station $station): void { $this->em->createQuery( <<<'DQL' UPDATE App\Entity\StationStreamerBroadcast ssb SET ssb.timestampEnd = :time WHERE ssb.station = :station AND ssb.timestampEnd = 0 DQL )->setParameter('time', time()) ->setParameter('station', $station) ->execute(); } /** * @param Station $station * * @return StationStreamerBroadcast[] */ public function getActiveBroadcasts(Station $station): array { return $this->repository->findBy([ 'station' => $station, 'timestampEnd' => 0, ]); } public function findByPath(Station $station, string $path): ?StationStreamerBroadcast { return $this->repository->findOneBy([ 'station' => $station, 'recordingPath' => $path, ]); } public function getOrCreateFromPath( Station $station, string $recordingPath, ): ?StationStreamerBroadcast { $streamerUsername = pathinfo($recordingPath, PATHINFO_DIRNAME); $streamer = $this->em->getRepository(StationStreamer::class) ->findOneBy([ 'station' => $station, 'streamer_username' => $streamerUsername, 'is_active' => 1, ]); if (null === $streamer) { return null; } $startTimeRaw = str_replace( StationStreamerBroadcast::PATH_PREFIX . '_', '', pathinfo($recordingPath, PATHINFO_FILENAME) ); /** @var CarbonImmutable|null $startTime */ $startTime = CarbonImmutable::createFromFormat( 'Ymd-His', $startTimeRaw, $station->getTimezoneObject() ); if (!$startTime) { return null; } $record = $this->em->createQuery( <<<'DQL' SELECT ssb FROM App\Entity\StationStreamerBroadcast ssb WHERE ssb.streamer = :streamer AND ssb.timestampStart >= :start AND ssb.timestampStart <= :end AND ssb.recordingPath IS NULL DQL )->setParameter('streamer', $streamer) ->setParameter('start', $startTime->subMinute()->getTimestamp()) ->setParameter('end', $startTime->addMinute()->getTimestamp()) ->setMaxResults(1) ->getOneOrNullResult(); if (null === $record) { $record = new StationStreamerBroadcast($streamer); } assert($record instanceof StationStreamerBroadcast); $record->setTimestampStart($startTime->getTimestamp()); $record->setRecordingPath($recordingPath); return $record; } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationStreamerBroadcastRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
859
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\ApiKey; use App\Entity\User; use App\Entity\UserLoginToken; use App\Security\SplitToken; /** * @template TEntity of ApiKey|UserLoginToken * @extends Repository<TEntity> */ abstract class AbstractSplitTokenRepository extends Repository { /** * Given an API key string in the format `identifier:verifier`, find and authenticate an API key. * * @param string $key */ public function authenticate(string $key): ?User { $userSuppliedToken = SplitToken::fromKeyString($key); $tokenEntity = $this->repository->find($userSuppliedToken->identifier); if ($tokenEntity instanceof $this->entityClass) { return ($tokenEntity->verify($userSuppliedToken)) ? $tokenEntity->getUser() : null; } return null; } } ```
/content/code_sandbox/backend/src/Entity/Repository/AbstractSplitTokenRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
207
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Assets\AssetTypes; use App\Container\EnvironmentAwareTrait; use App\Container\SettingsAwareTrait; use App\Doctrine\Repository; use App\Entity\Station; use App\Entity\StationHlsStream; use App\Entity\StationMount; use App\Flysystem\ExtendedFilesystemInterface; use App\Flysystem\StationFilesystems; use App\Radio\Enums\StreamFormats; use App\Service\Flow\UploadedFile; use Closure; use Psr\Http\Message\UriInterface; /** * @extends Repository<Station> */ final class StationRepository extends Repository { use EnvironmentAwareTrait; use SettingsAwareTrait; protected string $entityClass = Station::class; /** * @param string $identifier A numeric or string identifier for a station. */ public function findByIdentifier(string $identifier): ?Station { return is_numeric($identifier) ? $this->repository->find($identifier) : $this->repository->findOneBy(['short_name' => $identifier]); } public function getActiveCount(): int { return (int)$this->em->createQuery( <<<'DQL' SELECT COUNT(s.id) FROM App\Entity\Station s WHERE s.is_enabled = 1 DQL )->getSingleScalarResult(); } /** * @return array<array-key, Station> */ public function fetchAll(): mixed { return $this->em->createQuery( <<<'DQL' SELECT s FROM App\Entity\Station s ORDER BY s.name ASC DQL )->execute(); } /** * @inheritDoc */ public function fetchSelect( bool|string $addBlank = false, Closure $display = null, string $pk = 'id', string $orderBy = 'name' ): array { $select = []; // Specify custom text in the $add_blank parameter to override. if ($addBlank !== false) { $select[''] = ($addBlank === true) ? 'Select...' : $addBlank; } // Build query for records. // Assemble select values and, if necessary, call $display callback. foreach ($this->fetchArray() as $result) { $key = $result[$pk]; $select[$key] = ($display === null) ? $result['name'] : $display($result); } return $select; } /** * @return iterable<Station> */ public function iterateEnabledStations(): iterable { return $this->em->createQuery( <<<DQL SELECT s FROM App\Entity\Station s WHERE s.is_enabled = 1 DQL )->toIterable(); } /** * Reset mount points to their adapter defaults (in the event of an adapter change). */ public function resetMounts(Station $station): void { foreach ($station->getMounts() as $mount) { $this->em->remove($mount); } // Create default mountpoints if station supports them. if ($station->getFrontendType()->supportsMounts()) { $record = new StationMount($station); $record->setName('/radio.mp3'); $record->setIsDefault(true); $record->setEnableAutodj(true); $record->setAutodjFormat(StreamFormats::Mp3); $record->setAutodjBitrate(128); $this->em->persist($record); } $this->em->flush(); $this->em->refresh($station); } public function resetHls(Station $station): void { foreach ($station->getHlsStreams() as $hlsStream) { $this->em->remove($hlsStream); } if ($station->getEnableHls() && $station->getBackendType()->isEnabled()) { $streams = [ 'aac_lofi' => 48, 'aac_midfi' => 96, 'aac_hifi' => 192, ]; foreach ($streams as $name => $bitrate) { $record = new StationHlsStream($station); $record->setName($name); $record->setFormat(StreamFormats::Aac); $record->setBitrate($bitrate); $this->em->persist($record); } } $this->em->flush(); $this->em->refresh($station); } public function flushRelatedMedia(Station $station): void { $this->em->createQuery( <<<'DQL' UPDATE App\Entity\SongHistory sh SET sh.media = null WHERE sh.station = :station DQL )->setParameter('station', $station) ->execute(); $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationPlaylistMedia spm WHERE spm.playlist_id IN ( SELECT sp.id FROM App\Entity\StationPlaylist sp WHERE sp.station = :station ) DQL )->setParameter('station', $station) ->execute(); $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationQueue sq WHERE sq.station = :station DQL )->setParameter('station', $station) ->execute(); $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationRequest sr WHERE sr.station = :station DQL )->setParameter('station', $station) ->execute(); } /** * Return the URL to use for songs with no specified album artwork, when artwork is displayed. * * @param Station|null $station */ public function getDefaultAlbumArtUrl(?Station $station = null): UriInterface { if (null !== $station) { $stationAlbumArt = AssetTypes::AlbumArt->createObject($this->environment, $station); if ($stationAlbumArt->isUploaded()) { return $stationAlbumArt->getUri(); } $stationCustomUri = $station->getBrandingConfig()->getDefaultAlbumArtUrlAsUri(); if (null !== $stationCustomUri) { return $stationCustomUri; } } $customUrl = $this->readSettings()->getDefaultAlbumArtUrlAsUri(); return $customUrl ?? AssetTypes::AlbumArt->createObject($this->environment)->getUri(); } public function setFallback( Station $station, UploadedFile $file, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= StationFilesystems::buildConfigFilesystem($station); if (!empty($station->getFallbackPath())) { $this->doDeleteFallback($station, $fs); $station->setFallbackPath(null); } $originalPath = $file->getClientFilename(); $originalExt = pathinfo($originalPath, PATHINFO_EXTENSION); $fallbackPath = 'fallback.' . $originalExt; $fs->uploadAndDeleteOriginal($file->getUploadedPath(), $fallbackPath); $station->setFallbackPath($fallbackPath); $this->em->persist($station); $this->em->flush(); } public function doDeleteFallback( Station $station, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= StationFilesystems::buildConfigFilesystem($station); $fallbackPath = $station->getFallbackPath(); if (empty($fallbackPath)) { return; } $fs->delete($fallbackPath); } public function clearFallback( Station $station, ?ExtendedFilesystemInterface $fs = null ): void { $this->doDeleteFallback($station, $fs); $station->setFallbackPath(null); $this->em->persist($station); $this->em->flush(); } public function setStereoToolConfiguration( Station $station, UploadedFile $file, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= StationFilesystems::buildConfigFilesystem($station); $backendConfig = $station->getBackendConfig(); if (null !== $backendConfig->getStereoToolConfigurationPath()) { $this->doDeleteStereoToolConfiguration($station, $fs); $backendConfig->setStereoToolConfigurationPath(null); } $stereoToolConfigurationPath = 'stereo-tool.sts'; $fs->uploadAndDeleteOriginal($file->getUploadedPath(), $stereoToolConfigurationPath); $backendConfig->setStereoToolConfigurationPath($stereoToolConfigurationPath); $station->setBackendConfig($backendConfig); $this->em->persist($station); $this->em->flush(); } public function doDeleteStereoToolConfiguration( Station $station, ?ExtendedFilesystemInterface $fs = null ): void { $backendConfig = $station->getBackendConfig(); if (null === $backendConfig->getStereoToolConfigurationPath()) { return; } $fs ??= StationFilesystems::buildConfigFilesystem($station); $fs->delete($backendConfig->getStereoToolConfigurationPath()); } public function clearStereoToolConfiguration( Station $station, ?ExtendedFilesystemInterface $fs = null ): void { $this->doDeleteStereoToolConfiguration($station, $fs); $backendConfig = $station->getBackendConfig(); $backendConfig->setStereoToolConfigurationPath(null); $station->setBackendConfig($backendConfig); $this->em->persist($station); $this->em->flush(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,129
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Role; use App\Entity\RolePermission; use App\Enums\GlobalPermissions; /** * @extends Repository<RolePermission> */ final class RolePermissionRepository extends Repository { protected string $entityClass = RolePermission::class; /** * @param Role $role * * @return mixed[] */ public function getActionsForRole(Role $role): array { $roleHasAction = $this->em->createQuery( <<<'DQL' SELECT e FROM App\Entity\RolePermission e WHERE e.role_id = :role_id DQL )->setParameter('role_id', $role->getId()) ->getArrayResult(); $result = []; foreach ($roleHasAction as $row) { if ($row['station_id']) { $result['actions_' . $row['station_id']][] = $row['action_name']; } else { $result['actions_global'][] = $row['action_name']; } } return $result; } public function ensureSuperAdministratorRole(): Role { $superAdminRole = $this->em->createQuery( <<<'DQL' SELECT r FROM App\Entity\Role r LEFT JOIN r.permissions rp WHERE rp.station IS NULL AND rp.action_name = :action DQL )->setParameter('action', GlobalPermissions::All->value) ->setMaxResults(1) ->getOneOrNullResult(); if ($superAdminRole instanceof Role) { return $superAdminRole; } $newRole = new Role(); $newRole->setName('Super Administrator'); $this->em->persist($newRole); $newPerm = new RolePermission($newRole, null, GlobalPermissions::All); $this->em->persist($newPerm); $this->em->flush(); return $newRole; } } ```
/content/code_sandbox/backend/src/Entity/Repository/RolePermissionRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
433
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Enums\PlaylistSources; use App\Entity\Station; use App\Entity\StationPlaylist; /** * @extends AbstractStationBasedRepository<StationPlaylist> */ final class StationPlaylistRepository extends AbstractStationBasedRepository { protected string $entityClass = StationPlaylist::class; /** * @return StationPlaylist[] */ public function getAllForStation(Station $station): array { return $this->repository->findBy([ 'station' => $station, ]); } public function stationHasActivePlaylists(Station $station): bool { foreach ($station->getPlaylists() as $playlist) { if (!$playlist->getIsEnabled()) { continue; } if (PlaylistSources::RemoteUrl === $playlist->getSource()) { return true; } $mediaCount = $this->em->createQuery( <<<DQL SELECT COUNT(spm.id) FROM App\Entity\StationPlaylistMedia spm JOIN spm.playlist sp WHERE sp.station = :station DQL )->setParameter('station', $station) ->getSingleScalarResult(); if ($mediaCount > 0) { return true; } } return false; } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationPlaylistRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
282
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Interfaces\SongInterface; use App\Entity\SongHistory; use App\Entity\Station; use Carbon\CarbonImmutable; use RuntimeException; /** * @extends AbstractStationBasedRepository<SongHistory> */ final class SongHistoryRepository extends AbstractStationBasedRepository { protected string $entityClass = SongHistory::class; public function __construct( private readonly ListenerRepository $listenerRepository, private readonly StationQueueRepository $stationQueueRepository ) { } /** * @param Station $station * * @return SongHistory[] */ public function getVisibleHistory( Station $station, ?int $numEntries = null ): array { $numEntries ??= $station->getApiHistoryItems(); if (0 === $numEntries) { return []; } return $this->em->createQuery( <<<'DQL' SELECT sh FROM App\Entity\SongHistory sh LEFT JOIN sh.media sm WHERE sh.station = :station AND sh.is_visible = 1 ORDER BY sh.id DESC DQL )->setParameter('station', $station) ->setMaxResults($numEntries) ->execute(); } public function updateSongFromNowPlaying( Station $station, SongInterface $song ): void { if (!$this->isDifferentFromCurrentSong($station, $song)) { return; } // Handle track transition. $upcomingTrack = $this->stationQueueRepository->findRecentlyCuedSong($station, $song); if (null !== $upcomingTrack) { $this->stationQueueRepository->trackPlayed($station, $upcomingTrack); $newSong = SongHistory::fromQueue($upcomingTrack); } else { $newSong = new SongHistory($station, $song); } $this->changeCurrentSong($station, $newSong); } public function updateListenersFromNowPlaying( Station $station, int $listeners ): SongHistory { $currentSong = $station->getCurrentSong(); if (null === $currentSong) { throw new RuntimeException('No track to update.'); } $currentSong->addDeltaPoint($listeners); $this->em->persist($currentSong); $this->em->flush(); return $currentSong; } public function isDifferentFromCurrentSong( Station $station, SongInterface $toCompare ): bool { $currentSong = $station->getCurrentSong(); return !(null !== $currentSong) || $currentSong->getSongId() !== $toCompare->getSongId(); } public function changeCurrentSong( Station $station, SongHistory $newCurrentSong ): SongHistory { $previousCurrentSong = $station->getCurrentSong(); if (null !== $previousCurrentSong) { // Wrapping up processing on the previous SongHistory item (if present). $previousCurrentSong->playbackEnded(); $previousCurrentSong->setUniqueListeners( $this->listenerRepository->getUniqueListeners( $station, $previousCurrentSong->getTimestampStart(), time() ) ); $this->em->persist($previousCurrentSong); } $newCurrentSong->setListenersFromLastSong($previousCurrentSong); $newCurrentSong->setTimestampStart(time()); $newCurrentSong->updateVisibility(); $currentStreamer = $station->getCurrentStreamer(); if (null !== $currentStreamer) { $newCurrentSong->setStreamer($currentStreamer); } $this->em->persist($newCurrentSong); $station->setCurrentSong($newCurrentSong); $this->em->persist($station); return $newCurrentSong; } /** * @param Station $station * @param int $start * @param int $end * * @return array{int, int, float} */ public function getStatsByTimeRange(Station $station, int $start, int $end): array { $historyTotals = $this->em->createQuery( <<<'DQL' SELECT AVG(sh.listeners_end) AS listeners_avg, MAX(sh.listeners_end) AS listeners_max, MIN(sh.listeners_end) AS listeners_min FROM App\Entity\SongHistory sh WHERE sh.station = :station AND sh.timestamp_end >= :start AND sh.timestamp_start <= :end DQL )->setParameter('station', $station) ->setParameter('start', $start) ->setParameter('end', $end) ->getSingleResult(); $min = (int)$historyTotals['listeners_min']; $max = (int)$historyTotals['listeners_max']; $avg = round((float)$historyTotals['listeners_avg'], 2); return [$min, $max, $avg]; } public function cleanup(int $daysToKeep): void { $threshold = CarbonImmutable::now() ->subDays($daysToKeep) ->getTimestamp(); $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\SongHistory sh WHERE sh.timestamp_start != 0 AND sh.timestamp_start <= :threshold DQL )->setParameter('threshold', $threshold) ->execute(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/SongHistoryRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,177
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Station; use App\Entity\StationHlsStream; /** * @extends AbstractStationBasedRepository<StationHlsStream> */ final class StationHlsStreamRepository extends AbstractStationBasedRepository { protected string $entityClass = StationHlsStream::class; /** * @param Station $station * * @return mixed[] */ public function getDisplayNames(Station $station): array { $streams = $this->repository->findBy(['station' => $station]); $displayNames = []; /** @var StationHlsStream $stream */ foreach ($streams as $stream) { $displayNames[$stream->getIdRequired()] = 'HLS: ' . $stream->getName(); } return $displayNames; } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationHlsStreamRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
184
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Role; /** * @extends Repository<Role> */ final class RoleRepository extends Repository { protected string $entityClass = Role::class; } ```
/content/code_sandbox/backend/src/Entity/Repository/RoleRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
54
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Api\StationPlaylistQueue; use App\Entity\Enums\PlaylistOrders; use App\Entity\Enums\PlaylistSources; use App\Entity\Station; use App\Entity\StationMedia; use App\Entity\StationPlaylist; use App\Entity\StationPlaylistMedia; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Doctrine\ORM\NoResultException; use Doctrine\ORM\QueryBuilder; use InvalidArgumentException; use RuntimeException; /** * @extends Repository<StationPlaylistMedia> */ final class StationPlaylistMediaRepository extends Repository { protected string $entityClass = StationPlaylistMedia::class; public function __construct( private readonly StationQueueRepository $queueRepo ) { } /** * @param StationMedia $media * @param array<int, int> $playlists Playlists with weight as value (id => weight) * @return array<int, int> Affected playlist IDs (id => id) */ public function setPlaylistsForMedia( StationMedia $media, Station $station, array $playlists ): array { $toDelete = []; foreach ($this->getPlaylistsForMedia($media, $station) as $playlistId) { if (isset($playlists[$playlistId])) { unset($playlists[$playlistId]); } else { $toDelete[$playlistId] = $playlistId; } } if (0 !== count($toDelete)) { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationPlaylistMedia spm WHERE spm.media = :media AND spm.playlist_id IN (:playlistIds) DQL )->setParameter('media', $media) ->setParameter('playlistIds', $toDelete) ->execute(); } $added = []; foreach ($playlists as $playlistId => $weight) { $playlist = $this->em->find(StationPlaylist::class, $playlistId); if (!($playlist instanceof StationPlaylist)) { continue; } if (0 === $weight) { $weight = $this->getHighestSongWeight($playlist) + 1; } if (PlaylistOrders::Sequential !== $playlist->getOrder()) { $weight = random_int(1, $weight); } $record = new StationPlaylistMedia($playlist, $media); $record->setWeight($weight); $this->em->persist($record); $added[$playlistId] = $playlistId; } $this->em->flush(); return $toDelete + $added; } /** * @param StationMedia $media * @param Station $station * @return array<array-key, int> */ public function getPlaylistsForMedia( StationMedia $media, Station $station ): array { return $this->em->createQuery( <<<'DQL' SELECT sp.id FROM App\Entity\StationPlaylistMedia spm LEFT JOIN spm.playlist sp WHERE spm.media = :media AND sp.station = :station DQL )->setParameter('media', $media) ->setParameter('station', $station) ->getSingleColumnResult(); } /** * Add the specified media to the specified playlist. * Must flush the EntityManager after using. * * @param StationMedia $media * @param StationPlaylist $playlist * @param int $weight * * @return int The weight assigned to the newly added record. */ public function addMediaToPlaylist( StationMedia $media, StationPlaylist $playlist, int $weight = 0 ): int { if (PlaylistSources::Songs !== $playlist->getSource()) { throw new RuntimeException('This playlist is not meant to contain songs!'); } // Only update existing record for random-order playlists. $isNonSequential = PlaylistOrders::Sequential !== $playlist->getOrder(); $record = ($isNonSequential) ? $this->repository->findOneBy( [ 'media_id' => $media->getId(), 'playlist_id' => $playlist->getId(), ] ) : null; if ($record instanceof StationPlaylistMedia) { if (0 !== $weight) { $record->setWeight($weight); $this->em->persist($record); } } else { if (0 === $weight) { $weight = $this->getHighestSongWeight($playlist) + 1; } if ($isNonSequential) { $weight = random_int(1, $weight); } $record = new StationPlaylistMedia($playlist, $media); $record->setWeight($weight); $this->em->persist($record); } return $weight; } public function getHighestSongWeight(StationPlaylist $playlist): int { try { $highestWeight = $this->em->createQuery( <<<'DQL' SELECT MAX(e.weight) FROM App\Entity\StationPlaylistMedia e WHERE e.playlist_id = :playlist_id DQL )->setParameter('playlist_id', $playlist->getId()) ->getSingleScalarResult(); } catch (NoResultException) { $highestWeight = 1; } return (int)$highestWeight; } /** * Remove all playlist associations from the specified media object. * * @param StationMedia $media * @param Station|null $station * * @return array<int, int> Affected Playlist records (id => id) */ public function clearPlaylistsFromMedia( StationMedia $media, ?Station $station = null ): array { $affectedPlaylists = []; $playlists = $media->getPlaylists(); if (null !== $station) { $playlists = $playlists->filter( function (StationPlaylistMedia $spm) use ($station) { return $spm->getPlaylist()->getStation()->getId() === $station->getId(); } ); } foreach ($playlists as $spmRow) { $playlist = $spmRow->getPlaylist(); $affectedPlaylists[$playlist->getIdRequired()] = $playlist->getIdRequired(); $this->queueRepo->clearForMediaAndPlaylist($media, $playlist); $this->em->remove($spmRow); } return $affectedPlaylists; } public function emptyPlaylist( StationPlaylist $playlist ): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationPlaylistMedia spm WHERE spm.playlist = :playlist DQL )->setParameter('playlist', $playlist) ->execute(); $this->queueRepo->clearForPlaylist($playlist); } /** * Set the order of the media, specified as * [ * media_id => new_weight, * ... * ] * * @param StationPlaylist $playlist * @param array $mapping */ public function setMediaOrder(StationPlaylist $playlist, array $mapping): void { $updateQuery = $this->em->createQuery( <<<'DQL' UPDATE App\Entity\StationPlaylistMedia e SET e.weight = :weight WHERE e.playlist_id = :playlist_id AND e.id = :id DQL )->setParameter('playlist_id', $playlist->getId()); $this->em->wrapInTransaction( function () use ($updateQuery, $mapping): void { foreach ($mapping as $id => $weight) { $updateQuery->setParameter('id', $id) ->setParameter('weight', $weight) ->execute(); } } ); } public function resetQueue(StationPlaylist $playlist, CarbonInterface $now = null): void { if (PlaylistSources::Songs !== $playlist->getSource()) { throw new InvalidArgumentException('Playlist must contain songs.'); } if (PlaylistOrders::Sequential === $playlist->getOrder()) { $this->em->createQuery( <<<'DQL' UPDATE App\Entity\StationPlaylistMedia spm SET spm.is_queued = 1 WHERE spm.playlist = :playlist DQL )->setParameter('playlist', $playlist) ->execute(); } elseif (PlaylistOrders::Shuffle === $playlist->getOrder()) { $this->em->wrapInTransaction( function () use ($playlist): void { $allSpmRecordsQuery = $this->em->createQuery( <<<'DQL' SELECT spm.id FROM App\Entity\StationPlaylistMedia spm WHERE spm.playlist = :playlist ORDER BY RAND() DQL )->setParameter('playlist', $playlist); $updateSpmWeightQuery = $this->em->createQuery( <<<'DQL' UPDATE App\Entity\StationPlaylistMedia spm SET spm.weight=:weight, spm.is_queued=1 WHERE spm.id = :id DQL ); $allSpmRecords = $allSpmRecordsQuery->toIterable([], $allSpmRecordsQuery::HYDRATE_SCALAR); $weight = 1; foreach ($allSpmRecords as $spmId) { $updateSpmWeightQuery->setParameter('id', $spmId) ->setParameter('weight', $weight) ->execute(); $weight++; } } ); } $now = $now ?? CarbonImmutable::now($playlist->getStation()->getTimezoneObject()); $playlist->setQueueResetAt($now->getTimestamp()); $this->em->persist($playlist); $this->em->flush(); } public function resetAllQueues(Station $station): void { $now = CarbonImmutable::now($station->getTimezoneObject()); foreach ($station->getPlaylists() as $playlist) { if (PlaylistSources::Songs !== $playlist->getSource()) { continue; } $this->resetQueue($playlist, $now); } } /** * @return StationPlaylistQueue[] */ public function getQueue(StationPlaylist $playlist): array { if (PlaylistSources::Songs !== $playlist->getSource()) { throw new InvalidArgumentException('Playlist must contain songs.'); } $queuedMediaQuery = $this->em->createQueryBuilder() ->select(['spm.id AS spm_id', 'sm.id', 'sm.song_id', 'sm.artist', 'sm.title']) ->from(StationMedia::class, 'sm') ->join('sm.playlists', 'spm') ->where('spm.playlist = :playlist') ->setParameter('playlist', $playlist); if (PlaylistOrders::Random === $playlist->getOrder()) { $queuedMediaQuery = $queuedMediaQuery->orderBy('RAND()'); } else { $queuedMediaQuery = $queuedMediaQuery->andWhere('spm.is_queued = 1') ->orderBy('spm.weight', 'ASC'); } $queuedMedia = $queuedMediaQuery->getQuery()->getArrayResult(); return array_map( static function ($val): StationPlaylistQueue { $record = new StationPlaylistQueue(); $record->spm_id = $val['spm_id']; $record->media_id = $val['id']; $record->song_id = $val['song_id']; $record->artist = $val['artist'] ?? ''; $record->title = $val['title'] ?? ''; return $record; }, $queuedMedia ); } public function isQueueCompletelyFilled(StationPlaylist $playlist): bool { if (PlaylistSources::Songs !== $playlist->getSource()) { return true; } if (PlaylistOrders::Random === $playlist->getOrder()) { return true; } $notQueuedMediaCount = $this->getCountPlaylistMediaBaseQuery($playlist) ->andWhere('spm.is_queued = 0') ->getQuery() ->getSingleScalarResult(); return $notQueuedMediaCount === 0; } public function isQueueEmpty(StationPlaylist $playlist): bool { if (PlaylistSources::Songs !== $playlist->getSource()) { return false; } if (PlaylistOrders::Random === $playlist->getOrder()) { return false; } $totalMediaCount = $this->getCountPlaylistMediaBaseQuery($playlist) ->getQuery() ->getSingleScalarResult(); $notQueuedMediaCount = $this->getCountPlaylistMediaBaseQuery($playlist) ->andWhere('spm.is_queued = 0') ->getQuery() ->getSingleScalarResult(); return $notQueuedMediaCount === $totalMediaCount; } private function getCountPlaylistMediaBaseQuery(StationPlaylist $playlist): QueryBuilder { return $this->em->createQueryBuilder() ->select('count(spm.id)') ->from(StationMedia::class, 'sm') ->join('sm.playlists', 'spm') ->where('spm.playlist = :playlist') ->setParameter('playlist', $playlist); } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationPlaylistMediaRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,901
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\ApiKey; /** * @extends AbstractSplitTokenRepository<ApiKey> */ final class ApiKeyRepository extends AbstractSplitTokenRepository { protected string $entityClass = ApiKey::class; } ```
/content/code_sandbox/backend/src/Entity/Repository/ApiKeyRepository.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\Entity\Repository; use App\Entity\User; use App\Entity\UserLoginToken; use App\Security\SplitToken; /** * @extends AbstractSplitTokenRepository<UserLoginToken> */ final class UserLoginTokenRepository extends AbstractSplitTokenRepository { protected string $entityClass = UserLoginToken::class; public function createToken(User $user): SplitToken { $token = SplitToken::generate(); $loginToken = new UserLoginToken($user, $token); $this->em->persist($loginToken); $this->em->flush(); return $token; } public function revokeForUser(User $user): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\UserLoginToken ult WHERE ult.user = :user DQL )->setParameter('user', $user) ->execute(); } public function cleanup(): void { /** @noinspection SummerTimeUnsafeTimeManipulationInspection */ $threshold = time() - 86400; // One day $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\UserLoginToken ut WHERE ut.created_at <= :threshold DQL )->setParameter('threshold', $threshold) ->execute(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/UserLoginTokenRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
290
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Analytics; use App\Entity\Enums\AnalyticsIntervals; use App\Entity\Station; use App\Utilities\DateRange; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; /** * @extends Repository<Analytics> */ final class AnalyticsRepository extends Repository { protected string $entityClass = Analytics::class; /** * @return mixed[] */ public function findForStationInRange( Station $station, DateRange $dateRange, AnalyticsIntervals $type = AnalyticsIntervals::Daily ): array { return $this->em->createQuery( <<<'DQL' SELECT a FROM App\Entity\Analytics a WHERE a.station = :station AND a.type = :type AND a.moment BETWEEN :start AND :end DQL )->setParameter('station', $station) ->setParameter('type', $type) ->setParameter('start', $dateRange->getStart()) ->setParameter('end', $dateRange->getEnd()) ->getArrayResult(); } public function clearAll(): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\Analytics a DQL )->execute(); } public function cleanup(): void { $hourlyRetention = CarbonImmutable::now() ->subDays(14); $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\Analytics a WHERE a.type = :type AND a.moment <= :threshold DQL )->setParameter('type', AnalyticsIntervals::Hourly) ->setParameter('threshold', $hourlyRetention) ->execute(); } public function clearSingleMetric( AnalyticsIntervals $type, CarbonInterface $moment, ?Station $station = null ): void { if (null === $station) { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\Analytics a WHERE a.station IS NULL AND a.type = :type AND a.moment = :moment DQL )->setParameter('type', $type) ->setParameter('moment', $moment) ->execute(); } else { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\Analytics a WHERE a.station = :station AND a.type = :type AND a.moment = :moment DQL )->setParameter('station', $station) ->setParameter('type', $type) ->setParameter('moment', $moment) ->execute(); } } } ```
/content/code_sandbox/backend/src/Entity/Repository/AnalyticsRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
580
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\User; /** * @extends Repository<User> */ final class UserRepository extends Repository { protected string $entityClass = User::class; public function findByEmail(string $email): ?User { return $this->repository->findOneby(['email' => $email]); } public function authenticate(string $username, string $password): ?User { $user = $this->findByEmail($username); if ($user instanceof User && $user->verifyPassword($password)) { return $user; } // Verify a password (and do nothing with it) to avoid timing attacks on authentication. password_verify( $password, '$argon2id$v=19$m=65536,t=4,p=1$WHptOW0xM1UweHp0ZXpmNg$qC5anR37sV/G8k7l09eLKLHukkUD7e5csUdbmjGYsgs' ); return null; } public function getOrCreate(string $email): User { $user = $this->findByEmail($email); if (!($user instanceof User)) { $user = new User(); $user->setEmail($email); $user->setName($email); } return $user; } } ```
/content/code_sandbox/backend/src/Entity/Repository/UserRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
303
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Enums\PodcastSources; use App\Entity\Podcast; use App\Entity\Station; use App\Exception\StorageLocationFullException; use App\Flysystem\ExtendedFilesystemInterface; use App\Media\AlbumArt; use League\Flysystem\UnableToDeleteFile; use League\Flysystem\UnableToRetrieveMetadata; /** * @extends Repository<Podcast> */ final class PodcastRepository extends Repository { protected string $entityClass = Podcast::class; public function __construct( private readonly PodcastEpisodeRepository $podcastEpisodeRepo, private readonly StorageLocationRepository $storageLocationRepo ) { } public function fetchPodcastForStation(Station $station, string $podcastId): ?Podcast { return $this->repository->findOneBy( [ 'id' => $podcastId, 'storage_location' => $station->getPodcastsStorageLocation(), ] ); } /** * @param Station $station * @return string[] */ public function getPodcastIdsWithPublishedEpisodes(Station $station): array { return $this->em->createQuery( <<<'DQL' SELECT DISTINCT p.id FROM App\Entity\PodcastEpisode pe JOIN pe.podcast p LEFT JOIN pe.media pm LEFT JOIN pe.playlist_media sm WHERE ((p.source = :sourceManual AND pm.id IS NOT NULL) OR (p.source = :sourcePlaylist AND sm.id IS NOT NULL)) AND (pe.publish_at <= :time) DQL )->setParameter('time', time()) ->setParameter('sourceManual', PodcastSources::Manual->value) ->setParameter('sourcePlaylist', PodcastSources::Playlist->value) ->enableResultCache(60, 'podcast_ids_' . $station->getIdRequired()) ->getSingleColumnResult(); } public function writePodcastArt( Podcast $podcast, string $rawArtworkString, ?ExtendedFilesystemInterface $fs = null ): void { $storageLocation = $podcast->getStorageLocation(); $fs ??= $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $podcastArtworkString = AlbumArt::resize($rawArtworkString); $podcastArtworkSize = strlen($podcastArtworkString); if (!$storageLocation->canHoldFile($podcastArtworkSize)) { throw new StorageLocationFullException(); } $podcastArtworkPath = Podcast::getArtPath($podcast->getIdRequired()); $fs->write($podcastArtworkPath, $podcastArtworkString); $storageLocation->addStorageUsed($podcastArtworkSize); $this->em->persist($storageLocation); $podcast->setArtUpdatedAt(time()); $this->em->persist($podcast); } public function removePodcastArt( Podcast $podcast, ?ExtendedFilesystemInterface $fs = null ): void { $storageLocation = $podcast->getStorageLocation(); $fs ??= $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $artworkPath = Podcast::getArtPath($podcast->getIdRequired()); try { $size = $fs->fileSize($artworkPath); } catch (UnableToRetrieveMetadata) { $size = 0; } try { $fs->delete($artworkPath); } catch (UnableToDeleteFile) { } $storageLocation->removeStorageUsed($size); $this->em->persist($storageLocation); $podcast->setArtUpdatedAt(0); $this->em->persist($podcast); } public function delete( Podcast $podcast, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= $this->storageLocationRepo->getAdapter($podcast->getStorageLocation()) ->getFilesystem(); foreach ($podcast->getEpisodes() as $episode) { $this->podcastEpisodeRepo->delete($episode, $fs); } $this->removePodcastArt($podcast, $fs); $this->em->remove($podcast); $this->em->flush(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/PodcastRepository.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\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Api\StationSchedule as ApiStationSchedule; use App\Entity\ApiGenerator\ScheduleApiGenerator; use App\Entity\Station; use App\Entity\StationPlaylist; use App\Entity\StationSchedule; use App\Entity\StationStreamer; use App\Radio\AutoDJ\Scheduler; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; /** * @extends Repository<StationSchedule> */ final class StationScheduleRepository extends Repository { protected string $entityClass = StationSchedule::class; public function __construct( private readonly Scheduler $scheduler, private readonly ScheduleApiGenerator $scheduleApiGenerator ) { } /** * @param StationPlaylist|StationStreamer $relation * @param array $items */ public function setScheduleItems( StationPlaylist|StationStreamer $relation, array $items = [] ): void { $rawScheduleItems = $this->findByRelation($relation); $scheduleItems = []; foreach ($rawScheduleItems as $row) { $scheduleItems[$row->getId()] = $row; } foreach ($items as $item) { if (isset($item['id'], $scheduleItems[$item['id']])) { $record = $scheduleItems[$item['id']]; unset($scheduleItems[$item['id']]); } else { $record = new StationSchedule($relation); } $record->setStartTime((int)$item['start_time']); $record->setEndTime((int)$item['end_time']); $record->setStartDate($item['start_date']); $record->setEndDate($item['end_date']); $record->setDays($item['days'] ?? []); $record->setLoopOnce($item['loop_once'] ?? false); $this->em->persist($record); } foreach ($scheduleItems as $row) { $this->em->remove($row); } $this->em->flush(); } /** * @param StationPlaylist|StationStreamer $relation * * @return StationSchedule[] */ public function findByRelation(StationPlaylist|StationStreamer $relation): array { if ($relation instanceof StationPlaylist) { return $this->repository->findBy(['playlist' => $relation]); } return $this->repository->findBy(['streamer' => $relation]); } /** * @param Station $station * * @return StationSchedule[] */ public function getAllScheduledItemsForStation(Station $station): array { return $this->em->createQuery( <<<'DQL' SELECT ssc, sp, sst FROM App\Entity\StationSchedule ssc LEFT JOIN ssc.playlist sp LEFT JOIN ssc.streamer sst WHERE (sp.station = :station AND sp.is_jingle = 0 AND sp.is_enabled = 1) OR (sst.station = :station AND sst.is_active = 1) DQL )->setParameter('station', $station) ->execute(); } /** * @param Station $station * @param CarbonInterface|null $now * * @return ApiStationSchedule[] */ public function getUpcomingSchedule(Station $station, CarbonInterface $now = null): array { if (null === $now) { $now = CarbonImmutable::now($station->getTimezoneObject()); } $startDate = $now->subDay(); $endDate = $now->addDay()->addHour(); $events = []; foreach ($this->getAllScheduledItemsForStation($station) as $scheduleItem) { /** @var StationSchedule $scheduleItem */ $i = $startDate; while ($i <= $endDate) { $dayOfWeek = $i->dayOfWeekIso; if ( $this->scheduler->shouldSchedulePlayOnCurrentDate($scheduleItem, $i) && $this->scheduler->isScheduleScheduledToPlayToday($scheduleItem, $dayOfWeek) ) { $start = StationSchedule::getDateTime($scheduleItem->getStartTime(), $i); $end = StationSchedule::getDateTime($scheduleItem->getEndTime(), $i); // Handle overnight schedule items if ($end < $start) { $end = $end->addDay(); } // Skip events that have already happened today. if ($end->lessThan($now)) { $i = $i->addDay(); continue; } $events[] = ($this->scheduleApiGenerator)( $scheduleItem, $start, $end, $now ); } $i = $i->addDay(); } } usort( $events, static function ($a, $b) { return $a->start_timestamp <=> $b->start_timestamp; } ); return $events; } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationScheduleRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,079
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\StorageLocation; use App\Entity\UnprocessableMedia; use Generator; /** * @extends Repository<UnprocessableMedia> */ final class UnprocessableMediaRepository extends Repository { protected string $entityClass = UnprocessableMedia::class; public function findByPath( string $path, StorageLocation $storageLocation ): ?UnprocessableMedia { /** @var UnprocessableMedia|null $record */ $record = $this->repository->findOneBy( [ 'storage_location' => $storageLocation, 'path' => $path, ] ); return $record; } public function iteratePaths(array $paths, StorageLocation $storageLocation): Generator { foreach ($paths as $path) { $record = $this->findByPath($path, $storageLocation); if ($record instanceof UnprocessableMedia) { yield $path => $record; } } } public function clearForPath( StorageLocation $storageLocation, string $path ): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\UnprocessableMedia upm WHERE upm.storage_location = :storageLocation AND upm.path = :path DQL )->setParameter('storageLocation', $storageLocation) ->setParameter('path', $path) ->execute(); } public function setForPath( StorageLocation $storageLocation, string $path, ?string $error = null ): void { $record = $this->repository->findOneBy( [ 'storage_location' => $storageLocation, 'path' => $path, ] ); if (!$record instanceof UnprocessableMedia) { $record = new UnprocessableMedia($storageLocation, $path); $record->setError($error); } $record->setMtime(time() + 5); $this->em->persist($record); $this->em->flush(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/UnprocessableMediaRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
453
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\StationWebhook; /** * @extends AbstractStationBasedRepository<StationWebhook> */ final class StationWebhookRepository extends AbstractStationBasedRepository { protected string $entityClass = StationWebhook::class; } ```
/content/code_sandbox/backend/src/Entity/Repository/StationWebhookRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
64
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Settings; use App\Exception\ValidationException; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\Serializer; use Symfony\Component\Validator\Validator\ValidatorInterface; /** * @extends Repository<Settings> */ final class SettingsRepository extends Repository { protected string $entityClass = Settings::class; public function __construct( private readonly Serializer $serializer, private readonly ValidatorInterface $validator ) { } public function readSettings(): Settings { static $settingsId = null; if (null !== $settingsId) { $settings = $this->repository->find($settingsId); if ($settings instanceof Settings) { return $settings; } } $settings = $this->repository->findOneBy([]); if (!($settings instanceof Settings)) { $settings = new Settings(); $this->em->persist($settings); $this->em->flush(); } $settingsId = $settings->getAppUniqueIdentifier(); return $settings; } /** * @param Settings|array $settingsObj */ public function writeSettings(Settings|array $settingsObj): void { if (is_array($settingsObj)) { $settings = $this->readSettings(); $settings = $this->fromArray($settings, $settingsObj); } else { $settings = $settingsObj; } $errors = $this->validator->validate($settingsObj); if (count($errors) > 0) { throw ValidationException::fromValidationErrors($errors); } $this->em->persist($settings); $this->em->flush(); } public function fromArray(Settings $entity, array $source): Settings { return $this->serializer->denormalize( $source, Settings::class, null, [ AbstractNormalizer::OBJECT_TO_POPULATE => $entity, ] ); } public function toArray(Settings $entity): array { return (array)$this->serializer->normalize( $entity ); } } ```
/content/code_sandbox/backend/src/Entity/Repository/SettingsRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
472
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Interfaces\SongInterface; use App\Entity\Station; use App\Entity\StationMedia; use App\Entity\StationPlaylist; use App\Entity\StationQueue; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Doctrine\ORM\QueryBuilder; /** * @extends AbstractStationBasedRepository<StationQueue> */ final class StationQueueRepository extends AbstractStationBasedRepository { protected string $entityClass = StationQueue::class; public function clearForMediaAndPlaylist( StationMedia $media, StationPlaylist $playlist ): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationQueue sq WHERE sq.media = :media AND sq.playlist = :playlist AND sq.is_played = 0 DQL )->setParameter('media', $media) ->setParameter('playlist', $playlist) ->execute(); } public function clearForPlaylist( StationPlaylist $playlist ): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationQueue sq WHERE sq.playlist = :playlist AND sq.is_played = 0 DQL )->setParameter('playlist', $playlist) ->execute(); } public function getNextVisible(Station $station): ?StationQueue { return $this->getUnplayedBaseQuery($station) ->andWhere('sq.is_visible = 1') ->getQuery() ->setMaxResults(1) ->getOneOrNullResult(); } public function trackPlayed( Station $station, StationQueue $row ): void { $this->em->createQuery( <<<'DQL' UPDATE App\Entity\StationQueue sq SET sq.timestamp_played = :timestamp WHERE sq.station = :station AND sq.id = :id DQL )->setParameter('timestamp', time()) ->setParameter('station', $station) ->setParameter('id', $row->getIdRequired()) ->execute(); $this->em->createQuery( <<<'DQL' UPDATE App\Entity\StationQueue sq SET sq.is_played=1, sq.sent_to_autodj=1 WHERE sq.station = :station AND sq.is_played = 0 AND (sq.id = :id OR sq.timestamp_cued < :cued) DQL )->setParameter('station', $station) ->setParameter('id', $row->getIdRequired()) ->setParameter('cued', $row->getTimestampCued()) ->execute(); } public function isPlaylistRecentlyPlayed( StationPlaylist $playlist, ?int $playPerSongs = null, int $belowId = null ): bool { $playPerSongs ??= $playlist->getPlayPerSongs(); $recentPlayedQuery = $this->em->createQueryBuilder() ->select('sq.playlist_id') ->from(StationQueue::class, 'sq') ->where('sq.station = :station') ->setParameter('station', $playlist->getStation()) ->andWhere('sq.playlist_id is not null') ->andWhere('sq.playlist = :playlist OR sq.is_visible = 1') ->setParameter('playlist', $playlist) ->setMaxResults($playPerSongs) ->orderBy('sq.id', 'desc'); if (null !== $belowId) { $recentPlayedQuery = $recentPlayedQuery->andWhere('sq.id < :bel') ->setParameter('bel', $belowId); } return in_array( $playlist->getIdRequired(), $recentPlayedQuery->getQuery()->getSingleColumnResult(), true ); } /** * @return mixed[] */ public function getRecentlyPlayedByTimeRange( Station $station, CarbonInterface $now, int $minutes ): array { $threshold = $now->subMinutes($minutes)->getTimestamp(); return $this->em->createQuery( <<<'DQL' SELECT sq.song_id, sq.timestamp_played, sq.title, sq.artist FROM App\Entity\StationQueue sq WHERE sq.station = :station AND (sq.is_played = 0 OR sq.timestamp_played >= :threshold) ORDER BY sq.timestamp_played DESC DQL )->setParameter('station', $station) ->setParameter('threshold', $threshold) ->getArrayResult(); } /** * @param Station $station * @return StationQueue[] */ public function getUnplayedQueue(Station $station): array { return $this->getUnplayedBaseQuery($station)->getQuery()->execute(); } public function clearUpcomingQueue(Station $station): void { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationQueue sq WHERE sq.station = :station AND sq.sent_to_autodj = 0 DQL )->setParameter('station', $station) ->execute(); } public function getNextToSendToAutoDj(Station $station): ?StationQueue { return $this->getBaseQuery($station) ->andWhere('sq.sent_to_autodj = 0') ->orderBy('sq.timestamp_cued', 'ASC') ->getQuery() ->setMaxResults(1) ->getOneOrNullResult(); } public function findRecentlyCuedSong( Station $station, SongInterface $song ): ?StationQueue { return $this->getUnplayedBaseQuery($station) ->andWhere('sq.sent_to_autodj = 1') ->andWhere('sq.song_id = :song_id') ->setParameter('song_id', $song->getSongId()) ->getQuery() ->setMaxResults(1) ->getOneOrNullResult(); } public function hasCuedPlaylistMedia(StationPlaylist $playlist): bool { $station = $playlist->getStation(); $cuedPlaylistContentCountQuery = $this->getUnplayedBaseQuery($station) ->select('count(sq.id)') ->andWhere('sq.playlist = :playlist') ->setParameter('playlist', $playlist) ->getQuery(); $cuedPlaylistContentCount = $cuedPlaylistContentCountQuery->getSingleScalarResult(); return $cuedPlaylistContentCount > 0; } public function getLastPlayedTimeForPlaylist( StationPlaylist $playlist, CarbonInterface $now ): int { $sq = $this->em->createQuery( <<<'DQL' SELECT sq FROM App\Entity\StationQueue sq WHERE sq.playlist_id = :playlist and sq.timestamp_played < :now ORDER BY sq.timestamp_played DESC DQL )->setParameter('playlist', $playlist) ->setParameter('now', $now->getTimestamp()) ->setMaxResults(1) ->getOneOrNullResult(); return null === $sq ? 0 : $sq->getTimestampPlayed(); } public function getUnplayedBaseQuery(Station $station): QueryBuilder { return $this->getBaseQuery($station) ->andWhere('sq.is_played = 0') ->orderBy('sq.sent_to_autodj', 'DESC') ->addOrderBy('sq.timestamp_cued', 'ASC'); } private function getBaseQuery(Station $station): QueryBuilder { return $this->em->createQueryBuilder() ->select('sq, sm, sp') ->from(StationQueue::class, 'sq') ->leftJoin('sq.media', 'sm') ->leftJoin('sq.playlist', 'sp') ->where('sq.station = :station') ->setParameter('station', $station); } public function clearUnplayed(?Station $station = null): void { $qb = $this->em->createQueryBuilder() ->delete(StationQueue::class, 'sq') ->where('sq.is_played = 0'); if (null !== $station) { $qb->andWhere('sq.station = :station') ->setParameter('station', $station); } $qb->getQuery()->execute(); } public function cleanup(int $daysToKeep): void { $threshold = CarbonImmutable::now() ->subDays($daysToKeep) ->getTimestamp(); $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationQueue sq WHERE sq.timestamp_cued <= :threshold DQL )->setParameter('threshold', $threshold) ->execute(); } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationQueueRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,879
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\Interfaces\StationAwareInterface; use App\Entity\Station; use App\Exception\NotFoundException; /** * @template TEntity as object * @extends Repository<TEntity> */ abstract class AbstractStationBasedRepository extends Repository { /** * @return TEntity|null */ public function findForStation(int|string $id, Station $station): ?object { $record = $this->find($id); if ($record instanceof StationAwareInterface && $station === $record->getStation()) { return $record; } return null; } /** * @return TEntity */ public function requireForStation(int|string $id, Station $station): object { $record = $this->findForStation($id, $station); if (null === $record) { throw NotFoundException::generic(); } return $record; } } ```
/content/code_sandbox/backend/src/Entity/Repository/AbstractStationBasedRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
211
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Entity\Station; use App\Entity\StationPlaylist; use App\Entity\StationPlaylistFolder; /** * @extends AbstractStationBasedRepository<StationPlaylistFolder> */ final class StationPlaylistFolderRepository extends AbstractStationBasedRepository { protected string $entityClass = StationPlaylistFolder::class; /** * @param Station $station * @param string $path * @param array<int, int> $playlists An array of Playlist IDs (id => weight) */ public function addPlaylistsToFolder( Station $station, string $path, array $playlists ): void { $path = self::filterPath($path); foreach ($this->getPlaylistIdsForFolder($station, $path) as $playlistId) { unset($playlists[$playlistId]); } foreach ($playlists as $playlistId => $playlistWeight) { /** @var StationPlaylist $playlist */ $playlist = $this->em->getReference(StationPlaylist::class, $playlistId); $newRecord = new StationPlaylistFolder($station, $playlist, $path); $this->em->persist($newRecord); } $this->em->flush(); } /** * @param Station $station * @param string $path * @param array<int, int> $playlists An array of Playlist IDs (id => weight) */ public function setPlaylistsForFolder( Station $station, string $path, array $playlists ): void { $path = self::filterPath($path); $toDelete = []; foreach ($this->getPlaylistIdsForFolder($station, $path) as $playlistId) { if (isset($playlists[$playlistId])) { unset($playlists[$playlistId]); } else { $toDelete[] = $playlistId; } } if (0 !== count($toDelete)) { $this->em->createQuery( <<<'DQL' DELETE FROM App\Entity\StationPlaylistFolder spf WHERE spf.station = :station AND spf.path = :path AND spf.playlist_id IN (:playlistIds) DQL )->setParameter('station', $station) ->setParameter('path', $path) ->setParameter('playlistIds', $toDelete) ->execute(); } foreach ($playlists as $playlistId => $playlistWeight) { /** @var StationPlaylist $playlist */ $playlist = $this->em->getReference(StationPlaylist::class, $playlistId); $newRecord = new StationPlaylistFolder($station, $playlist, $path); $this->em->persist($newRecord); } $this->em->flush(); } /** * @return int[] */ public function getPlaylistIdsForFolderAndParents( Station $station, string $path ): array { $path = self::filterPath($path); $playlistIds = []; for ($i = 0; $i <= substr_count($path, '/'); $i++) { $pathToSearch = implode('/', explode('/', $path, 0 - $i)); $playlistIds = array_merge($playlistIds, $this->getPlaylistIdsForFolder($station, $pathToSearch)); } return array_unique($playlistIds); } /** * @return int[] */ protected function getPlaylistIdsForFolder( Station $station, string $path ): array { return $this->em->createQuery( <<<'DQL' SELECT spf.playlist_id FROM App\Entity\StationPlaylistFolder spf WHERE spf.station = :station AND spf.path = :path DQL )->setParameter('station', $station) ->setParameter('path', self::filterPath($path)) ->getSingleColumnResult(); } public static function filterPath(string $path): string { return trim($path, '/'); } } ```
/content/code_sandbox/backend/src/Entity/Repository/StationPlaylistFolderRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
888
```php <?php declare(strict_types=1); namespace App\Entity\Repository; use App\Doctrine\Repository; use App\Entity\User; use App\Entity\UserPasskey; use App\Security\WebAuthnPasskey; /** * @extends Repository<UserPasskey> */ final class UserPasskeyRepository extends Repository { protected string $entityClass = UserPasskey::class; public function findById(string $id): ?UserPasskey { $record = $this->repository->find(WebAuthnPasskey::hashIdentifier($id)); if (!($record instanceof UserPasskey)) { return null; } $record->verifyFullId($id); return $record; } /** * @param User $user * @return string[] */ public function getCredentialIds(User $user): array { /** @var string[] $records */ $records = $this->em->createQuery( <<<'DQL' SELECT up.full_id FROM App\Entity\UserPasskey up WHERE up.user = :user DQL )->setParameter('user', $user) ->getSingleColumnResult(); return array_map( fn($row) => base64_decode($row), $records ); } } ```
/content/code_sandbox/backend/src/Entity/Repository/UserPasskeyRepository.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
271
```php <?php declare(strict_types=1); namespace App\Entity\ApiGenerator; use App\Entity\Api\DetailedSongHistory; use App\Entity\Api\NowPlaying\SongHistory; use App\Entity\SongHistory as SongHistoryEntity; use App\Entity\StationPlaylist; use App\Entity\StationStreamer; use Psr\Http\Message\UriInterface; final class SongHistoryApiGenerator { public function __construct( private readonly SongApiGenerator $songApiGenerator ) { } public function __invoke( SongHistoryEntity $record, ?UriInterface $baseUri = null, bool $allowRemoteArt = false, bool $isNowPlaying = false, ): SongHistory { $response = new SongHistory(); $response->sh_id = $record->getIdRequired(); $response->played_at = (0 === $record->getTimestampStart()) ? 0 : $record->getTimestampStart() + SongHistoryEntity::PLAYBACK_DELAY_SECONDS; $response->duration = (int)$record->getDuration(); $response->is_request = ($record->getRequest() !== null); if ($record->getPlaylist() instanceof StationPlaylist) { $response->playlist = $record->getPlaylist()->getName(); } else { $response->playlist = ''; } if ($record->getStreamer() instanceof StationStreamer) { $response->streamer = $record->getStreamer()->getDisplayName(); } else { $response->streamer = ''; } if (null !== $record->getMedia()) { $response->song = ($this->songApiGenerator)( song: $record->getMedia(), station: $record->getStation(), baseUri: $baseUri, allowRemoteArt: $allowRemoteArt, isNowPlaying: $isNowPlaying ); } else { $response->song = ($this->songApiGenerator)( song: $record, station: $record->getStation(), baseUri: $baseUri, allowRemoteArt: $allowRemoteArt, isNowPlaying: $isNowPlaying ); } return $response; } /** * @param SongHistoryEntity[] $records * @param UriInterface|null $baseUri * @param bool $allowRemoteArt * * @return SongHistory[] */ public function fromArray( array $records, ?UriInterface $baseUri = null, bool $allowRemoteArt = false ): array { $apiRecords = []; foreach ($records as $record) { $apiRecords[] = ($this)($record, $baseUri, $allowRemoteArt); } return $apiRecords; } public function detailed( SongHistoryEntity $record, ?UriInterface $baseUri = null ): DetailedSongHistory { $apiHistory = ($this)($record, $baseUri); $response = new DetailedSongHistory(); $response->fromParentObject($apiHistory); $response->listeners_start = (int)$record->getListenersStart(); $response->listeners_end = (int)$record->getListenersEnd(); $response->delta_total = $record->getDeltaTotal(); $response->is_visible = $record->getIsVisible(); return $response; } } ```
/content/code_sandbox/backend/src/Entity/ApiGenerator/SongHistoryApiGenerator.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
719
```php <?php declare(strict_types=1); namespace App\Entity\ApiGenerator; use App\Cache\NowPlayingCache; use App\Container\LoggerAwareTrait; use App\Entity\Api\NowPlaying\CurrentSong; use App\Entity\Api\NowPlaying\Listeners; use App\Entity\Api\NowPlaying\Live; use App\Entity\Api\NowPlaying\NowPlaying; use App\Entity\Repository\SongHistoryRepository; use App\Entity\Repository\StationQueueRepository; use App\Entity\Repository\StationStreamerBroadcastRepository; use App\Entity\Song; use App\Entity\Station; use App\Entity\StationQueue; use App\Http\Router; use App\Radio\Adapters; use Exception; use GuzzleHttp\Psr7\Uri; use NowPlaying\Result\Result; use Psr\Http\Message\UriInterface; use RuntimeException; final class NowPlayingApiGenerator { use LoggerAwareTrait; public function __construct( private readonly SongApiGenerator $songApiGenerator, private readonly SongHistoryApiGenerator $songHistoryApiGenerator, private readonly StationApiGenerator $stationApiGenerator, private readonly StationQueueApiGenerator $stationQueueApiGenerator, private readonly SongHistoryRepository $historyRepo, private readonly StationQueueRepository $queueRepo, private readonly StationStreamerBroadcastRepository $broadcastRepo, private readonly Adapters $adapters, private readonly Router $router, private readonly NowPlayingCache $nowPlayingCache ) { } public function __invoke( Station $station, Result $npResult, ?NowPlaying $npOld ): NowPlaying { $baseUri = new Uri(''); // Only update songs directly from NP results if we're not getting them fed to us from the backend. $updateSongFromNowPlaying = !$station->getBackendType()->isEnabled(); if ($updateSongFromNowPlaying && empty($npResult->currentSong->text)) { return $this->offlineApi($station, $baseUri); } $np = new NowPlaying(); if ($updateSongFromNowPlaying) { $np->is_online = $npResult->meta->online; } else { $np->is_online = $this->adapters->getBackendAdapter($station)?->isRunning($station) ?? false; } $np->station = $this->stationApiGenerator->__invoke($station, $baseUri); $np->listeners = new Listeners( total: $npResult->listeners->total, unique: $npResult->listeners->unique ); try { if ($updateSongFromNowPlaying) { $this->historyRepo->updateSongFromNowPlaying( $station, Song::createFromNowPlayingSong($npResult->currentSong) ); } $this->historyRepo->updateListenersFromNowPlaying( $station, $np->listeners->current ); $history = $this->historyRepo->getVisibleHistory( $station, $station->getApiHistoryItems() + 1 ); $currentSong = array_shift($history); if (null === $currentSong) { throw new RuntimeException('No current song.'); } } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); return $this->offlineApi($station, $baseUri); } $apiSongHistory = $this->songHistoryApiGenerator->__invoke( record: $currentSong, baseUri: $baseUri, allowRemoteArt: true, isNowPlaying: true ); $apiCurrentSong = new CurrentSong(); $apiCurrentSong->fromParentObject($apiSongHistory); $np->now_playing = $apiCurrentSong; $np->song_history = $this->songHistoryApiGenerator->fromArray( $history, $baseUri, true ); $nextVisibleSong = $this->queueRepo->getNextVisible($station); if (null === $nextVisibleSong) { $np->playing_next = $npOld->playing_next ?? null; } else { $np->playing_next = ($this->stationQueueApiGenerator)( $nextVisibleSong, $baseUri, true ); } // Detect and report live DJ status $currentStreamer = $station->getCurrentStreamer(); if (null !== $currentStreamer) { $broadcastStart = $this->broadcastRepo->getLatestBroadcast($station)?->getTimestampStart(); $live = new Live(); $live->is_live = true; $live->streamer_name = $currentStreamer->getDisplayName(); $live->broadcast_start = $broadcastStart; if (0 !== $currentStreamer->getArtUpdatedAt()) { $live->art = $this->router->namedAsUri( routeName: 'api:stations:streamer:art', routeParams: [ 'station_id' => $station->getShortName(), 'id' => $currentStreamer->getIdRequired(), 'timestamp' => $currentStreamer->getArtUpdatedAt(), ], ); } $np->live = $live; } else { $np->live = new Live(); } $np->update(); return $np; } public function currentOrEmpty( Station $station ): NowPlaying { $np = $this->nowPlayingCache->getForStation($station); return $np ?? $this->offlineApi($station); } private function offlineApi( Station $station, ?UriInterface $baseUri = null ): NowPlaying { $np = new NowPlaying(); $np->station = $this->stationApiGenerator->__invoke($station, $baseUri); $np->listeners = new Listeners(); $songObj = Song::createOffline($station->getBrandingConfig()->getOfflineText()); $offlineApiNowPlaying = new CurrentSong(); $offlineApiNowPlaying->sh_id = 0; $offlineApiNowPlaying->song = $this->songApiGenerator->__invoke( song: $songObj, station: $station, baseUri: $baseUri ); $np->now_playing = $offlineApiNowPlaying; $np->song_history = $this->songHistoryApiGenerator->fromArray( $this->historyRepo->getVisibleHistory($station), $baseUri, true ); $nextVisible = $this->queueRepo->getNextVisible($station); if ($nextVisible instanceof StationQueue) { $np->playing_next = ($this->stationQueueApiGenerator)( $nextVisible, $baseUri, true ); } $np->live = new Live(); $np->update(); return $np; } } ```
/content/code_sandbox/backend/src/Entity/ApiGenerator/NowPlayingApiGenerator.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,469
```php <?php declare(strict_types=1); namespace App\Entity\ApiGenerator; use App\Entity\Api\Podcast as ApiPodcast; use App\Entity\Api\PodcastCategory as ApiPodcastCategory; use App\Entity\Podcast; use App\Entity\Repository\PodcastRepository; use App\Entity\Station; use App\Http\ServerRequest; use App\Utilities\Strings; use Symfony\Component\Intl\Exception\MissingResourceException; use Symfony\Component\Intl\Languages; final class PodcastApiGenerator { /** * @var array<string, array<string>> */ private array $publishedPodcasts = []; public function __construct( private readonly PodcastRepository $podcastRepo ) { } public function __invoke( Podcast $record, ServerRequest $request ): ApiPodcast { $router = $request->getRouter(); $isInternal = $request->isInternal(); $station = $request->getStation(); $return = new ApiPodcast(); $return->id = $record->getIdRequired(); $return->storage_location_id = $record->getStorageLocation()->getIdRequired(); $return->source = $record->getSource()->value; $return->playlist_id = $record->getPlaylist()?->getIdRequired(); $return->playlist_auto_publish = $record->playlistAutoPublish(); $return->title = $record->getTitle(); $return->link = $record->getLink(); $return->description = $record->getDescription(); $return->description_short = Strings::truncateText($return->description, 200); $return->is_enabled = $record->isEnabled(); $return->branding_config = $record->getBrandingConfig(); $return->language = $record->getLanguage(); try { $locale = $request->getCustomization()->getLocale(); $return->language_name = Languages::getName( $return->language, $locale->value ); } catch (MissingResourceException) { } $return->author = $record->getAuthor(); $return->email = $record->getEmail(); $categories = []; foreach ($record->getCategories() as $category) { $categoryRow = new ApiPodcastCategory(); $categoryRow->category = $category->getCategory(); $categoryRow->title = $category->getTitle(); $categoryRow->subtitle = $category->getSubTitle(); $categoryRow->text = (!empty($categoryRow->subtitle)) ? $categoryRow->title . ' - ' . $categoryRow->subtitle : $categoryRow->title; $categories[] = $categoryRow; } $return->categories = $categories; $return->is_published = $this->isPublished($record, $station); $return->art_updated_at = $record->getArtUpdatedAt(); $return->has_custom_art = (0 !== $record->getArtUpdatedAt()); $return->episodes = $record->getEpisodes()->count(); $baseRouteParams = [ 'station_id' => $station->getIdRequired(), 'podcast_id' => $record->getIdRequired(), ]; $artRouteParams = $baseRouteParams; if ($return->has_custom_art) { $artRouteParams['timestamp'] = $record->getArtUpdatedAt(); } $return->art = $router->named( routeName: 'api:stations:public:podcast:art', routeParams: $artRouteParams, absolute: !$isInternal ); $return->links = [ 'self' => $router->named( routeName: 'api:stations:public:podcast', routeParams: $baseRouteParams, absolute: !$isInternal ), 'episodes' => $router->named( routeName: 'api:stations:public:podcast:episodes', routeParams: $baseRouteParams, absolute: !$isInternal ), 'public_episodes' => $router->named( routeName: 'public:podcast', routeParams: $baseRouteParams, absolute: !$isInternal ), 'public_feed' => $router->named( routeName: 'public:podcast:feed', routeParams: $baseRouteParams, absolute: !$isInternal ), ]; return $return; } private function isPublished( Podcast $podcast, Station $station ): bool { if (!isset($this->publishedPodcasts[$station->getShortName()])) { $this->publishedPodcasts[$station->getShortName()] = $this->podcastRepo->getPodcastIdsWithPublishedEpisodes( $station ); } return in_array( $podcast->getIdRequired(), $this->publishedPodcasts[$station->getShortName()] ?? [], true ); } } ```
/content/code_sandbox/backend/src/Entity/ApiGenerator/PodcastApiGenerator.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,068
```php <?php declare(strict_types=1); namespace App\Entity\ApiGenerator; use App\Entity\Api\NowPlaying\Station as NowPlayingStation; use App\Entity\Station; use App\Http\Router; use App\Radio\Adapters; use Psr\Http\Message\UriInterface; final class StationApiGenerator { public function __construct( private readonly Adapters $adapters, private readonly Router $router ) { } public function __invoke( Station $station, ?UriInterface $baseUri = null, bool $showAllMounts = false ): NowPlayingStation { $frontend = $this->adapters->getFrontendAdapter($station); $backend = $this->adapters->getBackendAdapter($station); $response = new NowPlayingStation(); $response->id = (int)$station->getId(); $response->name = (string)$station->getName(); $response->shortcode = $station->getShortName(); $response->description = (string)$station->getDescription(); $response->frontend = $station->getFrontendType()->value; $response->backend = $station->getBackendType()->value; $response->timezone = $station->getTimezone(); $response->url = $station->getUrl(); $response->is_public = $station->getEnablePublicPage(); $response->public_player_url = $this->router->named( 'public:index', ['station_id' => $station->getShortName()] ); $response->playlist_pls_url = $this->router->named( 'public:playlist', ['station_id' => $station->getShortName(), 'format' => 'pls'] ); $response->playlist_m3u_url = $this->router->named( 'public:playlist', ['station_id' => $station->getShortName(), 'format' => 'm3u'] ); $mounts = []; if ( null !== $frontend && $station->getFrontendType()->supportsMounts() && $station->getMounts()->count() > 0 ) { foreach ($station->getMounts() as $mount) { if ($showAllMounts || $mount->getIsVisibleOnPublicPages()) { $mounts[] = $mount->api($frontend, $baseUri); } } } $response->mounts = $mounts; $remotes = []; foreach ($station->getRemotes() as $remote) { if ($showAllMounts || $remote->getIsVisibleOnPublicPages()) { $remotes[] = $remote->api( $this->adapters->getRemoteAdapter($remote) ); } } $response->remotes = $remotes; // Pull the "listen URL" from the best available source for the station. $response->listen_url = match (true) { (null !== $frontend) => $frontend->getStreamUrl($station, $baseUri), (count($remotes) > 0) => $remotes[0]->url, default => null }; $response->hls_enabled = $station->getBackendType()->isEnabled() && $station->getEnableHls(); $response->hls_is_default = $response->hls_enabled && $station->getBackendConfig()->getHlsIsDefault(); $response->hls_url = (null !== $backend && $response->hls_enabled) ? $backend->getHlsUrl($station, $baseUri) : null; $hlsListeners = 0; foreach ($station->getHlsStreams() as $hlsStream) { $hlsListeners += $hlsStream->getListeners(); } $response->hls_listeners = $hlsListeners; return $response; } } ```
/content/code_sandbox/backend/src/Entity/ApiGenerator/StationApiGenerator.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
849
```php <?php declare(strict_types=1); namespace App\Entity\ApiGenerator; use App\Entity\Api\NowPlaying\StationQueue as NowPlayingStationQueue; use App\Entity\StationPlaylist; use App\Entity\StationQueue; use Psr\Http\Message\UriInterface; final class StationQueueApiGenerator { public function __construct( private readonly SongApiGenerator $songApiGenerator ) { } public function __invoke( StationQueue $record, ?UriInterface $baseUri = null, bool $allowRemoteArt = false ): NowPlayingStationQueue { $response = new NowPlayingStationQueue(); $response->cued_at = $record->getTimestampCued(); $response->played_at = $record->getTimestampPlayed(); $response->duration = (int)$record->getDuration(); $response->is_request = $record->getRequest() !== null; if ($record->getPlaylist() instanceof StationPlaylist) { $response->playlist = $record->getPlaylist()->getName(); } else { $response->playlist = ''; } $recordMedia = $record->getMedia(); if (null !== $recordMedia) { $response->song = ($this->songApiGenerator)( song: $recordMedia, station: $record->getStation(), baseUri: $baseUri, allowRemoteArt: $allowRemoteArt ); } else { $response->song = ($this->songApiGenerator)( song: $record, station: $record->getStation(), baseUri: $baseUri, allowRemoteArt: $allowRemoteArt ); } return $response; } } ```
/content/code_sandbox/backend/src/Entity/ApiGenerator/StationQueueApiGenerator.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
363
```php <?php declare(strict_types=1); namespace App\Entity\ApiGenerator; use App\Entity\Api\PodcastEpisode as ApiPodcastEpisode; use App\Entity\Api\PodcastMedia as ApiPodcastMedia; use App\Entity\Enums\PodcastSources; use App\Entity\PodcastEpisode; use App\Entity\PodcastMedia; use App\Entity\StationMedia; use App\Http\ServerRequest; use App\Utilities\Strings; use Symfony\Component\Filesystem\Path; final class PodcastEpisodeApiGenerator { public function __construct( private readonly SongApiGenerator $songApiGen ) { } public function __invoke( PodcastEpisode $record, ServerRequest $request ): ApiPodcastEpisode { $router = $request->getRouter(); $isInternal = $request->isInternal(); $station = $request->getStation(); $podcast = $request->getPodcast(); $return = new ApiPodcastEpisode(); $return->id = $record->getIdRequired(); $return->title = $record->getTitle(); $return->link = $record->getLink(); $return->description = $record->getDescription(); $return->description_short = Strings::truncateText($return->description, 100); $return->explicit = $record->getExplicit(); $return->season_number = $record->getSeasonNumber(); $return->episode_number = $record->getEpisodeNumber(); $return->created_at = $record->getCreatedAt(); $return->publish_at = $record->getPublishAt(); $mediaExtension = ''; switch ($podcast->getSource()) { case PodcastSources::Playlist: $return->media = null; $playlistMediaRow = $record->getPlaylistMedia(); if ($playlistMediaRow instanceof StationMedia) { $return->has_media = true; $return->playlist_media = $this->songApiGen->__invoke($playlistMediaRow); $return->playlist_media_id = $playlistMediaRow->getUniqueId(); $mediaExtension = Path::getExtension($playlistMediaRow->getPath()); } else { $return->has_media = false; $return->playlist_media = null; $return->playlist_media_id = null; } break; case PodcastSources::Manual: $return->playlist_media = null; $return->playlist_media_id = null; $mediaRow = $record->getMedia(); $return->has_media = ($mediaRow instanceof PodcastMedia); if ($mediaRow instanceof PodcastMedia) { $media = new ApiPodcastMedia(); $media->id = $mediaRow->getId(); $media->original_name = $mediaRow->getOriginalName(); $media->length = $mediaRow->getLength(); $media->length_text = $mediaRow->getLengthText(); $media->path = $mediaRow->getPath(); $return->has_media = true; $return->media = $media; $mediaExtension = Path::getExtension($mediaRow->getPath()); } else { $return->has_media = false; $return->media = null; } break; } $return->is_published = $record->isPublished(); $return->art_updated_at = $record->getArtUpdatedAt(); $return->has_custom_art = (0 !== $return->art_updated_at); $baseRouteParams = [ 'station_id' => $station->getShortName(), 'podcast_id' => $podcast->getIdRequired(), 'episode_id' => $record->getIdRequired(), ]; $artRouteParams = $baseRouteParams; if (0 !== $return->art_updated_at) { $artRouteParams['timestamp'] = $return->art_updated_at; } $downloadRouteParams = $baseRouteParams; if ('' !== $mediaExtension) { $downloadRouteParams['extension'] = $mediaExtension; } $return->art = $router->named( routeName: 'api:stations:public:podcast:episode:art', routeParams: $artRouteParams, absolute: !$isInternal ); $return->links = [ 'self' => $router->named( routeName: 'api:stations:public:podcast:episode', routeParams: $baseRouteParams, absolute: !$isInternal ), 'public' => $router->fromHere( routeName: 'public:podcast:episode', routeParams: $baseRouteParams, absolute: !$isInternal ), 'download' => $router->fromHere( routeName: 'api:stations:public:podcast:episode:download', routeParams: $downloadRouteParams, absolute: !$isInternal ), ]; return $return; } } ```
/content/code_sandbox/backend/src/Entity/ApiGenerator/PodcastEpisodeApiGenerator.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,056
```php <?php declare(strict_types=1); namespace App\Entity\ApiGenerator; use App\Container\EntityManagerAwareTrait; use App\Entity\Api\Song; use App\Entity\Interfaces\SongInterface; use App\Entity\Repository\CustomFieldRepository; use App\Entity\Repository\StationRepository; use App\Entity\Station; use App\Entity\StationMedia; use App\Http\Router; use App\Media\RemoteAlbumArt; use GuzzleHttp\Psr7\UriResolver; use GuzzleHttp\Psr7\Utils; use Psr\Http\Message\UriInterface; final class SongApiGenerator { use EntityManagerAwareTrait; public function __construct( private readonly Router $router, private readonly StationRepository $stationRepo, private readonly CustomFieldRepository $customFieldRepo, private readonly RemoteAlbumArt $remoteAlbumArt ) { } public function __invoke( SongInterface $song, ?Station $station = null, ?UriInterface $baseUri = null, bool $allowRemoteArt = false, bool $isNowPlaying = false, ): Song { $response = new Song(); $response->id = $song->getSongId(); $response->text = $song->getText() ?? ''; $response->artist = $song->getArtist() ?? ''; $response->title = $song->getTitle() ?? ''; if ($song instanceof StationMedia) { $response->album = $song->getAlbum() ?? ''; $response->genre = $song->getGenre() ?? ''; $response->isrc = $song->getIsrc() ?? ''; $response->lyrics = $song->getLyrics() ?? ''; $response->custom_fields = $this->getCustomFields($song->getId()); } else { $response->custom_fields = $this->getCustomFields(); } $response->art = UriResolver::resolve( $baseUri ?? $this->router->getBaseUrl(), $this->getAlbumArtUrl($song, $station, $allowRemoteArt, $isNowPlaying) ); return $response; } private function getAlbumArtUrl( SongInterface $song, ?Station $station = null, bool $allowRemoteArt = false, bool $isNowPlaying = false, ): UriInterface { if (null !== $station && $song instanceof StationMedia) { $routeParams = [ 'station_id' => $station->getShortName(), 'media_id' => $song->getUniqueId(), ]; $mediaUpdatedTimestamp = $song->getArtUpdatedAt(); if (0 !== $mediaUpdatedTimestamp) { $routeParams['timestamp'] = $mediaUpdatedTimestamp; } return $this->router->namedAsUri( routeName: 'api:stations:media:art', routeParams: $routeParams ); } if ($allowRemoteArt && $this->remoteAlbumArt->enableForApis()) { $url = $this->remoteAlbumArt->getUrlForSong($song); if (null !== $url) { return Utils::uriFor($url); } } if ($isNowPlaying && null !== $station) { $currentStreamer = $station->getCurrentStreamer(); if (null !== $currentStreamer && 0 !== $currentStreamer->getArtUpdatedAt()) { return $this->router->namedAsUri( routeName: 'api:stations:streamer:art', routeParams: [ 'station_id' => $station->getShortName(), 'id' => $currentStreamer->getIdRequired(), 'timestamp' => $currentStreamer->getArtUpdatedAt(), ], ); } } return $this->stationRepo->getDefaultAlbumArtUrl($station); } /** * Return all custom fields, either with a null value or with the custom value assigned to the given Media ID. * * @param int|null $mediaId * * @return mixed[] */ private function getCustomFields(?int $mediaId = null): array { $fields = $this->customFieldRepo->getFieldIds(); $mediaFields = []; if ($mediaId !== null) { $mediaFieldsRaw = $this->em->createQuery( <<<'DQL' SELECT smcf.field_id, smcf.value FROM App\Entity\StationMediaCustomField smcf WHERE smcf.media_id = :media_id DQL )->setParameter('media_id', $mediaId) ->getArrayResult(); foreach ($mediaFieldsRaw as $row) { $mediaFields[$row['field_id']] = $row['value']; } } $customFields = []; foreach ($fields as $fieldId => $fieldKey) { $customFields[$fieldKey] = $mediaFields[$fieldId] ?? null; } return $customFields; } } ```
/content/code_sandbox/backend/src/Entity/ApiGenerator/SongApiGenerator.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,061
```php <?php declare(strict_types=1); namespace App\Entity\ApiGenerator; use App\Entity\Api\StationSchedule as StationScheduleApi; use App\Entity\StationPlaylist; use App\Entity\StationSchedule; use App\Entity\StationStreamer; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; final class ScheduleApiGenerator { public function __invoke( StationSchedule $scheduleItem, ?CarbonInterface $start, ?CarbonInterface $end, ?CarbonInterface $now ): StationScheduleApi { $playlist = $scheduleItem->getPlaylist(); $streamer = $scheduleItem->getStreamer(); if (null === $now) { if (null !== $playlist) { $station = $playlist->getStation(); } elseif (null !== $streamer) { $station = $streamer->getStation(); } else { $station = null; } $now = CarbonImmutable::now($station?->getTimezoneObject()); } if (null === $start || null === $end) { $start = StationSchedule::getDateTime($scheduleItem->getStartTime(), $now); $end = StationSchedule::getDateTime($scheduleItem->getEndTime(), $now); // Handle overnight schedule items if ($end < $start) { $end = $end->addDay(); } } $row = new StationScheduleApi(); $row->id = $scheduleItem->getIdRequired(); $row->start_timestamp = $start->getTimestamp(); $row->start = $start->toIso8601String(); $row->end_timestamp = $end->getTimestamp(); $row->end = $end->toIso8601String(); $row->is_now = ($start <= $now && $end >= $now); if ($playlist instanceof StationPlaylist) { $row->type = StationScheduleApi::TYPE_PLAYLIST; $row->name = $playlist->getName(); $row->title = $row->name; $row->description = sprintf(__('Playlist: %s'), $row->name); } elseif ($streamer instanceof StationStreamer) { $row->type = StationScheduleApi::TYPE_STREAMER; $row->name = $streamer->getDisplayName(); $row->title = $row->name; $row->description = sprintf(__('Streamer: %s'), $row->name); } return $row; } } ```
/content/code_sandbox/backend/src/Entity/ApiGenerator/ScheduleApiGenerator.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
528
```php <?php declare(strict_types=1); namespace App\Entity\Interfaces; use App\Radio\Enums\AdapterTypeInterface; use App\Radio\Enums\StreamFormats; use App\Radio\Enums\StreamProtocols; interface StationMountInterface { public function getEnableAutodj(): bool; public function getAutodjUsername(): ?string; public function getAutodjPassword(): ?string; public function getAutodjBitrate(): ?int; public function getAutodjFormat(): ?StreamFormats; public function getAutodjHost(): ?string; public function getAutodjPort(): ?int; public function getAutodjProtocol(): ?StreamProtocols; public function getAutodjMount(): ?string; public function getAutodjAdapterType(): AdapterTypeInterface; public function getIsPublic(): bool; public function getIsShoutcast(): bool; } ```
/content/code_sandbox/backend/src/Entity/Interfaces/StationMountInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
200
```php <?php declare(strict_types=1); namespace App\Entity\Interfaces; interface EntityGroupsInterface { public const string GROUP_ID = 'id'; public const string GROUP_GENERAL = 'general'; public const string GROUP_ADMIN = 'admin'; public const string GROUP_ALL = 'all'; } ```
/content/code_sandbox/backend/src/Entity/Interfaces/EntityGroupsInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
63
```php <?php declare(strict_types=1); namespace App\Entity\Interfaces; use App\Entity\Station; interface StationCloneAwareInterface extends StationAwareInterface { public function setStation(Station $station): void; } ```
/content/code_sandbox/backend/src/Entity/Interfaces/StationCloneAwareInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
46
```php <?php declare(strict_types=1); namespace App\Entity\Interfaces; use App\Entity\Station; interface StationAwareInterface { public function getStation(): ?Station; } ```
/content/code_sandbox/backend/src/Entity/Interfaces/StationAwareInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
38
```php <?php declare(strict_types=1); namespace App\Entity\Interfaces; interface PathAwareInterface { public function getPath(): string; public function setPath(string $path): void; } ```
/content/code_sandbox/backend/src/Entity/Interfaces/PathAwareInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
41
```php <?php declare(strict_types=1); namespace App\Entity\Interfaces; interface SongInterface { public function getSongId(): string; public function updateSongId(): void; public function getText(): ?string; public function setText(?string $text): void; public function getArtist(): ?string; public function setArtist(?string $artist): void; public function getTitle(): ?string; public function setTitle(?string $title): void; } ```
/content/code_sandbox/backend/src/Entity/Interfaces/SongInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
99
```php <?php declare(strict_types=1); namespace App\Entity\Interfaces; interface ProcessableMediaInterface { public static function needsReprocessing( int $fileModifiedTime = 0, int $dbModifiedTime = 0 ): bool; } ```
/content/code_sandbox/backend/src/Entity/Interfaces/ProcessableMediaInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
56
```php <?php declare(strict_types=1); namespace App\Entity\Interfaces; interface IdentifiableEntityInterface { public function getId(): null|int|string; public function getIdRequired(): int|string; } ```
/content/code_sandbox/backend/src/Entity/Interfaces/IdentifiableEntityInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
42
```php <?php declare(strict_types=1); namespace App\Media; use App\Container\EntityManagerAwareTrait; use App\Doctrine\ReadWriteBatchIteratorAggregate; use App\Entity\Interfaces\PathAwareInterface; use App\Entity\Repository\StationMediaRepository; use App\Entity\Repository\StorageLocationRepository; use App\Entity\Repository\UnprocessableMediaRepository; use App\Entity\StationMedia; use App\Entity\StationPlaylistFolder; use App\Entity\StorageLocation; use App\Entity\UnprocessableMedia; use App\Flysystem\ExtendedFilesystemInterface; use App\Utilities\File; use Throwable; final class BatchUtilities { use EntityManagerAwareTrait; public function __construct( private readonly StationMediaRepository $mediaRepo, private readonly UnprocessableMediaRepository $unprocessableMediaRepo, private readonly StorageLocationRepository $storageLocationRepo, ) { } public function handleRename( string $from, string $to, StorageLocation $storageLocation, ?ExtendedFilesystemInterface $fs = null ): void { $fs ??= $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); if ($fs->isDir($to)) { // Update the paths of all media contained within the directory. $toRename = [ $this->iterateMediaInDirectory($storageLocation, $from), $this->iterateUnprocessableMediaInDirectory($storageLocation, $from), $this->iteratePlaylistFoldersInDirectory($storageLocation, $from), ]; foreach ($toRename as $iterator) { foreach ($iterator as $record) { /** @var PathAwareInterface $record */ $record->setPath( File::renameDirectoryInPath($record->getPath(), $from, $to) ); $this->em->persist($record); } } } else { $record = $this->mediaRepo->findByPath($from, $storageLocation); if ($record instanceof StationMedia) { $record->setPath($to); $this->em->persist($record); $this->em->flush(); } else { $record = $this->unprocessableMediaRepo->findByPath($from, $storageLocation); if ($record instanceof UnprocessableMedia) { $record->setPath($to); $this->em->persist($record); $this->em->flush(); } } } } /** * @param array $files * @param array $directories * @param StorageLocation $storageLocation * @param ExtendedFilesystemInterface|null $fs * * @return array<int, int> Affected playlist IDs */ public function handleDelete( array $files, array $directories, StorageLocation $storageLocation, ?ExtendedFilesystemInterface $fs = null ): array { $fs ??= $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $affectedPlaylists = []; /* * NOTE: This iteration clears the entity manager. */ foreach ($this->iterateMedia($storageLocation, $files) as $media) { try { $affectedPlaylists += $this->mediaRepo->remove($media, false, $fs); } catch (Throwable) { } } /* * NOTE: This iteration clears the entity manager. */ foreach ($this->iterateUnprocessableMedia($storageLocation, $files) as $unprocessableMedia) { $this->em->remove($unprocessableMedia); } foreach ($directories as $dir) { foreach ($this->iteratePlaylistFoldersInDirectory($storageLocation, $dir) as $playlistFolder) { $this->em->remove($playlistFolder); } } $this->em->flush(); return $affectedPlaylists; } /** * Iterate through the found media records, while occasionally flushing and clearing the entity manager. * * @note This function flushes the entity manager. * * @param StorageLocation $storageLocation * @param array $paths * * @return iterable<StationMedia> */ public function iterateMedia(StorageLocation $storageLocation, array $paths): iterable { return ReadWriteBatchIteratorAggregate::fromTraversableResult( $this->mediaRepo->iteratePaths($paths, $storageLocation), $this->em, 25 ); } /** * @param StorageLocation $storageLocation * @param string $dir * * @return iterable<StationMedia> */ public function iterateMediaInDirectory(StorageLocation $storageLocation, string $dir): iterable { $query = $this->em->createQuery( <<<'DQL' SELECT sm FROM App\Entity\StationMedia sm WHERE sm.storage_location = :storageLocation AND sm.path LIKE :path DQL )->setParameter('storageLocation', $storageLocation) ->setParameter('path', $dir . '/%'); return ReadWriteBatchIteratorAggregate::fromQuery($query, 25); } /** * Iterate through unprocessable media, while occasionally flushing and clearing the entity manager. * * @note This function flushes the entity manager. * * @param StorageLocation $storageLocation * @param array $paths * * @return iterable<UnprocessableMedia> */ public function iterateUnprocessableMedia(StorageLocation $storageLocation, array $paths): iterable { return ReadWriteBatchIteratorAggregate::fromTraversableResult( $this->unprocessableMediaRepo->iteratePaths($paths, $storageLocation), $this->em, 25 ); } /** * @param StorageLocation $storageLocation * @param string $dir * * @return iterable<UnprocessableMedia> */ public function iterateUnprocessableMediaInDirectory( StorageLocation $storageLocation, string $dir ): iterable { $query = $this->em->createQuery( <<<'DQL' SELECT upm FROM App\Entity\UnprocessableMedia upm WHERE upm.storage_location = :storageLocation AND upm.path LIKE :path DQL )->setParameter('storageLocation', $storageLocation) ->setParameter('path', $dir . '/%'); return ReadWriteBatchIteratorAggregate::fromQuery($query, 25); } /** * @param StorageLocation $storageLocation * @param string $dir * * @return iterable<StationPlaylistFolder> */ public function iteratePlaylistFoldersInDirectory( StorageLocation $storageLocation, string $dir ): iterable { $query = $this->em->createQuery( <<<'DQL' SELECT spf FROM App\Entity\StationPlaylistFolder spf WHERE spf.station IN ( SELECT s FROM App\Entity\Station s WHERE s.media_storage_location = :storageLocation ) AND spf.path LIKE :path DQL )->setParameter('storageLocation', $storageLocation) ->setParameter('path', $dir . '%'); return ReadWriteBatchIteratorAggregate::fromQuery($query, 25); } } ```
/content/code_sandbox/backend/src/Media/BatchUtilities.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,563
```php <?php /** @noinspection SummerTimeUnsafeTimeManipulationInspection */ declare(strict_types=1); namespace App\Media; use App\Container\LoggerAwareTrait; use App\Container\SettingsAwareTrait; use App\Entity\Interfaces\SongInterface; use App\Entity\Song; use App\Event\Media\GetAlbumArt; use App\Version; use GuzzleHttp\Client; use GuzzleHttp\RequestOptions; use Psr\EventDispatcher\EventDispatcherInterface; use Psr\SimpleCache\CacheInterface; use Throwable; final class RemoteAlbumArt { use LoggerAwareTrait; use SettingsAwareTrait; public const int|float CACHE_LIFETIME = 86400 * 14; // Two Weeks public function __construct( private readonly CacheInterface $cache, private readonly EventDispatcherInterface $eventDispatcher, private readonly Client $httpClient ) { } public function enableForApis(): bool { return $this->readSettings()->getUseExternalAlbumArtInApis(); } public function enableForMedia(): bool { return $this->readSettings()->getUseExternalAlbumArtWhenProcessingMedia(); } public function getArtwork(SongInterface $media): ?string { $artUri = $this->getUrlForSong($media); if (empty($artUri)) { return null; } // Fetch external artwork. $response = $this->httpClient->request( 'GET', $artUri, [ RequestOptions::TIMEOUT => 10, RequestOptions::HEADERS => [ 'User-Agent' => 'AzuraCast ' . Version::STABLE_VERSION, ], ] ); return (string)$response->getBody(); } public function getUrlForSong(SongInterface $song): ?string { // Avoid tracks that shouldn't ever hit remote APIs. if ($song->getSongId() === Song::OFFLINE_SONG_ID) { return null; } // Catch the default error track and derivatives. if (false !== mb_stripos($song->getText() ?? '', 'AzuraCast')) { return null; } // Check for cached API hits for the same song ID before. $cacheKey = 'album_art.' . $song->getSongId(); if ($this->cache->has($cacheKey)) { $cacheResult = $this->cache->get($cacheKey); $this->logger->debug( 'Cached entry found for track.', [ 'result' => $cacheResult, 'song' => $song->getText(), 'songId' => $song->getSongId(), ] ); if ($cacheResult['success']) { return $cacheResult['url']; } return null; } // Dispatch new event to various registered handlers. try { $event = new GetAlbumArt($song); $this->eventDispatcher->dispatch($event); $albumArtUrl = $event->getAlbumArt(); if (null !== $albumArtUrl) { $this->cache->set( $cacheKey, [ 'success' => true, 'url' => $albumArtUrl, ], self::CACHE_LIFETIME ); } } catch (Throwable $e) { $albumArtUrl = null; $this->cache->set( $cacheKey, [ 'success' => false, 'message' => $e->getMessage(), ] ); } return $albumArtUrl; } } ```
/content/code_sandbox/backend/src/Media/RemoteAlbumArt.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
764
```php <?php declare(strict_types=1); namespace App\Media; use League\MimeTypeDetection\GeneratedExtensionToMimeTypeMap; final class MimeTypeExtensionMap extends GeneratedExtensionToMimeTypeMap { public const array ADDED_MIME_TYPES = [ 'mod' => 'audio/x-mod', 'stm' => 'audio/x-mod', ]; public function lookupMimeType(string $extension): ?string { return parent::lookupMimeType($extension) ?? self::ADDED_MIME_TYPES[$extension] ?? null; } } ```
/content/code_sandbox/backend/src/Media/MimeTypeExtensionMap.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
116
```php <?php declare(strict_types=1); namespace App\Media; /** * @phpstan-import-type KnownTags from MetadataInterface * @phpstan-import-type ExtraTags from MetadataInterface */ final class Metadata implements MetadataInterface { public const string MULTI_VALUE_SEPARATOR = ';'; /** @var KnownTags */ private array $knownTags = []; /** @var ExtraTags */ private array $extraTags = []; private float $duration = 0.0; private ?string $artwork = null; private string $mimeType = ''; public function getKnownTags(): array { return $this->knownTags; } public function setKnownTags(array $tags): void { $this->knownTags = $tags; } public function getExtraTags(): array { return $this->extraTags; } public function setExtraTags(array $tags): void { $this->extraTags = $tags; } public function getDuration(): float { return $this->duration; } public function setDuration(float $duration): void { $this->duration = $duration; } public function getArtwork(): ?string { return $this->artwork; } public function setArtwork(?string $artwork): void { $this->artwork = $artwork; } public function getMimeType(): string { return $this->mimeType; } public function setMimeType(string $mimeType): void { $this->mimeType = $mimeType; } } ```
/content/code_sandbox/backend/src/Media/Metadata.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
354
```php <?php declare(strict_types=1); namespace App\Media; use Intervention\Image\Drivers\Gd\Driver; use Intervention\Image\ImageManager; final class AlbumArt { public const int IMAGE_WIDTH = 1500; public static function resize( string $rawArtworkString, int $width = self::IMAGE_WIDTH, int $height = self::IMAGE_WIDTH, bool $upsize = false, ): string { $newArtwork = self::getImageManager()->read($rawArtworkString); if ($upsize) { $newArtwork->cover($width, $height); } else { $newArtwork->coverDown($width, $height); } return $newArtwork->toJpeg()->toString(); } public static function getImageManager(): ImageManager { return new ImageManager( new Driver() ); } } ```
/content/code_sandbox/backend/src/Media/AlbumArt.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
195
```php <?php declare(strict_types=1); namespace App\Media; use App\Media\Enums\MetadataTags; /** * @phpstan-type KnownTags array<value-of<MetadataTags>, mixed> * @phpstan-type ExtraTags array<string, mixed> */ interface MetadataInterface { /** * @return KnownTags */ public function getKnownTags(): array; /** * @param KnownTags $tags */ public function setKnownTags(array $tags): void; /** * @return ExtraTags */ public function getExtraTags(): array; /** * @param ExtraTags $tags */ public function setExtraTags(array $tags): void; /** * @return float */ public function getDuration(): float; /** * @param float $duration */ public function setDuration(float $duration): void; /** * @return string|null */ public function getArtwork(): ?string; public function setArtwork(?string $artwork): void; public function getMimeType(): string; public function setMimeType(string $mimeType): void; } ```
/content/code_sandbox/backend/src/Media/MetadataInterface.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
248
```php <?php declare(strict_types=1); namespace App\Media; use App\Container\LoggerAwareTrait; use App\Event\Media\ReadMetadata; use App\Event\Media\WriteMetadata; use App\Exception\CannotProcessMediaException; use Psr\EventDispatcher\EventDispatcherInterface; use Throwable; final class MetadataManager { use LoggerAwareTrait; public function __construct( private readonly EventDispatcherInterface $eventDispatcher ) { } public function read(string $filePath): MetadataInterface { if (!MimeType::isFileProcessable($filePath)) { $mimeType = MimeType::getMimeTypeFromFile($filePath); throw CannotProcessMediaException::forPath( $filePath, sprintf('MIME type "%s" is not processable.', $mimeType) ); } try { $event = new ReadMetadata($filePath); $this->eventDispatcher->dispatch($event); return $event->getMetadata(); } catch (Throwable $e) { $this->logger->error( sprintf( 'Cannot read metadata for file "%s": %s', $filePath, $e->getMessage() ), [ 'path' => $filePath, 'exception' => $e, ] ); return new Metadata(); } } public function write(MetadataInterface $metadata, string $filePath): void { try { $event = new WriteMetadata($metadata, $filePath); $this->eventDispatcher->dispatch($event); } catch (Throwable $e) { $this->logger->error( sprintf( 'Cannot write metadata for file "%s": %s', $filePath, $e->getMessage() ), [ 'path' => $filePath, 'exception' => $e, ] ); } } } ```
/content/code_sandbox/backend/src/Media/MetadataManager.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\Media; use App\Container\EntityManagerAwareTrait; use App\Container\LoggerAwareTrait; 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\Exception\CannotProcessMediaException; use App\Message\AddNewMediaMessage; use App\Message\ProcessCoverArtMessage; use App\Message\ReprocessMediaMessage; use Symfony\Component\Filesystem\Filesystem; final class MediaProcessor { use EntityManagerAwareTrait; use LoggerAwareTrait; public function __construct( private readonly StationMediaRepository $mediaRepo, private readonly UnprocessableMediaRepository $unprocessableMediaRepo, private readonly StorageLocationRepository $storageLocationRepo ) { } public function __invoke( ReprocessMediaMessage|AddNewMediaMessage|ProcessCoverArtMessage $message ): void { $storageLocation = $this->em->find(StorageLocation::class, $message->storage_location_id); if (!($storageLocation instanceof StorageLocation)) { return; } try { if ($message instanceof ReprocessMediaMessage) { $mediaRow = $this->em->find(StationMedia::class, $message->media_id); if ($mediaRow instanceof StationMedia) { $this->process($storageLocation, $mediaRow, $message->force); } } else { $this->process($storageLocation, $message->path); } } catch (CannotProcessMediaException $e) { $this->logger->error( $e->getMessage(), [ 'exception' => $e, ] ); } } public function processAndUpload( StorageLocation $storageLocation, string $path, string $localPath ): ?StationMedia { $fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); if (!(new Filesystem())->exists($localPath)) { throw CannotProcessMediaException::forPath( $path, sprintf('Local file path "%s" not found.', $localPath) ); } try { if (MimeType::isFileProcessable($localPath)) { $record = $this->mediaRepo->findByPath($path, $storageLocation); if (!($record instanceof StationMedia)) { $record = new StationMedia($storageLocation, $path); } $this->mediaRepo->loadFromFile($record, $localPath, $fs); $record->setMtime(time()); $this->em->persist($record); $this->em->flush(); $this->unprocessableMediaRepo->clearForPath($storageLocation, $path); return $record; } if (MimeType::isPathImage($localPath)) { $this->processCoverArt( $storageLocation, $path, file_get_contents($localPath) ?: '' ); return null; } throw CannotProcessMediaException::forPath( $path, 'File type cannot be processed.' ); } catch (CannotProcessMediaException $e) { $this->unprocessableMediaRepo->setForPath( $storageLocation, $path, $e->getMessage() ); throw $e; } finally { $fs->uploadAndDeleteOriginal($localPath, $path); } } public function process( StorageLocation $storageLocation, string|StationMedia $pathOrMedia, bool $force = false ): ?StationMedia { if ($pathOrMedia instanceof StationMedia) { $record = $pathOrMedia; $path = $pathOrMedia->getPath(); } else { $record = null; $path = $pathOrMedia; } try { if (MimeType::isPathProcessable($path)) { $record ??= $this->mediaRepo->findByPath($path, $storageLocation); $created = false; if (!($record instanceof StationMedia)) { $record = new StationMedia($storageLocation, $path); $created = true; } $reprocessed = $this->processMedia($storageLocation, $record, $force || $created); if ($created || $reprocessed) { $this->em->flush(); $this->unprocessableMediaRepo->clearForPath($storageLocation, $path); } return $record; } if (null === $record && MimeType::isPathImage($path)) { $this->processCoverArt( $storageLocation, $path ); return null; } throw CannotProcessMediaException::forPath( $path, 'File type cannot be processed.' ); } catch (CannotProcessMediaException $e) { $this->unprocessableMediaRepo->setForPath( $storageLocation, $path, $e->getMessage() ); throw $e; } } public function processMedia( StorageLocation $storageLocation, StationMedia $media, bool $force = false ): bool { $fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); $path = $media->getPath(); if (!$fs->fileExists($path)) { throw CannotProcessMediaException::forPath( $path, sprintf('Media path "%s" not found.', $path) ); } $fileModified = $fs->lastModified($path); $mediaProcessedAt = $media->getMtime(); // No need to update if all of these conditions are true. if (!$force && !StationMedia::needsReprocessing($fileModified, $mediaProcessedAt)) { return false; } $fs->withLocalFile( $path, function ($localPath) use ($media, $fs): void { $this->mediaRepo->loadFromFile($media, $localPath, $fs); } ); $media->setMtime(time() + 5); $this->em->persist($media); return true; } public function processCoverArt( StorageLocation $storageLocation, string $path, ?string $contents = null ): void { $fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem(); if (null === $contents) { if (!$fs->fileExists($path)) { throw CannotProcessMediaException::forPath( $path, sprintf('Cover art path "%s" not found.', $path) ); } $contents = $fs->read($path); } $folderHash = StationMedia::getFolderHashForPath($path); $destPath = StationMedia::getFolderArtPath($folderHash); $fs->write( $destPath, AlbumArt::resize($contents) ); } } ```
/content/code_sandbox/backend/src/Media/MediaProcessor.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,516
```php <?php declare(strict_types=1); namespace App\Media; use League\MimeTypeDetection\FinfoMimeTypeDetector; final class MimeType { private static FinfoMimeTypeDetector $detector; private static array $processableTypes = [ 'audio/aiff', // aiff (Audio Interchange File Format) 'audio/flac', // MIME type used by some FLAC files 'audio/mp4', // m4a mp4a 'audio/mpeg', // mpga mp2 mp2a mp3 m2a m3a 'audio/ogg', // oga ogg spx 'audio/s3m', // s3m (ScreamTracker 3 Module) 'audio/wav', // wav 'audio/xm', // xm 'audio/vnd.wave', // alt for wav (RFC 2361) 'audio/x-aac', // aac 'audio/x-aiff', // alt for aiff 'audio/x-flac', // flac 'audio/x-m4a', // alt for m4a/mp4a 'audio/x-mod', // stm, alt for xm 'audio/x-s3m', // alt for s3m 'audio/x-wav', // alt for wav 'audio/x-ms-wma', // wma (Windows Media Audio) 'video/mp4', // some MP4 audio files are recognized as this (#3569) 'video/x-ms-asf', // asf / wmv / alt for wma ]; private static array $imageTypes = [ 'image/gif', // gif 'image/jpeg', // jpg/jpeg 'image/png', // png ]; /** * @return string[] */ public static function getProcessableTypes(): array { return self::$processableTypes; } public static function getMimeTypeDetector(): FinfoMimeTypeDetector { if (!isset(self::$detector)) { self::$detector = new FinfoMimeTypeDetector( extensionMap: new MimeTypeExtensionMap() ); } return self::$detector; } public static function getMimeTypeFromFile(string $path): string { $fileMimeType = self::getMimeTypeDetector()->detectMimeTypeFromFile($path); if ('application/octet-stream' === $fileMimeType) { $fileMimeType = null; } return $fileMimeType ?? self::getMimeTypeFromPath($path); } public static function getMimeTypeFromPath(string $path): string { return self::getMimeTypeDetector()->detectMimeTypeFromPath($path) ?? 'application/octet-stream'; } public static function isPathProcessable(string $path): bool { $mimeType = self::getMimeTypeFromPath($path); return in_array($mimeType, self::$processableTypes, true); } public static function isPathImage(string $path): bool { $mimeType = self::getMimeTypeFromPath($path); return in_array($mimeType, self::$imageTypes, true); } public static function isFileProcessable(string $path): bool { $mimeType = self::getMimeTypeFromFile($path); return in_array($mimeType, self::$processableTypes, true); } } ```
/content/code_sandbox/backend/src/Media/MimeType.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
713
```php <?php declare(strict_types=1); namespace App\Media\Enums; enum MetadataTags: string { case Album = 'album'; // TAL, TALB case Artist = 'artist'; // TP1, TPE1 case Bpm = 'bpm'; // TBP, TBPM case Comment = 'comment'; // COM, COMM case Composer = 'composer'; // TCM, TCOM case EncodedBy = 'encoded_by'; // TEN, TENC case Genre = 'genre'; // TCO, TCON case Isrc = 'isrc'; // TRC, TSRC case Title = 'title'; // TIT2, TT2 case Year = 'year'; // TYE, TYER // Other possible metadata tags that may not be pulled by FFProbe case AlbumArtist = 'album_artist'; case AlbumArtistSortOrder = 'album_artist_sort_order'; // TS2, TSO2 case AlbumSortOrder = 'album_sort_order'; // TSA, TSOA case Band = 'band'; // TP2, TPE2 case CommercialInformation = 'commercial_information'; // WCM, WCOM case ComposerSortOrder = 'composer_sort_order'; // TSC, TSOC case Conductor = 'conductor'; // TP3, TPE3 case ContentGroupDescription = 'content_group_description'; // TIT1, TT1 case EncoderSettings = 'encoder_settings'; // TSS, TSSE case EncodingTime = 'encoding_time'; // TDEN case FileOwner = 'file_owner'; // TOWN case FileType = 'file_type'; // TFLT, TFT case InitialKey = 'initial_key'; // TKE, TKEY case InternetRadioStationName = 'internet_radio_station_name'; // TRSN case InternetRadioStationOwner = 'internet_radio_station_owner'; // TRSO case InvolvedPeopleList = 'involved_people_list'; // IPL, IPLS, TIPL case Language = 'language'; // TLA, TLAN case Length = 'length'; // TLE, TLEN case LinkedInformation = 'linked_information'; // LINK, LNK case Lyricist = 'lyricist'; // TEXT, TXT case MediaType = 'media_type'; // TMED, TMT case Mood = 'mood'; // TMOO case MusicCdIdentifier = 'music_cd_identifier'; // MCDI, MCI case MusicianCreditsList = 'musician_credits_list'; // TMCL case OriginalAlbum = 'original_album'; // TOAL, TOT case OriginalArtist = 'original_artist'; // TOA, TOPE case OriginalFilename = 'original_filename'; // TOF, TOFN case OriginalLyricist = 'original_lyricist'; // TOL, TOLY case OriginalReleaseTime = 'original_release_time'; // TDOR case OriginalYear = 'original_year'; // TOR, TORY case PartOfACompilation = 'part_of_a_compilation'; // TCMP, TCP case PartOfASet = 'part_of_a_set'; // TPA, TPOS case PerformerSortOrder = 'performer_sort_order'; // TSOP, TSP case PlaylistDelay = 'playlist_delay'; // TDLY, TDY case ProducedNotice = 'produced_notice'; // TPRO case Publisher = 'publisher'; // TPB, TPUB case RecordingTime = 'recording_time'; // TDRC case ReleaseTime = 'release_time'; // TDRL case Remixer = 'remixer'; // TP4, TPE4 case SetSubtitle = 'set_subtitle'; // TSST case Subtitle = 'subtitle'; // TIT3, TT3 case TaggingTime = 'tagging_time'; // TDTG case TermsOfUse = 'terms_of_use'; // USER case TitleSortOrder = 'title_sort_order'; // TSOT, TST case TrackNumber = 'track_number'; // TRCK, TRK case UnsynchronisedLyric = 'unsynchronised_lyric'; // ULT, USLT case UrlArtist = 'url_artist'; // WAR, WOAR case UrlFile = 'url_file'; // WAF, WOAF case UrlPayment = 'url_payment'; // WPAY case UrlPublisher = 'url_publisher'; // WPB, WPUB case UrlSource = 'url_source'; // WAS, WOAS case UrlStation = 'url_station'; // WORS case UrlUser = 'url_user'; // WXX, WXXX public static function getNames(): array { return [ self::Album->value => __('Album'), self::AlbumArtist->value => __('Album Artist'), self::AlbumArtistSortOrder->value => __('Album Artist Sort Order'), // TS2, TSO2 self::AlbumSortOrder->value => __('Album Sort Order'), // TSA, TSOA self::Artist->value => __('Artist'), self::Band->value => __('Band'), // TP2, TPE2 self::Bpm->value => __('BPM'), self::Comment->value => __('Comment'), self::CommercialInformation->value => __('Commercial Information'), // WCM, WCOM self::Composer->value => __('Composer'), self::ComposerSortOrder->value => __('Composer Sort Order'), // TSC, TSOC self::Conductor->value => __('Conductor'), // TP3, TPE3 self::ContentGroupDescription->value => __('Content Group Description'), // TIT1, TT1 self::EncodedBy->value => __('Encoded By'), self::EncoderSettings->value => __('Encoder Settings'), // TSS, TSSE self::EncodingTime->value => __('Encoding Time'), // TDEN self::FileOwner->value => __('File Owner'), // TOWN self::FileType->value => __('File Type'), // TFLT, TFT self::Genre->value => __('Genre'), self::InitialKey->value => __('Initial Key'), // TKE, TKEY self::InternetRadioStationName->value => __('Internet Radio Station Name'), // TRSN self::InternetRadioStationOwner->value => __('Internet Radio Station Owner'), // TRSO self::InvolvedPeopleList->value => __('Involved People List'), // IPL, IPLS, TIPL self::Isrc->value => __('ISRC'), self::Language->value => __('Language'), // TLA, TLAN self::Length->value => __('Length'), // TLE, TLEN self::LinkedInformation->value => __('Linked Information'), // LINK, LNK self::Lyricist->value => __('Lyricist'), // TEXT, TXT self::MediaType->value => __('Media Type'), // TMED, TMT self::Mood->value => __('Mood'), // TMOO self::MusicCdIdentifier->value => __('Music CD Identifier'), // MCDI, MCI self::MusicianCreditsList->value => __('Musician Credits List'), // TMCL self::OriginalAlbum->value => __('Original Album'), // TOAL, TOT self::OriginalArtist->value => __('Original Artist'), // TOA, TOPE self::OriginalFilename->value => __('Original Filename'), // TOF, TOFN self::OriginalLyricist->value => __('Original Lyricist'), // TOL, TOLY self::OriginalReleaseTime->value => __('Original Release Time'), // TDOR self::OriginalYear->value => __('Original Year'), // TOR, TORY self::PartOfACompilation->value => __('Part of a Compilation'), // TCMP, TCP self::PartOfASet->value => __('Part of a Set'), // TPA, TPOS self::PerformerSortOrder->value => __('Performer Sort Order'), // TSOP, TSP self::PlaylistDelay->value => __('Playlist Delay'), // TDLY, TDY self::ProducedNotice->value => __('Produced Notice'), // TPRO self::Publisher->value => __('Publisher'), // TPB, TPUB self::RecordingTime->value => __('Recording Time'), // TDRC self::ReleaseTime->value => __('Release Time'), // TDRL self::Remixer->value => __('Remixer'), // TP4, TPE4 self::SetSubtitle->value => __('Set Subtitle'), // TSST self::Subtitle->value => __('Subtitle'), // TIT3, TT3 self::TaggingTime->value => __('Tagging Time'), // TDTG self::TermsOfUse->value => __('Terms of Use'), // USER self::Title->value => __('Title'), self::TitleSortOrder->value => __('Title Sort Order'), // TSOT, TST self::TrackNumber->value => __('Track Number'), // TRCK, TRK self::UnsynchronisedLyric->value => __('Unsynchronised Lyrics'), // ULT, USLT self::UrlArtist->value => __('URL Artist'), // WAR, WOAR self::UrlFile->value => __('URL File'), // WAF, WOAF self::UrlPayment->value => __('URL Payment'), // WPAY self::UrlPublisher->value => __('URL Publisher'), // WPB, WPUB self::UrlSource->value => __('URL Source'), // WAS, WOAS self::UrlStation->value => __('URL Station'), // WORS self::UrlUser->value => __('URL User'), // WXX, WXXX self::Year->value => __('Year'), ]; } public static function getTag(string $value): ?self { $value = str_replace('-', '_', mb_strtolower($value)); $tag = self::tryFrom($value); if (null !== $tag) { return $tag; } $aliases = [ 'date' => self::Year, 'encoder' => self::EncodedBy, ]; return $aliases[$value] ?? null; } } ```
/content/code_sandbox/backend/src/Media/Enums/MetadataTags.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,272
```php <?php declare(strict_types=1); namespace App\Media\Metadata; use App\Event\Media\WriteMetadata; use JamesHeinrich\GetID3\WriteTags; use RuntimeException; final class Writer { public function __invoke(WriteMetadata $event): void { $path = $event->getPath(); $metadata = $event->getMetadata(); if (null === $metadata) { return; } $tagwriter = new WriteTags(); $tagwriter->filename = $path; $tagwriter->overwrite_tags = true; $tagwriter->tag_encoding = 'UTF8'; $tagwriter->remove_other_tags = true; $pathExt = strtolower(pathinfo($path, PATHINFO_EXTENSION)); $tagFormats = match ($pathExt) { 'mp3', 'mp2', 'mp1', 'riff' => ['id3v1', 'id3v2.3'], 'mpc' => ['ape'], 'flac' => ['metaflac'], 'real' => ['real'], 'ogg' => ['vorbiscomment'], default => null, }; if (null === $tagFormats) { throw new RuntimeException('Cannot write tag formats based on file type.'); } $tagwriter->tagformats = $tagFormats; $writeTags = $metadata->getKnownTags(); $writeTags['text'] = $metadata->getExtraTags(); if ($metadata->getArtwork()) { $artContents = $metadata->getArtwork(); if (false !== $artContents) { $writeTags['attached_picture'] = [ 'encodingid' => 0, // ISO-8859-1; 3=UTF8 but only allowed in ID3v2.4 'description' => 'cover art', 'data' => $artContents, 'picturetypeid' => 0x03, 'mime' => 'image/jpeg', ]; } } // All ID3 tags have to be written as ['key' => ['value']] (i.e. with "value" at position 0). $tagData = []; foreach ($writeTags as $tagKey => $tagValue) { $tagData[$tagKey] = [$tagValue]; } $tagwriter->tag_data = $tagData; $tagwriter->WriteTags(); if (!empty($tagwriter->errors) || !empty($tagwriter->warnings)) { $messages = array_merge($tagwriter->errors, $tagwriter->warnings); throw new RuntimeException(implode(', ', $messages)); } } } ```
/content/code_sandbox/backend/src/Media/Metadata/Writer.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
575