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\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
interface ConnectorInterface
{
/**
* Return a boolean indicating whether this connector should dispatch, given the current events
* that are set to be triggered, and the configured triggers for this connector.
*
* @param StationWebhook $webhook
* @param array<string> $triggers
*
* @return bool Whether the given webhook should dispatch with these triggers.
*/
public function shouldDispatch(
StationWebhook $webhook,
array $triggers = []
): bool;
/**
* Trigger the webhook for the specified station, now playing entry, and specified configuration.
*
* @param Station $station
* @param StationWebhook $webhook
* @param NowPlaying $np
* @param array<string> $triggers
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void;
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/ConnectorInterface.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 249 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Webhook\Enums\WebhookTriggers;
final class TuneIn extends AbstractConnector
{
protected function webhookShouldTrigger(StationWebhook $webhook, array $triggers = []): bool
{
return in_array(WebhookTriggers::SongChanged->value, $triggers, true);
}
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
if (empty($config['partner_id']) || empty($config['partner_key']) || empty($config['station_id'])) {
throw $this->incompleteConfigException($webhook);
}
$this->logger->debug('Dispatching TuneIn AIR API call...');
$messageQuery = [
'partnerId' => $config['partner_id'],
'partnerKey' => $config['partner_key'],
'id' => $config['station_id'],
'title' => $np->now_playing?->song?->title,
'artist' => $np->now_playing?->song?->artist,
'album' => $np->now_playing?->song?->album,
];
$response = $this->httpClient->get(
'path_to_url
[
'query' => $messageQuery,
]
);
$this->logHttpResponse(
$webhook,
$response,
$messageQuery
);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/TuneIn.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 373 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Webhook\Enums\WebhookTriggers;
final class RadioDe extends AbstractConnector
{
protected function webhookShouldTrigger(StationWebhook $webhook, array $triggers = []): bool
{
return in_array(WebhookTriggers::SongChanged->value, $triggers, true);
}
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
if (
empty($config['broadcastsubdomain'])
|| empty($config['apikey'])
) {
throw $this->incompleteConfigException($webhook);
}
$this->logger->debug('Dispatching RadioDe AIR API call...');
$messageBody = [
'broadcast' => $config['broadcastsubdomain'],
'apikey' => $config['apikey'],
'title' => $np->now_playing?->song?->title,
'artist' => $np->now_playing?->song?->artist,
'album' => $np->now_playing?->song?->album,
];
$response = $this->httpClient->get(
'path_to_url
[
'query' => $messageBody,
]
);
$this->logHttpResponse($webhook, $response, $messageBody);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/RadioDe.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 350 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\StationWebhook;
use App\Webhook\Enums\WebhookTriggers;
use Generator;
abstract class AbstractSocialConnector extends AbstractConnector
{
protected function getMessages(
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): Generator {
$config = $webhook->getConfig();
$messages = [
WebhookTriggers::SongChanged->value => $config['message'] ?? '',
WebhookTriggers::SongChangedLive->value => $config['message_song_changed_live'] ?? '',
WebhookTriggers::LiveConnect->value => $config['message_live_connect'] ?? '',
WebhookTriggers::LiveDisconnect->value => $config['message_live_disconnect'] ?? '',
WebhookTriggers::StationOffline->value => $config['message_station_offline'] ?? '',
WebhookTriggers::StationOnline->value => $config['message_station_online'] ?? '',
];
foreach ($triggers as $trigger) {
if (!$webhook->hasTrigger($trigger)) {
continue;
}
$message = $messages[$trigger] ?? '';
if (empty($message)) {
continue;
}
$vars = $this->replaceVariables(['message' => $message], $np);
yield $vars['message'];
}
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/AbstractSocialConnector.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\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Repository\ListenerRepository;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Http\RouterInterface;
use App\Utilities\Types;
use App\Utilities\Urls;
use GuzzleHttp\Client;
use Psr\Http\Message\UriInterface;
final class MatomoAnalytics extends AbstractConnector
{
public function __construct(
Client $httpClient,
private readonly RouterInterface $router,
private readonly ListenerRepository $listenerRepo
) {
parent::__construct($httpClient);
}
protected function webhookShouldTrigger(StationWebhook $webhook, array $triggers = []): bool
{
return true;
}
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
$matomoUrl = Types::stringOrNull($config['matomo_url'], true);
$siteId = Types::intOrNull($config['site_id']);
if (null === $matomoUrl || null === $siteId) {
throw $this->incompleteConfigException($webhook);
}
// Get listen URLs for each mount point.
$radioPort = $station->getFrontendConfig()->getPort();
$baseUri = $this->router->getBaseUrl();
$mountUrls = [];
$mountNames = [];
foreach ($station->getMounts() as $mount) {
$mountUrl = $baseUri->withPath('/radio/' . $radioPort . $mount->getName());
$mountUrls[$mount->getId()] = (string)$mountUrl;
$mountNames[$mount->getId()] = (string)$mount;
}
$remoteUrls = [];
$remoteNames = [];
foreach ($station->getRemotes() as $remote) {
$remoteUrl = $baseUri->withPath('/radio/remote' . $remote->getMount());
$remoteUrls[$remote->getId()] = (string)$remoteUrl;
$remoteNames[$remote->getId()] = (string)$remote;
}
// Build Matomo URI
$apiUrl = Urls::parseUserUrl(
$matomoUrl,
'Matomo Analytics URL',
)->withPath('/matomo.php');
$apiToken = Types::stringOrNull($config['token'], true);
$stationName = $station->getName();
// Get all current listeners
$liveListeners = $this->listenerRepo->iterateLiveListenersArray($station);
$webhookLastSent = Types::intOrNull($webhook->getMetadataKey($webhook::LAST_SENT_TIMESTAMP_KEY)) ?? 0;
$i = 0;
$entries = [];
foreach ($liveListeners as $listener) {
$listenerUrl = null;
$streamName = 'Stream';
if (!empty($listener['mount_id'])) {
$listenerUrl = $mountUrls[$listener['mount_id']] ?? null;
$streamName = $mountNames[$listener['mount_id']] ?? $streamName;
} elseif (!empty($listener['remote_id'])) {
$listenerUrl = $remoteUrls[$listener['remote_id']] ?? null;
$streamName = $remoteNames[$listener['remote_id']] ?? $streamName;
}
if (null === $listenerUrl) {
continue;
}
$entry = [
'idsite' => $siteId,
'rec' => 1,
'action_name' => 'Listeners / ' . $stationName . ' / ' . $streamName,
'url' => $listenerUrl,
'rand' => random_int(10000, 99999),
'apiv' => 1,
'ua' => $listener['listener_user_agent'],
'cid' => substr($listener['listener_hash'], 0, 16),
];
// If this listener is already registered, this is a "ping" update.
if ($listener['timestamp_start'] < $webhookLastSent) {
$entry['ping'] = 1;
}
if (!empty($apiToken)) {
$entry['cip'] = $listener['listener_ip'];
}
$entries[] = $entry;
$i++;
if (100 === $i) {
$this->sendBatch($webhook, $apiUrl, $apiToken, $entries);
$entries = [];
$i = 0;
}
}
$this->sendBatch($webhook, $apiUrl, $apiToken, $entries);
}
private function sendBatch(
StationWebhook $webhook,
UriInterface $apiUrl,
?string $apiToken,
array $entries
): void {
if (empty($entries)) {
return;
}
$jsonBody = [
'requests' => array_map(static function ($row) {
return '?' . http_build_query($row);
}, $entries),
];
if (!empty($apiToken)) {
$jsonBody['token_auth'] = $apiToken;
}
$response = $this->httpClient->post($apiUrl, [
'json' => $jsonBody,
]);
$this->logHttpResponse(
$webhook,
$response,
$jsonBody
);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/MatomoAnalytics.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,183 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Utilities\Types;
/**
* Telegram web hook connector.
*
* @package App\Webhook\Connector
*/
final class Telegram extends AbstractConnector
{
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
$botToken = Types::stringOrNull($config['bot_token'], true);
$chatId = Types::stringOrNull($config['chat_id'], true);
if (null === $botToken || null === $chatId) {
throw $this->incompleteConfigException($webhook);
}
$messages = $this->replaceVariables(
[
'text' => $config['text'],
],
$np
);
$apiUrl = Types::stringOrNull($config['api'], true);
$apiUrl = (null !== $apiUrl)
? rtrim($apiUrl, '/')
: 'path_to_url
$webhookUrl = $apiUrl . '/bot' . $botToken . '/sendMessage';
$requestParams = [
'chat_id' => $chatId,
'text' => $messages['text'],
'parse_mode' => Types::stringOrNull($config['parse_mode'], true) ?? 'Markdown', // Markdown or HTML
];
$response = $this->httpClient->request(
'POST',
$webhookUrl,
[
'headers' => [
'Content-Type' => 'application/json',
],
'json' => $requestParams,
]
);
$this->logHttpResponse(
$webhook,
$response,
$requestParams
);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/Telegram.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 422 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Utilities\Types;
use Br33f\Ga4\MeasurementProtocol\Dto\Event\BaseEvent;
use Br33f\Ga4\MeasurementProtocol\Dto\Request\BaseRequest;
use Br33f\Ga4\MeasurementProtocol\HttpClient as Ga4HttpClient;
use Br33f\Ga4\MeasurementProtocol\Service;
final class GoogleAnalyticsV4 extends AbstractGoogleAnalyticsConnector
{
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
$apiSecret = Types::stringOrNull($config['api_secret'], true);
$measurementId = Types::stringOrNull($config['measurement_id'], true);
if (null === $apiSecret) {
throw $this->incompleteConfigException($webhook);
}
// Get listen URLs for each mount point.
$listenUrls = $this->buildListenUrls($station);
// Build analytics
$gaHttpClient = new Ga4HttpClient();
$gaHttpClient->setClient($this->httpClient);
$ga4Service = new Service($apiSecret, $measurementId);
$ga4Service->setHttpClient($gaHttpClient);
// Get all current listeners
$liveListeners = $this->listenerRepo->iterateLiveListenersArray($station);
foreach ($liveListeners as $listener) {
$uid = Types::stringOrNull($listener['listener_uid'], true);
if (null === $uid) {
continue;
}
$listenerUrl = $this->getListenUrl($listener, $listenUrls);
if (null === $listenerUrl) {
continue;
}
$event = new BaseEvent('page_view');
$event->setParamValue('page_location', $listenerUrl)
->setParamValue('page_title', $listenerUrl)
->setParamValue('ip', $listener['listener_ip'])
->setParamValue('user_agent', $listener['listener_user_agent']);
$ga4Service->send(
(new BaseRequest())->setClientId($uid)->addEvent($event)
);
}
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/GoogleAnalyticsV4.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 512 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Webhook\Enums\WebhookTriggers;
final class GetMeRadio extends AbstractConnector
{
protected function webhookShouldTrigger(StationWebhook $webhook, array $triggers = []): bool
{
return in_array(WebhookTriggers::SongChanged->value, $triggers, true);
}
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
if (
empty($config['token'])
|| empty($config['station_id'])
) {
throw $this->incompleteConfigException($webhook);
}
$this->logger->debug('Dispatching GetMeRadio API call...');
$messageBody = [
'token' => $config['token'],
'station_id' => $config['station_id'],
'title' => $np->now_playing?->song?->title,
'artist' => $np->now_playing?->song?->artist,
];
$response = $this->httpClient->get(
'path_to_url
[
'query' => $messageBody,
]
);
$this->logHttpResponse($webhook, $response, $messageBody);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/GetMeRadio.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 333 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Service\Mail;
use App\Utilities\Types;
use GuzzleHttp\Client;
use RuntimeException;
final class Email extends AbstractConnector
{
public function __construct(
Client $httpClient,
private readonly Mail $mail
) {
parent::__construct($httpClient);
}
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
if (!$this->mail->isEnabled()) {
throw new RuntimeException('E-mail delivery is not currently enabled. Skipping webhook delivery...');
}
$config = $webhook->getConfig();
$emailTo = Types::stringOrNull($config['to'], true);
$emailSubject = Types::stringOrNull($config['subject'], true);
$emailBody = Types::stringOrNull($config['message'], true);
if (null === $emailTo || null === $emailSubject || null === $emailBody) {
throw $this->incompleteConfigException($webhook);
}
$email = $this->mail->createMessage();
foreach (explode(',', $emailTo) as $emailToPart) {
$email->addTo(trim($emailToPart));
}
$vars = [
'subject' => $emailSubject,
'body' => $emailBody,
];
$vars = $this->replaceVariables($vars, $np);
$email->subject($vars['subject']);
$email->text($vars['body']);
$this->mail->send($email);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/Email.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 381 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Webhook\Enums\WebhookTriggers;
final class RadioReg extends AbstractConnector
{
protected function webhookShouldTrigger(StationWebhook $webhook, array $triggers = []): bool
{
return in_array(WebhookTriggers::SongChanged->value, $triggers, true);
}
/**
* @optischa
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
if (
empty($config['apikey']) || empty($config['webhookurl'])
) {
throw $this->incompleteConfigException($webhook);
}
$this->logger->debug('Dispatching RadioReg API call...');
$messageBody = [
'title' => $np->now_playing?->song?->title,
'artist' => $np->now_playing?->song?->artist,
];
$response = $this->httpClient->post(
$config['webhookurl'],
[
'json' => $messageBody,
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => $config['apikey'],
],
],
);
$this->logHttpResponse($webhook, $response, $messageBody);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/RadioReg.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 353 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Utilities\Types;
use App\Utilities\Urls;
/**
* Mastodon web hook connector.
*/
final class Mastodon extends AbstractSocialConnector
{
protected function getRateLimitTime(StationWebhook $webhook): ?int
{
$config = $webhook->getConfig();
$rateLimitSeconds = Types::int($config['rate_limit'] ?? null);
return max(10, $rateLimitSeconds);
}
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
$instanceUrl = Types::stringOrNull($config['instance_url'], true);
$accessToken = Types::stringOrNull($config['access_token'], true);
if (null === $instanceUrl || null === $accessToken) {
throw $this->incompleteConfigException($webhook);
}
$instanceUri = Urls::parseUserUrl($instanceUrl, 'Mastodon Instance URL');
$visibility = Types::stringOrNull($config['visibility'], true) ?? 'public';
$this->logger->debug(
'Posting to Mastodon...',
[
'url' => (string)$instanceUri,
]
);
foreach ($this->getMessages($webhook, $np, $triggers) as $message) {
$messageBody = [
'status' => $message,
'visibility' => $visibility,
];
$response = $this->httpClient->request(
'POST',
$instanceUri->withPath('/api/v1/statuses'),
[
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json',
],
'json' => $messageBody,
]
);
$this->logHttpResponse(
$webhook,
$response,
$messageBody
);
}
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/Mastodon.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 465 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Enums;
use App\Webhook\Connector\Discord;
use App\Webhook\Connector\Email;
use App\Webhook\Connector\Generic;
use App\Webhook\Connector\GetMeRadio;
use App\Webhook\Connector\GoogleAnalyticsV4;
use App\Webhook\Connector\Mastodon;
use App\Webhook\Connector\MatomoAnalytics;
use App\Webhook\Connector\RadioDe;
use App\Webhook\Connector\RadioReg;
use App\Webhook\Connector\Telegram;
use App\Webhook\Connector\TuneIn;
enum WebhookTypes: string
{
case Generic = 'generic';
case Email = 'email';
case TuneIn = 'tunein';
case RadioDe = 'radiode';
case RadioReg = 'radioreg';
case GetMeRadio = 'getmeradio';
case Discord = 'discord';
case Telegram = 'telegram';
case Mastodon = 'mastodon';
case GoogleAnalyticsV4 = 'google_analytics_v4';
case MatomoAnalytics = 'matomo_analytics';
// Retired connectors
case Twitter = 'twitter';
case GoogleAnalyticsV3 = 'google_analytics';
/**
* @return class-string|null
*/
public function getClass(): ?string
{
return match ($this) {
self::Generic => Generic::class,
self::Email => Email::class,
self::TuneIn => TuneIn::class,
self::RadioReg => RadioReg::class,
self::RadioDe => RadioDe::class,
self::GetMeRadio => GetMeRadio::class,
self::Discord => Discord::class,
self::Telegram => Telegram::class,
self::Mastodon => Mastodon::class,
self::GoogleAnalyticsV4 => GoogleAnalyticsV4::class,
self::MatomoAnalytics => MatomoAnalytics::class,
default => null
};
}
}
``` | /content/code_sandbox/backend/src/Webhook/Enums/WebhookTypes.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 428 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Enums;
enum WebhookTriggers: string
{
case SongChanged = 'song_changed';
case SongChangedLive = 'song_changed_live';
case ListenerGained = 'listener_gained';
case ListenerLost = 'listener_lost';
case LiveConnect = 'live_connect';
case LiveDisconnect = 'live_disconnect';
case StationOffline = 'station_offline';
case StationOnline = 'station_online';
/**
* @return string[] All trigger values.
*/
public static function allTriggers(): array
{
return array_map(
fn(WebhookTriggers $trigger) => $trigger->value,
self::cases()
);
}
/**
* @return string[] All trigger values, except listener change ones.
*/
public static function allTriggersExceptListeners(): array
{
return array_diff(
self::allTriggers(),
[
self::ListenerGained->value,
self::ListenerLost->value,
]
);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Enums/WebhookTriggers.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 229 |
```php
<?php
declare(strict_types=1);
namespace App\Http;
use App\Acl;
use App\Auth;
use App\Customization;
use App\Entity\Podcast;
use App\Entity\Station;
use App\Entity\User;
use App\Enums\SupportedLocales;
use App\Exception\Http\InvalidRequestAttribute;
use App\RateLimit;
use App\Session;
use App\Utilities\Types;
use App\View;
use Mezzio\Session\SessionInterface;
use Slim\Http\ServerRequest as SlimServerRequest;
final class ServerRequest extends SlimServerRequest
{
public const string ATTR_IS_API = 'is_api';
public const string ATTR_VIEW = 'app_view';
public const string ATTR_SESSION = 'app_session';
public const string ATTR_SESSION_CSRF = 'app_session_csrf';
public const string ATTR_SESSION_FLASH = 'app_session_flash';
public const string ATTR_ROUTER = 'app_router';
public const string ATTR_RATE_LIMIT = 'app_rate_limit';
public const string ATTR_ACL = 'acl';
public const string ATTR_LOCALE = 'locale';
public const string ATTR_CUSTOMIZATION = 'customization';
public const string ATTR_AUTH = 'auth';
public const string ATTR_STATION = 'station';
public const string ATTR_PODCAST = 'podcast';
public const string ATTR_USER = 'user';
/**
* @throws InvalidRequestAttribute
*/
public function getView(): View
{
return $this->getAttributeOfClass(self::ATTR_VIEW, View::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getSession(): SessionInterface
{
return $this->getAttributeOfClass(self::ATTR_SESSION, SessionInterface::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getCsrf(): Session\Csrf
{
return $this->getAttributeOfClass(self::ATTR_SESSION_CSRF, Session\Csrf::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getFlash(): Session\Flash
{
return $this->getAttributeOfClass(self::ATTR_SESSION_FLASH, Session\Flash::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getRouter(): RouterInterface
{
return $this->getAttributeOfClass(self::ATTR_ROUTER, RouterInterface::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getRateLimit(): RateLimit
{
return $this->getAttributeOfClass(self::ATTR_RATE_LIMIT, RateLimit::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getLocale(): SupportedLocales
{
return $this->getAttributeOfClass(self::ATTR_LOCALE, SupportedLocales::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getCustomization(): Customization
{
return $this->getAttributeOfClass(self::ATTR_CUSTOMIZATION, Customization::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getAuth(): Auth
{
return $this->getAttributeOfClass(self::ATTR_AUTH, Auth::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getAcl(): Acl
{
return $this->getAttributeOfClass(self::ATTR_ACL, Acl::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getUser(): User
{
return $this->getAttributeOfClass(self::ATTR_USER, User::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getStation(): Station
{
return $this->getAttributeOfClass(self::ATTR_STATION, Station::class);
}
/**
* @throws InvalidRequestAttribute
*/
public function getPodcast(): Podcast
{
return $this->getAttributeOfClass(self::ATTR_PODCAST, Podcast::class);
}
public function isApi(): bool
{
return Types::bool($this->getAttribute(self::ATTR_IS_API));
}
/**
* @template T of object
*
* @param string $attr
* @param class-string<T> $className
* @return T
*
* @throws InvalidRequestAttribute
*/
private function getAttributeOfClass(string $attr, string $className): object
{
$object = $this->serverRequest->getAttribute($attr);
if (empty($object)) {
throw new InvalidRequestAttribute(
$this,
sprintf(
'Attribute "%s" is required and is empty in this request',
$attr
)
);
}
if (!($object instanceof $className)) {
throw new InvalidRequestAttribute(
$this,
sprintf(
'Attribute "%s" must be of type "%s".',
$attr,
$className
)
);
}
return $object;
}
public function isInternal(): bool
{
return Types::bool(
$this->getParam('internal', false),
false,
true
);
}
}
``` | /content/code_sandbox/backend/src/Http/ServerRequest.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,087 |
```php
<?php
declare(strict_types=1);
namespace App\Http;
use App\AppFactory;
use App\Container\EnvironmentAwareTrait;
use App\Entity\Api\Error;
use App\Enums\SupportedLocales;
use App\Exception;
use App\Exception\Http\NotLoggedInException;
use App\Exception\Http\PermissionDeniedException;
use App\Middleware\InjectSession;
use App\Session\Flash;
use App\View;
use Mezzio\Session\Session;
use Monolog\Level;
use Monolog\Logger;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\App;
use Slim\Exception\HttpException;
use Slim\Handlers\ErrorHandler as SlimErrorHandler;
use Throwable;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
/**
* @phpstan-import-type AppWithContainer from AppFactory
*/
final class ErrorHandler extends SlimErrorHandler
{
use EnvironmentAwareTrait;
private bool $returnJson = false;
private bool $showDetailed = false;
private Level $loggerLevel = Level::Error;
/**
* @param View $view
* @param Router $router
* @param InjectSession $injectSession
* @param AppWithContainer $app
* @param Logger $logger
*/
public function __construct(
private readonly View $view,
private readonly Router $router,
private readonly InjectSession $injectSession,
App $app,
Logger $logger,
) {
parent::__construct($app->getCallableResolver(), $app->getResponseFactory(), $logger);
}
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
): ResponseInterface {
if ($exception instanceof Exception\WrappedException) {
$exception = $exception->getPrevious() ?? $exception;
}
if ($exception instanceof Exception) {
$this->loggerLevel = $exception->getLoggerLevel();
} elseif ($exception instanceof HttpException) {
$this->loggerLevel = Level::Info;
}
$this->showDetailed = $this->environment->showDetailedErrors();
$this->returnJson = $this->shouldReturnJson($request);
return parent::__invoke($request, $exception, $displayErrorDetails, $logErrors, $logErrorDetails);
}
protected function determineStatusCode(): int
{
if ($this->method === 'OPTIONS') {
return 200;
}
if ($this->exception instanceof Exception || $this->exception instanceof HttpException) {
return $this->exception->getCode();
}
return 500;
}
private function shouldReturnJson(ServerRequestInterface $req): bool
{
// All API calls return JSON regardless.
if ($req instanceof ServerRequest && $req->isApi()) {
return true;
}
// Return JSON for all AJAX (XMLHttpRequest) queries.
$xhr = $req->getHeaderLine('X-Requested-With') === 'XMLHttpRequest';
if ($xhr || $this->environment->isCli() || $this->environment->isTesting()) {
return true;
}
// Return JSON if "application/json" is in the "Accept" header.
if ($req->hasHeader('Accept')) {
$accept = $req->getHeaderLine('Accept');
if (false !== stripos($accept, 'application/json')) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
protected function writeToErrorLog(): void
{
$context = [
'file' => $this->exception->getFile(),
'line' => $this->exception->getLine(),
'code' => $this->exception->getCode(),
];
if ($this->exception instanceof Exception) {
$context['context'] = $this->exception->getLoggingContext();
$context = array_merge($context, $this->exception->getExtraData());
}
if ($this->showDetailed) {
$context['trace'] = array_slice($this->exception->getTrace(), 0, 5);
}
$this->logger->log($this->loggerLevel, $this->exception->getMessage(), $context);
}
protected function respond(): ResponseInterface
{
if (!function_exists('__')) {
$locale = SupportedLocales::default();
$locale->register($this->environment);
}
if (!($this->request instanceof ServerRequest)) {
return parent::respond();
}
/** @var Response $response */
$response = $this->responseFactory->createResponse($this->statusCode);
// Special handling for cURL requests.
$ua = $this->request->getHeaderLine('User-Agent');
if (false !== stripos($ua, 'curl') || false !== stripos($ua, 'Liquidsoap')) {
$response->getBody()->write(
sprintf(
'Error: %s on %s L%s',
$this->exception->getMessage(),
$this->exception->getFile(),
$this->exception->getLine()
)
);
return $response;
}
if ($this->returnJson) {
$apiResponse = Error::fromException($this->exception, $this->showDetailed);
return $response->withJson($apiResponse);
}
if ($this->exception instanceof NotLoggedInException) {
// Redirect to login page for not-logged-in users.
$sessionPersistence = $this->injectSession->getSessionPersistence($this->request);
/** @var Session $session */
$session = $sessionPersistence->initializeSessionFromRequest($this->request);
$flash = new Flash($session);
$flash->error($this->exception->getMessage());
// Set referrer for login redirection.
$session->set('login_referrer', $this->request->getUri()->getPath());
/** @var Response $response */
$response = $sessionPersistence->persistSession($session, $response);
return $response->withRedirect($this->router->named('account:login'));
}
if ($this->exception instanceof PermissionDeniedException) {
$sessionPersistence = $this->injectSession->getSessionPersistence($this->request);
/** @var Session $session */
$session = $sessionPersistence->initializeSessionFromRequest($this->request);
$flash = new Flash($session);
$flash->error($this->exception->getMessage());
/** @var Response $response */
$response = $sessionPersistence->persistSession($session, $response);
// Bounce back to homepage for permission-denied users.
return $response->withRedirect($this->router->named('home'));
}
if ($this->showDetailed && class_exists(Run::class)) {
// Register error-handler.
$handler = new PrettyPageHandler();
$handler->setPageTitle('An error occurred!');
if ($this->exception instanceof Exception) {
foreach ($this->exception->getExtraData() as $legend => $data) {
$handler->addDataTable($legend, $data);
}
}
$run = new Run();
$run->prependHandler($handler);
return $response->write($run->handleException($this->exception));
}
try {
$view = $this->view->withRequest($this->request);
return $view->renderToResponse(
$response,
($this->exception instanceof HttpException)
? 'system/error_http'
: 'system/error_general',
[
'exception' => $this->exception,
]
);
} catch (Throwable) {
return parent::respond();
}
}
}
``` | /content/code_sandbox/backend/src/Http/ErrorHandler.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,653 |
```php
<?php
declare(strict_types=1);
namespace App\Http;
use App\Flysystem\Adapter\LocalAdapterInterface;
use App\Flysystem\ExtendedFilesystemInterface;
use App\Nginx\CustomUrls;
use InvalidArgumentException;
use League\Flysystem\FileAttributes;
use Psr\Http\Message\ResponseInterface;
use Slim\Http\Response as SlimResponse;
final class Response extends SlimResponse
{
/**
* Don't escape forward slashes by default on JSON responses.
*
* @param mixed $data
* @param int|null $status
* @param int $options
* @param int $depth
*/
public function withJson($data, ?int $status = null, int $options = 0, int $depth = 512): ResponseInterface
{
$options |= JSON_UNESCAPED_SLASHES;
$options |= JSON_UNESCAPED_UNICODE;
return parent::withJson($data, $status, $options, $depth);
}
/**
* Write a string of file data to the response as if it is a file for download.
*
* @param string $fileData
* @param string $contentType
* @param string|null $fileName
*
* @return static
*/
public function renderStringAsFile(string $fileData, string $contentType, ?string $fileName = null): Response
{
$response = $this->response
->withHeader('Pragma', 'public')
->withHeader('Expires', '0')
->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->withHeader('Content-Type', $contentType);
if ($fileName !== null) {
$response = $response->withHeader('Content-Disposition', 'attachment; filename=' . $fileName);
} else {
$response = $response->withHeader('Content-Disposition', 'inline');
}
$response->getBody()->write($fileData);
return new Response($response, $this->streamFactory);
}
public function streamFilesystemFile(
ExtendedFilesystemInterface $filesystem,
string $path,
string $fileName = null,
string $disposition = 'attachment',
bool $useXAccelRedirect = true
): ResponseInterface {
/** @var FileAttributes $fileMeta */
$fileMeta = $filesystem->getMetadata($path);
if (!$fileMeta->isFile()) {
throw new InvalidArgumentException('Specified file is not a file!');
}
$fileName ??= basename($path);
if ('attachment' === $disposition) {
/*
* The regex used below is to ensure that the $fileName contains only
* characters ranging from ASCII 128-255 and ASCII 0-31 and 127 are replaced with an empty string
*/
$disposition .= '; filename="' . preg_replace('/[\x00-\x1F\x7F\"]/', ' ', $fileName) . '"';
$disposition .= "; filename*=UTF-8''" . rawurlencode($fileName);
}
$response = $this->withHeader('Content-Disposition', $disposition)
->withHeader('Content-Length', (string)$fileMeta->fileSize());
if ($useXAccelRedirect) {
$adapter = $filesystem->getAdapter();
if ($adapter instanceof LocalAdapterInterface) {
// Special internal nginx routes to use X-Accel-Redirect for far more performant file serving.
$accelPath = CustomUrls::getXAccelPath($filesystem->getLocalPath($path));
if (null !== $accelPath) {
return $response->withHeader('Content-Type', $fileMeta->mimeType() ?? '')
->withHeader('X-Accel-Redirect', $accelPath);
}
}
}
return $response->withFile($filesystem->readStream($path), $fileMeta->mimeType() ?? true);
}
}
``` | /content/code_sandbox/backend/src/Http/Response.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 844 |
```php
<?php
declare(strict_types=1);
namespace App\Http;
use GuzzleHttp\Psr7\HttpFactory as GuzzleHttpFactory;
use GuzzleHttp\Psr7\ServerRequest as GuzzleServerRequest;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileFactoryInterface;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;
use Slim\Interfaces\ServerRequestCreatorInterface;
final class HttpFactory implements
RequestFactoryInterface,
ResponseFactoryInterface,
ServerRequestFactoryInterface,
StreamFactoryInterface,
UploadedFileFactoryInterface,
UriFactoryInterface,
ServerRequestCreatorInterface
{
private readonly GuzzleHttpFactory $httpFactory;
public function __construct()
{
$this->httpFactory = new GuzzleHttpFactory();
}
public function createUploadedFile(...$args): UploadedFileInterface
{
return $this->httpFactory->createUploadedFile(...$args);
}
public function createStream(string $content = ''): StreamInterface
{
return $this->httpFactory->createStream($content);
}
public function createStreamFromFile(...$args): StreamInterface
{
return $this->httpFactory->createStreamFromFile(...$args);
}
public function createStreamFromResource($resource): StreamInterface
{
return $this->httpFactory->createStreamFromResource($resource);
}
public function createServerRequest(...$args): ServerRequestInterface
{
$serverRequest = $this->httpFactory->createServerRequest(...$args);
return $this->decorateServerRequest($serverRequest);
}
public function createServerRequestFromGlobals(): ServerRequestInterface
{
return $this->decorateServerRequest(GuzzleServerRequest::fromGlobals());
}
private function decorateServerRequest(ServerRequestInterface $request): ServerRequestInterface
{
return new ServerRequest($request);
}
public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface
{
$response = $this->httpFactory->createResponse($code, $reasonPhrase);
return new Response($response, $this->httpFactory);
}
public function createRequest(string $method, $uri): RequestInterface
{
return $this->httpFactory->createRequest($method, $uri);
}
public function createUri(string $uri = ''): UriInterface
{
return $this->httpFactory->createUri($uri);
}
}
``` | /content/code_sandbox/backend/src/Http/HttpFactory.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 592 |
```php
<?php
declare(strict_types=1);
namespace App\Http;
use Psr\Http\Message\UriInterface;
interface RouterInterface
{
public function setRequest(?ServerRequest $request): void;
public function withRequest(?ServerRequest $request): self;
public function getBaseUrl(): UriInterface;
public function buildBaseUrl(?bool $useRequest = null): UriInterface;
/**
* Simpler format for calling "named" routes with parameters.
*/
public function named(
string $routeName,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): string;
/**
* Same as above, but returning a UriInterface.
*/
public function namedAsUri(
string $routeName,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): UriInterface;
/**
* Return a named route based on the current page and its route arguments.
*/
public function fromHere(
?string $routeName = null,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): string;
/**
* Same as above, but returns a UriInterface.
*/
public function fromHereAsUri(
?string $routeName = null,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): UriInterface;
/**
* Same as $this->fromHere(), but merging the current GET query parameters into the request as well.
*/
public function fromHereWithQuery(
?string $routeName = null,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): string;
/**
* Same as above, but returns a UriInterface.
*/
public function fromHereWithQueryAsUri(
?string $routeName = null,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): UriInterface;
}
``` | /content/code_sandbox/backend/src/Http/RouterInterface.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 425 |
```php
<?php
declare(strict_types=1);
namespace App\Cache;
use App\Entity\Relay;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
final class AzuraRelayCache
{
private const int CACHE_TTL = 600;
public function __construct(
private readonly CacheItemPoolInterface $cache
) {
}
public function setForRelay(
Relay $relay,
array $np
): void {
$cacheItem = $this->getCacheItem($relay);
$cacheItem->set($np);
$cacheItem->expiresAfter(self::CACHE_TTL);
$this->cache->save($cacheItem);
}
public function getForRelay(Relay $relay): array
{
$cacheItem = $this->getCacheItem($relay);
return $cacheItem->isHit()
? (array)$cacheItem->get()
: [];
}
private function getCacheItem(Relay $relay): CacheItemInterface
{
return $this->cache->getItem('azurarelay.relay_' . $relay->getIdRequired());
}
}
``` | /content/code_sandbox/backend/src/Cache/AzuraRelayCache.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 245 |
```php
<?php
declare(strict_types=1);
namespace App\Http;
use App\Container\SettingsAwareTrait;
use App\Traits\RequestAwareTrait;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriResolver;
use InvalidArgumentException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UriInterface;
use Slim\Interfaces\RouteInterface;
use Slim\Interfaces\RouteParserInterface;
use Slim\Routing\RouteContext;
final class Router implements RouterInterface
{
use RequestAwareTrait;
use SettingsAwareTrait;
private ?UriInterface $baseUrl = null;
private ?RouteInterface $currentRoute = null;
public function __construct(
private readonly RouteParserInterface $routeParser,
) {
}
public function setRequest(?ServerRequest $request): void
{
$this->request = $request;
$this->baseUrl = null;
$this->currentRoute = (null !== $request)
? RouteContext::fromRequest($request)->getRoute()
: null;
}
public function getBaseUrl(): UriInterface
{
if (null === $this->baseUrl) {
$this->baseUrl = $this->buildBaseUrl();
}
return $this->baseUrl;
}
public function buildBaseUrl(?bool $useRequest = null): UriInterface
{
$settings = $this->readSettings();
$useRequest ??= $settings->getPreferBrowserUrl();
$baseUrl = $settings->getBaseUrlAsUri() ?? new Uri('');
$useHttps = $settings->getAlwaysUseSsl();
if ($this->request instanceof ServerRequestInterface) {
$currentUri = $this->request->getUri();
if ('https' === $currentUri->getScheme()) {
$useHttps = true;
}
if ($useRequest || $baseUrl->getHost() === '') {
$ignoredHosts = ['web', 'nginx', 'localhost'];
if (!in_array($currentUri->getHost(), $ignoredHosts, true)) {
$baseUrl = (new Uri())
->withScheme($currentUri->getScheme())
->withHost($currentUri->getHost())
->withPort($currentUri->getPort());
}
}
}
if ($useHttps && $baseUrl->getScheme() !== '') {
$baseUrl = $baseUrl->withScheme('https');
}
// Avoid double-trailing slashes in various URLs
if ('/' === $baseUrl->getPath()) {
$baseUrl = $baseUrl->withPath('');
}
// Filter the base URL so it doesn't say path_to_url or path_to_url
if (Uri::isDefaultPort($baseUrl)) {
return $baseUrl->withPort(null);
}
return $baseUrl;
}
public function fromHereWithQueryAsUri(
?string $routeName = null,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): UriInterface {
if ($this->request instanceof ServerRequestInterface) {
$queryParams = array_merge($this->request->getQueryParams(), $queryParams);
}
return $this->fromHereAsUri($routeName, $routeParams, $queryParams, $absolute);
}
public function fromHereWithQuery(
?string $routeName = null,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): string {
if ($this->request instanceof ServerRequestInterface) {
$queryParams = array_merge($this->request->getQueryParams(), $queryParams);
}
return $this->fromHere($routeName, $routeParams, $queryParams, $absolute);
}
public function fromHereAsUri(
?string $routeName = null,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): UriInterface {
if (null !== $this->currentRoute) {
if (null === $routeName) {
$routeName = $this->currentRoute->getName();
}
$routeParams = array_merge($this->currentRoute->getArguments(), $routeParams);
}
if (null === $routeName) {
throw new InvalidArgumentException(
'Cannot specify a null route name if no existing route is configured.'
);
}
return $this->namedAsUri($routeName, $routeParams, $queryParams, $absolute);
}
public function fromHere(
?string $routeName = null,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): string {
if (null !== $this->currentRoute) {
if (null === $routeName) {
$routeName = $this->currentRoute->getName();
}
$routeParams = array_merge($this->currentRoute->getArguments(), $routeParams);
}
if (null === $routeName) {
throw new InvalidArgumentException(
'Cannot specify a null route name if no existing route is configured.'
);
}
return $this->named($routeName, $routeParams, $queryParams, $absolute);
}
public function namedAsUri(
string $routeName,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): UriInterface {
$relativeUri = $this->routeParser->relativeUrlFor($routeName, $routeParams, $queryParams);
return ($absolute)
? self::resolveUri($this->getBaseUrl(), $relativeUri, true)
: self::createUri($relativeUri);
}
public function named(
string $routeName,
array $routeParams = [],
array $queryParams = [],
bool $absolute = false
): string {
$relativeUri = $this->routeParser->relativeUrlFor($routeName, $routeParams, $queryParams);
return ($absolute)
? (string)self::resolveUri($this->getBaseUrl(), $relativeUri, true)
: $relativeUri;
}
/**
* Compose a URL, returning an absolute URL (including base URL) if the current settings or
* this function's parameters indicate an absolute URL is necessary
*
* @param UriInterface $base
* @param string|UriInterface $rel
* @param bool $absolute
*/
public static function resolveUri(
UriInterface $base,
UriInterface|string $rel,
bool $absolute = false
): UriInterface {
if (!$rel instanceof UriInterface) {
$rel = self::createUri($rel);
}
if (!$absolute) {
return $rel;
}
// URI has an authority solely because of its port.
if ($rel->getAuthority() !== '' && $rel->getHost() === '' && $rel->getPort()) {
// Strip the authority from the URI, then reapply the port after the merge.
$originalPort = $rel->getPort();
$newUri = UriResolver::resolve($base, $rel->withScheme('')->withHost('')->withPort(null));
return $newUri->withPort($originalPort);
}
return UriResolver::resolve($base, $rel);
}
public static function createUri(string $uri): UriInterface
{
return new Uri($uri);
}
}
``` | /content/code_sandbox/backend/src/Http/Router.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,558 |
```php
<?php
declare(strict_types=1);
namespace App\Radio;
final class PlaylistParser
{
/**
* @return string[]
*/
public static function getSongs(string $playlistRaw): array
{
// Process as full PLS if the header is present.
if (str_starts_with($playlistRaw, '[playlist]')) {
$parsedPlaylist = (array)parse_ini_string($playlistRaw, true, INI_SCANNER_RAW);
return array_filter(
$parsedPlaylist['playlist'],
static function ($key) {
return str_starts_with(strtolower($key), 'file');
},
ARRAY_FILTER_USE_KEY
);
}
// Process as a simple list of files or M3U-style playlist.
$lines = preg_split(
"/[\r\n]+/", // regex supports Windows, Linux/Unix & Old Macs EOL's
$playlistRaw,
-1,
PREG_SPLIT_NO_EMPTY
);
if (false === $lines) {
return [];
}
return array_filter(
array_map('trim', $lines),
static function ($line) {
return $line[0] !== '#';
}
);
}
}
``` | /content/code_sandbox/backend/src/Radio/PlaylistParser.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\Cache;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Utilities\Types;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
/**
* @phpstan-type LookupRow array{
* short_name: string,
* is_public: bool,
* updated_at: int
* }
*/
final class NowPlayingCache
{
private const int NOWPLAYING_CACHE_TTL = 180;
public function __construct(
private readonly CacheItemPoolInterface $cache
) {
}
public function setForStation(
Station $station,
?NowPlaying $nowPlaying
): void {
$this->populateLookupCache($station);
$stationCacheItem = $this->getStationCache($station->getShortName());
$stationCacheItem->set($nowPlaying);
$stationCacheItem->expiresAfter(self::NOWPLAYING_CACHE_TTL);
$this->cache->saveDeferred($stationCacheItem);
$this->cache->commit();
}
public function getForStation(string|Station $station): ?NowPlaying
{
if ($station instanceof Station) {
$station = $station->getShortName();
}
$stationCacheItem = $this->getStationCache($station);
if (!$stationCacheItem->isHit()) {
return null;
}
$np = $stationCacheItem->get();
assert($np instanceof NowPlaying);
return $np;
}
/**
* @param bool $publicOnly
* @return NowPlaying[]
*/
public function getForAllStations(bool $publicOnly = false): array
{
$lookupCacheItem = $this->getLookupCache();
if (!$lookupCacheItem->isHit()) {
return [];
}
$np = [];
/** @var LookupRow[] $lookupCache */
$lookupCache = (array)$lookupCacheItem->get();
foreach ($lookupCache as $stationInfo) {
if ($publicOnly && !$stationInfo['is_public']) {
continue;
}
$npRowItem = $this->getStationCache($stationInfo['short_name']);
$npRow = $npRowItem->isHit()
? $npRowItem->get()
: null;
if ($npRow instanceof NowPlaying) {
$np[] = $npRow;
}
}
return $np;
}
/**
* @return array<int, LookupRow>
*/
public function getLookup(): array
{
$lookupCacheItem = $this->getLookupCache();
return $lookupCacheItem->isHit()
? Types::array($lookupCacheItem->get())
: [];
}
/**
* Given a station, remove it from the lookup cache so that the NowPlaying task runner immediately runs its Now
* Playing task next. This encourages timely updates when songs change without interfering with concurrency of the
* NowPlaying sync command.
*
* @param Station $station
* @return void
*/
public function forceUpdate(Station $station): void
{
$this->populateLookupCache($station, 0);
$this->cache->commit();
}
private function getLookupCache(): CacheItemInterface
{
return $this->cache->getItem(
'now_playing.lookup'
);
}
private function populateLookupCache(
Station $station,
?int $updated = null
): void {
$lookupCacheItem = $this->getLookupCache();
$lookupCache = $lookupCacheItem->isHit()
? Types::array($lookupCacheItem->get())
: [];
$lookupCache[$station->getIdRequired()] = [
'short_name' => $station->getShortName(),
'is_public' => $station->getEnablePublicPage(),
'updated_at' => $updated ?? time(),
];
$lookupCacheItem->set($lookupCache);
$lookupCacheItem->expiresAfter(self::NOWPLAYING_CACHE_TTL);
$this->cache->saveDeferred($lookupCacheItem);
}
private function getStationCache(string $identifier): CacheItemInterface
{
if (is_numeric($identifier)) {
$lookupCache = $this->getLookup();
$identifier = Types::int($identifier);
if (isset($lookupCache[$identifier])) {
$identifier = $lookupCache[$identifier]['short_name'];
}
}
return $this->cache->getItem(
urlencode(
'now_playing.station_' . $identifier
)
);
}
}
``` | /content/code_sandbox/backend/src/Cache/NowPlayingCache.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,000 |
```php
<?php
declare(strict_types=1);
namespace App\Radio;
use App\Entity\Station;
use App\Environment;
use App\Utilities\File;
final class StereoTool
{
public const string VERSION_FILE = '.currentversion';
public static function isInstalled(): bool
{
$libraryPath = self::getLibraryPath();
return file_exists($libraryPath . '/' . self::VERSION_FILE)
|| file_exists($libraryPath . '/stereo_tool');
}
public static function getLibraryPath(): string
{
$parentDir = Environment::getInstance()->getParentDirectory();
return File::getFirstExistingDirectory([
$parentDir . '/storage/stereo_tool',
$parentDir . '/servers/stereo_tool',
]);
}
public static function isReady(Station $station): bool
{
if (!self::isInstalled()) {
return false;
}
$backendConfig = $station->getBackendConfig();
return !empty($backendConfig->getStereoToolConfigurationPath());
}
public static function getVersion(): ?string
{
if (!self::isInstalled()) {
return null;
}
$libraryPath = self::getLibraryPath();
if (file_exists($libraryPath . '/' . self::VERSION_FILE)) {
return file_get_contents($libraryPath . '/' . self::VERSION_FILE) . ' (Plugin)';
}
$binaryPath = $libraryPath . '/stereo_tool';
return file_exists($binaryPath)
? 'Legacy CLI'
: null;
}
}
``` | /content/code_sandbox/backend/src/Radio/StereoTool.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 331 |
```php
<?php
declare(strict_types=1);
namespace App\Radio;
use App\Container\EnvironmentAwareTrait;
use App\Entity\Station;
use App\Flysystem\StationFilesystems;
final class FallbackFile
{
use EnvironmentAwareTrait;
public function getFallbackPathForStation(Station $station): string
{
$stationFallback = $station->getFallbackPath();
if (!empty($stationFallback)) {
$fsConfig = StationFilesystems::buildConfigFilesystem($station);
if ($fsConfig->fileExists($stationFallback)) {
return $fsConfig->getLocalPath($stationFallback);
}
}
return $this->getDefaultFallbackPath();
}
public function getDefaultFallbackPath(): string
{
return $this->environment->isDocker()
? '/usr/local/share/icecast/web/error.mp3'
: $this->environment->getBaseDirectory() . '/resources/error.mp3';
}
}
``` | /content/code_sandbox/backend/src/Radio/FallbackFile.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 204 |
```php
<?php
declare(strict_types=1);
namespace App\Radio;
use App\Container\ContainerAwareTrait;
use App\Entity\Station;
use App\Entity\StationRemote;
use App\Exception\NotFoundException;
use App\Exception\StationUnsupportedException;
use App\Radio\Backend\Liquidsoap;
use App\Radio\Enums\AdapterTypeInterface;
use App\Radio\Enums\BackendAdapters;
use App\Radio\Enums\FrontendAdapters;
use App\Radio\Enums\RemoteAdapters;
/**
* Manager class for radio adapters.
*
* @phpstan-type AdapterInfo array<string, array{
* enum: AdapterTypeInterface,
* name: string,
* class: class-string|null
* }>
*/
final class Adapters
{
use ContainerAwareTrait;
public function getFrontendAdapter(Station $station): ?Frontend\AbstractFrontend
{
$className = $station->getFrontendType()->getClass();
return (null !== $className && $this->di->has($className))
? $this->di->get($className)
: null;
}
/**
* @throws StationUnsupportedException
*/
public function requireFrontendAdapter(Station $station): Frontend\AbstractFrontend
{
$frontend = $this->getFrontendAdapter($station);
if (null === $frontend) {
throw StationUnsupportedException::generic();
}
return $frontend;
}
/**
* @param bool $checkInstalled
* @return mixed[]
*/
public function listFrontendAdapters(bool $checkInstalled = false): array
{
return $this->listAdaptersFromEnum(FrontendAdapters::cases(), $checkInstalled);
}
public function getBackendAdapter(Station $station): ?Liquidsoap
{
$className = $station->getBackendType()->getClass();
return (null !== $className && $this->di->has($className))
? $this->di->get($className)
: null;
}
/**
* @throws StationUnsupportedException
*/
public function requireBackendAdapter(Station $station): Liquidsoap
{
$backend = $this->getBackendAdapter($station);
if (null === $backend) {
throw StationUnsupportedException::generic();
}
return $backend;
}
/**
* @param bool $checkInstalled
* @return mixed[]
*/
public function listBackendAdapters(bool $checkInstalled = false): array
{
return $this->listAdaptersFromEnum(BackendAdapters::cases(), $checkInstalled);
}
public function getRemoteAdapter(StationRemote $remote): Remote\AbstractRemote
{
$className = $remote->getType()->getClass();
if ($this->di->has($className)) {
return $this->di->get($className);
}
throw new NotFoundException(
sprintf('Adapter not found: %s', $className)
);
}
/**
* @return mixed[]
*/
public function listRemoteAdapters(): array
{
return $this->listAdaptersFromEnum(RemoteAdapters::cases());
}
/**
* @param array<AdapterTypeInterface> $cases
* @param bool $checkInstalled
* @return AdapterInfo
*/
private function listAdaptersFromEnum(array $cases, bool $checkInstalled = false): array
{
/** @var AdapterInfo $adapters */
$adapters = [];
foreach ($cases as $adapter) {
$adapters[$adapter->getValue()] = [
'enum' => $adapter,
'name' => $adapter->getName(),
'class' => $adapter->getClass(),
];
}
if ($checkInstalled) {
return array_filter(
$adapters,
function ($adapterInfo) {
if (null === $adapterInfo['class']) {
return true;
}
$adapter = $this->di->get($adapterInfo['class']);
return ($adapter instanceof AbstractLocalAdapter)
? $adapter->isInstalled()
: true;
}
);
}
return $adapters;
}
}
``` | /content/code_sandbox/backend/src/Radio/Adapters.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 890 |
```php
<?php
declare(strict_types=1);
namespace App\Radio;
use Brick\Math;
/**
* Static utility class for managing quotas.
*/
final class Quota
{
public static function getPercentage(Math\BigInteger $size, Math\BigInteger $total): int
{
if (-1 !== $size->compareTo($total)) {
return 100;
}
return $size->toBigDecimal()
->dividedBy($total, 2, Math\RoundingMode::HALF_CEILING)
->multipliedBy(100)
->toInt();
}
public static function getReadableSize(Math\BigInteger $bytes, int $decimals = 1): string
{
$bytesStr = (string)$bytes;
$size = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$factor = (int)floor((strlen($bytesStr) - 1) / 3);
if (isset($size[$factor])) {
$byteDivisor = Math\BigInteger::of(1024)->power($factor);
$sizeString = $bytes->toBigDecimal()
->dividedBy($byteDivisor, $decimals, Math\RoundingMode::HALF_DOWN);
return $sizeString . ' ' . $size[$factor];
}
return $bytesStr;
}
public static function convertFromReadableSize(Math\BigInteger|string|null $size): ?Math\BigInteger
{
if ($size instanceof Math\BigInteger) {
return $size;
}
if (empty($size)) {
return null;
}
// Remove the non-unit characters from the size.
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size) ?? '';
// Remove the non-numeric characters from the size.
$size = preg_replace('/[^\d.]/', '', $size) ?? '';
if ($unit) {
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by.
/** @noinspection StringFragmentMisplacedInspection */
$bytePower = stripos(
haystack: 'bkmgtpezy',
needle: $unit[0]
) ?: 0;
$byteMultiplier = Math\BigInteger::of(1024)->power($bytePower);
return Math\BigDecimal::of($size)
->multipliedBy($byteMultiplier)
->toScale(0, Math\RoundingMode::FLOOR)
->toBigInteger();
}
return Math\BigInteger::of($size);
}
}
``` | /content/code_sandbox/backend/src/Radio/Quota.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 567 |
```php
<?php
declare(strict_types=1);
namespace App\Radio;
use App\Container\EntityManagerAwareTrait;
use App\Container\EnvironmentAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Entity\Station;
use App\Exception\Supervisor\AlreadyRunningException;
use App\Exception\Supervisor\NotRunningException;
use App\Exception\SupervisorException;
use App\Http\Router;
use Psr\EventDispatcher\EventDispatcherInterface;
use Supervisor\Exception\Fault;
use Supervisor\Exception\SupervisorException as SupervisorLibException;
use Supervisor\SupervisorInterface;
abstract class AbstractLocalAdapter
{
use LoggerAwareTrait;
use EntityManagerAwareTrait;
use EnvironmentAwareTrait;
public function __construct(
protected SupervisorInterface $supervisor,
protected EventDispatcherInterface $dispatcher,
protected Router $router,
) {
}
/**
* Write configuration from Station object to the external service.
*
* @param Station $station
*
* @return bool Whether the newly written configuration differs from what was already on disk.
*/
public function write(Station $station): bool
{
$configPath = $this->getConfigurationPath($station);
if (null === $configPath) {
return false;
}
$currentConfig = (is_file($configPath))
? file_get_contents($configPath)
: null;
$newConfig = $this->getCurrentConfiguration($station);
file_put_contents($configPath, $newConfig);
return 0 !== strcmp($currentConfig ?: '', $newConfig ?: '');
}
/**
* Generate the configuration for this adapter as it would exist with current database settings.
*
* @param Station $station
*
*/
public function getCurrentConfiguration(Station $station): ?string
{
return null;
}
/**
* Returns the main path where configuration data is stored for this adapter.
*
*/
public function getConfigurationPath(Station $station): ?string
{
return null;
}
/**
* Indicate if the adapter in question is installed on the server.
*/
public function isInstalled(): bool
{
return (null !== $this->getBinary());
}
/**
* Return the binary executable location for this item.
*
* @return string|null Returns either the path to the binary if it exists or null for no binary.
*/
public function getBinary(): ?string
{
return null;
}
/**
* Check if the service is running.
*
* @param Station $station
*/
public function isRunning(Station $station): bool
{
if (!$this->hasCommand($station)) {
return false;
}
$programName = $this->getSupervisorFullName($station);
try {
return $this->supervisor->getProcess($programName)->isRunning();
} catch (Fault\BadNameException) {
return false;
}
}
/**
* Return a boolean indicating whether the adapter has an executable command associated with it.
*
* @param Station $station
*/
public function hasCommand(Station $station): bool
{
if ($this->environment->isTesting() || !$station->getIsEnabled()) {
return false;
}
return ($this->getCommand($station) !== null);
}
/**
* Return the shell command required to run the program.
*
* @param Station $station
*/
public function getCommand(Station $station): ?string
{
return null;
}
/**
* Return the program's fully qualified supervisord name.
*
* @param Station $station
*/
abstract public function getSupervisorProgramName(Station $station): string;
public function getSupervisorFullName(Station $station): string
{
return sprintf(
'%s:%s',
Configuration::getSupervisorGroupName($station),
$this->getSupervisorProgramName($station)
);
}
/**
* Restart the executable service.
*
* @param Station $station
*/
public function restart(Station $station): void
{
$this->stop($station);
$this->start($station);
}
/**
* Execute a non-destructive reload if the adapter supports it.
*
* @param Station $station
*/
public function reload(Station $station): void
{
$this->restart($station);
}
/**
* Stop the executable service.
*
* @param Station $station
*
* @throws SupervisorException
* @throws NotRunningException
*/
public function stop(Station $station): void
{
if ($this->hasCommand($station)) {
$programName = $this->getSupervisorFullName($station);
try {
$this->supervisor->stopProcess($programName);
$this->logger->info(
'Adapter "' . static::class . '" stopped.',
['station_id' => $station->getId(), 'station_name' => $station->getName()]
);
} catch (SupervisorLibException $e) {
$this->handleSupervisorException($e, $programName, $station);
}
}
}
/**
* Start the executable service.
*
* @param Station $station
*
* @throws SupervisorException
* @throws AlreadyRunningException
*/
public function start(Station $station): void
{
if ($this->hasCommand($station)) {
$programName = $this->getSupervisorFullName($station);
try {
$this->supervisor->startProcess($programName);
$this->logger->info(
'Adapter "' . static::class . '" started.',
['station_id' => $station->getId(), 'station_name' => $station->getName()]
);
} catch (SupervisorLibException $e) {
$this->handleSupervisorException($e, $programName, $station);
}
}
}
/**
* Internal handling of any Supervisor-related exception, to add richer data to it.
*
* @param SupervisorLibException $e
* @param string $programName
* @param Station $station
*
* @throws SupervisorException
*/
protected function handleSupervisorException(
SupervisorLibException $e,
string $programName,
Station $station
): void {
$eNew = SupervisorException::fromSupervisorLibException($e, $programName);
$eNew->addLoggingContext('station_id', $station->getId());
$eNew->addLoggingContext('station_name', $station->getName());
throw $eNew;
}
/**
* Return the path where logs are written to.
*
* @param Station $station
*/
public function getLogPath(Station $station): string
{
$configDir = $station->getRadioConfigDir();
$classParts = explode('\\', static::class);
$className = array_pop($classParts);
return $configDir . '/' . strtolower($className) . '.log';
}
}
``` | /content/code_sandbox/backend/src/Radio/AbstractLocalAdapter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,551 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\AutoDJ;
use App\Container\EntityManagerAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Entity\Repository\StationQueueRepository;
use App\Entity\Station;
use App\Entity\StationQueue;
use App\Event\Radio\BuildQueue;
use App\Utilities\Types;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Monolog\Handler\TestHandler;
use Monolog\LogRecord;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LogLevel;
use Psr\SimpleCache\CacheInterface;
/**
* Public methods related to the AutoDJ Queue process.
*/
final class Queue
{
use LoggerAwareTrait;
use EntityManagerAwareTrait;
public function __construct(
private readonly CacheInterface $cache,
private readonly EventDispatcherInterface $dispatcher,
private readonly StationQueueRepository $queueRepo,
private readonly Scheduler $scheduler,
) {
}
public function buildQueue(Station $station): void
{
// Early-fail if the station is disabled.
if (!$station->supportsAutoDjQueue()) {
$this->logger->info('Cannot build queue: station does not support AutoDJ queue.');
return;
}
// Adjust "expectedCueTime" time from current queue.
$tzObject = $station->getTimezoneObject();
$expectedCueTime = CarbonImmutable::now($tzObject);
// Get expected play time of each item.
$currentSong = $station->getCurrentSong();
if (null !== $currentSong) {
$expectedPlayTime = $this->addDurationToTime(
$station,
CarbonImmutable::createFromTimestamp($currentSong->getTimestampStart(), $tzObject),
$currentSong->getDuration()
);
if ($expectedPlayTime < $expectedCueTime) {
$expectedPlayTime = $expectedCueTime;
}
} else {
$expectedPlayTime = $expectedCueTime;
}
$maxQueueLength = $station->getBackendConfig()->getAutoDjQueueLength();
if ($maxQueueLength < 2) {
$maxQueueLength = 2;
}
$upcomingQueue = $this->queueRepo->getUnplayedQueue($station);
$lastSongId = null;
$queueLength = 0;
$removedPlaylistMedia = [];
$removedRequests = [];
$restOfQueueIsInvalid = false;
foreach ($upcomingQueue as $queueRow) {
if ($queueRow->getSentToAutodj()) {
$expectedCueTime = $this->addDurationToTime(
$station,
CarbonImmutable::createFromTimestamp($queueRow->getTimestampCued(), $tzObject),
$queueRow->getDuration()
);
if (0 === $queueLength) {
$queueLength = 1;
}
} else {
$playlist = $queueRow->getPlaylist();
$spm = $queueRow->getPlaylistMedia();
$request = $queueRow->getRequest();
if ($restOfQueueIsInvalid || !$this->isQueueRowStillValid($queueRow, $expectedPlayTime)) {
$this->logger->debug(
'Queue item is invalid and will be removed',
array_filter([
'id' => $queueRow->getId(),
'playlist' => $playlist?->getName(),
'song' => $spm?->getMedia()->getTitle(),
])
);
if (null !== $spm) {
$removedPlaylistMedia[] = $spm;
}
if (null !== $request) {
$removedRequests[] = $request;
}
$restOfQueueIsInvalid = true;
$this->em->remove($queueRow);
continue;
}
$queueRow->setTimestampCued($expectedCueTime->getTimestamp());
$expectedCueTime = $this->addDurationToTime($station, $expectedCueTime, $queueRow->getDuration());
// Only append to queue length for uncued songs.
$queueLength++;
}
$queueRow->setTimestampPlayed($expectedPlayTime->getTimestamp());
$this->em->persist($queueRow);
$expectedPlayTime = $this->addDurationToTime($station, $expectedPlayTime, $queueRow->getDuration());
$lastSongId = $queueRow->getSongId();
}
// Queue any removed playlist items to play again.
foreach ($removedPlaylistMedia as $spm) {
$this->logger->debug(
'Playlist media must be requeued on its original playlist.',
[
'media' => $spm->getMedia()->getTitle(),
'playlist' => $spm->getPlaylist()->getName(),
]
);
$spm->requeue();
$this->em->persist($spm);
}
// Mark any removed requests as unplayed so they requeue.
foreach ($removedRequests as $request) {
$this->logger->debug(
'Request must be marked unplayed.',
[
'media' => $request->getTrack()->getTitle(),
'Request id' => $request->getId(),
]
);
$request->setPlayedAt(0);
$this->em->persist($request);
}
$this->em->flush();
// Build the remainder of the queue.
while ($queueLength < $maxQueueLength) {
$this->logger->debug(
'Adding to station queue.',
[
'now' => (string)$expectedPlayTime,
]
);
// Push another test handler specifically for this one queue task.
$testHandler = new TestHandler(LogLevel::DEBUG, true);
$this->logger->pushHandler($testHandler);
$event = new BuildQueue(
$station,
$expectedCueTime,
$expectedPlayTime,
$lastSongId
);
try {
$this->dispatcher->dispatch($event);
} finally {
$this->logger->popHandler();
}
$nextSongs = $event->getNextSongs();
if (empty($nextSongs)) {
$this->em->flush();
break;
}
foreach ($nextSongs as $queueRow) {
$queueRow->setTimestampCued($expectedCueTime->getTimestamp());
$queueRow->setTimestampPlayed($expectedPlayTime->getTimestamp());
$queueRow->updateVisibility();
$this->em->persist($queueRow);
$this->em->flush();
$this->setQueueRowLog($queueRow, $testHandler->getRecords());
$lastSongId = $queueRow->getSongId();
$expectedCueTime = $this->addDurationToTime(
$station,
$expectedCueTime,
$queueRow->getDuration()
);
$expectedPlayTime = $this->addDurationToTime(
$station,
$expectedPlayTime,
$queueRow->getDuration()
);
$queueLength++;
}
}
}
/**
* @param Station $station
* @return StationQueue[]|null
*/
public function getInterruptingQueue(Station $station): ?array
{
// Early-fail if the station is disabled.
if (!$station->supportsAutoDjQueue()) {
$this->logger->notice('Cannot build queue: station does not support AutoDJ queue.');
return null;
}
$tzObject = $station->getTimezoneObject();
$expectedPlayTime = CarbonImmutable::now($tzObject);
$this->logger->debug(
'Fetching interrupting queue.',
[
'now' => (string)$expectedPlayTime,
]
);
// Push another test handler specifically for this one queue task.
$testHandler = new TestHandler(LogLevel::DEBUG, true);
$this->logger->pushHandler($testHandler);
$event = new BuildQueue(
$station,
$expectedPlayTime,
$expectedPlayTime,
null,
true
);
try {
$this->dispatcher->dispatch($event);
} finally {
$this->logger->popHandler();
}
$nextSongs = $event->getNextSongs();
if (empty($nextSongs)) {
$this->em->flush();
return null;
}
foreach ($nextSongs as $queueRow) {
$queueRow->setIsPlayed();
$queueRow->setTimestampCued($expectedPlayTime->getTimestamp());
$queueRow->setTimestampPlayed($expectedPlayTime->getTimestamp());
$queueRow->updateVisibility();
$this->em->persist($queueRow);
$this->em->flush();
$this->setQueueRowLog($queueRow, $testHandler->getRecords());
$expectedPlayTime = $this->addDurationToTime(
$station,
$expectedPlayTime,
$queueRow->getDuration()
);
}
return $nextSongs;
}
private function addDurationToTime(
Station $station,
CarbonInterface $now,
?int $duration
): CarbonInterface {
$duration ??= 1;
$startNext = $station->getBackendConfig()->getCrossfadeDuration();
$now = $now->addSeconds($duration);
return ($duration >= $startNext)
? $now->subMilliseconds((int)($startNext * 1000))
: $now;
}
private function isQueueRowStillValid(
StationQueue $queueRow,
CarbonInterface $expectedPlayTime
): bool {
$playlist = $queueRow->getPlaylist();
if (null === $playlist) {
return true;
}
return $playlist->getIsEnabled() &&
$this->scheduler->shouldPlaylistPlayNow(
$playlist,
$expectedPlayTime,
true,
$queueRow->getId()
);
}
public function getQueueRowLog(StationQueue $queueRow): ?array
{
return Types::arrayOrNull(
$this->cache->get($this->getQueueRowLogCacheKey($queueRow))
);
}
public function setQueueRowLog(StationQueue $queueRow, ?array $log): void
{
if (null !== $log) {
$log = array_map(
fn(LogRecord $logRecord) => $logRecord->formatted,
$log
);
}
$this->cache->set(
$this->getQueueRowLogCacheKey($queueRow),
$log,
StationQueue::QUEUE_LOG_TTL
);
}
private function getQueueRowLogCacheKey(StationQueue $queueRow): string
{
return 'queue_log.' . $queueRow->getIdRequired();
}
}
``` | /content/code_sandbox/backend/src/Radio/AutoDJ/Queue.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 2,324 |
```php
<?php
declare(strict_types=1);
namespace App\Radio;
use App\Container\EntityManagerAwareTrait;
use App\Container\EnvironmentAwareTrait;
use App\Entity\Enums\PlaylistTypes;
use App\Entity\Repository\StationPlaylistMediaRepository;
use App\Entity\Station;
use App\Entity\StationPlaylist;
use App\Exception;
use App\Radio\Enums\BackendAdapters;
use App\Radio\Enums\FrontendAdapters;
use RuntimeException;
use Supervisor\Exception\SupervisorException;
use Supervisor\SupervisorInterface;
final class Configuration
{
use EntityManagerAwareTrait;
use EnvironmentAwareTrait;
public const int DEFAULT_PORT_MIN = 8000;
public const int DEFAULT_PORT_MAX = 8499;
public const array PROTECTED_PORTS = [
3306, // MariaDB
6010, // Nginx internal
6379, // Redis
8080, // Common debug port
80, // HTTP
443, // HTTPS
2022, // SFTP
];
public function __construct(
private readonly Adapters $adapters,
private readonly SupervisorInterface $supervisor,
private readonly StationPlaylistMediaRepository $spmRepo,
) {
}
public function initializeConfiguration(Station $station): void
{
// Ensure default values for frontend/backend config exist.
$station->setFrontendConfig($station->getFrontendConfig());
$station->setBackendConfig($station->getBackendConfig());
// Ensure port configuration exists
$this->assignRadioPorts($station);
// Clear station caches and generate API adapter key if none exists.
if (empty($station->getAdapterApiKey())) {
$station->generateAdapterApiKey();
}
// Ensure all directories exist.
$station->ensureDirectoriesExist();
// Check for at least one playlist, and create one if it doesn't exist.
$defaultPlaylists = $station->getPlaylists()->filter(
function (StationPlaylist $row) {
return $row->getIsEnabled() && PlaylistTypes::default() === $row->getType();
}
);
if (0 === $defaultPlaylists->count()) {
$defaultPlaylist = new StationPlaylist($station);
$defaultPlaylist->setName('default');
$this->em->persist($defaultPlaylist);
}
$this->em->persist($station);
foreach ($station->getAllStorageLocations() as $storageLocation) {
$this->em->persist($storageLocation);
}
$this->em->flush();
$this->spmRepo->resetAllQueues($station);
}
/**
* Write all configuration changes to the filesystem and reload supervisord.
*/
public function writeConfiguration(
Station $station,
bool $reloadSupervisor = true,
bool $forceRestart = false,
bool $attemptReload = true
): void {
if ($this->environment->isTesting()) {
return;
}
$this->initializeConfiguration($station);
// Initialize adapters.
$supervisorConfig = [];
$supervisorConfigFile = $this->getSupervisorConfigFile($station);
$frontendEnum = $station->getFrontendType();
$backendEnum = $station->getBackendType();
$frontend = $this->adapters->getFrontendAdapter($station);
$backend = $this->adapters->getBackendAdapter($station);
// If no processes need to be managed, remove any existing config.
if (
(null === $frontend || !$frontend->hasCommand($station))
&& (null === $backend || !$backend->hasCommand($station))
) {
$this->unlinkAndStopStation($station, $reloadSupervisor, true);
throw new RuntimeException('Station has no local services.');
}
if (!$station->getHasStarted()) {
$this->unlinkAndStopStation($station, $reloadSupervisor);
throw new RuntimeException('Station has not started yet.');
}
if (!$station->getIsEnabled()) {
$this->unlinkAndStopStation($station, $reloadSupervisor);
throw new RuntimeException('Station is disabled.');
}
// Write group section of config
$programNames = [];
$programs = [];
if (null !== $backend && $backend->hasCommand($station)) {
$programName = $backend->getSupervisorProgramName($station);
$programs[$programName] = $backend;
$programNames[] = $programName;
}
if (null !== $frontend && $frontend->hasCommand($station)) {
$programName = $frontend->getSupervisorProgramName($station);
$programs[$programName] = $frontend;
$programNames[] = $programName;
}
$stationGroup = self::getSupervisorGroupName($station);
$supervisorConfig[] = '[group:' . $stationGroup . ']';
$supervisorConfig[] = 'programs=' . implode(',', $programNames);
$supervisorConfig[] = '';
foreach ($programs as $programName => $adapter) {
$configLines = [
'user' => 'azuracast',
'priority' => 950,
'startsecs' => 10,
'startretries' => 5,
'command' => $adapter->getCommand($station),
'directory' => $station->getRadioConfigDir(),
'environment' => 'TZ="' . $station->getTimezone() . '"',
'autostart' => 'false',
'autorestart' => 'true',
'stdout_logfile' => $adapter->getLogPath($station),
'stdout_logfile_maxbytes' => '5MB',
'stdout_logfile_backups' => '5',
'redirect_stderr' => 'true',
'stdout_events_enabled' => 'true',
'stderr_events_enabled' => 'true',
];
$supervisorConfig[] = '[program:' . $programName . ']';
foreach ($configLines as $configKey => $configValue) {
$supervisorConfig[] = $configKey . '=' . $configValue;
}
$supervisorConfig[] = '';
}
// Write config contents
$supervisorConfigData = implode("\n", $supervisorConfig);
file_put_contents($supervisorConfigFile, $supervisorConfigData);
// Write supporting configurations.
$frontend?->write($station);
$backend?->write($station);
$this->markAsStarted($station);
// Reload Supervisord and process groups
if ($reloadSupervisor) {
$affectedGroups = $this->reloadSupervisor();
$wasRestarted = in_array($stationGroup, $affectedGroups, true);
if (!$wasRestarted && $forceRestart) {
try {
if ($attemptReload && ($backendEnum->isEnabled() || $frontendEnum->supportsReload())) {
$backend?->reload($station);
$frontend?->reload($station);
} else {
$this->supervisor->stopProcessGroup($stationGroup);
$this->supervisor->startProcessGroup($stationGroup);
}
} catch (SupervisorException) {
}
}
}
}
private function getSupervisorConfigFile(Station $station): string
{
$configDir = $station->getRadioConfigDir();
return $configDir . '/supervisord.conf';
}
private function unlinkAndStopStation(
Station $station,
bool $reloadSupervisor = true,
bool $isRemoteOnly = false
): void {
$station->setHasStarted($isRemoteOnly);
$station->setNeedsRestart(false);
$station->setCurrentStreamer(null);
$station->setCurrentSong(null);
$this->em->persist($station);
$this->em->flush();
$supervisorConfigFile = $this->getSupervisorConfigFile($station);
@unlink($supervisorConfigFile);
if ($reloadSupervisor) {
$this->stopForStation($station);
}
}
private function stopForStation(Station $station): void
{
$this->markAsStarted($station);
$stationGroup = 'station_' . $station->getId();
$affectedGroups = $this->reloadSupervisor();
if (!in_array($stationGroup, $affectedGroups, true)) {
try {
$this->supervisor->stopProcessGroup($stationGroup, false);
} catch (SupervisorException) {
}
}
}
private function markAsStarted(Station $station): void
{
$station->setHasStarted(true);
$station->setNeedsRestart(false);
$station->setCurrentStreamer(null);
$station->setCurrentSong(null);
$this->em->persist($station);
$this->em->flush();
}
/**
* Trigger a supervisord reload and restart all relevant services.
*/
private function reloadSupervisor(): array
{
return $this->supervisor->reloadAndApplyConfig()->getAffected();
}
/**
* Assign the first available port range to this station, or ensure it already is configured properly.
*/
public function assignRadioPorts(Station $station, bool $force = false): void
{
if (
$station->getFrontendType()->isEnabled()
|| $station->getBackendType()->isEnabled()
) {
$frontendConfig = $station->getFrontendConfig();
$backendConfig = $station->getBackendConfig();
$basePort = $frontendConfig->getPort();
if ($force || null === $basePort) {
$basePort = $this->getFirstAvailableRadioPort($station);
$frontendConfig->setPort($basePort);
$station->setFrontendConfig($frontendConfig);
}
$djPort = $backendConfig->getDjPort();
if ($force || null === $djPort) {
$backendConfig->setDjPort($basePort + 5);
$station->setBackendConfig($backendConfig);
}
$telnetPort = $backendConfig->getTelnetPort();
if ($force || null === $telnetPort) {
$backendConfig->setTelnetPort($basePort + 4);
$station->setBackendConfig($backendConfig);
}
$this->em->persist($station);
$this->em->flush();
}
}
/**
* Determine the first available 10-port block that has no stations occupying it.
*/
public function getFirstAvailableRadioPort(Station $station = null): int
{
$usedPorts = $this->getUsedPorts($station);
// Iterate from port 8000 to 9000, in increments of 10
$protectedPorts = self::PROTECTED_PORTS;
$portMin = $this->environment->getAutoAssignPortMin();
$portMax = $this->environment->getAutoAssignPortMax();
for ($port = $portMin; $port <= $portMax; $port += 10) {
if (in_array($port, $protectedPorts, true)) {
continue;
}
$rangeInUse = false;
for ($i = $port; $i < $port + 10; $i++) {
if (isset($usedPorts[$i])) {
$rangeInUse = true;
break;
}
}
if (!$rangeInUse) {
return $port;
}
}
throw new Exception('This installation has no available ports for new radio stations.');
}
/**
* Get an array of all used ports across the system, except the ones used by the station specified (if specified).
*
* @return array<int, array{
* id: int,
* name: string
* }>
*/
public function getUsedPorts(Station $exceptStation = null): array
{
static $usedPorts;
if (null === $usedPorts) {
$usedPorts = [];
// Get all station used ports.
$stationConfigs = $this->em->createQuery(
<<<'DQL'
SELECT s.id, s.name, s.frontend_type, s.frontend_config, s.backend_type, s.backend_config
FROM App\Entity\Station s
DQL
)->getArrayResult();
/** @var array<array-key, int|string|array> $row */
foreach ($stationConfigs as $row) {
$stationReference = ['id' => $row['id'], 'name' => $row['name']];
if ($row['frontend_type'] !== FrontendAdapters::Remote->value) {
$frontendConfig = (array)$row['frontend_config'];
if (!empty($frontendConfig['port'])) {
$port = (int)$frontendConfig['port'];
$usedPorts[$port] = $stationReference;
}
}
if ($row['backend_type'] !== BackendAdapters::None->value) {
$backendConfig = (array)$row['backend_config'];
// For DJ port, consider both the assigned port and port+1 to be reserved and in-use.
if (!empty($backendConfig['dj_port'])) {
$port = (int)$backendConfig['dj_port'];
$usedPorts[$port] = $stationReference;
$usedPorts[$port + 1] = $stationReference;
}
if (!empty($backendConfig['telnet_port'])) {
$port = (int)$backendConfig['telnet_port'];
$usedPorts[$port] = $stationReference;
}
}
}
}
if (null !== $exceptStation && null !== $exceptStation->getId()) {
return array_filter(
$usedPorts,
static function ($stationReference) use ($exceptStation) {
return ($stationReference['id'] !== $exceptStation->getId());
}
);
}
return $usedPorts;
}
/**
* Remove configuration (i.e. prior to station removal) and trigger a Supervisor refresh.
*
* @param Station $station
*/
public function removeConfiguration(Station $station): void
{
if ($this->environment->isTesting()) {
return;
}
$stationGroup = 'station_' . $station->getId();
// Try forcing the group to stop, but don't hard-fail if it doesn't.
try {
$this->supervisor->stopProcessGroup($stationGroup);
$this->supervisor->removeProcessGroup($stationGroup);
} catch (SupervisorException) {
}
$supervisorConfigPath = $this->getSupervisorConfigFile($station);
@unlink($supervisorConfigPath);
$this->reloadSupervisor();
}
/**
* @return int[]
*/
public static function enumerateDefaultPorts(
int $rangeMin = self::DEFAULT_PORT_MIN,
int $rangeMax = self::DEFAULT_PORT_MAX,
): array {
$defaultPorts = [];
for ($i = $rangeMin; $i < $rangeMax; $i += 10) {
if (in_array($i, self::PROTECTED_PORTS, true)) {
continue;
}
$defaultPorts[] = $i;
$defaultPorts[] = $i + 5;
$defaultPorts[] = $i + 6;
}
return $defaultPorts;
}
public static function getSupervisorGroupName(Station $station): string
{
return 'station_' . $station->getIdRequired();
}
public static function getSupervisorProgramName(Station $station, string $category): string
{
return 'station_' . $station->getIdRequired() . '_' . $category;
}
}
``` | /content/code_sandbox/backend/src/Radio/Configuration.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 3,406 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\AutoDJ;
use App\Container\EntityManagerAwareTrait;
use App\Entity\Repository\StationQueueRepository;
use App\Entity\Station;
use App\Entity\StationMedia;
use App\Entity\StationMediaMetadata;
use App\Entity\StationQueue;
use App\Entity\StationRequest;
use App\Event\Radio\AnnotateNextSong;
use App\Radio\Backend\Liquidsoap\ConfigWriter;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class Annotations implements EventSubscriberInterface
{
use EntityManagerAwareTrait;
public function __construct(
private readonly StationQueueRepository $queueRepo,
private readonly EventDispatcherInterface $eventDispatcher,
) {
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
AnnotateNextSong::class => [
['annotateSongPath', 20],
['annotateForLiquidsoap', 15],
['annotatePlaylist', 10],
['annotateRequest', 5],
['enableAutoCue', -5],
['postAnnotation', -10],
],
];
}
/**
* Pulls the next song from the AutoDJ, dispatches the AnnotateNextSong event and returns the built result.
*/
public function annotateNextSong(
Station $station,
bool $asAutoDj = false,
): string|bool {
$queueRow = $this->queueRepo->getNextToSendToAutoDj($station);
if (null === $queueRow) {
return false;
}
$event = AnnotateNextSong::fromStationQueue($queueRow, $asAutoDj);
$this->eventDispatcher->dispatch($event);
return $event->buildAnnotations();
}
public function annotateSongPath(AnnotateNextSong $event): void
{
$media = $event->getMedia();
if ($media instanceof StationMedia) {
$event->setSongPath('media:' . ltrim($media->getPath(), '/'));
} else {
$queue = $event->getQueue();
if ($queue instanceof StationQueue) {
$customUri = $queue->getAutodjCustomUri();
if (!empty($customUri)) {
$event->setSongPath($customUri);
}
}
}
}
public function annotateForLiquidsoap(AnnotateNextSong $event): void
{
$media = $event->getMedia();
if (null === $media) {
return;
}
$station = $event->getStation();
if (!$station->getBackendType()->isEnabled()) {
return;
}
$annotations = [];
$annotationsRaw = array_filter([
'title' => $media->getTitle(),
'artist' => $media->getArtist(),
'duration' => $media->getLength(),
'song_id' => $media->getSongId(),
'media_id' => $media->getId(),
...$media->getExtraMetadata()->toArray(),
], fn ($row) => ('' !== $row && null !== $row));
// Safety checks for cue lengths.
if (
isset($annotationsRaw[StationMediaMetadata::CUE_OUT])
&& $annotationsRaw[StationMediaMetadata::CUE_OUT] < 0
) {
$cueOut = abs($annotationsRaw[StationMediaMetadata::CUE_OUT]);
if (0.0 === $cueOut) {
unset($annotationsRaw[StationMediaMetadata::CUE_OUT]);
}
if (isset($annotationsRaw['duration'])) {
if ($cueOut > $annotationsRaw['duration']) {
unset($annotationsRaw[StationMediaMetadata::CUE_OUT]);
} else {
$annotationsRaw[StationMediaMetadata::CUE_OUT] = max(0, $annotationsRaw['duration'] - $cueOut);
}
}
}
if (
isset($annotationsRaw[StationMediaMetadata::CUE_OUT], $annotationsRaw['duration'])
&& $annotationsRaw[StationMediaMetadata::CUE_OUT] > $annotationsRaw['duration']
) {
unset($annotationsRaw[StationMediaMetadata::CUE_OUT]);
}
if (
isset($annotationsRaw[StationMediaMetadata::CUE_IN], $annotationsRaw['duration'])
&& $annotationsRaw[StationMediaMetadata::CUE_IN] > $annotationsRaw['duration']
) {
unset($annotationsRaw[StationMediaMetadata::CUE_IN]);
}
foreach ($annotationsRaw as $name => $prop) {
$prop = ConfigWriter::annotateString((string)$prop);
if ('duration' === $name) {
$prop = ConfigWriter::toFloat($prop);
}
// Process Liquidsoap-specific annotations.
if (StationMediaMetadata::isLiquidsoapAnnotation($name)) {
$prop = match ($name) {
'liq_blank_skipped',
'liq_cue_file',
'liq_longtail',
'liq_sustained_ending'
=> ConfigWriter::toBool($prop),
'liq_amplify' => $prop . ' dB',
default => ConfigWriter::valueToString($prop)
};
}
$annotations[$name] = $prop;
}
$event->addAnnotations($annotations);
}
public function annotatePlaylist(AnnotateNextSong $event): void
{
$playlist = $event->getPlaylist();
if (null === $playlist) {
return;
}
$event->addAnnotations([
'playlist_id' => $playlist->getId(),
]);
if ($playlist->getIsJingle()) {
$event->addAnnotations([
'jingle_mode' => 'true',
]);
}
}
public function annotateRequest(AnnotateNextSong $event): void
{
$request = $event->getRequest();
if ($request instanceof StationRequest) {
$event->addAnnotations([
'request_id' => $request->getId(),
]);
}
}
public function enableAutoCue(AnnotateNextSong $event): void
{
if ($event->getStation()->getBackendConfig()->getEnableAutoCue()) {
$event->setProtocol('autocue');
}
}
public function postAnnotation(AnnotateNextSong $event): void
{
if (!$event->isAsAutoDj()) {
return;
}
$queueRow = $event->getQueue();
if ($queueRow instanceof StationQueue) {
$queueRow->setSentToAutodj();
$queueRow->setTimestampCued(time());
$this->em->persist($queueRow);
$this->em->flush();
}
}
}
``` | /content/code_sandbox/backend/src/Radio/AutoDJ/Annotations.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,468 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\AutoDJ;
use App\Container\LoggerAwareTrait;
use App\Entity\Api\StationPlaylistQueue;
/**
* @phpstan-type PlayedTrack array{
* song_id: string,
* text: string|null,
* artist: string|null,
* title: string|null,
* timestamp_played: int
* }
*/
final class DuplicatePrevention
{
use LoggerAwareTrait;
public const array ARTIST_SEPARATORS = [
', ',
' feat ',
' feat. ',
' ft ',
' ft. ',
' / ',
' & ',
' vs. ',
];
/**
* @param StationPlaylistQueue[] $eligibleTracks
* @param PlayedTrack[] $playedTracks
* @param bool $allowDuplicates Whether to return a media ID even if duplicates can't be prevented.
*/
public function preventDuplicates(
array $eligibleTracks = [],
array $playedTracks = [],
bool $allowDuplicates = false
): ?StationPlaylistQueue {
if (empty($eligibleTracks)) {
$this->logger->debug('Eligible song queue is empty!');
return null;
}
$latestSongIdsPlayed = [];
foreach ($playedTracks as $playedTrack) {
$songId = $playedTrack['song_id'];
if (!isset($latestSongIdsPlayed[$songId])) {
$latestSongIdsPlayed[$songId] = $playedTrack['timestamp_played'];
}
}
/** @var StationPlaylistQueue[] $notPlayedEligibleTracks */
$notPlayedEligibleTracks = [];
foreach ($eligibleTracks as $mediaId => $track) {
$songId = $track->song_id;
if (isset($latestSongIdsPlayed[$songId])) {
continue;
}
$notPlayedEligibleTracks[$mediaId] = $track;
}
$validTrack = $this->getDistinctTrack($notPlayedEligibleTracks, $playedTracks);
if (null !== $validTrack) {
$this->logger->info(
'Found track that avoids duplicate title and artist.',
[
'media_id' => $validTrack->media_id,
'title' => $validTrack->title,
'artist' => $validTrack->artist,
]
);
return $validTrack;
}
// If we reach this point, there's no way to avoid a duplicate title and artist.
if ($allowDuplicates) {
/** @var StationPlaylistQueue[] $mediaIdsByTimePlayed */
$mediaIdsByTimePlayed = [];
// For each piece of eligible media, get its latest played timestamp.
foreach ($eligibleTracks as $track) {
$songId = $track->song_id;
$trackKey = $latestSongIdsPlayed[$songId] ?? 0;
$mediaIdsByTimePlayed[$trackKey] = $track;
}
ksort($mediaIdsByTimePlayed);
$validTrack = array_shift($mediaIdsByTimePlayed);
// Pull the lowest value, which corresponds to the least recently played song.
if (null !== $validTrack) {
$this->logger->warning(
'No way to avoid same title OR same artist; using least recently played song.',
[
'media_id' => $validTrack->media_id,
'title' => $validTrack->title,
'artist' => $validTrack->artist,
]
);
return $validTrack;
}
}
return null;
}
/**
* Given an array of eligible tracks, return the first ID that doesn't have a duplicate artist/
* title with any of the previously played tracks.
*
* Both should be in the form of an array, i.e.:
* [ 'id' => ['artist' => 'Foo', 'title' => 'Fighters'] ]
*
* @param StationPlaylistQueue[] $eligibleTracks
* @param PlayedTrack[] $playedTracks
*
*/
public function getDistinctTrack(
array $eligibleTracks,
array $playedTracks
): ?StationPlaylistQueue {
$artists = [];
$titles = [];
foreach ($playedTracks as $playedTrack) {
$title = $this->prepareStringForMatching($playedTrack['title']);
$titles[$title] = $title;
foreach ($this->getArtistParts($playedTrack['artist']) as $artist) {
$artists[$artist] = $artist;
}
}
foreach ($eligibleTracks as $track) {
// Avoid all direct title matches.
$title = $this->prepareStringForMatching($track->title);
if (isset($titles[$title])) {
continue;
}
// Attempt to avoid an artist match, if possible.
$compareArtists = [];
foreach ($this->getArtistParts($track->artist) as $compareArtist) {
$compareArtists[$compareArtist] = $compareArtist;
}
if (empty(array_intersect_key($compareArtists, $artists))) {
return $track;
}
}
return null;
}
private function getArtistParts(?string $artists): array
{
$dividerString = chr(7);
$artistParts = explode(
$dividerString,
str_replace(self::ARTIST_SEPARATORS, $dividerString, trim($artists ?? ''))
);
return array_filter(
array_map(
[$this, 'prepareStringForMatching'],
$artistParts
)
);
}
private function prepareStringForMatching(?string $string): string
{
return mb_strtolower(trim($string ?? ''));
}
}
``` | /content/code_sandbox/backend/src/Radio/AutoDJ/DuplicatePrevention.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,237 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\AutoDJ;
use App\Container\EntityManagerAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Entity\Api\StationPlaylistQueue;
use App\Entity\Enums\PlaylistOrders;
use App\Entity\Enums\PlaylistRemoteTypes;
use App\Entity\Enums\PlaylistSources;
use App\Entity\Enums\PlaylistTypes;
use App\Entity\Repository\StationPlaylistMediaRepository;
use App\Entity\Repository\StationQueueRepository;
use App\Entity\Repository\StationRequestRepository;
use App\Entity\Song;
use App\Entity\StationMedia;
use App\Entity\StationPlaylist;
use App\Entity\StationPlaylistMedia;
use App\Entity\StationQueue;
use App\Event\Radio\BuildQueue;
use App\Radio\PlaylistParser;
use Carbon\CarbonInterface;
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* The internal steps of the AutoDJ Queue building process.
*/
final class QueueBuilder implements EventSubscriberInterface
{
use LoggerAwareTrait;
use EntityManagerAwareTrait;
public function __construct(
private readonly Scheduler $scheduler,
private readonly DuplicatePrevention $duplicatePrevention,
private readonly CacheInterface $cache,
private readonly StationPlaylistMediaRepository $spmRepo,
private readonly StationRequestRepository $requestRepo,
private readonly StationQueueRepository $queueRepo
) {
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
BuildQueue::class => [
['getNextSongFromRequests', 5],
['calculateNextSong', 0],
],
];
}
/**
* Determine the next-playing song for this station based on its playlist rotation rules.
*
* @param BuildQueue $event
*/
public function calculateNextSong(BuildQueue $event): void
{
$this->logger->info('AzuraCast AutoDJ is calculating the next song to play...');
$station = $event->getStation();
$expectedPlayTime = $event->getExpectedPlayTime();
$activePlaylistsByType = [];
foreach ($station->getPlaylists() as $playlist) {
/** @var StationPlaylist $playlist */
if ($playlist->isPlayable($event->isInterrupting())) {
$type = $playlist->getType()->value;
$subType = ($playlist->getScheduleItems()->count() > 0) ? 'scheduled' : 'unscheduled';
$activePlaylistsByType[$type . '_' . $subType][$playlist->getId()] = $playlist;
}
}
if (empty($activePlaylistsByType)) {
$this->logger->error('No valid playlists detected. Skipping AutoDJ calculations.');
return;
}
$recentSongHistoryForDuplicatePrevention = $this->queueRepo->getRecentlyPlayedByTimeRange(
$station,
$expectedPlayTime,
$station->getBackendConfig()->getDuplicatePreventionTimeRange()
);
$this->logger->debug(
'AutoDJ recent song playback history',
[
'history_duplicate_prevention' => $recentSongHistoryForDuplicatePrevention,
]
);
$typesToPlay = [
PlaylistTypes::OncePerHour->value,
PlaylistTypes::OncePerXSongs->value,
PlaylistTypes::OncePerXMinutes->value,
PlaylistTypes::Standard->value,
];
$typesToPlayByPriority = [];
foreach ($typesToPlay as $type) {
$typesToPlayByPriority[] = $type . '_scheduled';
$typesToPlayByPriority[] = $type . '_unscheduled';
}
foreach ($typesToPlayByPriority as $currentPlaylistType) {
if (empty($activePlaylistsByType[$currentPlaylistType])) {
continue;
}
$eligiblePlaylists = [];
$logPlaylists = [];
foreach ($activePlaylistsByType[$currentPlaylistType] as $playlistId => $playlist) {
/** @var StationPlaylist $playlist */
if (!$this->scheduler->shouldPlaylistPlayNow($playlist, $expectedPlayTime)) {
continue;
}
$eligiblePlaylists[$playlistId] = $playlist->getWeight();
$logPlaylists[] = [
'id' => $playlist->getId(),
'name' => $playlist->getName(),
'weight' => $playlist->getWeight(),
];
}
if (empty($eligiblePlaylists)) {
continue;
}
$this->logger->info(
sprintf(
'%d playable playlist(s) of type "%s" found.',
count($eligiblePlaylists),
$type
),
['playlists' => $logPlaylists]
);
$eligiblePlaylists = $this->weightedShuffle($eligiblePlaylists);
// Loop through the playlists and attempt to play them with no duplicates first,
// then loop through them again while allowing duplicates.
foreach ([false, true] as $allowDuplicates) {
foreach ($eligiblePlaylists as $playlistId => $weight) {
$playlist = $activePlaylistsByType[$currentPlaylistType][$playlistId];
if (
$event->setNextSongs(
$this->playSongFromPlaylist(
$playlist,
$recentSongHistoryForDuplicatePrevention,
$expectedPlayTime,
$allowDuplicates
)
)
) {
$this->logger->info(
'Playable track(s) found and registered.',
[
'next_song' => (string)$event,
]
);
return;
}
}
}
}
if ($event->isInterrupting()) {
$this->logger->info('No interrupting tracks to play.');
} else {
$this->logger->error('No playable tracks were found.');
}
}
/**
* Apply a weighted shuffle to the given array in the form:
* [ key1 => weight1, key2 => weight2 ]
*
* Based on: path_to_url
*
* @param array $original
* @return array
*/
private function weightedShuffle(array $original): array
{
$new = $original;
$max = 1.0 / mt_getrandmax();
array_walk(
$new,
static function (&$value) use ($max): void {
$value = (mt_rand() * $max) ** (1.0 / $value);
}
);
arsort($new);
array_walk(
$new,
static function (&$value, $key) use ($original): void {
$value = $original[$key];
}
);
return $new;
}
/**
* Given a specified (sequential or shuffled) playlist, choose a song from the playlist to play and return it.
*
* @param StationPlaylist $playlist
* @param array $recentSongHistory
* @param CarbonInterface $expectedPlayTime
* @param bool $allowDuplicates Whether to return a media ID even if duplicates can't be prevented.
* @return StationQueue|StationQueue[]|null
*/
private function playSongFromPlaylist(
StationPlaylist $playlist,
array $recentSongHistory,
CarbonInterface $expectedPlayTime,
bool $allowDuplicates = false
): StationQueue|array|null {
if (PlaylistSources::RemoteUrl === $playlist->getSource()) {
return $this->getSongFromRemotePlaylist($playlist, $expectedPlayTime);
}
if ($playlist->backendMerge()) {
$this->spmRepo->resetQueue($playlist);
$queueEntries = array_filter(
array_map(
function (StationPlaylistQueue $validTrack) use ($playlist, $expectedPlayTime) {
return $this->makeQueueFromApi($validTrack, $playlist, $expectedPlayTime);
},
$this->spmRepo->getQueue($playlist)
)
);
if (!empty($queueEntries)) {
$playlist->setPlayedAt($expectedPlayTime->getTimestamp());
$this->em->persist($playlist);
return $queueEntries;
}
} else {
$validTrack = match ($playlist->getOrder()) {
PlaylistOrders::Random => $this->getRandomMediaIdFromPlaylist(
$playlist,
$recentSongHistory,
$allowDuplicates
),
PlaylistOrders::Sequential => $this->getSequentialMediaIdFromPlaylist($playlist),
PlaylistOrders::Shuffle => $this->getShuffledMediaIdFromPlaylist(
$playlist,
$recentSongHistory,
$allowDuplicates
)
};
if (null !== $validTrack) {
$queueEntry = $this->makeQueueFromApi($validTrack, $playlist, $expectedPlayTime);
if (null !== $queueEntry) {
$playlist->setPlayedAt($expectedPlayTime->getTimestamp());
$this->em->persist($playlist);
return $queueEntry;
}
}
}
$this->logger->warning(
sprintf('Playlist "%s" did not return a playable track.', $playlist->getName()),
[
'playlist_id' => $playlist->getId(),
'playlist_order' => $playlist->getOrder()->value,
'allow_duplicates' => $allowDuplicates,
]
);
return null;
}
private function makeQueueFromApi(
StationPlaylistQueue $validTrack,
StationPlaylist $playlist,
CarbonInterface $expectedPlayTime,
): ?StationQueue {
$mediaToPlay = $this->em->find(StationMedia::class, $validTrack->media_id);
if (!$mediaToPlay instanceof StationMedia) {
return null;
}
$spm = $this->em->find(StationPlaylistMedia::class, $validTrack->spm_id);
if ($spm instanceof StationPlaylistMedia) {
$spm->played($expectedPlayTime->getTimestamp());
$this->em->persist($spm);
}
$stationQueueEntry = StationQueue::fromMedia($playlist->getStation(), $mediaToPlay);
$stationQueueEntry->setPlaylist($playlist);
$stationQueueEntry->setPlaylistMedia($spm);
$this->em->persist($stationQueueEntry);
return $stationQueueEntry;
}
private function getSongFromRemotePlaylist(
StationPlaylist $playlist,
CarbonInterface $expectedPlayTime
): ?StationQueue {
$mediaToPlay = $this->getMediaFromRemoteUrl($playlist);
if (is_array($mediaToPlay)) {
[$mediaUri, $mediaDuration] = $mediaToPlay;
$playlist->setPlayedAt($expectedPlayTime->getTimestamp());
$this->em->persist($playlist);
$stationQueueEntry = new StationQueue(
$playlist->getStation(),
Song::createFromText('Remote Playlist URL')
);
$stationQueueEntry->setPlaylist($playlist);
$stationQueueEntry->setAutodjCustomUri($mediaUri);
$stationQueueEntry->setDuration($mediaDuration);
$this->em->persist($stationQueueEntry);
return $stationQueueEntry;
}
return null;
}
/**
* Returns either an array containing the URL of a remote stream and the duration,
* an array with a media id and the duration or null if no media has been found.
*
* @return array{string|null, int}|null
*/
private function getMediaFromRemoteUrl(StationPlaylist $playlist): ?array
{
$remoteType = $playlist->getRemoteType() ?? PlaylistRemoteTypes::Stream;
// Handle a raw stream URL of possibly indeterminate length.
if (PlaylistRemoteTypes::Stream === $remoteType) {
// Annotate a hard-coded "duration" parameter to avoid infinite play for scheduled playlists.
$duration = $this->scheduler->getPlaylistScheduleDuration($playlist);
return [$playlist->getRemoteUrl(), $duration];
}
// Handle a remote playlist containing songs or streams.
$queueCacheKey = 'playlist_queue.' . $playlist->getId();
$mediaQueue = $this->cache->get($queueCacheKey);
if (empty($mediaQueue)) {
$mediaQueue = [];
$playlistRemoteUrl = $playlist->getRemoteUrl();
if (null !== $playlistRemoteUrl) {
$playlistRaw = file_get_contents($playlistRemoteUrl);
if (false !== $playlistRaw) {
$mediaQueue = PlaylistParser::getSongs($playlistRaw);
}
}
}
$mediaId = null;
if (!empty($mediaQueue)) {
$mediaId = array_shift($mediaQueue);
}
// Save the modified cache, sans the now-missing entry.
$this->cache->set($queueCacheKey, $mediaQueue, 6000);
return ($mediaId)
? [$mediaId, 0]
: null;
}
private function getRandomMediaIdFromPlaylist(
StationPlaylist $playlist,
array $recentSongHistory,
bool $allowDuplicates
): ?StationPlaylistQueue {
$mediaQueue = $this->spmRepo->getQueue($playlist);
if ($playlist->getAvoidDuplicates()) {
return $this->duplicatePrevention->preventDuplicates($mediaQueue, $recentSongHistory, $allowDuplicates);
}
return array_shift($mediaQueue);
}
private function getSequentialMediaIdFromPlaylist(
StationPlaylist $playlist
): ?StationPlaylistQueue {
$mediaQueue = $this->spmRepo->getQueue($playlist);
if (empty($mediaQueue)) {
$this->spmRepo->resetQueue($playlist);
$mediaQueue = $this->spmRepo->getQueue($playlist);
}
return array_shift($mediaQueue);
}
private function getShuffledMediaIdFromPlaylist(
StationPlaylist $playlist,
array $recentSongHistory,
bool $allowDuplicates
): ?StationPlaylistQueue {
$mediaQueue = $this->spmRepo->getQueue($playlist);
if (empty($mediaQueue)) {
$this->spmRepo->resetQueue($playlist);
$mediaQueue = $this->spmRepo->getQueue($playlist);
}
if (!$playlist->getAvoidDuplicates()) {
return array_shift($mediaQueue);
}
$queueItem = $this->duplicatePrevention->preventDuplicates($mediaQueue, $recentSongHistory, $allowDuplicates);
if (null !== $queueItem || $allowDuplicates) {
return $queueItem;
}
// Reshuffle the queue.
$this->logger->warning(
'Duplicate prevention yielded no playable song; resetting song queue.'
);
$this->spmRepo->resetQueue($playlist);
$mediaQueue = $this->spmRepo->getQueue($playlist);
return $this->duplicatePrevention->preventDuplicates($mediaQueue, $recentSongHistory, false);
}
public function getNextSongFromRequests(BuildQueue $event): void
{
// Don't use this to cue requests.
if ($event->isInterrupting()) {
return;
}
$expectedPlayTime = $event->getExpectedPlayTime();
$request = $this->requestRepo->getNextPlayableRequest($event->getStation(), $expectedPlayTime);
if (null === $request) {
return;
}
$this->logger->debug(sprintf('Queueing next song from request ID %d.', $request->getId()));
$stationQueueEntry = StationQueue::fromRequest($request);
$this->em->persist($stationQueueEntry);
$request->setPlayedAt($expectedPlayTime->getTimestamp());
$this->em->persist($request);
$event->setNextSongs($stationQueueEntry);
}
}
``` | /content/code_sandbox/backend/src/Radio/AutoDJ/QueueBuilder.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 3,389 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend;
use App\Entity\Station;
use App\Entity\StationStreamer;
use App\Event\Radio\WriteLiquidsoapConfiguration;
use App\Exception;
use App\Nginx\CustomUrls;
use App\Radio\AbstractLocalAdapter;
use App\Radio\Backend\Liquidsoap\ConfigWriter;
use App\Radio\Configuration;
use App\Radio\Enums\LiquidsoapQueues;
use LogicException;
use Psr\Http\Message\UriInterface;
use Symfony\Component\Process\Process;
final class Liquidsoap extends AbstractLocalAdapter
{
/**
* @inheritDoc
*/
public function getConfigurationPath(Station $station): ?string
{
return $station->getRadioConfigDir() . '/liquidsoap.liq';
}
/**
* @inheritDoc
*/
public function getCurrentConfiguration(Station $station): ?string
{
$event = new WriteLiquidsoapConfiguration($station, false, true);
$this->dispatcher->dispatch($event);
return $event->buildConfiguration();
}
/**
* Returns the port used for DJs/Streamers to connect to LiquidSoap for broadcasting.
*
* @param Station $station
*
* @return int The port number to use for this station.
*/
public function getStreamPort(Station $station): int
{
$djPort = $station->getBackendConfig()->getDjPort();
if (null !== $djPort) {
return $djPort;
}
// Default to frontend port + 5
$frontendConfig = $station->getFrontendConfig();
$frontendPort = $frontendConfig->getPort() ?? (8000 + (($station->getId() - 1) * 10));
return $frontendPort + 5;
}
/**
* Execute the specified remote command on LiquidSoap via the telnet API.
*
* @param Station $station
* @param string $commandStr
*
* @return string[]
*
* @throws Exception
*/
public function command(Station $station, string $commandStr): array
{
$socketPath = 'unix://' . $station->getRadioConfigDir() . '/liquidsoap.sock';
$fp = stream_socket_client(
$socketPath,
$errno,
$errstr,
20
);
if (!$fp) {
throw new Exception('Telnet failure: ' . $errstr . ' (' . $errno . ')');
}
fwrite($fp, str_replace(["\\'", '&'], ["'", '&'], urldecode($commandStr)) . "\nquit\n");
$response = [];
while (!feof($fp)) {
$response[] = trim(fgets($fp, 1024) ?: '');
}
fclose($fp);
return $response;
}
/**
* @inheritdoc
*/
public function getCommand(Station $station): ?string
{
if ($binary = $this->getBinary()) {
$configPath = $station->getRadioConfigDir() . '/liquidsoap.liq';
return $binary . ' ' . $configPath;
}
return null;
}
/**
* @inheritDoc
*/
public function getBinary(): ?string
{
return '/usr/local/bin/liquidsoap';
}
public function getVersion(): ?string
{
$binary = $this->getBinary();
if (null === $binary) {
return null;
}
$process = new Process([$binary, '--version']);
$process->run();
if (!$process->isSuccessful()) {
return null;
}
return preg_match('/^Liquidsoap (.+)$/im', $process->getOutput(), $matches)
? $matches[1]
: null;
}
public function getHlsUrl(Station $station, UriInterface $baseUrl = null): UriInterface
{
$baseUrl ??= $this->router->getBaseUrl();
return $baseUrl->withPath(
$baseUrl->getPath() . CustomUrls::getHlsUrl($station) . '/live.m3u8'
);
}
public function isQueueEmpty(
Station $station,
LiquidsoapQueues $queue
): bool {
$queueResult = $this->command(
$station,
sprintf('%s.queue', $queue->value)
);
return empty($queueResult[0]);
}
/**
* @return string[]
*/
public function enqueue(
Station $station,
LiquidsoapQueues $queue,
string $musicFile
): array {
return $this->command(
$station,
sprintf('%s.push %s', $queue->value, $musicFile)
);
}
/**
* @return string[]
*/
public function skip(Station $station): array
{
return $this->command(
$station,
'radio.skip'
);
}
/**
* @return string[]
*/
public function updateMetadata(Station $station, array $newMeta): array
{
$metaStr = [];
foreach ($newMeta as $metaKey => $metaVal) {
$metaStr[] = $metaKey . '="' . ConfigWriter::annotateString($metaVal) . '"';
}
return $this->command(
$station,
'custom_metadata.insert ' . implode(',', $metaStr),
);
}
/**
* Tell LiquidSoap to disconnect the current live streamer.
*
* @param Station $station
*
* @return string[]
*/
public function disconnectStreamer(Station $station): array
{
$currentStreamer = $station->getCurrentStreamer();
$disconnectTimeout = $station->getDisconnectDeactivateStreamer();
if ($currentStreamer instanceof StationStreamer && $disconnectTimeout > 0) {
$currentStreamer->deactivateFor($disconnectTimeout);
$this->em->persist($currentStreamer);
$this->em->flush();
}
return $this->command(
$station,
'input_streamer.stop'
);
}
public function getWebStreamingUrl(Station $station, UriInterface $baseUrl): UriInterface
{
$djMount = $station->getBackendConfig()->getDjMountPoint();
return $baseUrl
->withScheme('wss')
->withPath($baseUrl->getPath() . CustomUrls::getWebDjUrl($station) . $djMount);
}
public function verifyConfig(string $config): void
{
$binary = $this->getBinary();
$process = new Process([
$binary,
'--check',
'-',
]);
$process->setInput($config);
$process->run();
if (1 === $process->getExitCode()) {
throw new LogicException($process->getOutput());
}
}
public function getSupervisorProgramName(Station $station): string
{
return Configuration::getSupervisorProgramName($station, 'backend');
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,529 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\AutoDJ;
use App\Container\EntityManagerAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Entity\Enums\PlaylistTypes;
use App\Entity\Repository\StationPlaylistMediaRepository;
use App\Entity\Repository\StationQueueRepository;
use App\Entity\StationPlaylist;
use App\Entity\StationSchedule;
use App\Entity\StationStreamer;
use App\Utilities\DateRange;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Doctrine\Common\Collections\Collection;
use Monolog\LogRecord;
final class Scheduler
{
use LoggerAwareTrait;
use EntityManagerAwareTrait;
public function __construct(
private readonly StationPlaylistMediaRepository $spmRepo,
private readonly StationQueueRepository $queueRepo
) {
}
public function shouldPlaylistPlayNow(
StationPlaylist $playlist,
CarbonInterface $now = null,
bool $excludeSpecialRules = false,
int $belowIdForOncePerXSongs = null
): bool {
$this->logger->pushProcessor(
function (LogRecord $record) use ($playlist) {
$record->extra['playlist'] = [
'id' => $playlist->getId(),
'name' => $playlist->getName(),
];
return $record;
}
);
if (null === $now) {
$now = CarbonImmutable::now($playlist->getStation()->getTimezoneObject());
}
if (!$this->isPlaylistScheduledToPlayNow($playlist, $now, $excludeSpecialRules)) {
$this->logger->debug('Playlist is not scheduled to play now.');
$this->logger->popProcessor();
return false;
}
$shouldPlay = true;
switch ($playlist->getType()) {
case PlaylistTypes::OncePerHour:
$shouldPlay = $this->shouldPlaylistPlayNowPerHour($playlist, $now);
$this->logger->debug(
sprintf(
'Once-per-hour playlist %s been played yet this hour.',
$shouldPlay ? 'HAS NOT' : 'HAS'
)
);
break;
case PlaylistTypes::OncePerXSongs:
$playPerSongs = $playlist->getPlayPerSongs();
$shouldPlay = !$this->queueRepo->isPlaylistRecentlyPlayed(
$playlist,
$playPerSongs,
$belowIdForOncePerXSongs
);
$this->logger->debug(
sprintf(
'Once-per-X-songs playlist %s been played within the last %d song(s).',
$shouldPlay ? 'HAS NOT' : 'HAS',
$playPerSongs
)
);
break;
case PlaylistTypes::OncePerXMinutes:
$playPerMinutes = $playlist->getPlayPerMinutes();
$shouldPlay = !$this->wasPlaylistPlayedInLastXMinutes($playlist, $now, $playPerMinutes);
$this->logger->debug(
sprintf(
'Once-per-X-minutes playlist %s been played within the last %d minute(s).',
$shouldPlay ? 'HAS NOT' : 'HAS',
$playPerMinutes
)
);
break;
case PlaylistTypes::Advanced:
$this->logger->debug('Playlist is "Advanced" type and is not managed by the AutoDJ.');
$shouldPlay = false;
break;
case PlaylistTypes::Standard:
break;
}
$this->logger->popProcessor();
return $shouldPlay;
}
public function isPlaylistScheduledToPlayNow(
StationPlaylist $playlist,
CarbonInterface $now,
bool $excludeSpecialRules = false
): bool {
$scheduleItems = $playlist->getScheduleItems();
if (0 === $scheduleItems->count()) {
$this->logger->debug('Playlist has no schedule items; skipping schedule time check.');
return true;
}
$scheduleItem = $this->getActiveScheduleFromCollection($scheduleItems, $now, $excludeSpecialRules);
return null !== $scheduleItem;
}
private function shouldPlaylistPlayNowPerHour(
StationPlaylist $playlist,
CarbonInterface $now
): bool {
$currentMinute = $now->minute;
$targetMinute = $playlist->getPlayPerHourMinute();
if ($currentMinute < $targetMinute) {
$targetTime = $now->subHour()->minute($targetMinute);
} else {
$targetTime = $now->minute($targetMinute);
}
$playlistDiff = $targetTime->diffInMinutes($now, false);
if ($playlistDiff < 0 || $playlistDiff > 15) {
return false;
}
return !$this->wasPlaylistPlayedInLastXMinutes($playlist, $now, 30);
}
private function wasPlaylistPlayedInLastXMinutes(
StationPlaylist $playlist,
CarbonInterface $now,
int $minutes
): bool {
$playedAt = $this->queueRepo->getLastPlayedTimeForPlaylist($playlist, $now);
if (0 === $playedAt) {
return false;
}
$threshold = $now->subMinutes($minutes)->getTimestamp();
return ($playedAt > $threshold);
}
/**
* Get the duration of scheduled play time in seconds (used for remote URLs of indeterminate length).
*
* @param StationPlaylist $playlist
*/
public function getPlaylistScheduleDuration(StationPlaylist $playlist): int
{
$now = CarbonImmutable::now($playlist->getStation()->getTimezoneObject());
$scheduleItem = $this->getActiveScheduleFromCollection(
$playlist->getScheduleItems(),
$now
);
if ($scheduleItem instanceof StationSchedule) {
return $scheduleItem->getDuration();
}
return 0;
}
public function canStreamerStreamNow(
StationStreamer $streamer,
CarbonInterface $now = null
): bool {
if (!$streamer->enforceSchedule()) {
return true;
}
if (null === $now) {
$now = CarbonImmutable::now($streamer->getStation()->getTimezoneObject());
}
$scheduleItem = $this->getActiveScheduleFromCollection(
$streamer->getScheduleItems(),
$now
);
return null !== $scheduleItem;
}
/**
* @param Collection<int, StationSchedule> $scheduleItems
* @param CarbonInterface $now
* @return StationSchedule|null
*/
private function getActiveScheduleFromCollection(
Collection $scheduleItems,
CarbonInterface $now,
bool $excludeSpecialRules = false
): ?StationSchedule {
if ($scheduleItems->count() > 0) {
foreach ($scheduleItems as $scheduleItem) {
$scheduleName = (string)$scheduleItem;
if ($this->shouldSchedulePlayNow($scheduleItem, $now, $excludeSpecialRules)) {
$this->logger->debug(
sprintf(
'%s - Should Play Now',
$scheduleName
)
);
return $scheduleItem;
}
$this->logger->debug(
sprintf(
'%s - Not Eligible to Play Now',
$scheduleName
)
);
}
}
return null;
}
public function shouldSchedulePlayNow(
StationSchedule $schedule,
CarbonInterface $now,
bool $excludeSpecialRules = false
): bool {
$startTime = StationSchedule::getDateTime($schedule->getStartTime(), $now);
$endTime = StationSchedule::getDateTime($schedule->getEndTime(), $now);
$this->logger->debug('Checking to see whether schedule should play now.', [
'startTime' => $startTime,
'endTime' => $endTime,
]);
if (!$this->shouldSchedulePlayOnCurrentDate($schedule, $now)) {
$this->logger->debug('Schedule is not scheduled to play today.');
return false;
}
/** @var DateRange[] $comparePeriods */
$comparePeriods = [];
if ($startTime->equalTo($endTime)) {
// Create intervals for "play once" type dates.
$comparePeriods[] = new DateRange(
$startTime,
$endTime->addMinutes(15)
);
$comparePeriods[] = new DateRange(
$startTime->subDay(),
$endTime->subDay()->addMinutes(15)
);
$comparePeriods[] = new DateRange(
$startTime->addDay(),
$endTime->addDay()->addMinutes(15)
);
} elseif ($startTime->greaterThan($endTime)) {
// Create intervals for overnight playlists (one from yesterday to today, one from today to tomorrow).
$comparePeriods[] = new DateRange(
$startTime->subDay(),
$endTime
);
$comparePeriods[] = new DateRange(
$startTime,
$endTime->addDay()
);
} else {
$comparePeriods[] = new DateRange(
$startTime,
$endTime
);
}
foreach ($comparePeriods as $dateRange) {
if ($this->shouldPlayInSchedulePeriod($schedule, $dateRange, $now, $excludeSpecialRules)) {
return true;
}
}
return false;
}
private function shouldPlayInSchedulePeriod(
StationSchedule $schedule,
DateRange $dateRange,
CarbonInterface $now,
bool $excludeSpecialRules = false
): bool {
if (!$dateRange->contains($now)) {
return false;
}
// Check day-of-week limitations.
$dayToCheck = $dateRange->getStart()->dayOfWeekIso;
if (!$this->isScheduleScheduledToPlayToday($schedule, $dayToCheck)) {
return false;
}
// Check playlist special handling rules.
$playlist = $schedule->getPlaylist();
if (null === $playlist) {
return true;
}
// Skip the remaining checks if we're doing a "still scheduled to play" Queue check.
if ($excludeSpecialRules) {
return true;
}
// Handle "Play Single Track" advanced setting.
if (
$playlist->backendPlaySingleTrack()
&& $playlist->getPlayedAt() >= $dateRange->getStartTimestamp()
) {
return false;
}
// Handle "Loop Once" schedule specification.
if (
$schedule->getLoopOnce()
&& !$this->shouldPlaylistLoopNow($schedule, $dateRange, $now)
) {
return false;
}
return true;
}
private function shouldPlaylistLoopNow(
StationSchedule $schedule,
DateRange $dateRange,
CarbonInterface $now,
): bool {
$this->logger->debug('Checking if playlist should loop now.');
$playlist = $schedule->getPlaylist();
if (null === $playlist) {
$this->logger->error('Attempting to check playlist loop status on a non-playlist-based schedule item.');
return false;
}
$playlistPlayedAt = CarbonImmutable::createFromTimestamp(
$playlist->getPlayedAt(),
$now->getTimezone()
);
$isQueueEmpty = $this->spmRepo->isQueueEmpty($playlist);
$hasCuedPlaylistMedia = $this->queueRepo->hasCuedPlaylistMedia($playlist);
if (!$dateRange->contains($playlistPlayedAt)) {
$this->logger->debug('Playlist was not played yet.');
$isQueueFilled = $this->spmRepo->isQueueCompletelyFilled($playlist);
if ((!$isQueueFilled || $isQueueEmpty) && !$hasCuedPlaylistMedia) {
$now = $dateRange->getStart()->subSecond();
$this->logger->debug('Resetting playlist queue with now override', [$now]);
$this->spmRepo->resetQueue($playlist, $now);
$isQueueEmpty = false;
}
} elseif ($isQueueEmpty && !$hasCuedPlaylistMedia) {
$this->logger->debug('Resetting playlist queue.');
$this->spmRepo->resetQueue($playlist);
$isQueueEmpty = false;
}
$playlist = $this->em->refetch($playlist);
$playlistQueueResetAt = CarbonImmutable::createFromTimestamp(
$playlist->getQueueResetAt(),
$now->getTimezone()
);
if (!$isQueueEmpty && !$dateRange->contains($playlistQueueResetAt)) {
$this->logger->debug('Playlist should loop.');
return true;
}
$this->logger->debug('Playlist should NOT loop.');
return false;
}
public function shouldSchedulePlayOnCurrentDate(
StationSchedule $schedule,
CarbonInterface $now
): bool {
$startDate = $schedule->getStartDate();
$endDate = $schedule->getEndDate();
if (!empty($startDate)) {
$startDate = CarbonImmutable::createFromFormat('Y-m-d', $startDate, $now->getTimezone());
if (null !== $startDate) {
$startDate = StationSchedule::getDateTime(
$schedule->getStartTime(),
$startDate
);
if ($now->endOfDay()->lt($startDate)) {
return false;
}
}
}
if (!empty($endDate)) {
$endDate = CarbonImmutable::createFromFormat('Y-m-d', $endDate, $now->getTimezone());
if (null !== $endDate) {
$endDate = StationSchedule::getDateTime(
$schedule->getEndTime(),
$endDate
);
if ($now->startOfDay()->gt($endDate)) {
return false;
}
}
}
return true;
}
/**
* Given an ISO-8601 date, return if the playlist can be played on that day.
*
* @param StationSchedule $schedule
* @param int $dayToCheck ISO-8601 date (1 for Monday, 7 for Sunday)
*/
public function isScheduleScheduledToPlayToday(
StationSchedule $schedule,
int $dayToCheck
): bool {
$playOnceDays = $schedule->getDays();
return empty($playOnceDays)
|| in_array($dayToCheck, $playOnceDays, true);
}
}
``` | /content/code_sandbox/backend/src/Radio/AutoDJ/Scheduler.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 3,069 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend\Liquidsoap;
use App\Container\EntityManagerAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Entity\Station;
use App\Entity\StationMedia;
use App\Entity\StationPlaylist;
use App\Event\Radio\AnnotateNextSong;
use App\Event\Radio\WriteLiquidsoapConfiguration;
use App\Exception;
use App\Flysystem\StationFilesystems;
use App\Message;
use App\Radio\Backend\Liquidsoap;
use League\Flysystem\StorageAttributes;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Filesystem\Filesystem;
use Throwable;
final class PlaylistFileWriter implements EventSubscriberInterface
{
use LoggerAwareTrait;
use EntityManagerAwareTrait;
public function __construct(
private readonly EventDispatcherInterface $eventDispatcher,
private readonly Filesystem $fsUtils,
private readonly Liquidsoap $liquidsoap
) {
}
/**
* Handle event dispatch.
*
* @param Message\AbstractMessage $message
*/
public function __invoke(Message\AbstractMessage $message): void
{
if ($message instanceof Message\WritePlaylistFileMessage) {
$playlist = $this->em->find(StationPlaylist::class, $message->playlist_id);
if ($playlist instanceof StationPlaylist) {
$this->writePlaylistFile($playlist);
$playlistVarName = ConfigWriter::getPlaylistVariableName($playlist);
$station = $playlist->getStation();
try {
$this->liquidsoap->command($station, $playlistVarName . '.reload');
} catch (Exception $e) {
$this->logger->error(
'Could not reload playlist with AutoDJ.',
[
'message' => $e->getMessage(),
'playlist' => $playlistVarName,
'station' => $station->getId(),
]
);
}
}
}
}
public static function getSubscribedEvents(): array
{
return [
WriteLiquidsoapConfiguration::class => [
['writePlaylistsForLiquidsoap', 32],
],
];
}
public function writePlaylistsForLiquidsoap(WriteLiquidsoapConfiguration $event): void
{
if ($event->shouldWriteToDisk()) {
$this->writeAllPlaylistFiles($event->getStation());
}
}
public function writeAllPlaylistFiles(Station $station): void
{
// Clear out existing playlists directory.
$fsPlaylists = StationFilesystems::buildPlaylistsFilesystem($station);
foreach ($fsPlaylists->listContents('', false) as $file) {
/** @var StorageAttributes $file */
if ($file->isDir()) {
$fsPlaylists->deleteDirectory($file->path());
} else {
$fsPlaylists->delete($file->path());
}
}
foreach ($station->getPlaylists() as $playlist) {
if (!$playlist->getIsEnabled()) {
continue;
}
$this->writePlaylistFile($playlist);
}
}
private function writePlaylistFile(StationPlaylist $playlist): void
{
$station = $playlist->getStation();
$this->logger->info(
'Writing playlist file to disk...',
[
'station' => $station->getName(),
'playlist' => $playlist->getName(),
]
);
$playlistFile = [];
$mediaQuery = $this->em->createQuery(
<<<'DQL'
SELECT DISTINCT sm
FROM App\Entity\StationMedia sm
JOIN sm.playlists spm
WHERE spm.playlist = :playlist
ORDER BY spm.weight ASC
DQL
)->setParameter('playlist', $playlist);
/** @var StationMedia $mediaFile */
foreach ($mediaQuery->toIterable() as $mediaFile) {
$event = new AnnotateNextSong(
station: $station,
media: $mediaFile,
playlist: $playlist,
asAutoDj: false
);
try {
$this->eventDispatcher->dispatch($event);
$playlistFile[] = $event->buildAnnotations();
} catch (Throwable) {
}
}
$playlistFilePath = self::getPlaylistFilePath($playlist);
$this->fsUtils->dumpFile(
$playlistFilePath,
implode("\n", $playlistFile)
);
}
public static function getPlaylistFilePath(StationPlaylist $playlist): string
{
return $playlist->getStation()->getRadioPlaylistsDir() . '/'
. ConfigWriter::getPlaylistVariableName($playlist) . '.m3u';
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/PlaylistFileWriter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,000 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend\Liquidsoap\Command;
use App\Entity\Station;
use App\Flysystem\StationFilesystems;
use RuntimeException;
final class CopyCommand extends AbstractCommand
{
public function __construct(
private readonly StationFilesystems $stationFilesystems,
) {
}
protected function doRun(Station $station, bool $asAutoDj = false, array $payload = []): string
{
if (empty($payload['uri'])) {
throw new RuntimeException('No URI provided.');
}
$uri = $payload['uri'];
return $this->stationFilesystems->getMediaFilesystem($station)
->getLocalPath($uri);
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/Command/CopyCommand.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 156 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend\Liquidsoap\Command;
use App\Entity\Station;
use App\Radio\AutoDJ\Annotations;
final class NextSongCommand extends AbstractCommand
{
public function __construct(
private readonly Annotations $annotations
) {
}
protected function doRun(
Station $station,
bool $asAutoDj = false,
array $payload = []
): string|bool {
return $this->annotations->annotateNextSong(
$station,
$asAutoDj
);
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/Command/NextSongCommand.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 124 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend\Liquidsoap\Command;
use App\Entity\Repository\StationStreamerRepository;
use App\Entity\Station;
final class DjOnCommand extends AbstractCommand
{
public function __construct(
private readonly StationStreamerRepository $streamerRepo,
) {
}
protected function doRun(
Station $station,
bool $asAutoDj = false,
array $payload = []
): bool|string {
$user = $payload['user'] ?? '';
$this->logger->notice(
'Received "DJ connected" ping from Liquidsoap.',
[
'dj' => $user,
]
);
if (!$asAutoDj) {
return false;
}
return $this->streamerRepo->onConnect($station, $user);
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/Command/DjOnCommand.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 179 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend\Liquidsoap\Command;
use App\Entity\Repository\StationStreamerRepository;
use App\Entity\Station;
final class DjOffCommand extends AbstractCommand
{
public function __construct(
private readonly StationStreamerRepository $streamerRepo,
) {
}
protected function doRun(
Station $station,
bool $asAutoDj = false,
array $payload = []
): bool {
$this->logger->notice('Received "DJ disconnected" ping from Liquidsoap.');
if (!$asAutoDj) {
return false;
}
return $this->streamerRepo->onDisconnect($station);
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/Command/DjOffCommand.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 148 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend\Liquidsoap\Command;
use App\Entity\Repository\StationStreamerRepository;
use App\Entity\Station;
use RuntimeException;
final class DjAuthCommand extends AbstractCommand
{
public function __construct(
private readonly StationStreamerRepository $streamerRepo,
) {
}
protected function doRun(
Station $station,
bool $asAutoDj = false,
array $payload = []
): bool {
if (!$station->getEnableStreamers()) {
throw new RuntimeException('Attempted DJ authentication when streamers are disabled on this station.');
}
$user = $payload['user'] ?? '';
$pass = $payload['password'] ?? '';
// Allow connections using the exact broadcast source password.
$sourcePw = $station->getFrontendConfig()->getSourcePassword();
if (!empty($sourcePw) && strcmp($sourcePw, $pass) === 0) {
return true;
}
return $this->streamerRepo->authenticate($station, $user, $pass);
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/Command/DjAuthCommand.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 234 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend\Liquidsoap\Command;
use App\Container\LoggerAwareTrait;
use App\Entity\Station;
use App\Radio\Enums\BackendAdapters;
use App\Utilities\Types;
use Monolog\LogRecord;
use ReflectionClass;
use Throwable;
abstract class AbstractCommand
{
use LoggerAwareTrait;
public function run(
Station $station,
bool $asAutoDj = false,
?array $payload = []
): string {
$this->logger->pushProcessor(
function (LogRecord $record) use ($station) {
$record->extra['station'] = [
'id' => $station->getId(),
'name' => $station->getName(),
];
return $record;
}
);
$className = (new ReflectionClass(static::class))->getShortName();
$this->logger->debug(
sprintf('Running Internal Command %s', $className),
[
'asAutoDj' => $asAutoDj,
'payload' => $payload,
]
);
try {
if (BackendAdapters::Liquidsoap !== $station->getBackendType()) {
$this->logger->error('Station does not use Liquidsoap backend.');
return 'false';
}
$result = $this->doRun($station, $asAutoDj, $payload ?? []);
if (true === $result) {
return 'true';
}
if (false === $result) {
return 'false';
}
return Types::string($result);
} catch (Throwable $e) {
$this->logger->error(
sprintf(
'Error with Internal Command %s: %s',
$className,
$e->getMessage()
),
[
'exception' => $e,
]
);
return 'false';
} finally {
$this->logger->popProcessor();
}
}
abstract protected function doRun(
Station $station,
bool $asAutoDj = false,
array $payload = []
): mixed;
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/Command/AbstractCommand.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\Radio\Backend\Liquidsoap\Command;
use App\Cache\NowPlayingCache;
use App\Container\EntityManagerAwareTrait;
use App\Entity\Repository\SongHistoryRepository;
use App\Entity\Repository\StationQueueRepository;
use App\Entity\Song;
use App\Entity\SongHistory;
use App\Entity\Station;
use App\Entity\StationMedia;
use App\Entity\StationMediaMetadata;
use App\Entity\StationPlaylist;
use Exception;
use RuntimeException;
final class FeedbackCommand extends AbstractCommand
{
use EntityManagerAwareTrait;
public function __construct(
private readonly StationQueueRepository $queueRepo,
private readonly SongHistoryRepository $historyRepo,
private readonly NowPlayingCache $nowPlayingCache
) {
}
protected function doRun(
Station $station,
bool $asAutoDj = false,
array $payload = []
): bool {
if (!$asAutoDj) {
return false;
}
// Process Liquidsoap list.assoc to JSON mapping
$payload = array_map(
[StationMediaMetadata::class, 'normalizeLiquidsoapValue'],
$payload
);
// Process extra metadata sent by Liquidsoap (if it exists).
try {
$historyRow = $this->getSongHistory($station, $payload);
$this->em->persist($historyRow);
$this->historyRepo->changeCurrentSong($station, $historyRow);
$this->em->flush();
$this->nowPlayingCache->forceUpdate($station);
return true;
} catch (Exception $e) {
$this->logger->error(
sprintf('Liquidsoap feedback error: %s', $e->getMessage()),
[
'exception' => $e,
]
);
return false;
}
}
private function getSongHistory(
Station $station,
array $payload
): SongHistory {
if (empty($payload['media_id'])) {
if (empty($payload['artist']) && empty($payload['title'])) {
throw new RuntimeException('No payload provided.');
}
$newSong = Song::createFromArray([
'artist' => $payload['artist'] ?? '',
'title' => $payload['title'] ?? '',
]);
if (!$this->historyRepo->isDifferentFromCurrentSong($station, $newSong)) {
throw new RuntimeException('Song is not different from current song.');
}
return new SongHistory(
$station,
$newSong
);
}
$media = $this->em->find(StationMedia::class, $payload['media_id']);
if (!$media instanceof StationMedia) {
throw new RuntimeException('Media ID does not exist for station.');
}
// If AutoCue information exists, cache it back to the DB to improve performance.
if ($station->getBackendConfig()->getEnableAutoCue()) {
$currentExtraMeta = $media->getExtraMetadata()->toArray();
$media->setExtraMetadata($payload);
$newExtraMeta = $media->getExtraMetadata()->toArray();
if ($newExtraMeta !== $currentExtraMeta) {
$this->em->persist($media);
$this->em->flush();
}
}
if (!$this->historyRepo->isDifferentFromCurrentSong($station, $media)) {
throw new RuntimeException('Song is not different from current song.');
}
$sq = $this->queueRepo->findRecentlyCuedSong($station, $media);
if (null !== $sq) {
// If there's an existing record, ensure it has all the proper metadata.
if (null === $sq->getMedia()) {
$sq->setMedia($media);
}
if (!empty($payload['playlist_id']) && null === $sq->getPlaylist()) {
$playlist = $this->em->find(StationPlaylist::class, $payload['playlist_id']);
if ($playlist instanceof StationPlaylist) {
$sq->setPlaylist($playlist);
}
}
$this->em->persist($sq);
$this->em->flush();
$this->queueRepo->trackPlayed($station, $sq);
return SongHistory::fromQueue($sq);
}
$history = new SongHistory($station, $media);
$history->setMedia($media);
if (!empty($payload['playlist_id'])) {
$playlist = $this->em->find(StationPlaylist::class, $payload['playlist_id']);
if ($playlist instanceof StationPlaylist) {
$history->setPlaylist($playlist);
}
}
return $history;
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/Command/FeedbackCommand.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 992 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
enum LiquidsoapQueues: string
{
case Requests = 'requests';
case Interrupting = 'interrupting_requests';
public static function default(): self
{
return self::Requests;
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/LiquidsoapQueues.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 62 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
use App\Radio\Backend\Liquidsoap\Command;
enum LiquidsoapCommands: string
{
case Copy = 'cp';
case DjAuth = 'auth';
case DjOn = 'djon';
case DjOff = 'djoff';
case Feedback = 'feedback';
case NextSong = 'nextsong';
/** @return class-string<Command\AbstractCommand> */
public function getClass(): string
{
return match ($this) {
self::Copy => Command\CopyCommand::class,
self::DjAuth => Command\DjAuthCommand::class,
self::DjOn => Command\DjOnCommand::class,
self::DjOff => Command\DjOffCommand::class,
self::Feedback => Command\FeedbackCommand::class,
self::NextSong => Command\NextSongCommand::class
};
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/LiquidsoapCommands.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\Radio\Enums;
enum MasterMePresets: string
{
case MusicGeneral = 'music_general';
case SpeechGeneral = 'speech_general';
case EbuR128 = 'ebu_r128';
case ApplePodcasts = 'apple_podcasts';
case YouTube = 'youtube';
public static function default(): self
{
return self::MusicGeneral;
}
public function getOptions(): array
{
$defaults = [
"bypass" => false,
"target" => -16,
"brickwall_bypass" => false,
"brickwall_ceiling" => -1.0,
"brickwall_release" => 75.0,
"eq_bypass" => false,
"eq_highpass_freq" => 5.0,
"eq_side_bandwidth" => 1.0,
"eq_side_freq" => 600.0,
"eq_side_gain" => 1.0,
"eq_tilt_gain" => 0.0,
"gate_attack" => 0.0,
"gate_bypass" => true,
"gate_hold" => 50.0,
"gate_release" => 430.5,
"gate_threshold" => -90.0,
"kneecomp_attack" => 20.0,
"kneecomp_bypass" => false,
"kneecomp_dry_wet" => 50,
"kneecomp_ff_fb" => 50,
"kneecomp_knee" => 6.0,
"kneecomp_link" => 60,
"kneecomp_makeup" => 0.0,
"kneecomp_release" => 340.0,
"kneecomp_strength" => 20,
"kneecomp_tar_thresh" => -4.0,
"leveler_brake_threshold" => -10.0,
"leveler_bypass" => false,
"leveler_max" => 10.0,
"leveler_max__" => 10.0,
"leveler_speed" => 20,
"limiter_attack" => 3.0,
"limiter_bypass" => false,
"limiter_ff_fb" => 50,
"limiter_knee" => 3.0,
"limiter_makeup" => 0.0,
"limiter_release" => 40.0,
"limiter_strength" => 80,
"limiter_tar_thresh" => 6.0,
"mscomp_bypass" => false,
"high_attack" => 8.0,
"high_crossover" => 8000.0,
"high_knee" => 12.0,
"high_link" => 30,
"high_release" => 30.0,
"high_strength" => 30,
"high_tar_thresh" => -12.0,
"low_attack" => 15.0,
"low_crossover" => 60.0,
"low_knee" => 12.0,
"low_link" => 70,
"low_release" => 150.0,
"low_strength" => 10,
"low_tar_thresh" => -3.0,
"makeup" => 1.0,
"dc_blocker" => false,
"input_gain" => 0.0,
"mono" => false,
"phase_l" => false,
"phase_r" => false,
"stereo_correct" => false,
];
return match ($this) {
self::MusicGeneral => [
...$defaults,
],
self::SpeechGeneral => [
...$defaults,
"eq_highpass_freq" => 20.0,
"eq_side_gain" => 0.0,
"gate_attack" => 1.0,
"gate_release" => 500.0,
"kneecomp_attack" => 5.0,
"kneecomp_knee" => 9.0,
"kneecomp_release" => 50.0,
"kneecomp_strength" => 15,
"kneecomp_tar_thresh" => -6.0,
"leveler_brake_threshold" => -20.0,
"leveler_max" => 30.0,
"leveler_max__" => 30.0,
"limiter_attack" => 1.0,
"limiter_strength" => 80,
"limiter_tar_thresh" => 3.0,
"high_attack" => 0.0,
"high_release" => 50.0,
"high_strength" => 40,
"high_tar_thresh" => -7.0,
"low_attack" => 10.0,
"low_release" => 80.0,
"low_strength" => 20,
"low_tar_thresh" => -5.0,
"dc_blocker" => true,
],
self::EbuR128 => [
...$defaults,
"target" => -23,
"eq_highpass_freq" => 20.0,
"eq_side_gain" => 0.0,
"gate_attack" => 1.0,
"gate_release" => 500.0,
"kneecomp_attack" => 5.0,
"kneecomp_bypass" => true,
"kneecomp_knee" => 9.0,
"kneecomp_release" => 50.0,
"kneecomp_strength" => 15,
"kneecomp_tar_thresh" => -6.0,
"leveler_brake_threshold" => -20.0,
"leveler_max" => 30.0,
"leveler_max__" => 30.0,
"leveler_speed" => 40,
"limiter_attack" => 1.0,
"limiter_tar_thresh" => 3.0,
"high_attack" => 0.0,
"high_release" => 50.0,
"high_strength" => 40,
"high_tar_thresh" => -8.0,
"low_attack" => 10.0,
"low_release" => 80.0,
"low_strength" => 20,
"low_tar_thresh" => -6.0,
"dc_blocker" => true,
],
self::ApplePodcasts => [
...$defaults,
"bypass" => false,
"eq_highpass_freq" => 20.0,
"eq_side_gain" => 0.0,
"gate_attack" => 1.0,
"gate_release" => 500.0,
"kneecomp_attack" => 5.0,
"kneecomp_bypass" => true,
"kneecomp_knee" => 9.0,
"kneecomp_release" => 50.0,
"kneecomp_strength" => 15,
"kneecomp_tar_thresh" => -6.0,
"leveler_brake_threshold" => -20.0,
"leveler_max" => 30.0,
"leveler_max__" => 30.0,
"leveler_speed" => 50,
"limiter_attack" => 1.0,
"limiter_tar_thresh" => 3.0,
"high_attack" => 0.0,
"high_release" => 50.0,
"high_strength" => 40,
"high_tar_thresh" => -8.0,
"low_attack" => 10.0,
"low_release" => 80.0,
"low_strength" => 20,
"low_tar_thresh" => -6.0,
"dc_blocker" => true,
],
self::YouTube => [
...$defaults,
"target" => -14,
"eq_highpass_freq" => 20.0,
"eq_side_gain" => 0.0,
"gate_attack" => 1.0,
"gate_release" => 500.0,
"kneecomp_attack" => 5.0,
"kneecomp_bypass" => true,
"kneecomp_knee" => 9.0,
"kneecomp_release" => 50.0,
"kneecomp_strength" => 15,
"kneecomp_tar_thresh" => -6.0,
"leveler_brake_threshold" => -20.0,
"leveler_max" => 30.0,
"leveler_max__" => 30.0,
"leveler_speed" => 50,
"limiter_attack" => 1.0,
"limiter_tar_thresh" => 3.0,
"high_attack" => 0.0,
"high_strength" => 40,
"high_tar_thresh" => -8.0,
"low_attack" => 10.0,
"low_release" => 80.0,
"low_strength" => 20,
"low_tar_thresh" => -6.0,
"dc_blocker" => true,
]
};
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/MasterMePresets.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 2,080 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
enum StreamProtocols: string
{
case Icy = 'icy';
case Http = 'http';
case Https = 'https';
}
``` | /content/code_sandbox/backend/src/Radio/Enums/StreamProtocols.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 49 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
enum StreamFormats: string
{
case Mp3 = 'mp3';
case Ogg = 'ogg';
case Aac = 'aac';
case Opus = 'opus';
case Flac = 'flac';
public function getExtension(): string
{
return $this->value;
}
public function formatBitrate(?int $bitrate): string
{
if (null === $bitrate) {
return strtoupper($this->value);
}
return match ($this) {
self::Flac => 'FLAC',
default => $bitrate . 'kbps ' . strtoupper($this->value)
};
}
public function sendIcyMetadata(): bool
{
return match ($this) {
self::Flac => true,
default => false,
};
}
public static function default(): self
{
return self::Mp3;
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/StreamFormats.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 216 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
enum AudioProcessingMethods: string
{
case None = 'none';
case Liquidsoap = 'nrj';
case MasterMe = 'master_me';
case StereoTool = 'stereo_tool';
public function getValue(): string
{
return $this->value;
}
public static function default(): self
{
return self::None;
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/AudioProcessingMethods.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 97 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
use App\Radio\Remote\AbstractRemote;
use App\Radio\Remote\AzuraRelay;
use App\Radio\Remote\Icecast;
use App\Radio\Remote\Shoutcast1;
use App\Radio\Remote\Shoutcast2;
enum RemoteAdapters: string implements AdapterTypeInterface
{
case Shoutcast1 = 'shoutcast1';
case Shoutcast2 = 'shoutcast2';
case Icecast = 'icecast';
case AzuraRelay = 'azurarelay';
public function getValue(): string
{
return $this->value;
}
public function getName(): string
{
return match ($this) {
self::Shoutcast1 => 'Shoutcast 1',
self::Shoutcast2 => 'Shoutcast 2',
self::Icecast => 'Icecast',
self::AzuraRelay => 'AzuraRelay',
};
}
/**
* @return class-string<AbstractRemote>
*/
public function getClass(): string
{
return match ($this) {
self::Shoutcast1 => Shoutcast1::class,
self::Shoutcast2 => Shoutcast2::class,
self::Icecast => Icecast::class,
self::AzuraRelay => AzuraRelay::class,
};
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/RemoteAdapters.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 315 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
interface AdapterTypeInterface
{
public function getValue(): string;
public function getName(): string;
/** @return class-string|null */
public function getClass(): ?string;
}
``` | /content/code_sandbox/backend/src/Radio/Enums/AdapterTypeInterface.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\Radio\Enums;
use App\Radio\Frontend\AbstractFrontend;
use App\Radio\Frontend\Icecast;
use App\Radio\Frontend\Shoutcast;
enum FrontendAdapters: string implements AdapterTypeInterface
{
case Icecast = 'icecast';
case Shoutcast = 'shoutcast2';
case Remote = 'remote';
public function getValue(): string
{
return $this->value;
}
public function getName(): string
{
return match ($this) {
self::Icecast => 'Icecast 2.4',
self::Shoutcast => 'Shoutcast DNAS 2',
self::Remote => 'Remote',
};
}
/**
* @return class-string<AbstractFrontend>|null
*/
public function getClass(): ?string
{
return match ($this) {
self::Icecast => Icecast::class,
self::Shoutcast => Shoutcast::class,
default => null
};
}
public function isEnabled(): bool
{
return self::Remote !== $this;
}
public function supportsMounts(): bool
{
return match ($this) {
self::Shoutcast, self::Icecast => true,
default => false
};
}
public function supportsReload(): bool
{
return self::Icecast === $this;
}
public static function default(): self
{
return self::Icecast;
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/FrontendAdapters.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 338 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
use App\Radio\Backend\Liquidsoap;
enum BackendAdapters: string implements AdapterTypeInterface
{
case Liquidsoap = 'liquidsoap';
case None = 'none';
public function getValue(): string
{
return $this->value;
}
public function getName(): string
{
return match ($this) {
self::Liquidsoap => 'Liquidsoap',
self::None => 'Disabled',
};
}
/**
* @return class-string<Liquidsoap>|null
*/
public function getClass(): ?string
{
return match ($this) {
self::Liquidsoap => Liquidsoap::class,
default => null,
};
}
public function isEnabled(): bool
{
return self::None !== $this;
}
public static function default(): self
{
return self::Liquidsoap;
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/BackendAdapters.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 203 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Enums;
enum CrossfadeModes: string
{
case Normal = 'normal';
case Smart = 'smart';
case Disabled = 'none';
public static function default(): self
{
return self::Normal;
}
}
``` | /content/code_sandbox/backend/src/Radio/Enums/CrossfadeModes.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 65 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Remote;
use NowPlaying\Enums\AdapterTypes;
final class Shoutcast2 extends AbstractRemote
{
protected function getAdapterType(): AdapterTypes
{
return AdapterTypes::Shoutcast2;
}
}
``` | /content/code_sandbox/backend/src/Radio/Remote/Shoutcast2.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 62 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Remote;
use App\Cache\AzuraRelayCache;
use App\Container\EnvironmentAwareTrait;
use App\Container\SettingsAwareTrait;
use App\Entity\Relay;
use App\Entity\StationRemote;
use App\Nginx\CustomUrls;
use GuzzleHttp\Client;
use GuzzleHttp\Promise\Create;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Uri;
use InvalidArgumentException;
use NowPlaying\AdapterFactory;
use NowPlaying\Enums\AdapterTypes;
use NowPlaying\Result\Result;
final class AzuraRelay extends AbstractRemote
{
use EnvironmentAwareTrait;
use SettingsAwareTrait;
public function __construct(
private readonly AzuraRelayCache $azuraRelayCache,
Client $httpClient,
AdapterFactory $adapterFactory,
) {
parent::__construct($httpClient, $adapterFactory);
}
public function getNowPlayingAsync(StationRemote $remote, bool $includeClients = false): PromiseInterface
{
$station = $remote->getStation();
$relay = $remote->getRelay();
if (!$relay instanceof Relay) {
throw new InvalidArgumentException('AzuraRelay remote must have a corresponding relay.');
}
$npRawRelay = $this->azuraRelayCache->getForRelay($relay);
if (isset($npRawRelay[$station->getId()][$remote->getMount()])) {
$npRaw = $npRawRelay[$station->getId()][$remote->getMount()];
$result = Result::fromArray($npRaw);
if (!empty($result->clients)) {
foreach ($result->clients as $client) {
$client->mount = 'remote_' . $remote->getId();
}
}
$this->logger->debug(
'Response for remote relay',
['remote' => $remote->getDisplayName(), 'response' => $result]
);
$remote->setListenersTotal($result->listeners->total);
$remote->setListenersUnique($result->listeners->unique ?? 0);
$this->em->persist($remote);
return Create::promiseFor($result);
}
return Create::promiseFor(null);
}
protected function getAdapterType(): AdapterTypes
{
// Not used for this adapter.
return AdapterTypes::Icecast;
}
/**
* @inheritDoc
*/
public function getPublicUrl(StationRemote $remote): string
{
$station = $remote->getStation();
$relay = $remote->getRelay();
if (!$relay instanceof Relay) {
throw new InvalidArgumentException('AzuraRelay remote must have a corresponding relay.');
}
$baseUrl = new Uri(rtrim($relay->getBaseUrl(), '/'));
$useRadioProxy = $this->readSettings()->getUseRadioProxy();
if ($useRadioProxy || 'https' === $baseUrl->getScheme()) {
// Web proxy support.
return (string)$baseUrl
->withPath($baseUrl->getPath() . CustomUrls::getListenUrl($station) . $remote->getmount());
}
// Remove port number and other decorations.
return (string)$baseUrl
->withPort($station->getFrontendConfig()->getPort())
->withPath($remote->getMount() ?? '');
}
}
``` | /content/code_sandbox/backend/src/Radio/Remote/AzuraRelay.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 724 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Remote;
use NowPlaying\Enums\AdapterTypes;
final class Icecast extends AbstractRemote
{
protected function getAdapterType(): AdapterTypes
{
return AdapterTypes::Icecast;
}
}
``` | /content/code_sandbox/backend/src/Radio/Remote/Icecast.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\Radio\Remote;
use App\Entity\StationRemote;
use NowPlaying\Enums\AdapterTypes;
final class Shoutcast1 extends AbstractRemote
{
protected function getAdapterType(): AdapterTypes
{
return AdapterTypes::Shoutcast1;
}
/** @inheritDoc */
public function getPublicUrl(StationRemote $remote): string
{
return $this->getRemoteUrl($remote, '/;stream.nsv');
}
}
``` | /content/code_sandbox/backend/src/Radio/Remote/Shoutcast1.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 109 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Remote;
use App\Container\EntityManagerAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Entity\StationRemote;
use GuzzleHttp\Client;
use GuzzleHttp\Promise\PromiseInterface;
use NowPlaying\AdapterFactory;
use NowPlaying\Enums\AdapterTypes;
use NowPlaying\Result\Result;
abstract class AbstractRemote
{
use LoggerAwareTrait;
use EntityManagerAwareTrait;
public function __construct(
protected Client $httpClient,
protected AdapterFactory $adapterFactory
) {
}
public function getNowPlayingAsync(
StationRemote $remote,
bool $includeClients = false
): PromiseInterface {
$adapterType = $this->getAdapterType();
$npAdapter = $this->adapterFactory->getAdapter(
$adapterType,
$remote->getUrl()
);
$npAdapter->setAdminPassword($remote->getAdminPassword());
return $npAdapter->getNowPlayingAsync($remote->getMount(), $includeClients)->then(
function (Result $result) use ($remote) {
if (!empty($result->clients)) {
foreach ($result->clients as $client) {
$client->mount = 'remote_' . $remote->getId();
}
}
$this->logger->debug('NowPlaying adapter response', ['response' => $result]);
$remote->setListenersTotal($result->listeners->total);
$remote->setListenersUnique($result->listeners->unique ?? 0);
$this->em->persist($remote);
return $result;
}
);
}
abstract protected function getAdapterType(): AdapterTypes;
/**
* Return the likely "public" listen URL for the remote.
*
* @param StationRemote $remote
*/
public function getPublicUrl(StationRemote $remote): string
{
$customListenUrl = $remote->getCustomListenUrl();
return (!empty($customListenUrl))
? $customListenUrl
: $this->getRemoteUrl($remote, $remote->getMount());
}
/**
* Format and return a URL for the remote path.
*
* @param StationRemote $remote
* @param string|null $customPath
*/
protected function getRemoteUrl(StationRemote $remote, ?string $customPath = null): string
{
$uri = $remote->getUrlAsUri();
if (!empty($customPath)) {
return (string)$uri->withPath(
rtrim($uri->getPath(), '/')
. '/'
. ltrim($customPath, '/')
);
}
return (string)$uri;
}
}
``` | /content/code_sandbox/backend/src/Radio/Remote/AbstractRemote.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 577 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Frontend;
use App\Entity\Station;
use App\Entity\StationMount;
use App\Environment;
use App\Service\Acme;
use App\Utilities\File;
use GuzzleHttp\Promise\Utils;
use InvalidArgumentException;
use NowPlaying\Result\Result;
use Psr\Http\Message\UriInterface;
use Symfony\Component\Process\Process;
final class Shoutcast extends AbstractFrontend
{
/**
* @inheritDoc
*/
public function getBinary(): ?string
{
try {
$binaryPath = self::getDirectory() . '/sc_serv';
return file_exists($binaryPath)
? $binaryPath
: null;
} catch (InvalidArgumentException) {
return null;
}
}
public static function getDirectory(): string
{
$parentDir = Environment::getInstance()->getParentDirectory();
return File::getFirstExistingDirectory([
$parentDir . '/servers/shoutcast2',
$parentDir . '/storage/shoutcast2',
]);
}
public function getVersion(): ?string
{
$binary = $this->getBinary();
if (!$binary) {
return null;
}
$process = new Process([$binary, '--version']);
$process->setWorkingDirectory(dirname($binary));
$process->run();
if (!$process->isSuccessful()) {
return null;
}
return preg_match('/^Shoutcast .* v(\S+) .*$/i', $process->getOutput(), $matches)
? $matches[1]
: null;
}
public function getNowPlaying(Station $station, bool $includeClients = true): Result
{
$feConfig = $station->getFrontendConfig();
$radioPort = $feConfig->getPort();
$baseUrl = $this->environment->getLocalUri()
->withPort($radioPort);
$npAdapter = $this->adapterFactory->getShoutcast2Adapter($baseUrl);
$npAdapter->setAdminPassword($feConfig->getAdminPassword());
$mountPromises = [];
$defaultMountId = null;
$sid = 0;
foreach ($station->getMounts() as $mount) {
$sid++;
if ($mount->getIsDefault()) {
$defaultMountId = $sid;
}
$mountPromises[$sid] = $npAdapter->getNowPlayingAsync(
(string)$sid,
$includeClients
)->then(
function (Result $result) use ($mount) {
if (!empty($result->clients)) {
foreach ($result->clients as $client) {
$client->mount = 'local_' . $mount->getId();
}
}
$mount->setListenersTotal($result->listeners->total);
$mount->setListenersUnique($result->listeners->unique ?? 0);
$this->em->persist($mount);
return $result;
}
);
}
$mountPromiseResults = Utils::settle($mountPromises)->wait();
$this->em->flush();
$defaultResult = Result::blank();
$otherResults = [];
foreach ($mountPromiseResults as $mountId => $result) {
if ($mountId === $defaultMountId) {
$defaultResult = $result['value'] ?? Result::blank();
} else {
$otherResults[] = $result['value'] ?? Result::blank();
}
}
foreach ($otherResults as $otherResult) {
$defaultResult = $defaultResult->merge($otherResult);
}
return $defaultResult;
}
public function getConfigurationPath(Station $station): ?string
{
return $station->getRadioConfigDir() . '/sc_serv.conf';
}
public function getCurrentConfiguration(Station $station): ?string
{
$configPath = $station->getRadioConfigDir();
$frontendConfig = $station->getFrontendConfig();
[$certPath, $certKey] = Acme::getCertificatePaths();
$urlHost = $this->getPublicUrl($station)->getHost();
$config = [
'password' => $frontendConfig->getSourcePassword(),
'adminpassword' => $frontendConfig->getAdminPassword(),
'logfile' => $configPath . '/sc_serv.log',
'w3clog' => $configPath . '/sc_w3c.log',
'banfile' => $this->writeIpBansFile($station),
'agentfile' => $this->writeUserAgentBansFile($station, 'sc_serv.agent'),
'ripfile' => $configPath . '/sc_serv.rip',
'maxuser' => $frontendConfig->getMaxListeners() ?? 250,
'portbase' => $frontendConfig->getPort(),
'requirestreamconfigs' => 1,
'savebanlistonexit' => '0',
'saveagentlistonexit' => '0',
'userid' => $frontendConfig->getScUserId(),
'sslCertificateFile' => $certPath,
'sslCertificateKeyFile' => $certKey,
'destdns' => $urlHost,
'destip' => $urlHost,
'publicdns' => $urlHost,
'publicip' => $urlHost,
];
$customConfig = trim($frontendConfig->getCustomConfiguration() ?? '');
if (!empty($customConfig)) {
$customConf = $this->processCustomConfig($customConfig);
if (false !== $customConf) {
$config = array_merge($config, $customConf);
}
}
$i = 0;
/** @var StationMount $mountRow */
foreach ($station->getMounts() as $mountRow) {
$i++;
$config['streamid_' . $i] = $i;
$config['streampath_' . $i] = $mountRow->getName();
if (!empty($mountRow->getIntroPath())) {
$introPath = $mountRow->getIntroPath();
$config['streamintrofile_' . $i] = $station->getRadioConfigDir() . '/' . $introPath;
}
if ($mountRow->getRelayUrl()) {
$config['streamrelayurl_' . $i] = $mountRow->getRelayUrl();
}
if ($mountRow->getAuthhash()) {
$config['streamauthhash_' . $i] = $mountRow->getAuthhash();
}
if ($mountRow->getMaxListenerDuration()) {
$config['streamlistenertime_' . $i] = $mountRow->getMaxListenerDuration();
}
}
$configFileOutput = '';
foreach ($config as $configKey => $configValue) {
$configFileOutput .= $configKey . '=' . str_replace("\n", '', (string)$configValue) . "\n";
}
return $configFileOutput;
}
public function getCommand(Station $station): ?string
{
if ($binary = $this->getBinary()) {
return $binary . ' ' . $this->getConfigurationPath($station);
}
return null;
}
public function getAdminUrl(Station $station, UriInterface $baseUrl = null): UriInterface
{
$publicUrl = $this->getPublicUrl($station, $baseUrl);
return $publicUrl
->withPath($publicUrl->getPath() . '/admin.cgi');
}
protected function writeIpBansFile(
Station $station,
string $fileName = 'sc_serv.ban',
string $ipsSeparator = ";255;\n"
): string {
$ips = $this->getBannedIps($station);
$configDir = $station->getRadioConfigDir();
$bansFile = $configDir . '/' . $fileName;
$bannedIpsString = implode($ipsSeparator, $ips);
if (!empty($bannedIpsString)) {
$bannedIpsString .= $ipsSeparator;
}
file_put_contents($bansFile, $bannedIpsString);
return $bansFile;
}
}
``` | /content/code_sandbox/backend/src/Radio/Frontend/Shoutcast.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,785 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Backend\Liquidsoap;
use App\Container\EnvironmentAwareTrait;
use App\Container\SettingsAwareTrait;
use App\Entity\Enums\PlaylistOrders;
use App\Entity\Enums\PlaylistRemoteTypes;
use App\Entity\Enums\PlaylistSources;
use App\Entity\Enums\PlaylistTypes;
use App\Entity\Enums\StationBackendPerformanceModes;
use App\Entity\Interfaces\StationMountInterface;
use App\Entity\StationBackendConfiguration;
use App\Entity\StationMount;
use App\Entity\StationPlaylist;
use App\Entity\StationRemote;
use App\Entity\StationSchedule;
use App\Entity\StationStreamerBroadcast;
use App\Event\Radio\WriteLiquidsoapConfiguration;
use App\Radio\Backend\Liquidsoap;
use App\Radio\Enums\AudioProcessingMethods;
use App\Radio\Enums\CrossfadeModes;
use App\Radio\Enums\FrontendAdapters;
use App\Radio\Enums\LiquidsoapQueues;
use App\Radio\Enums\StreamFormats;
use App\Radio\Enums\StreamProtocols;
use App\Radio\FallbackFile;
use App\Radio\StereoTool;
use App\Utilities\Types;
use Carbon\CarbonImmutable;
use RuntimeException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class ConfigWriter implements EventSubscriberInterface
{
use EnvironmentAwareTrait;
use SettingsAwareTrait;
public function __construct(
private readonly Liquidsoap $liquidsoap,
private readonly FallbackFile $fallbackFile
) {
}
/**
* @return mixed[]
*/
public static function getSubscribedEvents(): array
{
return [
WriteLiquidsoapConfiguration::class => [
['writeHeaderFunctions', 35],
['writePlaylistConfiguration', 30],
['writeCrossfadeConfiguration', 25],
['writeHarborConfiguration', 20],
['writePreBroadcastConfiguration', 10],
['writeLocalBroadcastConfiguration', 5],
['writeHlsBroadcastConfiguration', 2],
['writeRemoteBroadcastConfiguration', 0],
['writePostBroadcastConfiguration', -5],
],
];
}
public function writeCustomConfigurationSection(WriteLiquidsoapConfiguration $event, string $sectionName): void
{
if ($event->isForEditing()) {
$divider = self::getDividerString();
$event->appendLines(
[
$divider . $sectionName . $divider,
]
);
return;
}
$settings = $this->readSettings();
if (!$settings->getEnableAdvancedFeatures()) {
return;
}
$settings = $event->getStation()->getBackendConfig();
$customConfig = $settings->getCustomConfigurationSection($sectionName);
if (!empty($customConfig)) {
$event->appendLines(
[
'# Custom Configuration (Specified in Station Profile)',
$customConfig,
]
);
}
}
public function writePostProcessingSection(WriteLiquidsoapConfiguration $event): void
{
$station = $event->getStation();
$settings = $event->getBackendConfig();
switch ($settings->getAudioProcessingMethodEnum()) {
case AudioProcessingMethods::Liquidsoap:
// NRJ normalization
$event->appendBlock(
<<<LIQ
# Normalization and Compression
radio = normalize(target = 0., window = 0.03, gain_min = -16., gain_max = 0., radio)
radio = compress.exponential(radio, mu = 1.0)
LIQ
);
break;
case AudioProcessingMethods::MasterMe:
// MasterMe Presets
$lines = [
'radio = ladspa.master_me(',
];
$preset = $settings->getMasterMePresetEnum();
$presetOptions = $preset->getOptions();
if (0 !== ($loudnessTarget = $settings->getMasterMeLoudnessTarget())) {
$presetOptions['target'] = $loudnessTarget;
}
foreach ($presetOptions as $presetKey => $presetVal) {
$presetVal = match (true) {
is_int($presetVal) => self::toFloat($presetVal, 0),
is_float($presetVal) => self::toFloat($presetVal),
is_bool($presetVal) => ($presetVal) ? 'true' : 'false',
default => $presetVal
};
$lines[] = ' ' . $presetKey . ' = ' . $presetVal . ',';
}
$lines[] = ' radio';
$lines[] = ')';
$event->appendLines($lines);
break;
case AudioProcessingMethods::StereoTool:
// Stereo Tool processing
if (!StereoTool::isReady($station)) {
return;
}
$stereoToolLibraryPath = StereoTool::getLibraryPath();
$stereoToolBinary = $stereoToolLibraryPath . '/stereo_tool';
$stereoToolConfiguration = $station->getRadioConfigDir()
. DIRECTORY_SEPARATOR . $settings->getStereoToolConfigurationPath();
if (is_file($stereoToolBinary)) {
$stereoToolProcess = $stereoToolBinary . ' --silent - - -s ' . $stereoToolConfiguration;
}
$event->appendBlock(
<<<LIQ
# Stereo Tool Pipe
radio = pipe(replay_delay=1.0, process='{$stereoToolProcess}', radio)
LIQ
);
} else {
$serverArch = php_uname('m');
$stereoToolLibrary = match ($serverArch) {
'x86' => $stereoToolLibraryPath . '/libStereoTool_intel32.so',
'aarch64', 'arm64' => $stereoToolLibraryPath . '/libStereoTool_arm64.so',
default => $stereoToolLibraryPath . '/libStereoTool_intel64.so',
};
if (!file_exists($stereoToolLibrary)) {
// Stereo Tool 10.0 uploaded using a different format.
$is64Bit = in_array($serverArch, ['x86_64', 'arm64'], true);
if ($is64Bit && file_exists($stereoToolLibraryPath . '/libStereoTool_64.so')) {
$stereoToolLibrary = $stereoToolLibraryPath . '/libStereoTool_64.so';
} elseif (file_exists(($stereoToolLibraryPath . '/libStereoTool.so'))) {
$stereoToolLibrary = $stereoToolLibraryPath . '/libStereoTool.so';
} else {
break;
}
}
$event->appendBlock(
<<<LIQ
# Stereo Tool Pipe
radio = stereotool(
library_file="{$stereoToolLibrary}",
preset="{$stereoToolConfiguration}",
radio
)
LIQ
);
}
break;
case AudioProcessingMethods::None:
// Noop
break;
}
}
public static function getDividerString(): string
{
return chr(7);
}
public function writeHeaderFunctions(WriteLiquidsoapConfiguration $event): void
{
if (!$event->isForEditing()) {
$event->prependLines(
[
'# WARNING! This file is automatically generated by AzuraCast.',
'# Do not update it directly!',
]
);
}
$this->writeCustomConfigurationSection($event, StationBackendConfiguration::CUSTOM_TOP);
$station = $event->getStation();
$configDir = $station->getRadioConfigDir();
$pidfile = $configDir . DIRECTORY_SEPARATOR . 'liquidsoap.pid';
$socketFile = $configDir . DIRECTORY_SEPARATOR . 'liquidsoap.sock';
$stationTz = self::cleanUpString($station->getTimezone());
$event->appendBlock(
<<<LIQ
init.daemon.set(false)
init.daemon.pidfile.path.set("{$pidfile}")
log.stdout.set(true)
log.file.set(false)
settings.server.log.level.set(4)
settings.server.socket.set(true)
settings.server.socket.permissions.set(0o660)
settings.server.socket.path.set("{$socketFile}")
settings.harbor.bind_addrs.set(["0.0.0.0"])
settings.encoder.metadata.export.set(["artist","title","album","song"])
environment.set("TZ", "{$stationTz}")
autodj_is_loading = ref(true)
ignore(autodj_is_loading)
autodj_ping_attempts = ref(0)
ignore(autodj_ping_attempts)
# Track live-enabled status.
live_enabled = ref(false)
ignore(live_enabled)
# Track live transition for crossfades.
to_live = ref(false)
ignore(to_live)
# Reimplement LS's now-deprecated drop_metadata function.
def drop_metadata(~id=null(), s)
let {metadata=_, ...tracks} = source.tracks(s)
source(id=id, tracks)
end
# Transport for HTTPS outputs.
https_transport = http.transport.ssl()
ignore(https_transport)
LIQ
);
$stationApiAuth = self::cleanUpString($station->getAdapterApiKey());
$stationApiUrl = self::cleanUpString(
(string)$this->environment->getInternalUri()
->withPath('/api/internal/' . $station->getId() . '/liquidsoap')
);
$event->appendBlock(
<<<LIQ
azuracast_api_url = "{$stationApiUrl}"
azuracast_api_key = "{$stationApiAuth}"
def azuracast_api_call(~timeout=2.0, url, payload) =
full_url = "#{azuracast_api_url}/#{url}"
log("API #{url} - Sending POST request to '#{full_url}' with body: #{payload}")
try
response = http.post(full_url,
headers=[
("Content-Type", "application/json"),
("User-Agent", "Liquidsoap AzuraCast"),
("X-Liquidsoap-Api-Key", "#{azuracast_api_key}")
],
timeout=timeout,
data=payload
)
log("API #{url} - Response (#{response.status_code}): #{response}")
"#{response}"
catch err do
log("API #{url} - Error: #{error.kind(err)} - #{error.message(err)}")
"false"
end
end
LIQ
);
$mediaStorageLocation = $station->getMediaStorageLocation();
if ($mediaStorageLocation->isLocal()) {
$stationMediaDir = $mediaStorageLocation->getFilteredPath();
$event->appendBlock(
<<<LIQ
station_media_dir = "{$stationMediaDir}"
def azuracast_media_protocol(~rlog=_,~maxtime=_,arg) =
["#{station_media_dir}/#{arg}"]
end
protocol.add(
"media",
azuracast_media_protocol,
doc="Pull files from AzuraCast media directory.",
syntax="media:uri"
)
LIQ
);
} else {
$event->appendBlock(
<<<LIQ
def azuracast_media_protocol(~rlog=_,~maxtime,arg) =
timeout = 1000.0 * (maxtime - time())
j = json()
j.add("uri", arg)
[azuracast_api_call(timeout=timeout, "cp", json.stringify(j))]
end
protocol.add(
"media",
azuracast_media_protocol,
temporary=true,
doc="Pull files from AzuraCast media directory.",
syntax="media:uri"
)
LIQ
);
}
$backendConfig = $event->getBackendConfig();
$perfMode = $backendConfig->getPerformanceModeEnum();
if ($perfMode !== StationBackendPerformanceModes::Disabled) {
$gcSpaceOverhead = match ($backendConfig->getPerformanceModeEnum()) {
StationBackendPerformanceModes::LessMemory => 20,
StationBackendPerformanceModes::LessCpu => 140,
StationBackendPerformanceModes::Balanced => 80,
StationBackendPerformanceModes::Disabled => 0,
};
$event->appendBlock(
<<<LIQ
# Optimize Performance
runtime.gc.set(runtime.gc.get().{
space_overhead = {$gcSpaceOverhead},
allocation_policy = 2
})
LIQ
);
}
// Add AutoCue common configuration.
if ($backendConfig->getEnableAutoCue()) {
$autoCueCommon = $this->environment->getParentDirectory() . '/autocue/autocue.liq';
$event->appendBlock(
<<<LIQ
# AutoCue
%include "{$autoCueCommon}"
settings.autocue.cue_file.nice := true
settings.request.prefetch := 2
LIQ
);
}
}
public function writePlaylistConfiguration(WriteLiquidsoapConfiguration $event): void
{
$station = $event->getStation();
$this->writeCustomConfigurationSection($event, StationBackendConfiguration::CUSTOM_PRE_PLAYLISTS);
// Override some AutoCue settings if they're set in the section above.
$enableAutoCue = $event->getBackendConfig()->getEnableAutoCue();
if ($enableAutoCue) {
$event->appendBlock(
<<<LIQ
# Ensure AutoCue settings are valid
ignore(check_autocue_setup(shutdown=true, print=false))
LIQ
);
}
// Set up playlists using older format as a fallback.
$playlistVarNames = [];
$genPlaylistWeights = [];
$genPlaylistVars = [];
$specialPlaylists = [
'once_per_x_songs' => [
'# Once per x Songs Playlists',
],
'once_per_x_minutes' => [
'# Once per x Minutes Playlists',
],
];
$scheduleSwitches = [];
$scheduleSwitchesInterrupting = [];
$scheduleSwitchesRemoteUrl = [];
$fallbackRemoteUrl = null;
foreach ($station->getPlaylists() as $playlist) {
if (!$playlist->getIsEnabled()) {
continue;
}
if (!self::shouldWritePlaylist($event, $playlist)) {
continue;
}
$playlistVarName = self::getPlaylistVariableName($playlist);
if (in_array($playlistVarName, $playlistVarNames, true)) {
$playlistVarName .= '_' . $playlist->getId();
}
$scheduleItems = $playlist->getScheduleItems();
$playlistVarNames[] = $playlistVarName;
$playlistConfigLines = [];
if (PlaylistSources::Songs === $playlist->getSource()) {
$playlistFilePath = PlaylistFileWriter::getPlaylistFilePath($playlist);
$playlistParams = [
'id="' . self::cleanUpString($playlistVarName) . '"',
'mime_type="audio/x-mpegurl"',
];
$playlistMode = match ($playlist->getOrder()) {
PlaylistOrders::Sequential => 'normal',
PlaylistOrders::Shuffle => 'randomize',
PlaylistOrders::Random => 'random'
};
$playlistParams[] = 'mode="' . $playlistMode . '"';
$playlistParams[] = 'reload_mode="watch"';
$playlistParams[] = '"' . $playlistFilePath . '"';
$playlistConfigLines[] = $playlistVarName . ' = playlist('
. implode(',', $playlistParams) . ')';
if ($playlist->backendMerge()) {
$playlistConfigLines[] = $playlistVarName . ' = merge_tracks(id="merge_'
. self::cleanUpString($playlistVarName) . '", ' . $playlistVarName . ')';
}
} elseif (PlaylistRemoteTypes::Playlist === $playlist->getRemoteType()) {
$playlistFunc = 'playlist("'
. self::cleanUpString($playlist->getRemoteUrl())
. '")';
$playlistConfigLines[] = $playlistVarName . ' = ' . $playlistFunc;
} else {
// Special handling for Remote Stream URLs.
$remoteUrl = $playlist->getRemoteUrl();
if (null === $remoteUrl) {
continue;
}
$buffer = $playlist->getRemoteBuffer();
$buffer = ($buffer < 1) ? StationPlaylist::DEFAULT_REMOTE_BUFFER : $buffer;
$inputFunc = match ($playlist->getRemoteType()) {
PlaylistRemoteTypes::Stream => 'input.http',
default => 'input.external.ffmpeg'
};
$remoteUrlFunc = 'mksafe(buffer(buffer=' . $buffer . '., '
. $inputFunc . '("' . self::cleanUpString($remoteUrl) . '")))';
if (0 === $scheduleItems->count()) {
$fallbackRemoteUrl = $remoteUrlFunc;
continue;
}
$playlistConfigLines[] = $playlistVarName . ' = ' . $remoteUrlFunc;
$event->appendLines($playlistConfigLines);
foreach ($scheduleItems as $scheduleItem) {
$playTime = $this->getScheduledPlaylistPlayTime($event, $scheduleItem);
$scheduleTiming = '({ ' . $playTime . ' }, ' . $playlistVarName . ')';
$scheduleSwitchesRemoteUrl[] = $scheduleTiming;
}
continue;
}
if ($playlist->getIsJingle()) {
$playlistConfigLines[] = $playlistVarName . ' = drop_metadata(' . $playlistVarName . ')';
}
if (PlaylistTypes::Advanced === $playlist->getType()) {
$playlistConfigLines[] = 'ignore(' . $playlistVarName . ')';
}
$event->appendLines($playlistConfigLines);
switch ($playlist->getType()) {
case PlaylistTypes::Standard:
if ($scheduleItems->count() > 0) {
foreach ($scheduleItems as $scheduleItem) {
$playTime = $this->getScheduledPlaylistPlayTime($event, $scheduleItem);
$scheduleTiming = $playlist->backendPlaySingleTrack()
? '(predicate.at_most(1, {' . $playTime . '}), ' . $playlistVarName . ')'
: '({ ' . $playTime . ' }, ' . $playlistVarName . ')';
if ($playlist->backendInterruptOtherSongs()) {
$scheduleSwitchesInterrupting[] = $scheduleTiming;
} else {
$scheduleSwitches[] = $scheduleTiming;
}
}
} else {
$genPlaylistWeights[] = $playlist->getWeight();
$genPlaylistVars[] = $playlistVarName;
}
break;
case PlaylistTypes::OncePerXSongs:
case PlaylistTypes::OncePerXMinutes:
if (PlaylistTypes::OncePerXSongs === $playlist->getType()) {
$playlistScheduleVar = 'rotate(weights=[1,'
. $playlist->getPlayPerSongs() . '], [' . $playlistVarName . ', radio])';
} else {
$delaySeconds = $playlist->getPlayPerMinutes() * 60;
$delayTrackSensitive = $playlist->backendInterruptOtherSongs() ? 'false' : 'true';
$playlistScheduleVar = 'fallback(track_sensitive=' . $delayTrackSensitive . ', [delay(' . $delaySeconds . '., ' . $playlistVarName . '), radio])';
}
if ($scheduleItems->count() > 0) {
foreach ($scheduleItems as $scheduleItem) {
$playTime = $this->getScheduledPlaylistPlayTime($event, $scheduleItem);
$scheduleTiming = $playlist->backendPlaySingleTrack()
? '(predicate.at_most(1, {' . $playTime . '}), ' . $playlistScheduleVar . ')'
: '({ ' . $playTime . ' }, ' . $playlistScheduleVar . ')';
if ($playlist->backendInterruptOtherSongs()) {
$scheduleSwitchesInterrupting[] = $scheduleTiming;
} else {
$scheduleSwitches[] = $scheduleTiming;
}
}
} else {
$specialPlaylists[$playlist->getType()->value][] = 'radio = ' . $playlistScheduleVar;
}
break;
case PlaylistTypes::OncePerHour:
$minutePlayTime = $playlist->getPlayPerHourMinute() . 'm';
if ($scheduleItems->count() > 0) {
foreach ($scheduleItems as $scheduleItem) {
$playTime = '(' . $minutePlayTime . ') and ('
. $this->getScheduledPlaylistPlayTime($event, $scheduleItem) . ')';
$scheduleTiming = $playlist->backendPlaySingleTrack()
? '(predicate.at_most(1, {' . $playTime . '}), ' . $playlistVarName . ')'
: '({ ' . $playTime . ' }, ' . $playlistVarName . ')';
if ($playlist->backendInterruptOtherSongs()) {
$scheduleSwitchesInterrupting[] = $scheduleTiming;
} else {
$scheduleSwitches[] = $scheduleTiming;
}
}
} else {
$scheduleTiming = $playlist->backendPlaySingleTrack()
? '(predicate.at_most(1, {' . $minutePlayTime . '}), ' . $playlistVarName . ')'
: '({ ' . $minutePlayTime . ' }, ' . $playlistVarName . ')';
if ($playlist->backendInterruptOtherSongs()) {
$scheduleSwitchesInterrupting[] = $scheduleTiming;
} else {
$scheduleSwitches[] = $scheduleTiming;
}
}
break;
case PlaylistTypes::Advanced:
// NOOP
}
}
// Build "default" type playlists.
$event->appendLines(
[
'# Standard Playlists',
sprintf(
'radio = random(id="standard_playlists", weights=[%s], [%s])',
implode(', ', $genPlaylistWeights),
implode(', ', $genPlaylistVars)
),
]
);
if (!empty($scheduleSwitches)) {
$event->appendLines(['# Standard Schedule Switches']);
// Chunk scheduled switches to avoid hitting the max amount of playlists in a switch()
foreach (array_chunk($scheduleSwitches, 168, true) as $scheduleSwitchesChunk) {
$scheduleSwitchesChunk[] = '({true}, radio)';
$event->appendLines(
[
sprintf(
'radio = switch(id="schedule_switch", track_sensitive=true, [ %s ])',
implode(', ', $scheduleSwitchesChunk)
),
]
);
}
}
// Add in special playlists if necessary.
foreach ($specialPlaylists as $playlistConfigLines) {
if (count($playlistConfigLines) > 1) {
$event->appendLines($playlistConfigLines);
}
}
if (!empty($scheduleSwitchesInterrupting)) {
$event->appendLines(['# Interrupting Schedule Switches']);
foreach (array_chunk($scheduleSwitchesInterrupting, 168, true) as $scheduleSwitchesChunk) {
$scheduleSwitchesChunk[] = '({true}, radio)';
$event->appendLines(
[
sprintf(
'radio = switch(id="schedule_switch", track_sensitive=false, [ %s ])',
implode(', ', $scheduleSwitchesChunk)
),
]
);
}
}
if (!$station->useManualAutoDJ()) {
$nextSongTimeout = $enableAutoCue ? 'settings.autocue.cue_file.timeout()' : '20.0';
$event->appendBlock(
<<< LIQ
# AutoDJ Next Song Script
def autodj_next_song() =
response = azuracast_api_call(
"nextsong",
""
)
if (response == "") or (response == "false") then
null()
else
request.create(response)
end
end
# Delayed ping for AutoDJ Next Song
def wait_for_next_song(autodj)
autodj_ping_attempts.set(autodj_ping_attempts() + 1)
if source.is_ready(autodj) then
log("AutoDJ is ready!")
autodj_is_loading.set(false)
-1.0
elsif autodj_ping_attempts() > 200 then
log("AutoDJ could not be initialized within the specified timeout.")
autodj_is_loading.set(false)
-1.0
else
0.5
end
end
dynamic = request.dynamic(id="next_song", timeout={$nextSongTimeout}, retry_delay=10., autodj_next_song)
dynamic_startup = fallback(
id = "dynamic_startup",
track_sensitive = false,
[
dynamic,
source.available(
blank(id = "autodj_startup_blank", duration = 120.),
predicate.activates({autodj_is_loading()})
)
]
)
radio = fallback(id="autodj_fallback", track_sensitive = true, [dynamic_startup, radio])
ref_dynamic = ref(dynamic);
thread.run.recurrent(delay=0.25, { wait_for_next_song(ref_dynamic()) })
LIQ
);
}
// Handle remote URL fallbacks.
if (null !== $fallbackRemoteUrl) {
$event->appendBlock(
<<< LIQ
remote_url = {$fallbackRemoteUrl}
radio = fallback(id="fallback_remote_url", track_sensitive = false, [remote_url, radio])
LIQ
);
}
$requestsQueueName = LiquidsoapQueues::Requests->value;
$interruptingQueueName = LiquidsoapQueues::Interrupting->value;
$requestQueueTimeout = $enableAutoCue ? 'settings.autocue.cue_file.timeout()' : '20.0';
$event->appendBlock(
<<< LIQ
requests = request.queue(id="{$requestsQueueName}", timeout={$requestQueueTimeout})
radio = fallback(id="requests_fallback", track_sensitive = true, [requests, radio])
interrupting_queue = request.queue(id="{$interruptingQueueName}", timeout={$requestQueueTimeout})
radio = fallback(id="interrupting_fallback", track_sensitive = false, [interrupting_queue, radio])
LIQ
);
if (!empty($scheduleSwitchesRemoteUrl)) {
$event->appendLines(['# Remote URL Schedule Switches']);
foreach (array_chunk($scheduleSwitchesRemoteUrl, 168, true) as $scheduleSwitchesChunk) {
$scheduleSwitchesChunk[] = '({true}, radio)';
$event->appendLines(
[
sprintf(
'radio = switch(id="schedule_switch", track_sensitive=false, [ %s ])',
implode(', ', $scheduleSwitchesChunk)
),
]
);
}
}
$event->appendBlock(
<<<LIQ
# Skip command (used by web UI)
def add_skip_command(s) =
def skip(_) =
source.skip(s)
"Done!"
end
server.register(namespace="radio", usage="skip", description="Skip the current song.", "skip",skip)
end
add_skip_command(radio)
LIQ
);
}
/**
* Given a scheduled playlist, return the time criteria that Liquidsoap can use to determine when to play it.
*
* @param WriteLiquidsoapConfiguration $event
* @param StationSchedule $playlistSchedule
* @return string
*/
private function getScheduledPlaylistPlayTime(
WriteLiquidsoapConfiguration $event,
StationSchedule $playlistSchedule
): string {
$startTime = $playlistSchedule->getStartTime();
$endTime = $playlistSchedule->getEndTime();
// Handle multi-day playlists.
if ($startTime > $endTime) {
$playTimes = [
self::formatTimeCode($startTime) . '-23h59m59s',
'00h00m-' . self::formatTimeCode($endTime),
];
$playlistScheduleDays = $playlistSchedule->getDays();
if (!empty($playlistScheduleDays) && count($playlistScheduleDays) < 7) {
$currentPlayDays = [];
$nextPlayDays = [];
foreach ($playlistScheduleDays as $day) {
$currentPlayDays[] = (($day === 7) ? '0' : $day) . 'w';
$day++;
if ($day > 7) {
$day = 1;
}
$nextPlayDays[] = (($day === 7) ? '0' : $day) . 'w';
}
$playTimes[0] = '(' . implode(' or ', $currentPlayDays) . ') and ' . $playTimes[0];
$playTimes[1] = '(' . implode(' or ', $nextPlayDays) . ') and ' . $playTimes[1];
}
return '(' . implode(') or (', $playTimes) . ')';
}
// Handle once-per-day playlists.
$playTime = ($startTime === $endTime)
? self::formatTimeCode($startTime)
: self::formatTimeCode($startTime) . '-' . self::formatTimeCode($endTime);
$playlistScheduleDays = $playlistSchedule->getDays();
if (!empty($playlistScheduleDays) && count($playlistScheduleDays) < 7) {
$playDays = [];
foreach ($playlistScheduleDays as $day) {
$playDays[] = (($day === 7) ? '0' : $day) . 'w';
}
$playTime = '(' . implode(' or ', $playDays) . ') and ' . $playTime;
}
// Handle start-date and end-date boundaries.
$startDate = $playlistSchedule->getStartDate();
$endDate = $playlistSchedule->getEndDate();
if (!empty($startDate) || !empty($endDate)) {
$tzObject = $event->getStation()->getTimezoneObject();
$customFunctionBody = [];
$scheduleMethod = 'schedule_' . $playlistSchedule->getIdRequired() . '_date_range';
$customFunctionBody[] = 'def ' . $scheduleMethod . '() =';
$conditions = [];
if (!empty($startDate)) {
$startDateObj = CarbonImmutable::createFromFormat('Y-m-d', $startDate, $tzObject);
if (null !== $startDateObj) {
$startDateObj = $startDateObj->setTime(0, 0);
$customFunctionBody[] = ' # ' . $startDateObj->__toString();
$customFunctionBody[] = ' range_start = ' . $startDateObj->getTimestamp() . '.';
$conditions[] = 'range_start <= current_time';
}
}
if (!empty($endDate)) {
$endDateObj = CarbonImmutable::createFromFormat('Y-m-d', $endDate, $tzObject);
if (null !== $endDateObj) {
$endDateObj = $endDateObj->setTime(23, 59, 59);
$customFunctionBody[] = ' # ' . $endDateObj->__toString();
$customFunctionBody[] = ' range_end = ' . $endDateObj->getTimestamp() . '.';
$conditions[] = 'current_time <= range_end';
}
}
$customFunctionBody[] = ' current_time = time()';
$customFunctionBody[] = ' result = (' . implode(' and ', $conditions) . ')';
$customFunctionBody[] = ' result';
$customFunctionBody[] = 'end';
$event->appendLines($customFunctionBody);
$playTime = $scheduleMethod . '() and ' . $playTime;
}
return $playTime;
}
public function writeCrossfadeConfiguration(WriteLiquidsoapConfiguration $event): void
{
$settings = $event->getStation()->getBackendConfig();
// Write pre-crossfade section.
$this->writeCustomConfigurationSection($event, StationBackendConfiguration::CUSTOM_PRE_FADE);
// Need to move amplify & Replaygain after CUSTOM_PRE_FADE
// in case user has defined own fallbacks/switches
// Amplify
$event->appendBlock(
<<<LIQ
# Apply amplification metadata (if supplied)
radio = amplify(override="liq_amplify", 1., radio)
LIQ
);
// Replaygain metadata
$settings = $event->getBackendConfig();
if ($settings->useReplayGain()) {
$event->appendBlock(
<<<LIQ
# Replaygain Metadata
enable_replaygain_metadata()
radio = replaygain(radio)
LIQ
);
}
// Show metadata, used with and without Autocue
$showMetaFunc = <<<LS
# Show metadata in log (Debug)
def show_meta(m)
label="show_meta"
l = list.sort.natural(metadata.cover.remove(m))
list.iter(fun(v) -> log(level=4, label=label, "#{v}"), l)
nowplaying = ref(m["artist"] ^ " - " ^ m["title"])
if m["artist"] == "" then
if string.contains(substring=" - ", m["title"]) then
let (a, t) = string.split.first(separator=" - ", m["title"])
nowplaying := a ^ " - " ^ t
end
end
# show `liq_` & other metadata in level 3
def fl(k, _) =
tags = ["duration", "media_id", "replaygain_track_gain", "replaygain_reference_loudness"]
string.contains(prefix="liq_", k) or list.mem(k, tags)
end
liq = list.assoc.filter((fl), l)
list.iter(fun(v) -> log(level=3, label=label, "#{v}"), liq)
log(level=3, label=label, "Now playing: #{nowplaying()}")
if m["liq_amplify"] == "" then
log(level=2, label=label, "Warning: No liq_amplify found, expect loudness jumps!")
end
if m["liq_blank_skipped"] == "true" then
log(level=2, label=label, "Blank (silence) detected in track, ending early.")
end
end
radio.on_metadata(show_meta)
LS;
if ($settings->getEnableAutoCue()) {
// AutoCue preempts normal fading to use its own settings.
$event->appendBlock(
<<<LS
{$showMetaFunc}
# Fading/crossing/segueing
def live_aware_crossfade(old, new) =
if to_live() then
# If going to the live show, play a simple sequence
# fade out AutoDJ, do (almost) not fade in streamer
sequence([
fade.out(duration=settings.autocue.cue_file.fade_out(), old.source),
fade.in(duration=settings.autocue.cue_file.fade_in(), new.source)
])
else
# Otherwise, use a beautiful add
add(normalize=false, [
fade.in(
initial_metadata=new.metadata,
duration=settings.autocue.cue_file.fade_in(),
new.source
),
fade.out(
initial_metadata=old.metadata,
duration=settings.autocue.cue_file.fade_out(),
old.source
)
])
end
end
radio = cross(
duration=settings.autocue.cue_file.fade_out(),
live_aware_crossfade,
radio
)
LS
);
} elseif ($settings->isCrossfadeEnabled()) {
// Crossfading happens before the live broadcast is mixed in, because of buffer issues.
$crossfadeType = $settings->getCrossfadeTypeEnum();
$crossfade = self::toFloat($settings->getCrossfade());
$crossDuration = self::toFloat($settings->getCrossfadeDuration());
if (CrossfadeModes::Smart === $crossfadeType) {
$crossfadeFunc = 'cross.smart(old, new, margin=8., fade_in=' . $crossfade
. ', fade_out=' . $crossfade . ')';
} else {
$crossfadeFunc = 'cross.simple(old.source, new.source, fade_in=' . $crossfade
. ', fade_out=' . $crossfade . ')';
}
$event->appendBlock(
<<<LS
# reinstate liq_cross_duration if AutoCue is disabled
def set_cross_duration(m) =
fade_out = float_of_string(default=0., m["liq_fade_out"])
duration = float_of_string(default=0., m["duration"])
cue_out = float_of_string(default=duration, m["liq_cue_out"])
start_next = float_of_string(default=cue_out, m["liq_cross_start_next"])
cross_duration = max(cue_out - start_next, fade_out)
log(level=4, label="set_cross_duration", "Setting liq_cross_duration=#{cross_duration}")
if cross_duration > 0. then
[("liq_cross_duration", "#{cross_duration}")]
else
[]
end
end
radio = metadata.map(set_cross_duration, radio)
{$showMetaFunc}
def live_aware_crossfade(old, new) =
if to_live() then
# If going to the live show, play a simple sequence
sequence([fade.out(old.source),fade.in(new.source)])
else
# Otherwise, use the smart transition
{$crossfadeFunc}
end
end
radio = cross(minimum=0., duration={$crossDuration}, live_aware_crossfade, radio)
LS
);
}
if ($settings->isAudioProcessingEnabled() && !$settings->getPostProcessingIncludeLive()) {
$this->writePostProcessingSection($event);
}
}
public function writeHarborConfiguration(WriteLiquidsoapConfiguration $event): void
{
$station = $event->getStation();
if (!$station->getEnableStreamers()) {
return;
}
$this->writeCustomConfigurationSection($event, StationBackendConfiguration::CUSTOM_PRE_LIVE);
$settings = $event->getBackendConfig();
$charset = $settings->getCharset();
$djMount = $settings->getDjMountPoint();
$recordLiveStreams = $settings->recordStreams();
$event->appendBlock(
<<< LIQ
# DJ Authentication
last_authenticated_dj = ref("")
live_dj = ref("")
def dj_auth(login) =
auth_info =
if (login.user == "source" or login.user == "") and (string.match(pattern="(:|,)+", login.password)) then
auth_string = string.split(separator="(:|,)", login.password)
{user = list.nth(default="", auth_string, 0),
password = list.nth(default="", auth_string, 2)}
else
{user = login.user, password = login.password}
end
response = azuracast_api_call(
timeout=5.0,
"auth",
json.stringify(auth_info)
)
if (response == "true") then
last_authenticated_dj.set(auth_info.user)
true
else
false
end
end
def live_connected(header) =
dj = last_authenticated_dj()
log("DJ Source connected! Last authenticated DJ: #{dj} - #{header}")
live_enabled.set(true)
live_dj.set(dj)
_ = azuracast_api_call(
timeout=5.0,
"djon",
json.stringify({user = dj})
)
end
def live_disconnected() =
_ = azuracast_api_call(
timeout=5.0,
"djoff",
json.stringify({user = live_dj()})
)
live_enabled.set(false)
live_dj.set("")
end
LIQ
);
$harborParams = [
'"' . self::cleanUpString($djMount) . '"',
'id = "input_streamer"',
'port = ' . $this->liquidsoap->getStreamPort($station),
'auth = dj_auth',
'icy = true',
'icy_metadata_charset = "' . $charset . '"',
'metadata_charset = "' . $charset . '"',
'on_connect = live_connected',
'on_disconnect = live_disconnected',
];
$djBuffer = $settings->getDjBuffer();
if (0 !== $djBuffer) {
$harborParams[] = 'buffer = ' . self::toFloat($djBuffer);
$harborParams[] = 'max = ' . self::toFloat(max($djBuffer + 5, 10));
}
$harborParams = implode(', ', $harborParams);
$liveBroadcastText = self::cleanUpString(
$settings->getLiveBroadcastText()
);
$event->appendBlock(
<<<LIQ
# A Pre-DJ source of radio that can be broadcast if needed
radio_without_live = radio
ignore(radio_without_live)
# Live Broadcasting
live = input.harbor({$harborParams})
last_live_meta = ref([])
def insert_missing(m) =
def updates =
if m == [] then
[("title", "{$liveBroadcastText}"), ("is_live", "true")]
else
[("is_live", "true")]
end
end
last_live_meta := [...m, ...list.assoc.remove("title", updates)]
updates
end
live = metadata.map(insert_missing, live)
live = insert_metadata(live)
def insert_latest_live_metadata() =
log("Inserting last live meta: #{last_live_meta()}")
live.insert_metadata(last_live_meta())
end
def transition_to_live(_, s) =
log("executing transition to live")
insert_latest_live_metadata()
s
end
def transition_to_radio(_, s) = s end
radio = fallback(
id="live_fallback",
track_sensitive=false,
replay_metadata=true,
transitions=[transition_to_live, transition_to_radio],
[live, radio]
)
# Skip non-live track when live DJ goes live.
def check_live() =
if live.is_ready() then
if not to_live() then
to_live.set(true)
radio_without_live.skip()
end
else
to_live.set(false)
end
end
# Continuously check on live.
radio = source.on_frame(radio, check_live)
LIQ
);
if ($recordLiveStreams) {
$recordLiveStreamsFormat = $settings->getRecordStreamsFormatEnum();
$recordLiveStreamsBitrate = $settings->getRecordStreamsBitrate();
$formatString = $this->getOutputFormatString($recordLiveStreamsFormat, $recordLiveStreamsBitrate);
$recordExtension = $recordLiveStreamsFormat->getExtension();
$recordBasePath = self::cleanUpString($station->getRadioTempDir());
$recordPathPrefix = StationStreamerBroadcast::PATH_PREFIX;
$event->appendBlock(
<<< LIQ
# Record Live Broadcasts
recording_base_path = "{$recordBasePath}"
recording_extension = "{$recordExtension}"
output.file(
{$formatString},
fun () -> begin
if (live_enabled()) then
time.string("#{recording_base_path}/#{live_dj()}/{$recordPathPrefix}_%Y%m%d-%H%M%S.#{recording_extension}.tmp")
else
""
end
end,
live,
fallible=true,
on_close=fun (tempPath) -> begin
path = string.replace(pattern=".tmp$", (fun(_) -> ""), tempPath)
log("Recording stopped: Switching from #{tempPath} to #{path}")
process.run("mv #{tempPath} #{path}")
()
end
)
LIQ
);
}
}
public function writePreBroadcastConfiguration(WriteLiquidsoapConfiguration $event): void
{
$station = $event->getStation();
$settings = $event->getBackendConfig();
$event->appendBlock(
<<<LIQ
# Allow for Telnet-driven insertion of custom metadata.
radio = server.insert_metadata(id="custom_metadata", radio)
LIQ
);
if ($settings->isAudioProcessingEnabled() && $settings->getPostProcessingIncludeLive()) {
$this->writePostProcessingSection($event);
}
// Write fallback to safety file to ensure infallible source for the broadcast outputs.
$errorFile = $this->fallbackFile->getFallbackPathForStation($station);
$event->appendBlock(
<<<LIQ
error_file = single(id="error_jingle", "{$errorFile}")
def tag_error_file(m) =
ignore(m)
[("is_error_file", "true")]
end
error_file = metadata.map(tag_error_file, error_file)
radio = fallback(id="safe_fallback", track_sensitive = false, [radio, error_file])
LIQ
);
$event->appendBlock(
<<<LIQ
# Send metadata changes back to AzuraCast
last_title = ref("")
last_artist = ref("")
def metadata_updated(m) =
def f() =
if (m["is_error_file"] != "true") then
if (m["title"] != last_title() or m["artist"] != last_artist()) then
last_title.set(m["title"])
last_artist.set(m["artist"])
# Only send some metadata to AzuraCast
def fl(k, _) =
tags = ["song_id", "media_id", "playlist_id", "artist", "title"]
string.contains(prefix="liq_", k) or string.contains(prefix="replaygain_", k) or list.mem(k, tags)
end
feedback_meta = list.assoc.filter((fl), metadata.cover.remove(m))
j = json()
for item = list.iterator(feedback_meta) do
let (tag, value) = item
j.add(tag, value)
end
_ = azuracast_api_call(
"feedback",
json.stringify(compact=true, j)
)
end
end
end
thread.run(f)
end
radio.on_metadata(metadata_updated)
# Handle "Jingle Mode" tracks by replaying the previous metadata.
last_metadata = ref([])
def handle_jingle_mode(m) =
if (m["jingle_mode"] == "true") then
last_metadata()
else
last_metadata.set(m)
m
end
end
radio = metadata.map(update=false, strip=true, handle_jingle_mode, radio)
LIQ
);
// Custom configuration
$this->writeCustomConfigurationSection($event, StationBackendConfiguration::CUSTOM_PRE_BROADCAST);
}
public function writeLocalBroadcastConfiguration(WriteLiquidsoapConfiguration $event): void
{
$station = $event->getStation();
if (FrontendAdapters::Remote === $station->getFrontendType()) {
return;
}
$lsConfig = [
'# Local Broadcasts',
];
// Configure the outbound broadcast.
$i = 0;
foreach ($station->getMounts() as $mountRow) {
$i++;
/** @var StationMount $mountRow */
if (!$mountRow->getEnableAutodj()) {
continue;
}
$lsConfig[] = $this->getOutputString($event, $mountRow, 'local_', $i);
}
$event->appendLines($lsConfig);
}
public function writeHlsBroadcastConfiguration(WriteLiquidsoapConfiguration $event): void
{
$station = $event->getStation();
if (!$station->getEnableHls()) {
return;
}
$lsConfig = [
'# HLS Broadcasting',
];
// Configure the outbound broadcast.
$hlsStreams = [];
foreach ($station->getHlsStreams() as $hlsStream) {
$streamVarName = self::cleanUpVarName($hlsStream->getName());
if (StreamFormats::Aac !== $hlsStream->getFormat()) {
continue;
}
$streamBitrate = $hlsStream->getBitrate() ?? 128;
$lsConfig[] = <<<LIQ
{$streamVarName} = %ffmpeg(
format="mpegts",
%audio(
codec="aac",
samplerate=44100,
channels=2,
b="{$streamBitrate}k",
profile="aac_low"
)
)
LIQ;
$hlsStreams[] = $streamVarName;
}
if (empty($hlsStreams)) {
return;
}
$lsConfig[] = 'hls_streams = [' . implode(
', ',
array_map(
static fn($row) => '("' . $row . '", ' . $row . ')',
$hlsStreams
)
) . ']';
$event->appendLines($lsConfig);
$configDir = $station->getRadioConfigDir();
$hlsBaseDir = $station->getRadioHlsDir();
$tempDir = $station->getRadioTempDir();
$backendConfig = $event->getBackendConfig();
$hlsSegmentLength = $backendConfig->getHlsSegmentLength();
$hlsSegmentsInPlaylist = $backendConfig->getHlsSegmentsInPlaylist();
$hlsSegmentsOverhead = $backendConfig->getHlsSegmentsOverhead();
$event->appendBlock(
<<<LIQ
def hls_segment_name(~position,~extname,stream_name) =
timestamp = int_of_float(time())
duration = {$hlsSegmentLength}
"#{stream_name}_#{duration}_#{timestamp}_#{position}.#{extname}"
end
output.file.hls(playlist="live.m3u8",
segment_duration={$hlsSegmentLength}.0,
segments={$hlsSegmentsInPlaylist},
segments_overhead={$hlsSegmentsOverhead},
segment_name=hls_segment_name,
persist_at="{$configDir}/hls.config",
temp_dir="{$tempDir}",
"{$hlsBaseDir}",
hls_streams,
radio
)
LIQ
);
}
/**
* Given outbound broadcast information, produce a suitable LiquidSoap configuration line for the stream.
*/
private function getOutputString(
WriteLiquidsoapConfiguration $event,
StationMountInterface $mount,
string $idPrefix,
int $id
): string {
$station = $event->getStation();
$charset = $event->getBackendConfig()->getCharset();
$format = $mount->getAutodjFormat() ?? StreamFormats::default();
$outputFormat = $this->getOutputFormatString(
$format,
$mount->getAutodjBitrate() ?? 128
);
$outputParams = [];
$outputParams[] = $outputFormat;
$outputParams[] = 'id="' . $idPrefix . $id . '"';
$outputParams[] = 'host = "' . self::cleanUpString($mount->getAutodjHost()) . '"';
$outputParams[] = 'port = ' . (int)$mount->getAutodjPort();
$username = $mount->getAutodjUsername();
if (!empty($username)) {
$outputParams[] = 'user = "' . self::cleanUpString($username) . '"';
}
$password = self::cleanUpString($mount->getAutodjPassword());
$adapterType = $mount->getAutodjAdapterType();
if (FrontendAdapters::Shoutcast === $adapterType) {
$password .= ':#' . $id;
}
$outputParams[] = 'password = "' . $password . '"';
$protocol = $mount->getAutodjProtocol();
$mountPoint = $mount->getAutodjMount();
if (StreamProtocols::Icy === $protocol) {
if (!empty($mountPoint)) {
$outputParams[] = 'icy_id = ' . $id;
}
} else {
if (empty($mountPoint)) {
$mountPoint = '/';
}
$outputParams[] = 'mount = "' . self::cleanUpString($mountPoint) . '"';
}
$outputParams[] = 'name = "' . self::cleanUpString($station->getName()) . '"';
if (!$mount->getIsShoutcast()) {
$outputParams[] = 'description = "' . self::cleanUpString($station->getDescription()) . '"';
}
$outputParams[] = 'genre = "' . self::cleanUpString($station->getGenre()) . '"';
if (!empty($station->getUrl())) {
$outputParams[] = 'url = "' . self::cleanUpString($station->getUrl()) . '"';
}
$outputParams[] = 'public = ' . ($mount->getIsPublic() ? 'true' : 'false');
$outputParams[] = 'encoding = "' . $charset . '"';
if (StreamProtocols::Https === $protocol) {
$outputParams[] = 'transport=https_transport';
}
if ($format->sendIcyMetadata()) {
$outputParams[] = 'send_icy_metadata=true';
}
$outputParams[] = 'radio';
$outputCommand = ($mount->getIsShoutcast())
? 'output.shoutcast'
: 'output.icecast';
return $outputCommand . '(' . implode(', ', $outputParams) . ')';
}
private function getOutputFormatString(StreamFormats $format, int $bitrate = 128): string
{
switch ($format) {
case StreamFormats::Aac:
$afterburner = ($bitrate >= 160) ? 'true' : 'false';
$aot = ($bitrate >= 96) ? 'mpeg4_aac_lc' : 'mpeg4_he_aac_v2';
return '%fdkaac(channels=2, samplerate=44100, bitrate=' . $bitrate . ', afterburner=' . $afterburner . ', aot="' . $aot . '", sbr_mode=true)';
case StreamFormats::Ogg:
return '%ffmpeg(format="ogg", %audio(codec="libvorbis", samplerate=48000, b="' . $bitrate . 'k", channels=2))';
case StreamFormats::Opus:
return '%ffmpeg(format="ogg", %audio(codec="libopus", samplerate=48000, b="' . $bitrate . 'k", vbr="constrained", application="audio", channels=2, compression_level=10, cutoff=20000))';
case StreamFormats::Flac:
return '%ogg(%flac(samplerate=48000, channels=2, compression=4, bits_per_sample=24))';
case StreamFormats::Mp3:
return '%mp3(samplerate=44100, stereo=true, bitrate=' . $bitrate . ')';
default:
throw new RuntimeException(sprintf('Unsupported stream format: %s', $format->value));
}
}
public function writeRemoteBroadcastConfiguration(WriteLiquidsoapConfiguration $event): void
{
$station = $event->getStation();
$lsConfig = [
'# Remote Relays',
];
// Set up broadcast to remote relays.
$i = 0;
foreach ($station->getRemotes() as $remoteRow) {
$i++;
/** @var StationRemote $remoteRow */
if (!$remoteRow->getEnableAutodj()) {
continue;
}
$lsConfig[] = $this->getOutputString($event, $remoteRow, 'relay_', $i);
}
$event->appendLines($lsConfig);
}
public function writePostBroadcastConfiguration(WriteLiquidsoapConfiguration $event): void
{
$this->writeCustomConfigurationSection($event, StationBackendConfiguration::CUSTOM_BOTTOM);
}
/**
* Convert an integer or float into a Liquidsoap configuration compatible float.
*
* @param float|int|string $number
* @param int $decimals
*/
public static function toFloat(float|int|string $number, int $decimals = 2): string
{
return number_format(
Types::float($number),
$decimals,
'.',
''
);
}
/**
* Convert a boolean-ish value into a Liquidsoap annotated boolean.
*
* @param string|bool $value
* @return string
*/
public static function toBool(string|bool $value): string
{
return Types::bool($value, false, true)
? 'true'
: 'false';
}
public static function valueToString(string|int|float|bool $dataVal): string
{
return match (true) {
'true' === $dataVal || 'false' === $dataVal => $dataVal,
is_bool($dataVal) => self::toBool($dataVal),
is_numeric($dataVal) => self::toFloat($dataVal),
default => Types::string($dataVal)
};
}
public static function formatTimeCode(int $timeCode): string
{
$hours = floor($timeCode / 100);
$mins = $timeCode % 100;
return $hours . 'h' . $mins . 'm';
}
/**
* Filter a user-supplied string to be a valid LiquidSoap config entry.
*
* @param string|null $string
*
*/
public static function cleanUpString(?string $string): string
{
return str_replace(['"', "\n", "\r"], ['\'', '', ''], $string ?? '');
}
/**
* Apply a more aggressive string filtering to variable names used in Liquidsoap.
*
* @param string $str
*
* @return string The cleaned up, variable-name-friendly string.
*/
public static function cleanUpVarName(string $str): string
{
$str = strtolower(
preg_replace(
['/[\r\n\t ]+/', '/[\"*\/:<>?\'|]+/'],
' ',
strip_tags($str)
) ?? ''
);
$str = html_entity_decode($str, ENT_QUOTES, "utf-8");
$str = htmlentities($str, ENT_QUOTES, "utf-8");
$str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str) ?? '';
$str = rawurlencode(str_replace(' ', '_', $str));
return str_replace(['%', '-', '.'], ['', '_', '_'], $str);
}
public static function getPlaylistVariableName(StationPlaylist $playlist): string
{
return self::cleanUpVarName('playlist_' . $playlist->getShortName());
}
public static function annotateString(string $str): string
{
$str = mb_convert_encoding($str, 'UTF-8');
return str_replace(['"', "\n", "\t", "\r"], ['\"', '', '', ''], $str);
}
public static function shouldWritePlaylist(
WriteLiquidsoapConfiguration $event,
StationPlaylist $playlist
): bool {
$station = $event->getStation();
$backendConfig = $event->getBackendConfig();
if ($backendConfig->getWritePlaylistsToLiquidsoap()) {
return true;
}
if ($station->useManualAutoDJ()) {
return true;
}
if (PlaylistSources::Songs !== $playlist->getSource()) {
return true;
}
if (
$playlist->backendInterruptOtherSongs()
|| $playlist->backendPlaySingleTrack()
|| $playlist->backendMerge()
|| PlaylistTypes::Advanced === $playlist->getType()
) {
return true;
}
return false;
}
}
``` | /content/code_sandbox/backend/src/Radio/Backend/Liquidsoap/ConfigWriter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 13,058 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Frontend;
use App\Entity\Station;
use App\Entity\StationMount;
use App\Radio\Enums\StreamFormats;
use App\Service\Acme;
use App\Utilities;
use App\Xml\Writer;
use GuzzleHttp\Promise\Utils;
use GuzzleHttp\Psr7\Uri;
use NowPlaying\Result\Result;
use Psr\Http\Message\UriInterface;
use Supervisor\Exception\SupervisorException as SupervisorLibException;
use Symfony\Component\Filesystem\Path;
final class Icecast extends AbstractFrontend
{
public const int LOGLEVEL_DEBUG = 4;
public const int LOGLEVEL_INFO = 3;
public const int LOGLEVEL_WARN = 2;
public const int LOGLEVEL_ERROR = 1;
public function reload(Station $station): void
{
if ($this->hasCommand($station)) {
$programName = $this->getSupervisorFullName($station);
try {
$this->supervisor->signalProcess($programName, 'HUP');
$this->logger->info(
'Adapter "' . self::class . '" reloaded.',
['station_id' => $station->getId(), 'station_name' => $station->getName()]
);
} catch (SupervisorLibException $e) {
$this->handleSupervisorException($e, $programName, $station);
}
}
}
public function getNowPlaying(Station $station, bool $includeClients = true): Result
{
$feConfig = $station->getFrontendConfig();
$radioPort = $feConfig->getPort();
$baseUrl = $this->environment->getLocalUri()
->withPort($radioPort);
$npAdapter = $this->adapterFactory->getIcecastAdapter($baseUrl);
$npAdapter->setAdminPassword($feConfig->getAdminPassword());
$mountPromises = [];
$defaultMountId = null;
foreach ($station->getMounts() as $mount) {
if ($mount->getIsDefault()) {
$defaultMountId = $mount->getIdRequired();
}
$mountPromises[$mount->getIdRequired()] = $npAdapter->getNowPlayingAsync(
$mount->getName(),
$includeClients
)->then(
function (Result $result) use ($mount) {
if (!empty($result->clients)) {
foreach ($result->clients as $client) {
$client->mount = 'local_' . $mount->getId();
}
}
$mount->setListenersTotal($result->listeners->total);
$mount->setListenersUnique($result->listeners->unique ?? 0);
$this->em->persist($mount);
return $result;
}
);
}
$mountPromiseResults = Utils::settle($mountPromises)->wait();
$this->em->flush();
$defaultResult = Result::blank();
$otherResults = [];
foreach ($mountPromiseResults as $mountId => $result) {
if ($mountId === $defaultMountId) {
$defaultResult = $result['value'] ?? Result::blank();
} else {
$otherResults[] = $result['value'] ?? Result::blank();
}
}
foreach ($otherResults as $otherResult) {
$defaultResult = $defaultResult->merge($otherResult);
}
return $defaultResult;
}
public function getConfigurationPath(Station $station): ?string
{
return $station->getRadioConfigDir() . '/icecast.xml';
}
public function getCurrentConfiguration(Station $station): ?string
{
$frontendConfig = $station->getFrontendConfig();
$configDir = $station->getRadioConfigDir();
$settingsBaseUrl = $this->settingsRepo->readSettings()->getBaseUrlAsUri();
$baseUrl = $settingsBaseUrl ?? new Uri('path_to_url
[$certPath, $certKey] = Acme::getCertificatePaths();
$config = [
'location' => 'AzuraCast',
'admin' => 'icemaster@localhost',
'hostname' => $baseUrl->getHost(),
'limits' => [
'clients' => $frontendConfig->getMaxListeners() ?? 2500,
'sources' => $station->getMounts()->count(),
'queue-size' => 524288,
'client-timeout' => 30,
'header-timeout' => 15,
'source-timeout' => 10,
'burst-size' => 65535,
],
'authentication' => [
'source-password' => $frontendConfig->getSourcePassword(),
'relay-password' => $frontendConfig->getRelayPassword(),
'admin-user' => 'admin',
'admin-password' => $frontendConfig->getAdminPassword(),
],
'listen-socket' => [
'port' => $frontendConfig->getPort(),
],
'mount' => [],
'fileserve' => 1,
'paths' => [
'basedir' => '/usr/local/share/icecast',
'logdir' => $configDir,
'webroot' => '/usr/local/share/icecast/web',
'adminroot' => '/usr/local/share/icecast/admin',
'pidfile' => $configDir . '/icecast.pid',
'alias' => [
[
'@source' => '/',
'@dest' => '/status.xsl',
],
],
'ssl-private-key' => $certKey,
'ssl-certificate' => $certPath,
// phpcs:disable Generic.Files.LineLength
'ssl-allowed-ciphers' => 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
// phpcs:enable
'deny-ip' => $this->writeIpBansFile($station),
'deny-agents' => $this->writeUserAgentBansFile($station),
'x-forwarded-for' => '127.0.0.1',
],
'logging' => [
'accesslog' => 'icecast_access.log',
'errorlog' => '/dev/stderr',
'loglevel' => $this->environment->isProduction() ? self::LOGLEVEL_WARN : self::LOGLEVEL_INFO,
'logsize' => 10000,
],
'security' => [
'chroot' => 0,
],
];
$bannedCountries = $station->getFrontendConfig()->getBannedCountries() ?? [];
$allowedIps = $this->getIpsAsArray($station->getFrontendConfig()->getAllowedIps());
$useListenerAuth = !empty($bannedCountries) || !empty($allowedIps);
/** @var StationMount $mountRow */
foreach ($station->getMounts() as $mountRow) {
$mount = [
'@type' => 'normal',
'mount-name' => $mountRow->getName(),
'charset' => 'UTF8',
'stream-name' => $station->getName(),
'listenurl' => $this->getUrlForMount($station, $mountRow),
];
if (!empty($station->getDescription())) {
$mount['stream-description'] = $station->getDescription();
}
if (!empty($station->getUrl())) {
$mount['stream-url'] = $station->getUrl();
}
if (!empty($station->getGenre())) {
$mount['genre'] = $station->getGenre();
}
if (!$mountRow->getIsVisibleOnPublicPages()) {
$mount['hidden'] = 1;
}
if (!empty($mountRow->getIntroPath())) {
$introPath = $mountRow->getIntroPath();
// The intro path is appended to webroot, so the path should be relative to it.
$mount['intro'] = Path::makeRelative(
$station->getRadioConfigDir() . '/' . $introPath,
'/usr/local/share/icecast/web'
);
}
if (!empty($mountRow->getFallbackMount())) {
$mount['fallback-mount'] = $mountRow->getFallbackMount();
$mount['fallback-override'] = 1;
} elseif ($mountRow->getEnableAutodj()) {
$autoDjFormat = $mountRow->getAutodjFormat() ?? StreamFormats::default();
$autoDjBitrate = $mountRow->getAutodjBitrate();
$mount['fallback-mount'] = '/fallback-[' . $autoDjBitrate . '].' . $autoDjFormat->getExtension();
$mount['fallback-override'] = 1;
}
if ($mountRow->getMaxListenerDuration()) {
$mount['max-listener-duration'] = $mountRow->getMaxListenerDuration();
}
$mountFrontendConfig = trim($mountRow->getFrontendConfig() ?? '');
if (!empty($mountFrontendConfig)) {
$mountConf = $this->processCustomConfig($mountFrontendConfig);
if (false !== $mountConf) {
$mount = Utilities\Arrays::arrayMergeRecursiveDistinct($mount, $mountConf);
}
}
$mountRelayUri = $mountRow->getRelayUrlAsUri();
if (null !== $mountRelayUri) {
$config['relay'][] = array_filter([
'server' => $mountRelayUri->getHost(),
'port' => $mountRelayUri->getPort(),
'mount' => $mountRelayUri->getPath(),
'local-mount' => $mountRow->getName(),
]);
}
if ($useListenerAuth) {
$mountAuthenticationUrl = $this->environment->getInternalUri()
->withPath('/api/internal/' . $station->getIdRequired() . '/listener-auth')
->withQuery(
http_build_query([
'api_auth' => $station->getAdapterApiKey(),
])
);
$mount['authentication'][] = [
'@type' => 'url',
'option' => [
[
'@name' => 'listener_add',
'@value' => (string)$mountAuthenticationUrl,
],
[
'@name' => 'auth_header',
'@value' => 'icecast-auth-user: 1',
],
],
];
}
$config['mount'][] = $mount;
}
$customConfig = trim($frontendConfig->getCustomConfiguration() ?? '');
if (!empty($customConfig)) {
$customConfParsed = $this->processCustomConfig($customConfig);
if (false !== $customConfParsed) {
// Special handling for aliases.
if (isset($customConfParsed['paths']['alias'])) {
$alias = (array)$customConfParsed['paths']['alias'];
if (!is_numeric(key($alias))) {
$alias = [$alias];
}
$customConfParsed['paths']['alias'] = $alias;
}
$config = Utilities\Arrays::arrayMergeRecursiveDistinct($config, $customConfParsed);
}
}
return Writer::toString($config, 'icecast', false);
}
public function getCommand(Station $station): ?string
{
if ($binary = $this->getBinary()) {
return $binary . ' -c ' . $this->getConfigurationPath($station);
}
return null;
}
/**
* @inheritDoc
*/
public function getBinary(): ?string
{
$newPath = '/usr/local/bin/icecast';
$legacyPath = '/usr/bin/icecast2';
if ($this->environment->isDocker() || file_exists($newPath)) {
return $newPath;
}
if (file_exists($legacyPath)) {
return $legacyPath;
}
return null;
}
public function getAdminUrl(Station $station, UriInterface $baseUrl = null): UriInterface
{
$publicUrl = $this->getPublicUrl($station, $baseUrl);
return $publicUrl
->withPath($publicUrl->getPath() . '/admin.html');
}
}
``` | /content/code_sandbox/backend/src/Radio/Frontend/Icecast.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 2,682 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Frontend;
use App\Container\SettingsAwareTrait;
use App\Entity\Repository\StationMountRepository;
use App\Entity\Station;
use App\Entity\StationMount;
use App\Http\Router;
use App\Nginx\CustomUrls;
use App\Radio\AbstractLocalAdapter;
use App\Radio\Configuration;
use App\Xml\Reader;
use Exception;
use GuzzleHttp\Client;
use InvalidArgumentException;
use NowPlaying\AdapterFactory;
use NowPlaying\Result\Result;
use PhpIP\IP;
use PhpIP\IPBlock;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Message\UriInterface;
use Supervisor\SupervisorInterface;
abstract class AbstractFrontend extends AbstractLocalAdapter
{
use SettingsAwareTrait;
public function __construct(
protected AdapterFactory $adapterFactory,
protected Client $httpClient,
protected StationMountRepository $stationMountRepo,
SupervisorInterface $supervisor,
EventDispatcherInterface $dispatcher,
Router $router
) {
parent::__construct($supervisor, $dispatcher, $router);
}
/**
* @inheritdoc
*/
public function getSupervisorProgramName(Station $station): string
{
return Configuration::getSupervisorProgramName($station, 'frontend');
}
/**
* @param Station $station
* @param UriInterface|null $baseUrl
*/
public function getStreamUrl(Station $station, UriInterface $baseUrl = null): UriInterface
{
$defaultMount = $this->stationMountRepo->getDefaultMount($station);
return $this->getUrlForMount($station, $defaultMount, $baseUrl);
}
public function getUrlForMount(
Station $station,
?StationMount $mount = null,
?UriInterface $baseUrl = null
): UriInterface {
if ($mount === null) {
return $this->getPublicUrl($station, $baseUrl);
}
$customListenUri = $mount->getCustomListenUrlAsUri();
if (null !== $customListenUri) {
return $customListenUri;
}
$publicUrl = $this->getPublicUrl($station, $baseUrl);
return $publicUrl->withPath($publicUrl->getPath() . $mount->getName());
}
public function getPublicUrl(Station $station, ?UriInterface $baseUrl = null): UriInterface
{
$radioPort = $station->getFrontendConfig()->getPort();
$baseUrl ??= $this->router->getBaseUrl();
$useRadioProxy = $this->readSettings()->getUseRadioProxy();
if (
$useRadioProxy
|| 'https' === $baseUrl->getScheme()
|| (!$this->environment->isProduction() && !$this->environment->isDocker())
) {
// Web proxy support.
return $baseUrl
->withPath($baseUrl->getPath() . CustomUrls::getListenUrl($station));
}
// Remove port number and other decorations.
return $baseUrl
->withPort($radioPort)
->withPath('');
}
abstract public function getAdminUrl(Station $station, UriInterface $baseUrl = null): UriInterface;
public function getNowPlaying(Station $station, bool $includeClients = true): Result
{
return Result::blank();
}
/**
* @param string $customConfigRaw
*
* @return mixed[]|false
*/
protected function processCustomConfig(string $customConfigRaw): array|false
{
try {
if (str_starts_with($customConfigRaw, '{')) {
return json_decode($customConfigRaw, true, 512, JSON_THROW_ON_ERROR);
}
if (str_starts_with($customConfigRaw, '<')) {
$xmlConfig = Reader::fromString('<custom_config>' . $customConfigRaw . '</custom_config>');
return (false !== $xmlConfig)
? (array)$xmlConfig
: false;
}
} catch (Exception $e) {
$this->logger->error(
'Could not parse custom configuration.',
[
'config' => $customConfigRaw,
'exception' => $e,
]
);
}
return false;
}
protected function writeUserAgentBansFile(
Station $station,
string $fileName = 'user_agent_bans.txt',
): string {
$bannedUserAgents = array_filter(
array_map(
'trim',
explode("\n", $station->getFrontendConfig()->getBannedUserAgents() ?? '')
)
);
$configDir = $station->getRadioConfigDir();
$bansFile = $configDir . '/' . $fileName;
file_put_contents($bansFile, implode("\n", $bannedUserAgents));
return $bansFile;
}
protected function writeIpBansFile(
Station $station,
string $fileName = 'ip_bans.txt',
string $ipsSeparator = "\n"
): string {
$ips = $this->getBannedIps($station);
$configDir = $station->getRadioConfigDir();
$bansFile = $configDir . '/' . $fileName;
file_put_contents($bansFile, implode($ipsSeparator, $ips));
return $bansFile;
}
protected function getBannedIps(Station $station): array
{
return $this->getIpsAsArray($station->getFrontendConfig()->getBannedIps());
}
protected function getIpsAsArray(?string $ipString): array
{
$ips = [];
if (!empty($ipString)) {
foreach (array_filter(array_map('trim', explode("\n", $ipString))) as $ip) {
try {
if (!str_contains($ip, '/')) {
$ipObj = IP::create($ip);
$ips[] = (string)$ipObj;
} else {
// Iterate through CIDR notation
foreach (IPBlock::create($ip) as $ipObj) {
$ips[] = (string)$ipObj;
}
}
} catch (InvalidArgumentException) {
}
}
}
return $ips;
}
}
``` | /content/code_sandbox/backend/src/Radio/Frontend/AbstractFrontend.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,350 |
```php
<?php
declare(strict_types=1);
namespace App\Event;
use App\Acl;
use Symfony\Contracts\EventDispatcher\Event;
/**
* @phpstan-import-type PermissionsArray from Acl
*/
final class BuildPermissions extends Event
{
/**
* @param PermissionsArray $permissions
*/
public function __construct(
private array $permissions
) {
}
/**
* @return PermissionsArray
*/
public function getPermissions(): array
{
return $this->permissions;
}
/**
* @param PermissionsArray $permissions
*/
public function setPermissions(array $permissions): void
{
$this->permissions = $permissions;
}
}
``` | /content/code_sandbox/backend/src/Event/BuildPermissions.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 147 |
```php
<?php
declare(strict_types=1);
namespace App\Event;
use App\Entity\Api\Notification;
use App\Http\ServerRequest;
use Symfony\Contracts\EventDispatcher\Event;
final class GetNotifications extends Event
{
private array $notifications = [];
public function __construct(
private readonly ServerRequest $request
) {
}
public function getRequest(): ServerRequest
{
return $this->request;
}
/**
* Add a new notification to the list that will be displayed.
*
* @param Notification $notification
*/
public function addNotification(Notification $notification): void
{
$this->notifications[] = $notification;
}
/**
* Retrieve the complete list of notifications that were triggered.
*
* @return Notification[]
*/
public function getNotifications(): array
{
return $this->notifications;
}
}
``` | /content/code_sandbox/backend/src/Event/GetNotifications.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 185 |
```php
<?php
declare(strict_types=1);
namespace App\Radio\Frontend\Blocklist;
use App\Entity\Station;
use App\Radio\Enums\FrontendAdapters;
use App\Service\IpGeolocation;
use InvalidArgumentException;
use PhpIP\IP;
use PhpIP\IPBlock;
final class BlocklistParser
{
public function __construct(
private readonly IpGeolocation $ipGeolocation
) {
}
public function isAllowed(
Station $station,
string $ip,
?string $userAgent = null
): bool {
if ($this->hasAllowedIps($station)) {
return $this->isIpExplicitlyAllowed($station, $ip);
}
if ($this->isIpExplicitlyBanned($station, $ip)) {
return false;
}
if ($this->isCountryBanned($station, $ip)) {
return false;
}
if (null !== $userAgent && $this->isUserAgentBanned($station, $userAgent)) {
return false;
}
return true;
}
private function hasAllowedIps(Station $station): bool
{
if (FrontendAdapters::Remote === $station->getFrontendType()) {
return false;
}
$allowedIps = trim($station->getFrontendConfig()->getAllowedIps() ?? '');
return !empty($allowedIps);
}
private function isIpExplicitlyAllowed(
Station $station,
string $ip
): bool {
if (FrontendAdapters::Remote === $station->getFrontendType()) {
return false;
}
$allowedIps = $station->getFrontendConfig()->getAllowedIps() ?? '';
return $this->isIpInList($ip, $allowedIps);
}
private function isIpExplicitlyBanned(
Station $station,
string $ip
): bool {
if (FrontendAdapters::Remote === $station->getFrontendType()) {
return false;
}
$bannedIps = $station->getFrontendConfig()->getBannedIps() ?? '';
return $this->isIpInList($ip, $bannedIps);
}
private function isIpInList(
string $listenerIp,
string $ipList
): bool {
if (empty($ipList)) {
return false;
}
foreach (array_filter(array_map('trim', explode("\n", $ipList))) as $ip) {
try {
if (!str_contains($ip, '/')) {
$ipObj = IP::create($ip);
if ($ipObj->matches($listenerIp)) {
return true;
}
} else {
// Iterate through CIDR notation
foreach (IPBlock::create($ip) as $ipObj) {
if ($ipObj->matches($listenerIp)) {
return true;
}
}
}
} catch (InvalidArgumentException) {
}
}
return false;
}
private function isCountryBanned(
Station $station,
string $listenerIp
): bool {
if (FrontendAdapters::Remote === $station->getFrontendType()) {
return false;
}
$bannedCountries = $station->getFrontendConfig()->getBannedCountries() ?? [];
if (empty($bannedCountries)) {
return false;
}
$listenerLocation = $this->ipGeolocation->getLocationInfo($listenerIp);
return (null !== $listenerLocation->country)
&& in_array($listenerLocation->country, $bannedCountries, true);
}
public function isUserAgentBanned(
Station $station,
string $listenerUserAgent
): bool {
if (FrontendAdapters::Remote === $station->getFrontendType()) {
return false;
}
$bannedUserAgents = $station->getFrontendConfig()->getBannedUserAgents() ?? '';
if (empty($bannedUserAgents)) {
return false;
}
foreach (array_filter(array_map('trim', explode("\n", $bannedUserAgents))) as $userAgent) {
if (fnmatch($userAgent, $listenerUserAgent)) {
return true;
}
}
return false;
}
}
``` | /content/code_sandbox/backend/src/Radio/Frontend/Blocklist/BlocklistParser.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 939 |
```php
<?php
declare(strict_types=1);
namespace App\Event;
use Symfony\Contracts\EventDispatcher\Event;
final class BuildDoctrineMappingPaths extends Event
{
public function __construct(
private array $mappingClassesPaths,
private readonly string $baseDir
) {
}
/**
* @return string[]
*/
public function getMappingClassesPaths(): array
{
return $this->mappingClassesPaths;
}
public function setMappingClassesPaths(array $mappingClassesPaths): void
{
$this->mappingClassesPaths = $mappingClassesPaths;
}
public function getBaseDir(): string
{
return $this->baseDir;
}
}
``` | /content/code_sandbox/backend/src/Event/BuildDoctrineMappingPaths.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 145 |
```php
<?php
declare(strict_types=1);
namespace App\Event;
use Symfony\Contracts\EventDispatcher\Event;
final class BuildMigrationConfigurationArray extends Event
{
public function __construct(
private array $migrationConfigurations,
private readonly string $baseDir
) {
}
/**
* @return mixed[]
*/
public function getMigrationConfigurations(): array
{
return $this->migrationConfigurations;
}
public function setMigrationConfigurations(array $migrationConfigurations): void
{
$this->migrationConfigurations = $migrationConfigurations;
}
public function getBaseDir(): string
{
return $this->baseDir;
}
}
``` | /content/code_sandbox/backend/src/Event/BuildMigrationConfigurationArray.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 145 |
```php
<?php
declare(strict_types=1);
namespace App\Event;
use App\Sync\Task\AbstractTask;
use Generator;
/**
* @phpstan-type TaskClass class-string<AbstractTask>
*/
final class GetSyncTasks
{
/** @var TaskClass[] */
private array $tasks = [];
/** @return Generator<TaskClass> */
public function getTasks(): Generator
{
yield from $this->tasks;
}
/**
* @param TaskClass $className
*/
public function addTask(string $className): void
{
$this->tasks[] = $className;
}
public function addTasks(array $classNames): void
{
foreach ($classNames as $className) {
$this->addTask($className);
}
}
}
``` | /content/code_sandbox/backend/src/Event/GetSyncTasks.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 166 |
```php
<?php
declare(strict_types=1);
namespace App\Event;
use App\View;
use Symfony\Contracts\EventDispatcher\Event;
final class BuildView extends Event
{
public function __construct(
private readonly View $view
) {
}
public function getView(): View
{
return $this->view;
}
}
``` | /content/code_sandbox/backend/src/Event/BuildView.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 70 |
```php
<?php
declare(strict_types=1);
namespace App\Event;
use App\AppFactory;
use Psr\Container\ContainerInterface;
use Slim\App;
use Symfony\Contracts\EventDispatcher\Event;
/**
* @phpstan-import-type AppWithContainer from AppFactory
*/
final class BuildRoutes extends Event
{
/**
* @param AppWithContainer $app
* @param ContainerInterface $container
*/
public function __construct(
private readonly App $app,
private readonly ContainerInterface $container
) {
}
/**
* @return AppWithContainer
*/
public function getApp(): App
{
return $this->app;
}
public function getContainer(): ContainerInterface
{
return $this->container;
}
}
``` | /content/code_sandbox/backend/src/Event/BuildRoutes.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 159 |
```php
<?php
declare(strict_types=1);
namespace App\Event;
use App\Entity\Settings;
use App\Enums\PermissionInterface;
use App\Http\ServerRequest;
use Symfony\Contracts\EventDispatcher\Event;
abstract class AbstractBuildMenu extends Event
{
protected array $menu = [];
public function __construct(
protected ServerRequest $request,
protected Settings $settings
) {
}
public function getRequest(): ServerRequest
{
return $this->request;
}
public function getSettings(): Settings
{
return $this->settings;
}
/**
* Add a single item to the menu.
*
* @param string $itemId
* @param array $itemDetails
*/
public function addItem(string $itemId, array $itemDetails): void
{
$this->merge([$itemId => $itemDetails]);
}
/**
* Merge a menu subtree into the menu.
*
* @param array $items
*/
public function merge(array $items): void
{
$this->menu = array_merge_recursive($this->menu, $items);
}
/**
* @return mixed[]
*/
public function getFilteredMenu(): array
{
$menu = $this->menu;
foreach ($menu as &$item) {
if (isset($item['items'])) {
$item['items'] = array_filter($item['items'], [$this, 'filterMenuItem']);
}
}
return array_filter($menu, [$this, 'filterMenuItem']);
}
/**
* @param array $item
*/
protected function filterMenuItem(array $item): bool
{
if (isset($item['items']) && 0 === count($item['items'])) {
return false;
}
if (isset($item['visible']) && !$item['visible']) {
return false;
}
if (isset($item['permission']) && !$this->checkPermission($item['permission'])) {
return false;
}
return true;
}
public function checkPermission(string|PermissionInterface $permissionName): bool
{
return $this->request->getAcl()->isAllowed($permissionName);
}
}
``` | /content/code_sandbox/backend/src/Event/AbstractBuildMenu.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\Event;
use App\Console\Application;
use App\Environment;
use Psr\Container\ContainerInterface;
use Symfony\Contracts\EventDispatcher\Event;
final class BuildConsoleCommands extends Event
{
private array $aliases = [];
public function __construct(
private readonly Application $cli,
private readonly ContainerInterface $di,
private readonly Environment $environment
) {
}
public function getConsole(): Application
{
return $this->cli;
}
public function getContainer(): ContainerInterface
{
return $this->di;
}
public function getEnvironment(): Environment
{
return $this->environment;
}
public function addAliases(array $aliases): void
{
$this->aliases = array_merge($this->aliases, $aliases);
}
public function getAliases(): array
{
return $this->aliases;
}
}
``` | /content/code_sandbox/backend/src/Event/BuildConsoleCommands.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\Event\Media;
use App\Entity\Interfaces\SongInterface;
use Symfony\Contracts\EventDispatcher\Event;
final class GetAlbumArt extends Event
{
private ?string $albumArt = null;
public function __construct(
private readonly SongInterface $song
) {
}
public function getSong(): SongInterface
{
return $this->song;
}
public function setAlbumArt(?string $albumArt): void
{
$this->albumArt = !empty($albumArt)
? $albumArt
: null;
if (null !== $this->albumArt) {
$this->stopPropagation();
}
}
public function getAlbumArt(): ?string
{
return $this->albumArt;
}
}
``` | /content/code_sandbox/backend/src/Event/Media/GetAlbumArt.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 175 |
```php
<?php
declare(strict_types=1);
namespace App\Event\Media;
use App\Media\MetadataInterface;
use Symfony\Contracts\EventDispatcher\Event;
final class WriteMetadata extends Event
{
public function __construct(
private readonly MetadataInterface $metadata,
private readonly string $path
) {
}
public function getMetadata(): ?MetadataInterface
{
return $this->metadata;
}
public function getPath(): string
{
return $this->path;
}
}
``` | /content/code_sandbox/backend/src/Event/Media/WriteMetadata.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 105 |
```php
<?php
declare(strict_types=1);
namespace App\Event\Media;
use App\Media\Metadata;
use App\Media\MetadataInterface;
use Symfony\Contracts\EventDispatcher\Event;
final class ReadMetadata extends Event
{
private ?MetadataInterface $metadata = null;
public function __construct(
private readonly string $path
) {
}
public function getPath(): string
{
return $this->path;
}
public function setMetadata(MetadataInterface $metadata): void
{
$this->metadata = $metadata;
}
public function getMetadata(): MetadataInterface
{
return $this->metadata ?? new Metadata();
}
}
``` | /content/code_sandbox/backend/src/Event/Media/ReadMetadata.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 142 |
```php
<?php
declare(strict_types=1);
namespace App\Event\Nginx;
use App\Entity\Station;
use Symfony\Contracts\EventDispatcher\Event;
final class WriteNginxConfiguration extends Event
{
private array $configLines = [];
public function __construct(
private readonly Station $station,
private readonly bool $writeToDisk = true
) {
}
public function getStation(): Station
{
return $this->station;
}
public function shouldWriteToDisk(): bool
{
return $this->writeToDisk;
}
/**
* Append one of more lines to the end of the configuration string.
*
* @param array $lines
*/
public function appendLines(array $lines): void
{
$this->configLines = array_merge($this->configLines, [''], $lines);
}
public function appendBlock(string $lines): void
{
$this->appendLines(explode("\n", $lines));
}
/**
* Prepend one or more lines to the front of the configuration string.
*
* @param array $lines
*/
public function prependLines(array $lines): void
{
$this->configLines = array_merge($lines, [''], $this->configLines);
}
/**
* Compile the configuration lines together and return the result.
*/
public function buildConfiguration(): string
{
return implode("\n", $this->configLines);
}
}
``` | /content/code_sandbox/backend/src/Event/Nginx/WriteNginxConfiguration.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 320 |
```php
<?php
declare(strict_types=1);
namespace App\Event\Radio;
use App\Entity\Station;
use App\Entity\StationBackendConfiguration;
use Symfony\Contracts\EventDispatcher\Event;
final class WriteLiquidsoapConfiguration extends Event
{
private array $configLines = [];
private StationBackendConfiguration $backendConfig;
public function __construct(
private readonly Station $station,
private readonly bool $forEditing = false,
private readonly bool $writeToDisk = true
) {
$this->backendConfig = $station->getBackendConfig();
}
public function getStation(): Station
{
return $this->station;
}
public function getBackendConfig(): StationBackendConfiguration
{
return $this->backendConfig;
}
public function isForEditing(): bool
{
return $this->forEditing;
}
public function shouldWriteToDisk(): bool
{
return $this->writeToDisk && !$this->forEditing;
}
/**
* Append one of more lines to the end of the configuration string.
*
* @param array $lines
*/
public function appendLines(array $lines): void
{
$this->configLines = array_merge($this->configLines, [''], $lines);
}
public function appendBlock(string $lines): void
{
$this->appendLines(explode("\n", $lines));
}
/**
* Prepend one or more lines to the front of the configuration string.
*
* @param array $lines
*/
public function prependLines(array $lines): void
{
$this->configLines = array_merge($lines, [''], $this->configLines);
}
/**
* Replace the line at the specified index with the specified string.
*
* @param int $index
* @param string $line
*/
public function replaceLine(int $index, string $line): void
{
$this->configLines[$index] = $line;
}
/**
* Compile the configuration lines together and return the result.
*/
public function buildConfiguration(): string
{
return implode("\n", $this->configLines);
}
}
``` | /content/code_sandbox/backend/src/Event/Radio/WriteLiquidsoapConfiguration.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 476 |
```php
<?php
declare(strict_types=1);
namespace App\Event\Radio;
use App\Entity\Station;
use App\Entity\StationRemote;
use App\Radio\Adapters;
use App\Radio\Frontend\AbstractFrontend;
use App\Radio\Remote\AbstractRemote;
use NowPlaying\Result\Result;
use Symfony\Contracts\EventDispatcher\Event;
use Traversable;
final class GenerateRawNowPlaying extends Event
{
private ?Result $result = null;
public function __construct(
private readonly Adapters $adapters,
private readonly Station $station,
private readonly bool $includeClients = false
) {
}
public function getStation(): Station
{
return $this->station;
}
public function getFrontend(): ?AbstractFrontend
{
return $this->adapters->getFrontendAdapter($this->station);
}
/**
* @return Traversable<StationRemote>
*/
public function getRemotes(): Traversable
{
return $this->station->getRemotes();
}
public function getRemoteAdapter(StationRemote $remote): AbstractRemote
{
return $this->adapters->getRemoteAdapter($remote);
}
public function includeClients(): bool
{
return $this->includeClients;
}
public function getResult(): Result
{
return $this->result ?? Result::blank();
}
public function setResult(Result $result): void
{
$this->result = $result;
}
}
``` | /content/code_sandbox/backend/src/Event/Radio/GenerateRawNowPlaying.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 322 |
```php
<?php
declare(strict_types=1);
namespace App\Event\Radio;
use App\Entity\Station;
use App\Entity\StationQueue;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Symfony\Contracts\EventDispatcher\Event;
final class BuildQueue extends Event
{
/** @var StationQueue[] */
private array $nextSongs = [];
private CarbonInterface $expectedCueTime;
private CarbonInterface $expectedPlayTime;
public function __construct(
private readonly Station $station,
?CarbonInterface $expectedCueTime = null,
?CarbonInterface $expectedPlayTime = null,
private readonly ?string $lastPlayedSongId = null,
private readonly bool $isInterrupting = false
) {
$this->expectedCueTime = $expectedCueTime ?? CarbonImmutable::now($station->getTimezoneObject());
$this->expectedPlayTime = $expectedPlayTime ?? CarbonImmutable::now($station->getTimezoneObject());
}
public function getStation(): Station
{
return $this->station;
}
public function getExpectedCueTime(): CarbonInterface
{
return $this->expectedCueTime;
}
public function getExpectedPlayTime(): CarbonInterface
{
return $this->expectedPlayTime;
}
public function getLastPlayedSongId(): ?string
{
return $this->lastPlayedSongId;
}
public function isInterrupting(): bool
{
return $this->isInterrupting;
}
/**
* @return StationQueue[]
*/
public function getNextSongs(): array
{
return $this->nextSongs;
}
/**
* @param StationQueue|StationQueue[]|null $nextSongs
* @return bool
*/
public function setNextSongs(StationQueue|array|null $nextSongs): bool
{
if (null === $nextSongs) {
return false;
}
if (!is_array($nextSongs)) {
if ($this->lastPlayedSongId === $nextSongs->getSongId()) {
return false;
}
$this->nextSongs = [$nextSongs];
} else {
$this->nextSongs = $nextSongs;
}
$this->stopPropagation();
return true;
}
public function __toString(): string
{
return !empty($this->nextSongs)
? implode(', ', array_map('strval', $this->nextSongs))
: 'No Song';
}
}
``` | /content/code_sandbox/backend/src/Event/Radio/BuildQueue.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 534 |
```php
<?php
declare(strict_types=1);
namespace App\Event\Radio;
use App\Entity\Station;
use App\Entity\StationMedia;
use App\Entity\StationPlaylist;
use App\Entity\StationQueue;
use App\Entity\StationRequest;
use RuntimeException;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Event triggered every time the next-playing song is preparing to be annotated for delivery to Liquidsoap.
*
* @package App\Event\Radio
*/
final class AnnotateNextSong extends Event
{
private ?string $songPath;
private ?string $protocol = null;
/** @var array Custom annotations that should be sent along with the AutoDJ response. */
private array $annotations = [];
public function __construct(
private readonly Station $station,
private readonly ?StationQueue $queue = null,
private readonly ?StationMedia $media = null,
private readonly ?StationPlaylist $playlist = null,
private readonly ?StationRequest $request = null,
private readonly bool $asAutoDj = false
) {
}
public function getQueue(): ?StationQueue
{
return $this->queue;
}
public function getStation(): Station
{
return $this->station;
}
public function getMedia(): ?StationMedia
{
return $this->media;
}
public function getPlaylist(): ?StationPlaylist
{
return $this->playlist;
}
public function getRequest(): ?StationRequest
{
return $this->request;
}
public function setAnnotations(array $annotations): void
{
$this->annotations = $annotations;
}
public function addAnnotations(array $annotations): void
{
$this->annotations = array_merge($this->annotations, $annotations);
}
public function setSongPath(string $songPath): void
{
$this->songPath = $songPath;
}
public function setProtocol(string $protocol): void
{
$this->protocol = $protocol;
}
public function isAsAutoDj(): bool
{
return $this->asAutoDj;
}
/**
* Compile the resulting annotations into one string for Liquidsoap to consume.
*/
public function buildAnnotations(): string
{
if (empty($this->songPath)) {
throw new RuntimeException('No valid path for song.');
}
$this->annotations = array_filter($this->annotations);
if (!empty($this->annotations)) {
$annotationsStr = [];
foreach ($this->annotations as $annotationKey => $annotationVal) {
$annotationsStr[] = $annotationKey . '="' . $annotationVal . '"';
}
$annotateParts = [
'annotate',
implode(',', $annotationsStr),
$this->songPath,
];
if (null !== $this->protocol) {
array_unshift($annotateParts, $this->protocol);
}
return implode(':', $annotateParts);
}
return $this->songPath;
}
public static function fromStationMedia(
Station $station,
StationMedia $media,
bool $asAutoDj = false
): self {
return new self(
station: $station,
media: $media,
asAutoDj: $asAutoDj
);
}
public static function fromStationQueue(
StationQueue $queue,
bool $asAutoDj = false
): self {
return new self(
station: $queue->getStation(),
queue: $queue,
media: $queue->getMedia(),
playlist: $queue->getPlaylist(),
request: $queue->getRequest(),
asAutoDj: $asAutoDj
);
}
}
``` | /content/code_sandbox/backend/src/Event/Radio/AnnotateNextSong.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 800 |
```php
<?php
declare(strict_types=1);
namespace App\Assets;
use Intervention\Image\Interfaces\ImageInterface;
use Psr\Http\Message\UriInterface;
interface CustomAssetInterface
{
public const string UPLOADS_URL_PREFIX = '/uploads';
public function getPath(): string;
public function isUploaded(): bool;
public function getUrl(): string;
public function getUri(): UriInterface;
public function upload(ImageInterface $image, string $mimeType): void;
public function delete(): void;
}
``` | /content/code_sandbox/backend/src/Assets/CustomAssetInterface.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 104 |
```php
<?php
declare(strict_types=1);
namespace App\Assets;
use Intervention\Image\Interfaces\ImageInterface;
use Symfony\Component\Filesystem\Filesystem;
final class BrowserIconCustomAsset extends AbstractCustomAsset
{
public const array ICON_SIZES = [
16, // Favicon
32, // Favicon
36, // Android
48, // Android
57, // Apple
60, // Apple
72, // Android/Apple
76, // Apple
96, // Android/Favicon
114, // Apple
120, // Apple
144, // Android/Apple/MS
152, // Apple
180, // Apple
192, // Android/Apple
];
protected function getPattern(): string
{
return 'browser_icon/original%s.png';
}
protected function getDefaultUrl(): string
{
$assetUrl = $this->environment->getAssetUrl();
return $assetUrl . '/icons/' . $this->environment->getAppEnvironmentEnum()->value . '/original.png';
}
public function upload(ImageInterface $image, string $mimeType): void
{
$this->delete();
$uploadsDir = $this->environment->getUploadsDirectory() . '/browser_icon';
$this->ensureDirectoryExists($uploadsDir);
$newImage = clone $image;
$newImage->resize(256, 256);
$newImage->toPng()->save($uploadsDir . '/original.png');
foreach (self::ICON_SIZES as $iconSize) {
$newImage = clone $image;
$newImage->resize($iconSize, $iconSize);
$newImage->toPng()->save($uploadsDir . '/' . $iconSize . '.png');
}
}
public function delete(): void
{
$uploadsDir = $this->environment->getUploadsDirectory() . '/browser_icon';
(new Filesystem())->remove($uploadsDir);
}
public function getUrlForSize(int $size): string
{
$assetUrl = $this->environment->getAssetUrl();
$uploadsDir = $this->environment->getUploadsDirectory();
$iconPath = $uploadsDir . '/browser_icon/' . $size . '.png';
if (is_file($iconPath)) {
$mtime = filemtime($iconPath);
return $assetUrl . '/uploads/browser_icon/' . $size . '.' . $mtime . '.png';
}
return $assetUrl . '/icons/' . $this->environment->getAppEnvironmentEnum()->value . '/' . $size . '.png';
}
}
``` | /content/code_sandbox/backend/src/Assets/BrowserIconCustomAsset.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 585 |
```php
<?php
declare(strict_types=1);
namespace App\Assets;
use App\Container\EnvironmentAwareTrait;
use App\Entity\Station;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\UriInterface;
use Symfony\Component\Filesystem\Filesystem;
abstract class AbstractCustomAsset implements CustomAssetInterface
{
use EnvironmentAwareTrait;
public function __construct(
protected readonly ?Station $station = null
) {
}
abstract protected function getPattern(): string;
abstract protected function getDefaultUrl(): string;
public function getPath(): string
{
$pattern = sprintf($this->getPattern(), '');
return $this->getBasePath() . '/' . $pattern;
}
protected function getBasePath(): string
{
$basePath = $this->environment->getUploadsDirectory();
if (null !== $this->station) {
$basePath .= '/' . $this->station->getShortName();
}
return $basePath;
}
public function getUrl(): string
{
$path = $this->getPath();
if (is_file($path)) {
$pattern = $this->getPattern();
$mtime = filemtime($path);
return $this->getBaseUrl() . '/' . sprintf(
$pattern,
'.' . $mtime
);
}
return $this->getDefaultUrl();
}
protected function getBaseUrl(): string
{
$baseUrl = $this->environment->getAssetUrl() . self::UPLOADS_URL_PREFIX;
if (null !== $this->station) {
$baseUrl .= '/' . $this->station->getShortName();
}
return $baseUrl;
}
public function getUri(): UriInterface
{
return new Uri($this->getUrl());
}
public function isUploaded(): bool
{
return is_file($this->getPath());
}
public function delete(): void
{
@unlink($this->getPath());
}
protected function ensureDirectoryExists(string $path): void
{
(new Filesystem())->mkdir($path);
}
}
``` | /content/code_sandbox/backend/src/Assets/AbstractCustomAsset.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 446 |
```php
<?php
declare(strict_types=1);
namespace App\Assets;
use Intervention\Image\Interfaces\EncoderInterface;
abstract class AbstractMultiPatternCustomAsset extends AbstractCustomAsset
{
/**
* @return array<string, array{string, EncoderInterface}>
*/
abstract protected function getPatterns(): array;
protected function getPattern(): string
{
return $this->getPatterns()['default'][0];
}
protected function getPathForPattern(string $pattern): string
{
$pattern = sprintf($pattern, '');
return $this->getBasePath() . '/' . $pattern;
}
public function getPath(): string
{
$patterns = $this->getPatterns();
foreach ($patterns as [$pattern, $encoder]) {
$path = $this->getPathForPattern($pattern);
if (is_file($path)) {
return $path;
}
}
return $this->getPathForPattern($patterns['default'][0]);
}
public function delete(): void
{
foreach ($this->getPatterns() as [$pattern, $encoder]) {
@unlink($this->getPathForPattern($pattern));
}
}
public function getUrl(): string
{
foreach ($this->getPatterns() as [$pattern, $encoder]) {
$path = $this->getPathForPattern($pattern);
if (is_file($path)) {
$mtime = filemtime($path);
return $this->getBaseUrl() . '/' . sprintf(
$pattern,
'.' . $mtime
);
}
}
return $this->getDefaultUrl();
}
}
``` | /content/code_sandbox/backend/src/Assets/AbstractMultiPatternCustomAsset.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 344 |
```php
<?php
declare(strict_types=1);
namespace App\Assets;
use Intervention\Image\Encoders\JpegEncoder;
use Intervention\Image\Encoders\PngEncoder;
use Intervention\Image\Encoders\WebpEncoder;
use Intervention\Image\Interfaces\ImageInterface;
final class AlbumArtCustomAsset extends AbstractMultiPatternCustomAsset
{
protected function getPatterns(): array
{
return [
'default' => [
'album_art%s.jpg',
new JpegEncoder(90),
],
'image/png' => [
'album_art%s.png',
new PngEncoder(),
],
'image/webp' => [
'album_art%s.webp',
new WebpEncoder(90),
],
];
}
protected function getDefaultUrl(): string
{
return $this->environment->getAssetUrl() . '/img/generic_song.jpg';
}
public function upload(ImageInterface $image, string $mimeType): void
{
$newImage = clone $image;
$newImage->resizeDown(1500, 1500);
$this->delete();
$patterns = $this->getPatterns();
[$pattern, $encoder] = $patterns[$mimeType] ?? $patterns['default'];
$destPath = $this->getPathForPattern($pattern);
$this->ensureDirectoryExists(dirname($destPath));
$newImage->encode($encoder)->save($destPath);
}
}
``` | /content/code_sandbox/backend/src/Assets/AlbumArtCustomAsset.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 308 |
```php
<?php
declare(strict_types=1);
namespace App\Assets;
use App\Entity\Station;
use App\Environment;
enum AssetTypes: string
{
case AlbumArt = 'album_art';
case Background = 'background';
case BrowserIcon = 'browser_icon';
public function createObject(
Environment $environment,
?Station $station = null
): CustomAssetInterface {
$instance = match ($this) {
self::AlbumArt => new AlbumArtCustomAsset($station),
self::Background => new BackgroundCustomAsset($station),
self::BrowserIcon => new BrowserIconCustomAsset($station),
};
$instance->setEnvironment($environment);
return $instance;
}
}
``` | /content/code_sandbox/backend/src/Assets/AssetTypes.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 151 |
```php
<?php
declare(strict_types=1);
namespace App\Assets;
use Intervention\Image\Encoders\JpegEncoder;
use Intervention\Image\Encoders\PngEncoder;
use Intervention\Image\Encoders\WebpEncoder;
use Intervention\Image\Interfaces\ImageInterface;
final class BackgroundCustomAsset extends AbstractMultiPatternCustomAsset
{
protected function getPatterns(): array
{
return [
'default' => [
'background%s.jpg',
new JpegEncoder(90),
],
'image/png' => [
'background%s.png',
new PngEncoder(),
],
'image/webp' => [
'background%s.webp',
new WebpEncoder(90),
],
];
}
protected function getDefaultUrl(): string
{
return $this->environment->getAssetUrl() . '/img/hexbg.png';
}
public function upload(ImageInterface $image, string $mimeType): void
{
$newImage = clone $image;
$newImage->resizeDown(3264, 2160);
$this->delete();
$patterns = $this->getPatterns();
[$pattern, $encoder] = $patterns[$mimeType] ?? $patterns['default'];
$destPath = $this->getPathForPattern($pattern);
$this->ensureDirectoryExists(dirname($destPath));
$newImage->encode($encoder)->save($destPath);
}
}
``` | /content/code_sandbox/backend/src/Assets/BackgroundCustomAsset.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 304 |
```php
<?php
declare(strict_types=1);
namespace App\Translations;
use App\Enums\SupportedLocales;
use Gettext\Generator\Generator;
use Gettext\Translation;
use Gettext\Translations;
final class JsonGenerator extends Generator
{
public function __construct(
private readonly SupportedLocales $locale
) {
}
public function generateString(Translations $translations): string
{
$array = $this->generateArray($translations);
return json_encode($array, JSON_PRETTY_PRINT) ?: '';
}
public function generateArray(Translations $translations): array
{
$pluralForm = $translations->getHeaders()->getPluralForm();
$pluralSize = is_array($pluralForm) ? (int)($pluralForm[0] - 1) : null;
$messages = [];
/** @var Translation $translation */
foreach ($translations as $translation) {
if (!$translation->getTranslation() || $translation->isDisabled()) {
continue;
}
$original = $translation->getOriginal();
if (self::hasPluralTranslations($translation)) {
$messages[$original] = $translation->getPluralTranslations($pluralSize);
array_unshift($messages[$original], $translation->getTranslation());
} else {
$messages[$original] = $translation->getTranslation();
}
}
return [
$this->locale->getLocaleWithoutEncoding() => $messages,
];
}
private static function hasPluralTranslations(Translation $translation): bool
{
return implode('', $translation->getPluralTranslations()) !== '';
}
}
``` | /content/code_sandbox/backend/src/Translations/JsonGenerator.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 347 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Http\ServerRequest;
use App\RateLimit;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Inject core services into the request object for use further down the stack.
*/
final class InjectRateLimit extends AbstractMiddleware
{
public function __construct(
private readonly RateLimit $rateLimit
) {
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$request = $request->withAttribute(ServerRequest::ATTR_RATE_LIMIT, $this->rateLimit);
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/InjectRateLimit.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 145 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Exception\NotFoundException;
use App\Http\ServerRequest;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Require that the user be logged in to view this page.
*/
final class RequireStation extends AbstractMiddleware
{
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
try {
$request->getStation();
} catch (Exception) {
throw NotFoundException::station();
}
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/RequireStation.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 128 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Enums\PermissionInterface;
use App\Exception\Http\PermissionDeniedException;
use App\Http\ServerRequest;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Get the current user entity object and assign it into the request if it exists.
*/
final class Permissions extends AbstractMiddleware
{
public function __construct(
private readonly string|PermissionInterface $action,
private readonly bool $useStation = false
) {
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($this->useStation) {
$stationId = $request->getStation()->getId();
} else {
$stationId = null;
}
try {
$user = $request->getUser();
} catch (Exception) {
throw PermissionDeniedException::create($request);
}
$acl = $request->getAcl();
if (!$acl->userAllowed($user, $this->action, $stationId)) {
throw PermissionDeniedException::create($request);
}
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/Permissions.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\Middleware;
use App\Entity\Repository\PodcastRepository;
use App\Exception\NotFoundException;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Require that the podcast has a published episode for public access
*/
final class RequirePublishedPodcastEpisodeMiddleware extends AbstractMiddleware
{
public function __construct(
private readonly PodcastRepository $podcastRepository
) {
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$station = $request->getStation();
$publishedPodcastIds = $this->podcastRepository->getPodcastIdsWithPublishedEpisodes($station);
$podcast = $request->getPodcast();
if (!$podcast->isEnabled() || !in_array($podcast->getIdRequired(), $publishedPodcastIds, true)) {
throw NotFoundException::podcast();
}
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/RequirePublishedPodcastEpisodeMiddleware.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 218 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Http\ServerRequest;
use App\View;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Inject the view object into the request and prepare it for rendering templates.
*/
final class EnableView extends AbstractMiddleware
{
public function __construct(
private readonly View $view
) {
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$view = $this->view->withRequest($request);
$request = $request->withAttribute(ServerRequest::ATTR_VIEW, $view);
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/EnableView.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\Middleware;
use App\Entity\Podcast;
use App\Entity\Repository\PodcastRepository;
use App\Exception\NotFoundException;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;
/**
* Retrieve the podcast specified in the request parameters.
*/
final class GetAndRequirePodcast extends AbstractMiddleware
{
public function __construct(
private readonly PodcastRepository $podcastRepo
) {
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$routeArgs = RouteContext::fromRequest($request)->getRoute()?->getArguments();
$id = $routeArgs['podcast_id'] ?? $routeArgs['id'] ?? null;
if (empty($id)) {
throw NotFoundException::podcast();
}
$record = $this->podcastRepo->fetchPodcastForStation(
$request->getStation(),
$id
);
if (!($record instanceof Podcast)) {
throw NotFoundException::podcast();
}
$request = $request->withAttribute(ServerRequest::ATTR_PODCAST, $record);
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/GetAndRequirePodcast.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 270 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\AppFactory;
use App\Container\SettingsAwareTrait;
use App\Http\ServerRequest;
use App\Utilities\Types;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\App;
/**
* Remove trailing slash from all URLs when routing.
* @phpstan-import-type AppWithContainer from AppFactory
*/
final class EnforceSecurity extends AbstractMiddleware
{
use SettingsAwareTrait;
private ResponseFactoryInterface $responseFactory;
/**
* @param AppWithContainer $app
*/
public function __construct(
App $app
) {
$this->responseFactory = $app->getResponseFactory();
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$alwaysUseSsl = $this->readSettings()->getAlwaysUseSsl();
// Requests through the internal port (:6010) have this server param set.
$isInternal = Types::bool($request->getServerParam('IS_INTERNAL'), false, true);
$addHstsHeader = false;
if ('https' === $request->getUri()->getScheme()) {
$addHstsHeader = true;
} elseif ($alwaysUseSsl && !$isInternal) {
return $this->responseFactory->createResponse(307)
->withHeader('Location', (string)$request->getUri()->withScheme('https'));
}
$response = $handler->handle($request);
if ($addHstsHeader) {
$response = $response->withHeader('Strict-Transport-Security', 'max-age=3600');
}
// Opt out of FLoC
$permissionsPolicies = [
'autoplay=*', // Explicitly allow autoplay
'fullscreen=*', // Explicitly allow fullscreen
'interest-cohort=()', // Disable FLoC tracking
];
$response = $response->withHeader('Permissions-Policy', implode(', ', $permissionsPolicies));
// Deny crawling on any pages that don't explicitly allow it.
$robotsHeader = $response->getHeaderLine('X-Robots-Tag');
if ('' === $robotsHeader) {
$response = $response->withHeader('X-Robots-Tag', 'noindex, nofollow');
}
// Set frame-deny header before next middleware, so it can be overwritten.
$frameOptions = $response->getHeaderLine('X-Frame-Options');
if ('*' === $frameOptions) {
$response = $response->withoutHeader('X-Frame-Options');
} else {
$response = $response->withHeader('X-Frame-Options', 'DENY');
}
return $response;
}
}
``` | /content/code_sandbox/backend/src/Middleware/EnforceSecurity.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 610 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Entity\Repository\StationRepository;
use App\Entity\Station;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;
/**
* Retrieve the station specified in the request parameters.
*/
final class GetStation extends AbstractMiddleware
{
public function __construct(
private readonly StationRepository $stationRepo
) {
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$routeArgs = RouteContext::fromRequest($request)->getRoute()?->getArguments();
$id = $routeArgs['station_id'] ?? null;
if (!empty($id)) {
$record = $this->stationRepo->findByIdentifier($id);
if ($record instanceof Station) {
$request = $request->withAttribute(ServerRequest::ATTR_STATION, $record);
}
}
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/GetStation.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 219 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Http\ServerRequest;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Remove trailing slash from all URLs when routing.
*/
final class RemoveSlashes extends AbstractMiddleware
{
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$uri = $request->getUri();
$path = $uri->getPath();
if ($path !== '/' && str_ends_with($path, '/')) {
// permanently redirect paths with a trailing slash
// to their non-trailing counterpart
$uri = $uri->withPath(substr($path, 0, -1));
/** @var ResponseInterface $response */
$response = new Response(308);
return $response->withHeader('Location', (string)$uri);
}
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/RemoveSlashes.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 208 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Http\ServerRequest;
use App\Utilities\Types;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Apply the "X-Forwarded-*" headers if they exist.
*/
final class ApplyXForwarded extends AbstractMiddleware
{
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$uri = $request->getUri();
$hasXForwardedHeader = false;
if ($request->hasHeader('X-Forwarded-For')) {
$hasXForwardedHeader = true;
}
if ($request->hasHeader('X-Forwarded-Proto')) {
$hasXForwardedHeader = true;
$xfProto = Types::stringOrNull($request->getHeaderLine('X-Forwarded-Proto'), true);
if (null !== $xfProto) {
$uri = $uri->withScheme($xfProto);
}
}
if ($request->hasHeader('X-Forwarded-Host')) {
$hasXForwardedHeader = true;
$xfHost = Types::stringOrNull($request->getHeaderLine('X-Forwarded-Host'), true);
if (null !== $xfHost) {
$uri = $uri->withHost($xfHost);
}
}
if ($request->hasHeader('X-Forwarded-Port')) {
$xfPort = Types::intOrNull($request->getHeaderLine('X-Forwarded-Port'));
if (null !== $xfPort) {
$uri = $uri->withPort($xfPort);
}
} elseif ($hasXForwardedHeader) {
// A vast majority of reverse proxies will be proxying to the default web ports, so
// if *any* X-Forwarded-* value is set, unset the port in the request.
$uri = $uri->withPort(null);
}
$request = $request->withUri($uri);
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/ApplyXForwarded.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 451 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Enums\StationFeatures;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class StationSupportsFeature extends AbstractMiddleware
{
public function __construct(
private readonly StationFeatures $feature
) {
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->feature->assertSupportedForStation($request->getStation());
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/StationSupportsFeature.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 124 |
```php
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Http\RouterInterface;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Set the current route on the URL object, and inject the URL object into the router.
*/
final class InjectRouter extends AbstractMiddleware
{
public function __construct(
private readonly RouterInterface $router
) {
}
public function __invoke(ServerRequest $request, RequestHandlerInterface $handler): ResponseInterface
{
$router = $this->router->withRequest($request);
$request = $request->withAttribute(ServerRequest::ATTR_ROUTER, $router);
return $handler->handle($request);
}
}
``` | /content/code_sandbox/backend/src/Middleware/InjectRouter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 159 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.