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\Controller\Api\Stations\Podcasts\Art;
use App\Container\EntityManagerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Status;
use App\Entity\Repository\PodcastRepository;
use App\Http\Response;
use App\Http\ServerRequest;
use App\OpenApi;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface;
#[OA\Delete(
path: '/station/{station_id}/podcast/{podcast_id}/art',
operationId: 'deletePodcastArt',
description: 'Removes the album art for a podcast.',
security: OpenApi::API_KEY_SECURITY,
tags: ['Stations: Podcasts'],
parameters: [
new OA\Parameter(ref: OpenApi::REF_STATION_ID_REQUIRED),
new OA\Parameter(
name: 'podcast_id',
description: 'Podcast ID',
in: 'path',
required: true,
schema: new OA\Schema(type: 'string')
),
],
responses: [
new OA\Response(ref: OpenApi::REF_RESPONSE_SUCCESS, response: 200),
new OA\Response(ref: OpenApi::REF_RESPONSE_ACCESS_DENIED, response: 403),
new OA\Response(ref: OpenApi::REF_RESPONSE_NOT_FOUND, response: 404),
new OA\Response(ref: OpenApi::REF_RESPONSE_GENERIC_ERROR, response: 500),
]
)]
final class DeleteArtAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
public function __construct(
private readonly PodcastRepository $podcastRepo,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$podcast = $request->getPodcast();
$this->podcastRepo->removePodcastArt($podcast);
$this->em->persist($podcast);
$this->em->flush();
return $response->withJson(Status::deleted());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Podcasts/Art/DeleteArtAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 430 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports;
use App\Container\EntityManagerAwareTrait;
use App\Controller\Api\Traits\CanSearchResults;
use App\Controller\Api\Traits\CanSortResults;
use App\Entity\Api\Status;
use App\Entity\Repository\StationRequestRepository;
use App\Entity\StationRequest;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Paginator;
use App\Utilities\Types;
use Doctrine\Common\Collections\Order;
use Doctrine\ORM\AbstractQuery;
use Psr\Http\Message\ResponseInterface;
final class RequestsController
{
use EntityManagerAwareTrait;
use CanSortResults;
use CanSearchResults;
public function __construct(
private readonly StationRequestRepository $requestRepo
) {
}
public function listAction(
ServerRequest $request,
Response $response
): ResponseInterface {
$station = $request->getStation();
$qb = $this->em->createQueryBuilder()
->select('sr, sm')
->from(StationRequest::class, 'sr')
->join('sr.track', 'sm')
->where('sr.station = :station')
->setParameter('station', $station);
$type = Types::string($request->getParam('type', 'recent'));
$qb = match ($type) {
'history' => $qb->andWhere('sr.played_at != 0'),
default => $qb->andWhere('sr.played_at = 0'),
};
$qb = $this->sortQueryBuilder(
$request,
$qb,
[
'name' => 'sm.title',
'title' => 'sm.title',
'artist' => 'sm.artist',
'album' => 'sm.album',
'genre' => 'sm.genre',
],
'sr.timestamp',
Order::Descending
);
$qb = $this->searchQueryBuilder(
$request,
$qb,
[
'sm.title',
'sm.artist',
'sm.album',
]
);
$query = $qb->getQuery()
->setHydrationMode(AbstractQuery::HYDRATE_ARRAY);
$paginator = Paginator::fromQuery($query, $request);
$router = $request->getRouter();
$paginator->setPostprocessor(function ($row) use ($router) {
$row['links'] = [];
if (0 === $row['played_at']) {
$row['links']['delete'] = $router->fromHere(
'api:stations:reports:requests:delete',
['request_id' => $row['id']]
);
}
return $row;
});
return $paginator->write($response);
}
public function deleteAction(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $requestId */
$requestId = $params['request_id'];
$station = $request->getStation();
$media = $this->requestRepo->getPendingRequest($requestId, $station);
if ($media instanceof StationRequest) {
$this->em->remove($media);
$this->em->flush();
}
return $response->withJson(Status::deleted());
}
public function clearAction(
ServerRequest $request,
Response $response
): ResponseInterface {
$station = $request->getStation();
$this->requestRepo->clearPendingRequests($station);
return $response->withJson(Status::deleted());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/RequestsController.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 752 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports\Overview;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class ByClient extends AbstractReportAction
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
// Get current analytics level.
if (!$this->isAllAnalyticsEnabled()) {
return $response->withStatus(400)
->withJson(new Status(false, 'Reporting is restricted due to system analytics level.'));
}
$station = $request->getStation();
$stationTz = $station->getTimezoneObject();
$dateRange = $this->getDateRange($request, $stationTz);
$statsRaw = $this->em->getConnection()->fetchAllAssociative(
<<<'SQL'
SELECT l.client_raw,
COUNT(l.listener_hash) AS listeners,
SUM(l.connected_seconds) AS connected_seconds
FROM (
SELECT
CASE
WHEN device_is_bot = 1 THEN 'bot'
WHEN device_is_mobile = 1 THEN 'mobile'
WHEN device_is_browser = 1 THEN 'desktop'
ELSE 'non_browser'
END AS client_raw,
SUM(timestamp_end - timestamp_start) AS connected_seconds,
listener_hash
FROM listener
WHERE station_id = :station_id
AND timestamp_end >= :start
AND timestamp_start <= :end
GROUP BY listener_hash
) AS l
GROUP BY l.client_raw
SQL,
[
'station_id' => $station->getIdRequired(),
'start' => $dateRange->getStartTimestamp(),
'end' => $dateRange->getEndTimestamp(),
]
);
$clientTypes = [
'bot' => __('Bot/Crawler'),
'mobile' => __('Mobile Device'),
'desktop' => __('Desktop Browser'),
'non_browser' => __('Non-Browser'),
];
$listenersByClient = [];
$connectedTimeByClient = [];
$stats = [];
foreach ($statsRaw as $row) {
$row['client'] = $clientTypes[$row['client_raw']];
$stats[] = $row;
$listenersByClient[$row['client']] = $row['listeners'];
$connectedTimeByClient[$row['client']] = $row['connected_seconds'];
}
return $response->withJson([
'all' => $stats,
'top_listeners' => $this->buildChart($listenersByClient, __('Listeners'), null),
'top_connected_time' => $this->buildChart($connectedTimeByClient, __('Connected Seconds'), null),
]);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/Overview/ByClient.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 593 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports;
use App\Container\EntityManagerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Song;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Service\MusicBrainz;
use Carbon\CarbonImmutable;
use Psr\Http\Message\ResponseInterface;
use Throwable;
/**
* Produce a report in SoundExchange (the US webcaster licensing agency) format.
*/
final class SoundExchangeAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
public function __construct(
private readonly MusicBrainz $musicBrainz
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
$tzObject = $station->getTimezoneObject();
$defaultStartDate = CarbonImmutable::parse('first day of last month', $tzObject)
->format('Y-m-d');
$defaultEndDate = CarbonImmutable::parse('last day of last month', $tzObject)
->format('Y-m-d');
$data = $request->getParams();
$data['start_date'] ??= $defaultStartDate;
$data['end_date'] ??= $defaultEndDate;
$startDate = CarbonImmutable::parse($data['start_date'] . ' 00:00:00', $tzObject)
->shiftTimezone($tzObject);
$endDate = CarbonImmutable::parse($data['end_date'] . ' 23:59:59', $tzObject)
->shiftTimezone($tzObject);
$fetchIsrc = 'true' === ($data['fetch_isrc'] ?? 'false');
$export = [
[
'NAME_OF_SERVICE',
'TRANSMISSION_CATEGORY',
'FEATURED_ARTIST',
'SOUND_RECORDING_TITLE',
'ISRC',
'ALBUM_TITLE',
'MARKETING_LABEL',
'ACTUAL_TOTAL_PERFORMANCES',
],
];
$allMedia = $this->em->createQuery(
<<<'DQL'
SELECT sm, spm, sp, smcf
FROM App\Entity\StationMedia sm
LEFT JOIN sm.custom_fields smcf
LEFT JOIN sm.playlists spm
LEFT JOIN spm.playlist sp
WHERE sm.storage_location = :storageLocation
AND sp.station IS NULL OR sp.station = :station
DQL
)->setParameter('station', $station)
->setParameter('storageLocation', $station->getMediaStorageLocation())
->getArrayResult();
$mediaById = array_column($allMedia, null, 'id');
$historyRows = $this->em->createQuery(
<<<'DQL'
SELECT sh.song_id AS song_id, sh.text, sh.artist, sh.title, sh.media_id, COUNT(sh.id) AS plays,
SUM(sh.unique_listeners) AS unique_listeners
FROM App\Entity\SongHistory sh
WHERE sh.station = :station
AND sh.timestamp_start <= :time_end
AND sh.timestamp_end >= :time_start
GROUP BY sh.song_id
DQL
)->setParameter('station', $station)
->setParameter('time_start', $startDate->getTimestamp())
->setParameter('time_end', $endDate->getTimestamp())
->getArrayResult();
// TODO: Fix this (not all song rows have a media_id)
$historyRowsById = array_column($historyRows, null, 'media_id');
// Remove any reference to the "Stream Offline" song.
$offlineSongHash = Song::OFFLINE_SONG_ID;
unset($historyRowsById[$offlineSongHash]);
// Assemble report items
$stationName = $station->getName();
$setIsrcQuery = $this->em->createQuery(
<<<'DQL'
UPDATE App\Entity\StationMedia sm
SET sm.isrc = :isrc
WHERE sm.id = :media_id
DQL
);
foreach ($historyRowsById as $songId => $historyRow) {
$songRow = $mediaById[$songId] ?? $historyRow;
// Try to find the ISRC if it's not already listed.
if ($fetchIsrc && empty($songRow['isrc'])) {
$isrc = $this->findISRC($songRow);
$songRow['isrc'] = $isrc;
if (null !== $isrc && isset($songRow['media_id'])) {
$setIsrcQuery->setParameter('isrc', $isrc)
->setParameter('media_id', $songRow['media_id'])
->execute();
}
}
$export[] = [
$stationName,
'A',
$songRow['artist'] ?? '',
$songRow['title'] ?? '',
$songRow['isrc'] ?? '',
$songRow['album'] ?? '',
'',
$historyRow['unique_listeners'],
];
}
// Assemble export into SoundExchange format
$exportTxtRaw = [];
foreach ($export as $exportRow) {
foreach ($exportRow as $i => $exportCol) {
if (!is_numeric($exportCol)) {
$exportRow[$i] = '^' . str_replace(['^', '|'], ['', ''], strtoupper($exportCol)) . '^';
}
}
$exportTxtRaw[] = implode('|', $exportRow);
}
$exportTxt = implode("\n", $exportTxtRaw);
// Example: WABC01012009-31012009_A.txt
$exportFilename = strtoupper($station->getShortName())
. $startDate->format('dmY') . '-'
. $endDate->format('dmY') . '_A.txt';
return $response->renderStringAsFile($exportTxt, 'text/plain', $exportFilename);
}
private function findISRC(array $songRow): ?string
{
$song = Song::createFromArray($songRow);
try {
foreach ($this->musicBrainz->findRecordingsForSong($song, 'isrcs') as $recording) {
if (!empty($recording['isrcs'])) {
return $recording['isrcs'][0];
}
}
return null;
} catch (Throwable) {
return null;
}
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/SoundExchangeAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,381 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports\Overview;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class ByBrowser extends AbstractReportAction
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
// Get current analytics level.
if (!$this->isAllAnalyticsEnabled()) {
return $response->withStatus(400)
->withJson(new Status(false, 'Reporting is restricted due to system analytics level.'));
}
$station = $request->getStation();
$stationTz = $station->getTimezoneObject();
$dateRange = $this->getDateRange($request, $stationTz);
$stats = $this->em->getConnection()->fetchAllAssociative(
<<<'SQL'
SELECT device_browser_family AS browser,
COUNT(l.listener_hash) AS listeners,
SUM(l.connected_seconds) AS connected_seconds
FROM (
SELECT device_browser_family,
SUM(timestamp_end - timestamp_start) AS connected_seconds,
listener_hash
FROM listener
WHERE station_id = :station_id
AND device_browser_family IS NOT NULL
AND timestamp_end >= :start
AND timestamp_start <= :end
AND device_is_browser = 1
GROUP BY listener_hash
) AS l
GROUP BY l.device_browser_family
SQL,
[
'station_id' => $station->getIdRequired(),
'start' => $dateRange->getStartTimestamp(),
'end' => $dateRange->getEndTimestamp(),
]
);
$listenersByBrowser = array_column($stats, 'listeners', 'browser');
$connectedTimeByBrowser = array_column($stats, 'connected_seconds', 'browser');
return $response->withJson([
'all' => $stats,
'top_listeners' => $this->buildChart($listenersByBrowser, __('Listeners')),
'top_connected_time' => $this->buildChart($connectedTimeByBrowser, __('Connected Seconds')),
]);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/Overview/ByBrowser.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 462 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports\Overview;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Utilities\Types;
use Psr\Http\Message\ResponseInterface;
final class ByListeningTime extends AbstractReportAction
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
// Get current analytics level.
if (!$this->isAnalyticsEnabled()) {
return $response->withStatus(400)
->withJson(new Status(false, 'Reporting is restricted due to system analytics level.'));
}
$station = $request->getStation();
$stationTz = $station->getTimezoneObject();
$dateRange = $this->getDateRange($request, $stationTz);
$statsRaw = $this->em->getConnection()->fetchAllAssociative(
<<<'SQL'
SELECT SUM(timestamp_end - timestamp_start) AS connected_seconds, listener_hash
FROM listener
WHERE station_id = :station_id
AND timestamp_end >= :start
AND timestamp_start <= :end
GROUP BY listener_hash
SQL,
[
'station_id' => $station->getIdRequired(),
'start' => $dateRange->getStartTimestamp(),
'end' => $dateRange->getEndTimestamp(),
]
);
$ranges = [
[30, __('Less than Thirty Seconds')],
[60, __('Thirty Seconds to One Minute')],
[300, __('One Minute to Five Minutes')],
[600, __('Five Minutes to Ten Minutes')],
[1800, __('Ten Minutes to Thirty Minutes')],
[3600, __('Thirty Minutes to One Hour')],
[7200, __('One Hour to Two Hours')],
[PHP_INT_MAX, __('More than Two Hours')],
];
$statsByRange = [];
foreach ($ranges as [$max, $label]) {
$statsByRange[$label] = 0;
}
foreach ($statsRaw as $row) {
$listenerTime = Types::int($row['connected_seconds']);
foreach ($ranges as [$max, $label]) {
if ($listenerTime <= $max) {
$statsByRange[$label]++;
break;
}
}
}
$stats = [];
foreach ($statsByRange as $key => $row) {
$stats[] = [
'label' => $key,
'value' => $row,
];
}
return $response->withJson([
'all' => $stats,
'chart' => $this->buildChart(
array_filter($statsByRange),
__('Listeners'),
null
),
]);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/Overview/ByListeningTime.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 588 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports\Overview;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Intl\Countries;
final class ByCountry extends AbstractReportAction
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
// Get current analytics level.
if (!$this->isAllAnalyticsEnabled()) {
return $response->withStatus(400)
->withJson(new Status(false, 'Reporting is restricted due to system analytics level.'));
}
$station = $request->getStation();
$stationTz = $station->getTimezoneObject();
$dateRange = $this->getDateRange($request, $stationTz);
$statsRaw = $this->em->getConnection()->fetchAllAssociative(
<<<'SQL'
SELECT l.location_country AS country_code,
COUNT(l.listener_hash) AS listeners,
SUM(l.connected_seconds) AS connected_seconds
FROM (
SELECT location_country, SUM(timestamp_end - timestamp_start) AS connected_seconds, listener_hash
FROM listener
WHERE station_id = :station_id
AND location_country IS NOT NULL
AND timestamp_end >= :start
AND timestamp_start <= :end
GROUP BY listener_hash
) AS l
GROUP BY l.location_country
SQL,
[
'station_id' => $station->getIdRequired(),
'start' => $dateRange->getStartTimestamp(),
'end' => $dateRange->getEndTimestamp(),
]
);
$countryNames = Countries::getNames($request->getLocale()->getLocaleWithoutEncoding());
$listenersByCountry = [];
$connectedTimeByCountry = [];
$stats = [];
foreach ($statsRaw as $stat) {
if (empty($stat['country_code'])) {
continue;
}
$stat['country'] = $countryNames[$stat['country_code']];
$stats[] = $stat;
$listenersByCountry[$stat['country']] = $stat['listeners'];
$connectedTimeByCountry[$stat['country']] = $stat['connected_seconds'];
}
return $response->withJson([
'all' => $stats,
'top_listeners' => $this->buildChart($listenersByCountry, __('Listeners')),
'top_connected_time' => $this->buildChart($connectedTimeByCountry, __('Connected Seconds')),
]);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/Overview/ByCountry.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 543 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports\Overview;
use App\Entity\Api\Status;
use App\Entity\Enums\AnalyticsIntervals;
use App\Entity\Repository\AnalyticsRepository;
use App\Http\Response;
use App\Http\ServerRequest;
use Carbon\CarbonImmutable;
use Psr\Http\Message\ResponseInterface;
use stdClass;
final class ChartsAction extends AbstractReportAction
{
public function __construct(
private readonly AnalyticsRepository $analyticsRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
// Get current analytics level.
if (!$this->isAnalyticsEnabled()) {
return $response->withStatus(400)
->withJson(new Status(false, 'Reporting is restricted due to system analytics level.'));
}
$queryParams = $request->getQueryParams();
$statKey = match ($queryParams['type'] ?? null) {
'average' => 'number_avg',
default => 'number_unique'
};
$station = $request->getStation();
$stationTz = $station->getTimezoneObject();
$dateRange = $this->getDateRange($request, $stationTz);
$stats = [];
// Statistics by day.
$dailyStats = $this->analyticsRepo->findForStationInRange(
$station,
$dateRange
);
$dailyChart = new stdClass();
$dailyChart->label = __('Listeners by Day');
$dailyChart->type = 'line';
$dailyChart->fill = false;
$dailyAlt = [
'label' => $dailyChart->label,
'values' => [],
];
$dailyAverages = [];
$daysOfWeek = [];
foreach ($dailyStats as $stat) {
$statTime = CarbonImmutable::instance($stat['moment']);
$statTime = $statTime->shiftTimezone($stationTz);
$avgRow = new stdClass();
$avgRow->x = $statTime->getTimestampMs();
$avgRow->y = round((float)$stat[$statKey], 2);
$dailyAverages[] = $avgRow;
$rowDate = $statTime->format('Y-m-d');
$dailyAlt['values'][] = [
'label' => $rowDate,
'type' => 'time',
'original' => $avgRow->x,
'value' => $avgRow->y . ' ' . __('Listeners'),
];
$dayOfWeek = (int)$statTime->format('N') - 1;
$daysOfWeek[$dayOfWeek][] = $stat[$statKey];
}
$dailyChart->data = $dailyAverages;
$stats['daily'] = [
'metrics' => [
$dailyChart,
],
'alt' => [
$dailyAlt,
],
];
$dayOfWeekChart = new stdClass();
$dayOfWeekChart->label = __('Listeners by Day of Week');
$dayOfWeekAlt = [
'label' => $dayOfWeekChart->label,
'values' => [],
];
$daysOfWeekNames = [
__('Monday'),
__('Tuesday'),
__('Wednesday'),
__('Thursday'),
__('Friday'),
__('Saturday'),
__('Sunday'),
];
$dayOfWeekStats = [];
foreach ($daysOfWeekNames as $dayIndex => $dayName) {
$dayTotals = $daysOfWeek[$dayIndex] ?? [0];
$statValue = ($statKey === 'number_unique')
? array_sum($dayTotals)
: round(array_sum($dayTotals) / count($dayTotals), 2);
$dayOfWeekStats[] = $statValue;
$dayOfWeekAlt['values'][] = [
'label' => $dayName,
'type' => 'string',
'value' => $statValue . ' ' . __('Listeners'),
];
}
$dayOfWeekChart->data = $dayOfWeekStats;
$stats['day_of_week'] = [
'labels' => $daysOfWeekNames,
'metrics' => [
$dayOfWeekChart,
],
'alt' => [
$dayOfWeekAlt,
],
];
// Statistics by hour.
$hourlyStats = $this->analyticsRepo->findForStationInRange(
$station,
$dateRange,
AnalyticsIntervals::Hourly
);
$hourlyTotalCategories = [
'all',
'day0',
'day1',
'day2',
'day3',
'day4',
'day5',
'day6',
];
$totalsByHour = [];
foreach ($hourlyTotalCategories as $category) {
$categoryHours = [];
for ($i = 0; $i < 24; $i++) {
$categoryHours[$i] = [];
}
$totalsByHour[$category] = $categoryHours;
}
foreach ($hourlyStats as $stat) {
$statTime = CarbonImmutable::instance($stat['moment']);
$statTime = $statTime->shiftTimezone($stationTz);
$hour = $statTime->hour;
$statValue = $stat[$statKey];
$totalsByHour['all'][$hour][] = $statValue;
$dayOfWeek = 'day' . ((int)$statTime->format('N') - 1);
$totalsByHour[$dayOfWeek][$hour][] = $statValue;
}
$hourlyCharts = [];
foreach ($hourlyTotalCategories as $category) {
$hourlyLabels = [];
$hourlyChart = new stdClass();
$hourlyChart->label = __('Listeners by Hour');
$hourlyRows = [];
$hourlyAlt = [
'label' => $hourlyChart->label,
'values' => [],
];
for ($i = 0; $i < 24; $i++) {
$hourlyLabels[] = $i . ':00';
$totals = $totalsByHour[$category][$i] ?? [];
if (0 === count($totals)) {
$totals = [0];
}
$statValue = ($statKey === 'number_unique')
? array_sum($totals)
: round(array_sum($totals) / count($totals), 2);
$hourlyRows[] = $statValue;
$hourlyAlt['values'][] = [
'label' => $i . ':00',
'type' => 'string',
'value' => $statValue . ' ' . __('Listeners'),
];
}
$hourlyChart->data = $hourlyRows;
$hourlyCharts[$category] = [
'labels' => $hourlyLabels,
'metrics' => [
$hourlyChart,
],
'alt' => [
$hourlyAlt,
],
];
}
$stats['hourly'] = $hourlyCharts;
return $response->withJson($stats);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/Overview/ChartsAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,528 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports\Overview;
use App\Container\EntityManagerAwareTrait;
use App\Container\SettingsAwareTrait;
use App\Controller\Api\Traits\AcceptsDateRange;
use App\Controller\SingleActionInterface;
use App\Entity\Enums\AnalyticsLevel;
abstract class AbstractReportAction implements SingleActionInterface
{
use AcceptsDateRange;
use EntityManagerAwareTrait;
use SettingsAwareTrait;
protected function isAllAnalyticsEnabled(): bool
{
return AnalyticsLevel::All === $this->readSettings()->getAnalytics();
}
protected function isAnalyticsEnabled(): bool
{
return $this->readSettings()->isAnalyticsEnabled();
}
protected function buildChart(
array $rows,
string $valueLabel,
?int $limitResults = 10
): array {
arsort($rows);
$topRows = (null !== $limitResults)
? array_slice($rows, 0, $limitResults)
: $rows;
$alt = [
'label' => $valueLabel,
'values' => [],
];
$labels = [];
$data = [];
foreach ($topRows as $key => $value) {
$labels[] = $key;
$data[] = (int)$value;
$alt['values'][] = [
'label' => $key,
'type' => 'string',
'value' => $value . ' ' . $valueLabel,
];
}
return [
'labels' => $labels,
'datasets' => [
[
'label' => $valueLabel,
'data' => $data,
],
],
'alt' => [
$alt,
],
];
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/Overview/AbstractReportAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 382 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports\Overview;
use App\Entity\Api\Status;
use App\Entity\ApiGenerator\SongApiGenerator;
use App\Entity\Song;
use App\Entity\SongHistory;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Utilities\DateRange;
use Psr\Http\Message\ResponseInterface;
final class BestAndWorstAction extends AbstractReportAction
{
public function __construct(
private readonly SongApiGenerator $songApiGenerator,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
// Get current analytics level.
if (!$this->isAnalyticsEnabled()) {
return $response->withStatus(400)
->withJson(new Status(false, 'Reporting is restricted due to system analytics level.'));
}
$dateRange = $this->getDateRange($request, $request->getStation()->getTimezoneObject());
return $response->withJson([
'bestAndWorst' => $this->getBestAndWorst($request, $dateRange),
'mostPlayed' => $this->getMostPlayed($request, $dateRange),
]);
}
private function getBestAndWorst(
ServerRequest $request,
DateRange $dateRange
): array {
$station = $request->getStation();
// Get all songs played in timeline.
$baseQuery = $this->em->createQueryBuilder()
->select('sh')
->from(SongHistory::class, 'sh')
->where('sh.station = :station')
->setParameter('station', $station)
->andWhere('sh.timestamp_start <= :end AND sh.timestamp_end >= :start')
->setParameter('start', $dateRange->getStartTimestamp())
->setParameter('end', $dateRange->getEndTimestamp())
->andWhere('sh.is_visible = 1')
->andWhere('sh.listeners_start IS NOT NULL')
->andWhere('sh.timestamp_end != 0')
->setMaxResults(5);
$rawStats = [
'best' => (clone $baseQuery)->orderBy('sh.delta_total', 'DESC')
->getQuery()->getArrayResult(),
'worst' => (clone $baseQuery)->orderBy('sh.delta_total', 'ASC')
->getQuery()->getArrayResult(),
];
$stats = [];
$baseUrl = $request->getRouter()->getBaseUrl();
foreach ($rawStats as $category => $rawRows) {
$stats[$category] = array_map(
function ($row) use ($station, $baseUrl) {
$song = ($this->songApiGenerator)(Song::createFromArray($row), $station);
$song->resolveUrls($baseUrl);
return [
'song' => $song,
'stat_start' => $row['listeners_start'] ?? 0,
'stat_end' => $row['listeners_end'] ?? 0,
'stat_delta' => $row['delta_total'],
];
},
$rawRows
);
}
return $stats;
}
private function getMostPlayed(
ServerRequest $request,
DateRange $dateRange
): array {
$station = $request->getStation();
$rawRows = $this->em->createQuery(
<<<'DQL'
SELECT sh.song_id, sh.text, sh.artist, sh.title, COUNT(sh.id) AS records
FROM App\Entity\SongHistory sh
WHERE sh.station = :station
AND sh.is_visible = 1
AND sh.timestamp_start <= :end
AND sh.timestamp_end >= :start
GROUP BY sh.song_id
ORDER BY records DESC
DQL
)->setParameter('station', $request->getStation())
->setParameter('start', $dateRange->getStartTimestamp())
->setParameter('end', $dateRange->getEndTimestamp())
->setMaxResults(10)
->getArrayResult();
$baseUrl = $request->getRouter()->getBaseUrl();
return array_map(
function ($row) use ($station, $baseUrl) {
$song = ($this->songApiGenerator)(Song::createFromArray($row), $station);
$song->resolveUrls($baseUrl);
return [
'song' => $song,
'num_plays' => $row['records'],
];
},
$rawRows
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/Overview/BestAndWorstAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 956 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Reports\Overview;
use App\Entity\Api\Status;
use App\Entity\Repository\StationHlsStreamRepository;
use App\Entity\Repository\StationMountRepository;
use App\Entity\Repository\StationRemoteRepository;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class ByStream extends AbstractReportAction
{
public function __construct(
private readonly StationMountRepository $mountRepo,
private readonly StationRemoteRepository $remoteRepo,
private readonly StationHlsStreamRepository $hlsStreamRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
// Get current analytics level.
if (!$this->isAnalyticsEnabled()) {
return $response->withStatus(400)
->withJson(new Status(false, 'Reporting is restricted due to system analytics level.'));
}
$station = $request->getStation();
$stationTz = $station->getTimezoneObject();
$dateRange = $this->getDateRange($request, $stationTz);
$statsRaw = $this->em->getConnection()->fetchAllAssociative(
<<<'SQL'
SELECT l.stream_id,
COUNT(l.listener_hash) AS listeners,
SUM(l.connected_seconds) AS connected_seconds
FROM (
SELECT CASE
WHEN mount_id IS NOT NULL THEN CONCAT('local_', mount_id)
WHEN hls_stream_id IS NOT NULL THEN CONCAT('hls_', hls_stream_id)
WHEN remote_id IS NOT NULL THEN CONCAT('remote_', remote_id)
ELSE 'unknown'
END AS stream_id,
SUM(timestamp_end - timestamp_start) AS connected_seconds,
listener_hash
FROM listener
WHERE station_id = :station_id
AND timestamp_end >= :start
AND timestamp_start <= :end
GROUP BY listener_hash
) AS l
GROUP BY l.stream_id
SQL,
[
'station_id' => $station->getIdRequired(),
'start' => $dateRange->getStartTimestamp(),
'end' => $dateRange->getEndTimestamp(),
]
);
$streamLookup = [];
foreach ($this->mountRepo->getDisplayNames($station) as $id => $displayName) {
$streamLookup['local_' . $id] = $displayName;
}
foreach ($this->remoteRepo->getDisplayNames($station) as $id => $displayName) {
$streamLookup['remote_' . $id] = $displayName;
}
foreach ($this->hlsStreamRepo->getDisplayNames($station) as $id => $displayName) {
$streamLookup['hls_' . $id] = $displayName;
}
$listenersByStream = [];
$connectedTimeByStream = [];
$stats = [];
foreach ($statsRaw as $row) {
if (!isset($streamLookup[$row['stream_id']])) {
continue;
}
$row['stream'] = $streamLookup[$row['stream_id']];
$stats[] = $row;
$listenersByStream[$row['stream']] = $row['listeners'];
$connectedTimeByStream[$row['stream']] = $row['connected_seconds'];
}
return $response->withJson([
'all' => $stats,
'top_listeners' => $this->buildChart($listenersByStream, __('Listeners')),
'top_connected_time' => $this->buildChart($connectedTimeByStream, __('Connected Seconds')),
]);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Reports/Overview/ByStream.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 769 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\CustomAssets;
use App\Assets\AssetTypes;
use App\Container\EnvironmentAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class DeleteCustomAssetAction implements SingleActionInterface
{
use EnvironmentAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $type */
$type = $params['type'];
$customAsset = AssetTypes::from($type)->createObject(
$this->environment,
$request->getStation()
);
$customAsset->delete();
return $response->withJson(Status::success());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/CustomAssets/DeleteCustomAssetAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 184 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\CustomAssets;
use App\Assets\AssetTypes;
use App\Container\EnvironmentAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Media\AlbumArt;
use App\Media\MimeType;
use App\Service\Flow;
use Psr\Http\Message\ResponseInterface;
final class PostCustomAssetAction implements SingleActionInterface
{
use EnvironmentAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $type */
$type = $params['type'];
$customAsset = AssetTypes::from($type)->createObject(
$this->environment,
$request->getStation()
);
$flowResponse = Flow::process($request, $response);
if ($flowResponse instanceof ResponseInterface) {
return $flowResponse;
}
$imageContents = $flowResponse->readAndDeleteUploadedFile();
$customAsset->upload(
AlbumArt::getImageManager()->read($imageContents),
MimeType::getMimeTypeDetector()->detectMimeTypeFromBuffer($imageContents) ?? 'image/jpeg'
);
return $response->withJson(Status::success());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/CustomAssets/PostCustomAssetAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 287 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\CustomAssets;
use App\Assets\AssetTypes;
use App\Container\EnvironmentAwareTrait;
use App\Controller\SingleActionInterface;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class GetCustomAssetAction implements SingleActionInterface
{
use EnvironmentAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $type */
$type = $params['type'];
$customAsset = AssetTypes::from($type)->createObject(
$this->environment,
$request->getStation()
);
return $response->withJson(
[
'is_uploaded' => $customAsset->isUploaded(),
'url' => $customAsset->getUrl(),
]
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/CustomAssets/GetCustomAssetAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 197 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Art;
use App\Controller\SingleActionInterface;
use App\Entity\Repository\StationMediaRepository;
use App\Entity\Repository\StationRepository;
use App\Entity\Station;
use App\Entity\StationMedia;
use App\Flysystem\ExtendedFilesystemInterface;
use App\Flysystem\StationFilesystems;
use App\Http\Response;
use App\Http\ServerRequest;
use App\OpenApi;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface;
#[OA\Get(
path: '/station/{station_id}/art/{media_id}',
operationId: 'getMediaArt',
description: 'Returns the album art for a song, or a generic image.',
tags: ['Stations: Media'],
parameters: [
new OA\Parameter(ref: OpenApi::REF_STATION_ID_REQUIRED),
new OA\Parameter(
name: 'media_id',
description: 'The station media unique ID',
in: 'path',
required: true,
schema: new OA\Schema(type: 'string')
),
],
responses: [
new OA\Response(
response: 200,
description: 'The requested album artwork'
),
new OA\Response(
response: 404,
description: 'Image not found; generic filler image.'
),
]
)]
final class GetArtAction implements SingleActionInterface
{
public function __construct(
private readonly StationRepository $stationRepo,
private readonly StationMediaRepository $mediaRepo,
private readonly StationFilesystems $stationFilesystems
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $mediaId */
$mediaId = $params['media_id'];
$station = $request->getStation();
$fsMedia = $this->stationFilesystems->getMediaFilesystem($station);
$mediaPath = $this->getMediaPath($station, $fsMedia, $mediaId);
if (null !== $mediaPath) {
return $response->streamFilesystemFile(
$fsMedia,
$mediaPath,
null,
'inline',
false
);
}
return $response->withRedirect((string)$this->stationRepo->getDefaultAlbumArtUrl($station), 302);
}
private function getMediaPath(
Station $station,
ExtendedFilesystemInterface $fsMedia,
string $mediaId
): ?string {
if (StationMedia::UNIQUE_ID_LENGTH === strlen($mediaId)) {
$mediaPath = StationMedia::getArtPath($mediaId);
if ($fsMedia->fileExists($mediaPath)) {
return $mediaPath;
}
}
$media = $this->mediaRepo->findForStation($mediaId, $station);
if (!($media instanceof StationMedia)) {
return null;
}
$mediaPath = StationMedia::getArtPath($media->getUniqueId());
if ($fsMedia->fileExists($mediaPath)) {
return $mediaPath;
}
$folderPath = StationMedia::getFolderArtPath(
StationMedia::getFolderHashForPath($media->getPath())
);
if ($fsMedia->fileExists($folderPath)) {
return $folderPath;
}
return null;
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Art/GetArtAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 728 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Art;
use App\Container\EntityManagerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Status;
use App\Entity\Repository\StationMediaRepository;
use App\Http\Response;
use App\Http\ServerRequest;
use App\OpenApi;
use App\Service\Flow;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface;
#[OA\Post(
path: '/station/{station_id}/art/{media_id}',
operationId: 'postMediaArt',
description: 'Sets the album art for a track.',
security: OpenApi::API_KEY_SECURITY,
tags: ['Stations: Media'],
parameters: [
new OA\Parameter(ref: OpenApi::REF_STATION_ID_REQUIRED),
new OA\Parameter(
name: 'media_id',
description: 'Media ID',
in: 'path',
required: true,
schema: new OA\Schema(
anyOf: [
new OA\Schema(type: 'integer', format: 'int64'),
new OA\Schema(type: 'string'),
]
)
),
],
responses: [
new OA\Response(ref: OpenApi::REF_RESPONSE_SUCCESS, response: 200),
new OA\Response(ref: OpenApi::REF_RESPONSE_ACCESS_DENIED, response: 403),
new OA\Response(ref: OpenApi::REF_RESPONSE_NOT_FOUND, response: 404),
new OA\Response(ref: OpenApi::REF_RESPONSE_GENERIC_ERROR, response: 500),
]
)]
final class PostArtAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
public function __construct(
private readonly StationMediaRepository $mediaRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $mediaId */
$mediaId = $params['media_id'];
$station = $request->getStation();
$media = $this->mediaRepo->requireForStation($mediaId, $station);
$flowResponse = Flow::process($request, $response, $station->getRadioTempDir());
if ($flowResponse instanceof ResponseInterface) {
return $flowResponse;
}
$this->mediaRepo->updateAlbumArt(
$media,
$flowResponse->readAndDeleteUploadedFile()
);
$this->em->flush();
return $response->withJson(Status::updated());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Art/PostArtAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 531 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Art;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Status;
use App\Entity\Repository\StationMediaRepository;
use App\Http\Response;
use App\Http\ServerRequest;
use App\OpenApi;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface;
#[OA\Delete(
path: '/station/{station_id}/art/{media_id}',
operationId: 'deleteMediaArt',
description: 'Removes the album art for a track.',
security: OpenApi::API_KEY_SECURITY,
tags: ['Stations: Media'],
parameters: [
new OA\Parameter(ref: OpenApi::REF_STATION_ID_REQUIRED),
new OA\Parameter(
name: 'media_id',
description: 'Media ID',
in: 'path',
required: true,
schema: new OA\Schema(
anyOf: [
new OA\Schema(type: 'integer', format: 'int64'),
new OA\Schema(type: 'string'),
]
)
),
],
responses: [
new OA\Response(ref: OpenApi::REF_RESPONSE_SUCCESS, response: 200),
new OA\Response(ref: OpenApi::REF_RESPONSE_ACCESS_DENIED, response: 403),
new OA\Response(ref: OpenApi::REF_RESPONSE_NOT_FOUND, response: 404),
new OA\Response(ref: OpenApi::REF_RESPONSE_GENERIC_ERROR, response: 500),
]
)]
final class DeleteArtAction implements SingleActionInterface
{
public function __construct(
private readonly StationMediaRepository $mediaRepo,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $mediaId */
$mediaId = $params['media_id'];
$station = $request->getStation();
$media = $this->mediaRepo->requireForStation($mediaId, $station);
$this->mediaRepo->removeAlbumArt($media);
return $response->withJson(Status::deleted());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Art/DeleteArtAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 450 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Webhooks;
use App\Controller\Api\Traits\HasLogViewer;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Error;
use App\Entity\Repository\StationWebhookRepository;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Utilities\File;
use Psr\Http\Message\ResponseInterface;
final class TestLogAction implements SingleActionInterface
{
use HasLogViewer;
public function __construct(
private readonly StationWebhookRepository $webhookRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $id */
$id = $params['id'];
/** @var string $path */
$path = $params['path'];
$this->webhookRepo->requireForStation($id, $request->getStation());
$logPathPortion = 'webhook_test_' . $id;
if (!str_contains($path, $logPathPortion)) {
return $response
->withStatus(403)
->withJson(new Error(403, 'Invalid log path.'));
}
$tempPath = File::validateTempPath($path);
return $this->streamLogToResponse(
$request,
$response,
$tempPath
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Webhooks/TestLogAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 300 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Webhooks;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Status;
use App\Entity\Repository\StationWebhookRepository;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class ToggleAction implements SingleActionInterface
{
public function __construct(
private readonly StationWebhookRepository $webhookRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $id */
$id = $params['id'];
$record = $this->webhookRepo->requireForStation($id, $request->getStation());
$newValue = !$record->getIsEnabled();
$record->setIsEnabled($newValue);
$em = $this->webhookRepo->getEntityManager();
$em->persist($record);
$em->flush();
$flashMessage = ($newValue)
? __('Web hook enabled.')
: __('Web hook disabled.');
return $response->withJson(new Status(true, $flashMessage));
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Webhooks/ToggleAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 253 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Stations\Webhooks;
use App\Container\EnvironmentAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Repository\StationWebhookRepository;
use App\Enums\GlobalPermissions;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Message\TestWebhookMessage;
use App\Utilities\File;
use Monolog\Level;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Messenger\MessageBus;
final class TestAction implements SingleActionInterface
{
use EnvironmentAwareTrait;
public function __construct(
private readonly StationWebhookRepository $webhookRepo,
private readonly MessageBus $messageBus
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $id */
$id = $params['id'];
$station = $request->getStation();
$acl = $request->getAcl();
$webhook = $this->webhookRepo->requireForStation($id, $station);
$logLevel = ($this->environment->isDevelopment() || $acl->isAllowed(GlobalPermissions::View))
? Level::Debug
: Level::Info;
$tempFile = File::generateTempPath('webhook_test_' . $id . '.log');
touch($tempFile);
$message = new TestWebhookMessage();
$message->webhookId = $webhook->getIdRequired();
$message->outputPath = $tempFile;
$message->logLevel = $logLevel->value;
$this->messageBus->dispatch($message);
$router = $request->getRouter();
return $response->withJson(
[
'success' => true,
'links' => [
'log' => $router->fromHere('api:stations:webhook:test-log', [
'path' => basename($tempFile),
]),
],
]
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Stations/Webhooks/TestAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 434 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Internal;
use App\Container\EntityManagerAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\SftpUser;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class SftpAuthAction implements SingleActionInterface
{
use LoggerAwareTrait;
use EntityManagerAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$errorResponse = $response
->withStatus(500)
->withJson(['username' => '']);
$parsedBody = (array)$request->getParsedBody();
$username = $parsedBody['username'] ?? '';
$password = $parsedBody['password'] ?? '';
$pubKey = $parsedBody['public_key'] ?? '';
if (empty($username)) {
return $errorResponse;
}
$sftpUser = $this->em->getRepository(SftpUser::class)->findOneBy(['username' => $username]);
if (!($sftpUser instanceof SftpUser)) {
$this->logger->notice(
sprintf(
'SFTP user "%s" not found.',
$username
)
);
return $errorResponse;
}
if (!$sftpUser->authenticate($password, $pubKey)) {
$this->logger->notice(
sprintf(
'SFTP user "%s" could not authenticate.',
$username
),
[
'hasPassword' => !empty($password),
'hasPubKey' => !empty($pubKey),
]
);
return $errorResponse;
}
$storageLocation = $sftpUser->getStation()->getMediaStorageLocation();
if (!$storageLocation->isLocal()) {
$this->logger->error(
sprintf(
'SFTP login failed for user "%s": Storage Location %s is not local.',
$username,
$storageLocation
)
);
return $errorResponse;
}
$quotaRaw = $storageLocation->getStorageQuotaBytes();
$quota = $quotaRaw ?? 0;
$row = [
'status' => 1,
'username' => $sftpUser->getUsername(),
'expiration_date' => 0,
'home_dir' => $storageLocation->getPath(),
'uid' => 0,
'gid' => 0,
'quota_size' => $quota,
'permissions' => [
'/' => ['*'],
],
];
return $response->withJson(
$row,
options: JSON_NUMERIC_CHECK
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Internal/SftpAuthAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 589 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Internal;
use App\Cache\AzuraRelayCache;
use App\Container\EntityManagerAwareTrait;
use App\Container\SettingsAwareTrait;
use App\Entity\Api\Admin\Relay as ApiRelay;
use App\Entity\Api\Status;
use App\Entity\Relay;
use App\Entity\Station;
use App\Entity\StationMount;
use App\Entity\StationRemote;
use App\Enums\StationPermissions;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Radio\Adapters;
use App\Radio\Enums\FrontendAdapters;
use App\Radio\Enums\RemoteAdapters;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface;
#[
OA\Get(
path: '/internal/relays',
operationId: 'internalGetRelayDetails',
description: "Returns all necessary information to relay all 'relayable' stations.",
tags: ['Administration: Relays'],
parameters: [],
responses: [
new OA\Response(
response: 200,
description: 'Success',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: '#/components/schemas/Api_Admin_Relay')
)
),
]
)
]
final class RelaysController
{
use EntityManagerAwareTrait;
use SettingsAwareTrait;
public function __construct(
private readonly Adapters $adapters,
private readonly AzuraRelayCache $azuraRelayCache
) {
}
public function __invoke(
ServerRequest $request,
Response $response
): ResponseInterface {
$stations = $this->getManageableStations($request);
$router = $request->getRouter();
$return = [];
foreach ($stations as $station) {
$row = new ApiRelay();
$row->id = $station->getIdRequired();
$row->name = $station->getName();
$row->shortcode = $station->getShortName();
$row->description = $station->getDescription();
$row->url = $station->getUrl();
$row->genre = $station->getGenre();
$row->type = $station->getFrontendType()->value;
$frontendConfig = $station->getFrontendConfig();
$row->port = $frontendConfig->getPort();
$row->relay_pw = $frontendConfig->getRelayPassword();
$row->admin_pw = $frontendConfig->getAdminPassword();
$mounts = [];
$fa = $this->adapters->getFrontendAdapter($station);
if (null !== $fa && $station->getMounts()->count() > 0) {
foreach ($station->getMounts() as $mount) {
/** @var StationMount $mount */
$mounts[] = $mount->api($fa);
}
}
$row->mounts = $mounts;
$row->resolveUrls($router->getBaseUrl());
$return[] = $row;
}
return $response->withJson($return);
}
/**
* @param ServerRequest $request
*
* @return Station[]
*/
private function getManageableStations(ServerRequest $request): array
{
$allStations = $this->em->createQuery(
<<<'DQL'
SELECT s, sm
FROM App\Entity\Station s
JOIN s.mounts sm
WHERE s.is_enabled = 1
AND s.frontend_type != :remote_frontend
DQL
)->setParameter('remote_frontend', FrontendAdapters::Remote->value)
->execute();
$acl = $request->getAcl();
return array_filter(
$allStations,
static function (Station $station) use ($acl) {
return $acl->isAllowed(StationPermissions::Broadcasting, $station->getId());
}
);
}
public function updateAction(
ServerRequest $request,
Response $response
): ResponseInterface {
$relayRepo = $this->em->getRepository(Relay::class);
$body = (array)$request->getParsedBody();
if (!empty($body['base_url'])) {
$baseUrl = $body['base_url'];
} else {
/** @noinspection HttpUrlsUsage */
$baseUrl = 'path_to_url . $this->readSettings()->getIp($request);
}
$relay = $relayRepo->findOneBy(['base_url' => $baseUrl]);
if (!$relay instanceof Relay) {
$relay = new Relay($baseUrl);
}
$relay->setName($body['name'] ?? 'Relay');
$relay->setIsVisibleOnPublicPages($body['is_visible_on_public_pages'] ?? true);
$relay->setUpdatedAt(time());
$this->em->persist($relay);
// List existing remotes to avoid duplication.
$existingRemotes = [];
foreach ($relay->getRemotes() as $remote) {
/** @var StationRemote $remote */
$existingRemotes[$remote->getStation()->getId()][$remote->getMount()] = $remote;
}
// Iterate through all remotes that *should* exist.
foreach ($this->getManageableStations($request) as $station) {
$stationId = $station->getId();
foreach ($station->getMounts() as $mount) {
/** @var StationMount $mount */
$mountPath = $mount->getName();
if (isset($existingRemotes[$stationId][$mountPath])) {
/** @var StationRemote $remote */
$remote = $existingRemotes[$stationId][$mountPath];
unset($existingRemotes[$stationId][$mountPath]);
} else {
$remote = new StationRemote($station);
}
$remote->setRelay($relay);
$remote->setType(RemoteAdapters::AzuraRelay);
$remote->setDisplayName($mount->getDisplayName() . ' (' . $relay->getName() . ')');
$remote->setIsVisibleOnPublicPages($relay->getIsVisibleOnPublicPages());
$remote->setAutodjBitrate($mount->getAutodjBitrate());
$remote->setAutodjFormat($mount->getAutodjFormat());
$remote->setUrl($relay->getBaseUrl());
$remote->setMount($mount->getName());
$this->em->persist($remote);
}
}
// Remove all remotes that weren't processed earlier.
foreach ($existingRemotes as $existingRemoteStation) {
foreach ($existingRemoteStation as $existingRemote) {
$this->em->remove($existingRemote);
}
}
$this->em->flush();
$this->azuraRelayCache->setForRelay($relay, (array)$body['nowplaying']);
return $response->withJson(Status::success());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Internal/RelaysController.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,506 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Internal;
use App\Container\ContainerAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Enums\StationPermissions;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Radio\Backend\Liquidsoap\Command\AbstractCommand;
use App\Radio\Enums\LiquidsoapCommands;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;
use Throwable;
final class LiquidsoapAction implements SingleActionInterface
{
use LoggerAwareTrait;
use ContainerAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $action */
$action = $params['action'];
$station = $request->getStation();
$asAutoDj = $request->hasHeader('X-Liquidsoap-Api-Key');
$payload = (array)$request->getParsedBody();
try {
$acl = $request->getAcl();
if (!$acl->isAllowed(StationPermissions::View, $station->getIdRequired())) {
$authKey = $request->getHeaderLine('X-Liquidsoap-Api-Key');
if (!$station->validateAdapterApiKey($authKey)) {
throw new RuntimeException('Invalid API key.');
}
}
$command = LiquidsoapCommands::tryFrom($action);
if (null === $command || !$this->di->has($command->getClass())) {
throw new InvalidArgumentException('Command not found.');
}
/** @var AbstractCommand $commandObj */
$commandObj = $this->di->get($command->getClass());
$result = $commandObj->run($station, $asAutoDj, $payload);
$response->getBody()->write($result);
} catch (Throwable $e) {
$this->logger->error(
sprintf(
'Liquidsoap command "%s" error: %s',
$action,
$e->getMessage()
),
[
'station' => (string)$station,
'payload' => $payload,
'as-autodj' => $asAutoDj,
]
);
return $response->withStatus(400)
->write('false');
}
return $response;
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Internal/LiquidsoapAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 500 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Internal;
use App\Container\EntityManagerAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Repository\StorageLocationRepository;
use App\Entity\SftpUser;
use App\Entity\StorageLocation;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Media\BatchUtilities;
use App\Message\AddNewMediaMessage;
use League\Flysystem\PathPrefixer;
use LogicException;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Messenger\MessageBus;
use Throwable;
final class SftpEventAction implements SingleActionInterface
{
use LoggerAwareTrait;
use EntityManagerAwareTrait;
public function __construct(
private readonly MessageBus $messageBus,
private readonly BatchUtilities $batchUtilities,
private readonly StorageLocationRepository $storageLocationRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$errorResponse = $response->withStatus(500)->withJson(['success' => false]);
$parsedBody = (array)$request->getParsedBody();
$action = $parsedBody['action'] ?? null;
$username = $parsedBody['username'] ?? null;
$path = $parsedBody['path'] ?? null;
$targetPath = $parsedBody['target_path'] ?? null;
$sshCmd = $parsedBody['ssh_cmd'] ?? null;
$this->logger->notice(
'SFTP file event triggered',
[
'action' => $action,
'username' => $username,
'path' => $path,
'targetPath' => $targetPath,
'sshCmd' => $sshCmd,
]
);
// Determine which station the username belongs to.
$sftpUser = $this->em->getRepository(SftpUser::class)->findOneBy(
[
'username' => $username,
]
);
if (!$sftpUser instanceof SftpUser) {
$this->logger->error('SFTP Username not found.', ['username' => $username]);
return $errorResponse;
}
$storageLocation = $sftpUser->getStation()->getMediaStorageLocation();
if (!$storageLocation->isLocal()) {
$this->logger->error(sprintf('Storage location "%s" is not local.', $storageLocation));
return $errorResponse;
}
if (null === $path) {
$this->logger->error('No path specified for action.');
return $errorResponse;
}
try {
match ($action) {
'upload' => $this->handleNewUpload($storageLocation, $path),
'pre-delete' => $this->handleDelete($storageLocation, $path),
'rename' => $this->handleRename($storageLocation, $path, $targetPath),
default => null,
};
return $response->withJson(['success' => true]);
} catch (Throwable $e) {
$this->logger->error(
sprintf('SFTP Event: %s', $e->getMessage()),
[
'exception' => $e,
]
);
return $errorResponse;
}
}
private function handleNewUpload(
StorageLocation $storageLocation,
string $path
): void {
$pathPrefixer = new PathPrefixer($storageLocation->getPath(), DIRECTORY_SEPARATOR);
$relativePath = $pathPrefixer->stripPrefix($path);
$this->logger->notice(
'Processing new SFTP upload.',
[
'storageLocation' => (string)$storageLocation,
'path' => $relativePath,
]
);
$message = new AddNewMediaMessage();
$message->storage_location_id = $storageLocation->getIdRequired();
$message->path = $relativePath;
$this->messageBus->dispatch($message);
}
private function handleDelete(
StorageLocation $storageLocation,
string $path
): void {
$pathPrefixer = new PathPrefixer($storageLocation->getPath(), DIRECTORY_SEPARATOR);
$relativePath = $pathPrefixer->stripPrefix($path);
$this->logger->notice(
'Processing SFTP file/folder deletion.',
[
'storageLocation' => (string)$storageLocation,
'path' => $relativePath,
]
);
$directories = [];
$files = [];
if (is_dir($path)) {
$directories[] = $relativePath;
} else {
$files[] = $relativePath;
}
$fs = $this->storageLocationRepo->getAdapter($storageLocation)->getFilesystem();
$this->batchUtilities->handleDelete(
$files,
$directories,
$storageLocation,
$fs
);
$fs->delete($relativePath);
}
private function handleRename(
StorageLocation $storageLocation,
string $path,
?string $newPath
): void {
if (null === $newPath) {
throw new LogicException('No new path specified for rename.');
}
$pathPrefixer = new PathPrefixer($storageLocation->getPath(), DIRECTORY_SEPARATOR);
$from = $pathPrefixer->stripPrefix($path);
$to = $pathPrefixer->stripPrefix($newPath);
$this->logger->notice(
'Processing SFTP file/folder rename.',
[
'storageLocation' => (string)$storageLocation,
'from' => $from,
'to' => $to,
]
);
$this->batchUtilities->handleRename(
$from,
$to,
$storageLocation
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Internal/SftpEventAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,235 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account;
use App\Controller\SingleActionInterface;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class GetTwoFactorAction implements SingleActionInterface
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$user = $request->getUser();
return $response->withJson([
'two_factor_enabled' => !empty($user->getTwoFactorSecret()),
]);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/GetTwoFactorAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 125 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Internal;
use App\Container\LoggerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Enums\StationPermissions;
use App\Exception\Http\PermissionDeniedException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Radio\Frontend\Blocklist\BlocklistParser;
use App\Utilities\Types;
use Psr\Http\Message\ResponseInterface;
final class ListenerAuthAction implements SingleActionInterface
{
use LoggerAwareTrait;
public function __construct(
private readonly BlocklistParser $blocklistParser
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
$acl = $request->getAcl();
if (!$acl->isAllowed(StationPermissions::View, $station->getId())) {
$authKey = Types::string($request->getQueryParam('api_auth'));
if (!$station->validateAdapterApiKey($authKey)) {
$this->logger->error(
'Invalid API key supplied for internal API call.',
[
'station_id' => $station->getId(),
'station_name' => $station->getName(),
]
);
throw PermissionDeniedException::create($request);
}
}
$station = $request->getStation();
$listenerIp = Types::string($request->getParam('ip'));
if ($this->blocklistParser->isAllowed($station, $listenerIp)) {
return $response->withHeader('icecast-auth-user', '1');
}
return $response
->withHeader('icecast-auth-user', '0')
->withHeader('icecast-auth-message', 'geo-blocked');
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Internal/ListenerAuthAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 384 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account;
use App\Container\EntityManagerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class DeleteTwoFactorAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$user = $request->getUser();
$user = $this->em->refetch($user);
$user->setTwoFactorSecret();
$this->em->persist($user);
$this->em->flush();
return $response->withJson(Status::updated());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/DeleteTwoFactorAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 171 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account;
use App\Controller\Api\AbstractApiCrudController;
use App\Entity\Interfaces\EntityGroupsInterface;
use App\Entity\UserPasskey;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
/**
* @template TEntity as UserPasskey
* @extends AbstractApiCrudController<TEntity>
*/
final class PasskeysController extends AbstractApiCrudController
{
protected string $entityClass = UserPasskey::class;
protected string $resourceRouteName = 'api:frontend:passkey';
public function listAction(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$query = $this->em->createQuery(
<<<'DQL'
SELECT e FROM App\Entity\UserPasskey e WHERE e.user = :user
DQL
)->setParameter('user', $request->getUser());
return $this->listPaginatedFromQuery($request, $response, $query);
}
public function createAction(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
throw new RuntimeException('Not implemented. See /frontend/account/webauthn/register.');
}
public function editAction(ServerRequest $request, Response $response, array $params): ResponseInterface
{
throw new RuntimeException('Not implemented.');
}
/**
* @return UserPasskey|null
*/
protected function getRecord(ServerRequest $request, array $params): ?object
{
/** @var string $id */
$id = $params['id'];
/** @var UserPasskey|null $record */
$record = $this->em->getRepository(UserPasskey::class)->findOneBy([
'id' => $id,
'user' => $request->getUser(),
]);
return $record;
}
/**
* @param TEntity $record
* @param array<string, mixed> $context
*
* @return array<mixed>
*/
protected function toArray(object $record, array $context = []): array
{
$context[AbstractNormalizer::GROUPS] = [
EntityGroupsInterface::GROUP_ID,
EntityGroupsInterface::GROUP_GENERAL,
];
return parent::toArray($record, $context);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/PasskeysController.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 518 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account;
use App\Controller\Api\Admin\UsersController;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Status;
use App\Entity\Interfaces\EntityGroupsInterface;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
final class PutMeAction extends UsersController implements SingleActionInterface
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$user = $request->getUser();
$user = $this->em->refetch($user);
$this->editRecord(
(array)$request->getParsedBody(),
$user,
[
AbstractNormalizer::GROUPS => [
EntityGroupsInterface::GROUP_ID,
EntityGroupsInterface::GROUP_GENERAL,
],
]
);
return $response->withJson(Status::updated());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/PutMeAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 215 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account;
use App\Controller\Api\AbstractApiCrudController;
use App\Entity\ApiKey;
use App\Entity\Interfaces\EntityGroupsInterface;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Security\SplitToken;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
/**
* @template TEntity as ApiKey
* @extends AbstractApiCrudController<TEntity>
*/
final class ApiKeysController extends AbstractApiCrudController
{
protected string $entityClass = ApiKey::class;
protected string $resourceRouteName = 'api:frontend:api-key';
public function listAction(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$query = $this->em->createQuery(
<<<'DQL'
SELECT e FROM App\Entity\ApiKey e WHERE e.user = :user
DQL
)->setParameter('user', $request->getUser());
return $this->listPaginatedFromQuery($request, $response, $query);
}
public function createAction(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$newKey = SplitToken::generate();
$record = new ApiKey(
$request->getUser(),
$newKey
);
/** @var TEntity $record */
$this->editRecord((array)$request->getParsedBody(), $record);
$return = $this->viewRecord($record, $request);
$return['key'] = (string)$newKey;
return $response->withJson($return);
}
/**
* @return TEntity|null
*/
protected function getRecord(ServerRequest $request, array $params): ?object
{
/** @var string $id */
$id = $params['id'];
/** @var TEntity|null $record */
$record = $this->em->getRepository(ApiKey::class)->findOneBy([
'id' => $id,
'user' => $request->getUser(),
]);
return $record;
}
/**
* @inheritDoc
*/
protected function editRecord(?array $data, ?object $record = null, array $context = []): object
{
$context[AbstractNormalizer::GROUPS] = [
EntityGroupsInterface::GROUP_GENERAL,
];
return parent::editRecord($data, $record, $context);
}
/**
* @param TEntity $record
* @param array<string, mixed> $context
*
* @return array<mixed>
*/
protected function toArray(object $record, array $context = []): array
{
$context[AbstractNormalizer::GROUPS] = [
EntityGroupsInterface::GROUP_ID,
EntityGroupsInterface::GROUP_GENERAL,
];
return parent::toArray($record, $context);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/ApiKeysController.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 634 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account;
use App\Auth;
use App\Container\EntityManagerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Error;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use InvalidArgumentException;
use OTPHP\TOTP;
use ParagonIE\ConstantTime\Base32;
use Psr\Http\Message\ResponseInterface;
use Throwable;
final class PutTwoFactorAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$params = (array)$request->getParsedBody();
try {
if (!empty($params['secret'])) {
$secret = $params['secret'];
if (64 !== strlen($secret)) {
throw new InvalidArgumentException('Secret is not the correct length.');
}
} else {
// Generate new TOTP secret.
$secret = substr(trim(Base32::encodeUpper(random_bytes(128)), '='), 0, 64);
}
// Customize TOTP code
$user = $request->getUser();
$totp = TOTP::create($secret);
$totp->setLabel($user->getEmail() ?: 'AzuraCast');
if (!empty($params['otp'])) {
if ($totp->verify($params['otp'], null, Auth::TOTP_WINDOW)) {
$user = $this->em->refetch($user);
$user->setTwoFactorSecret($totp->getProvisioningUri());
$this->em->persist($user);
$this->em->flush();
return $response->withJson(Status::success());
}
throw new InvalidArgumentException('Could not verify TOTP code.');
}
// Further customize TOTP code (with metadata that won't be stored in the DB)
$totp->setIssuer('AzuraCast');
$totp->setParameter('image', 'path_to_url
return $response->withJson([
'secret' => $secret,
'totp_uri' => $totp->getProvisioningUri(),
]);
} catch (Throwable $e) {
return $response->withStatus(400)->withJson(Error::fromException($e));
}
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/PutTwoFactorAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 504 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account;
use App\Container\EntityManagerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Error;
use App\Entity\Api\Status;
use App\Http\Response;
use App\Http\ServerRequest;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use Throwable;
final class PutPasswordAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$user = $request->getUser();
$body = (array)$request->getParsedBody();
try {
if (empty($body['current_password'])) {
throw new InvalidArgumentException('Current password not provided (current_password).');
}
$currentPassword = $body['current_password'];
if (!$user->verifyPassword($currentPassword)) {
throw new InvalidArgumentException('Invalid current password.');
}
if (empty($body['new_password'])) {
throw new InvalidArgumentException('New password not provided (new_password).');
}
$user = $this->em->refetch($user);
$user->setNewPassword($body['new_password']);
$this->em->persist($user);
$this->em->flush();
return $response->withJson(Status::updated());
} catch (Throwable $e) {
return $response->withStatus(400)->withJson(Error::fromException($e));
}
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/PutPasswordAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 321 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account;
use App\Container\EntityManagerAwareTrait;
use App\Controller\Api\Admin\UsersController;
use App\Controller\SingleActionInterface;
use App\Entity\Interfaces\EntityGroupsInterface;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Service\Avatar;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Validator\Validator\ValidatorInterface;
final class GetMeAction extends UsersController implements SingleActionInterface
{
use EntityManagerAwareTrait;
public function __construct(
private readonly Avatar $avatar,
Serializer $serializer,
ValidatorInterface $validator,
) {
parent::__construct($serializer, $validator);
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$user = $request->getUser();
$user = $this->em->refetch($user);
$return = $this->toArray($user, [
AbstractNormalizer::GROUPS => [
EntityGroupsInterface::GROUP_ID,
EntityGroupsInterface::GROUP_GENERAL,
],
]);
// Avatars
$avatarService = $this->avatar->getAvatarService();
$email = $user->getEmail();
$return['roles'] = [];
$return['avatar'] = [
'url_32' => $this->avatar->getAvatar($email, 32),
'url_64' => $this->avatar->getAvatar($email, 64),
'url_128' => $this->avatar->getAvatar($email, 128),
'service_name' => $avatarService->getServiceName(),
'service_url' => $avatarService->getServiceUrl(),
];
foreach ($user->getRoles() as $role) {
$return['roles'][] = [
'id' => $role->getIdRequired(),
'name' => $role->getName(),
];
}
return $response->withJson($return);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/GetMeAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 447 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account\WebAuthn;
use App\Controller\Traits\UsesWebAuthnTrait;
use App\Entity\Repository\UserPasskeyRepository;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class GetRegistrationAction
{
use UsesWebAuthnTrait;
public function __construct(
private readonly UserPasskeyRepository $passkeyRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$user = $request->getUser();
$webAuthn = $this->getWebAuthn($request);
$createArgs = $webAuthn->getCreateArgs(
(string)$user->getId(),
$user->getEmail(),
$user->getDisplayName(),
self::WEBAUTHN_TIMEOUT,
requireResidentKey: 'required',
requireUserVerification: 'preferred',
excludeCredentialIds: $this->passkeyRepo->getCredentialIds($user),
);
$this->setChallenge($request, $webAuthn->getChallenge());
return $response->withJson($createArgs);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/WebAuthn/GetRegistrationAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 264 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Account\WebAuthn;
use App\Container\EntityManagerAwareTrait;
use App\Controller\Traits\UsesWebAuthnTrait;
use App\Entity\Api\Status;
use App\Entity\UserPasskey;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Security\WebAuthnPasskey;
use App\Utilities\Types;
use Psr\Http\Message\ResponseInterface;
final class PutRegistrationAction
{
use UsesWebAuthnTrait;
use EntityManagerAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$user = $request->getUser();
$webAuthn = $this->getWebAuthn($request);
$parsedBody = Types::array($request->getParsedBody());
$challenge = $this->getChallenge($request);
// Turn the submitted data into a raw passkey.
$passkeyRaw = $webAuthn->processCreate(
base64_decode($parsedBody['createResponse']['clientDataJSON'] ?? ''),
base64_decode($parsedBody['createResponse']['attestationObject'] ?? ''),
$challenge,
requireUserVerification: true
);
$passkey = WebAuthnPasskey::fromWebAuthnObject($passkeyRaw);
$record = new UserPasskey(
$user,
$parsedBody['name'] ?? 'New Passkey',
$passkey
);
$this->em->persist($record);
$this->em->flush();
return $response->withJson(Status::success());
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Account/WebAuthn/PutRegistrationAction.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\Controller\Api\Frontend\Dashboard;
use App\Container\EntityManagerAwareTrait;
use App\Container\SettingsAwareTrait;
use App\Controller\Api\Traits\CanSearchResults;
use App\Controller\Api\Traits\CanSortResults;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Dashboard;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\ApiGenerator\NowPlayingApiGenerator;
use App\Entity\Station;
use App\Enums\StationPermissions;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Paginator;
use Psr\Http\Message\ResponseInterface;
final class StationsAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
use SettingsAwareTrait;
use CanSortResults;
use CanSearchResults;
public function __construct(
private readonly NowPlayingApiGenerator $npApiGenerator
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$acl = $request->getAcl();
/** @var Station[] $stations */
$stations = array_filter(
$this->em->getRepository(Station::class)->findBy([
'is_enabled' => 1,
]),
static function (Station $station) use ($acl) {
return $acl->isAllowed(StationPermissions::View, $station->getId());
}
);
/** @var NowPlaying[] $viewStations */
$viewStations = array_map(
fn(Station $station) => $this->npApiGenerator->currentOrEmpty($station),
$stations
);
$viewStations = $this->searchArray(
$request,
$viewStations,
[
'station.name',
]
);
$viewStations = $this->sortArray(
$request,
$viewStations,
[
'name' => 'station.name',
'listeners' => 'listeners.current',
'now_playing' => 'is_online',
],
'station.name'
);
$paginator = Paginator::fromArray($viewStations, $request);
$router = $request->getRouter();
$baseUrl = $router->getBaseUrl();
$listenersEnabled = $this->readSettings()->isAnalyticsEnabled();
$paginator->setPostprocessor(
function (NowPlaying $np) use ($router, $baseUrl, $listenersEnabled, $acl) {
$np->resolveUrls($baseUrl);
$row = new Dashboard();
$row->fromParentObject($np);
$row->links = [
'public' => $router->named('public:index', ['station_id' => $np->station->shortcode]),
'manage' => $router->named('stations:index:index', ['station_id' => $np->station->id]),
];
if ($listenersEnabled && $acl->isAllowed(StationPermissions::Reports, $np->station->id)) {
$row->links['listeners'] = $router->named(
'stations:reports:listeners',
['station_id' => $np->station->id]
);
}
return $row;
}
);
return $paginator->write($response);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Dashboard/StationsAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 697 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Dashboard;
use App\CallableEventDispatcherInterface;
use App\Controller\SingleActionInterface;
use App\Event;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class NotificationsAction implements SingleActionInterface
{
public function __construct(
private readonly CallableEventDispatcherInterface $eventDispatcher,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$event = new Event\GetNotifications($request);
$this->eventDispatcher->dispatch($event);
return $response->withJson(
$event->getNotifications()
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Dashboard/NotificationsAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 161 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Api\Frontend\Dashboard;
use App\Container\EntityManagerAwareTrait;
use App\Container\SettingsAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Api\Error;
use App\Entity\Enums\AnalyticsIntervals;
use App\Entity\Station;
use App\Enums\GlobalPermissions;
use App\Enums\StationPermissions;
use App\Http\Response;
use App\Http\ServerRequest;
use Carbon\CarbonImmutable;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\CacheInterface;
final class ChartsAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
use SettingsAwareTrait;
public function __construct(
private readonly CacheInterface $cache,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
if (!$this->readSettings()->isAnalyticsEnabled()) {
return $response->withStatus(403, 'Forbidden')
->withJson(new Error(403, 'Analytics are disabled for this installation.'));
}
$acl = $request->getAcl();
// Don't show stations the user can't manage.
$showAdmin = $acl->isAllowed(GlobalPermissions::View);
/** @var Station[] $stations */
$stations = array_filter(
$this->em->getRepository(Station::class)->findAll(),
static function ($station) use ($acl) {
/** @var Station $station */
return $station->getIsEnabled() &&
$acl->isAllowed(StationPermissions::View, $station->getId());
}
);
// Generate unique cache ID for stations.
$stationIds = [];
foreach ($stations as $station) {
$stationId = $station->getId();
$stationIds[$stationId] = $stationId;
}
$cacheName = 'homepage_metrics_' . implode(',', $stationIds);
if ($this->cache->has($cacheName)) {
$stationStats = $this->cache->get($cacheName);
} else {
$threshold = CarbonImmutable::parse('-180 days');
$stats = $this->em->createQuery(
<<<'DQL'
SELECT a.station_id, a.moment, a.number_avg, a.number_unique
FROM App\Entity\Analytics a
WHERE a.station_id IN (:stations)
AND a.type = :type
AND a.moment >= :threshold
DQL
)->setParameter('stations', $stationIds)
->setParameter('type', AnalyticsIntervals::Daily)
->setParameter('threshold', $threshold)
->getArrayResult();
$showAllStations = $showAdmin && count($stationIds) > 1;
$rawStats = [
'average' => [],
'unique' => [],
];
foreach ($stats as $row) {
$stationId = $row['station_id'];
$moment = $row['moment'];
$sortableKey = $moment->format('Y-m-d');
$jsTimestamp = $moment->getTimestamp() * 1000;
$average = round((float)$row['number_avg'], 2);
$unique = $row['number_unique'];
$rawStats['average'][$stationId][$sortableKey] = [
$jsTimestamp,
$average,
];
if (null !== $unique) {
$rawStats['unique'][$stationId][$sortableKey] = [
$jsTimestamp,
$unique,
];
}
if ($showAllStations) {
if (!isset($rawStats['average']['all'][$sortableKey])) {
$rawStats['average']['all'][$sortableKey] = [
$jsTimestamp,
0,
];
}
$rawStats['average']['all'][$sortableKey][1] += $average;
if (null !== $unique) {
if (!isset($stationStats['unique']['all'][$sortableKey])) {
$stationStats['unique']['all'][$sortableKey] = [
$jsTimestamp,
0,
];
}
$stationStats['unique']['all'][$sortableKey][1] += $unique;
}
}
}
$stationsInMetric = [];
if ($showAllStations) {
$stationsInMetric['all'] = __('All Stations');
}
foreach ($stations as $station) {
$stationsInMetric[$station->getId()] = $station->getName();
}
$stationStats = [
'average' => [
'metrics' => [],
'alt' => [],
],
'unique' => [
'metrics' => [],
'alt' => [],
],
];
foreach ($stationsInMetric as $stationId => $stationName) {
foreach ($rawStats as $statKey => $statRows) {
if (!isset($statRows[$stationId])) {
continue;
}
$series = [
'label' => $stationName,
'type' => 'line',
'fill' => false,
'data' => [],
];
$stationAlt = [
'label' => $stationName,
'values' => [],
];
ksort($statRows[$stationId]);
foreach ($statRows[$stationId] as $sortableKey => [$jsTimestamp, $value]) {
$series['data'][] = [
'x' => $jsTimestamp,
'y' => $value,
];
$stationAlt['values'][] = [
'label' => $sortableKey,
'type' => 'time',
'original' => $jsTimestamp,
'value' => $value . ' ' . __('Listeners'),
];
}
$stationStats[$statKey]['alt'][] = $stationAlt;
$stationStats[$statKey]['metrics'][] = $series;
}
}
$this->cache->set($cacheName, $stationStats, 600);
}
return $response->withJson($stationStats);
}
}
``` | /content/code_sandbox/backend/src/Controller/Api/Frontend/Dashboard/ChartsAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,292 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend;
use App\Container\SettingsAwareTrait;
use App\Controller\SingleActionInterface;
use App\Enums\GlobalPermissions;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class DashboardAction implements SingleActionInterface
{
use SettingsAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$settings = $this->readSettings();
// Detect current analytics level.
$showCharts = $settings->isAnalyticsEnabled();
$router = $request->getRouter();
$acl = $request->getAcl();
return $request->getView()->renderVuePage(
response: $response,
component: 'Dashboard',
id: 'dashboard',
title: __('Dashboard'),
props: [
'profileUrl' => $router->named('profile:index'),
'adminUrl' => $router->named('admin:index:index'),
'showAdmin' => $acl->isAllowed(GlobalPermissions::View),
'showCharts' => $showCharts,
'manageStationsUrl' => $router->named('admin:stations:index'),
'showAlbumArt' => !$settings->getHideAlbumArt(),
]
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/DashboardAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 287 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend;
use App\Container\SettingsAwareTrait;
use App\Controller\SingleActionInterface;
use App\Exception\Http\InvalidRequestAttribute;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class IndexAction implements SingleActionInterface
{
use SettingsAwareTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
// Redirect to complete setup, if it hasn't been completed yet.
$settings = $this->readSettings();
if (!$settings->isSetupComplete()) {
return $response->withRedirect($request->getRouter()->named('setup:index'));
}
// Redirect to login screen if the user isn't logged in.
try {
$request->getUser();
// Redirect to dashboard if no other custom redirection rules exist.
return $response->withRedirect($request->getRouter()->named('dashboard'));
} catch (InvalidRequestAttribute) {
// Redirect to a custom homepage URL if specified in settings.
$homepageRedirect = $settings->getHomepageRedirectUrl();
if (null !== $homepageRedirect) {
return $response->withRedirect($homepageRedirect, 302);
}
return $response->withRedirect($request->getRouter()->named('account:login'));
}
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/IndexAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 297 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Controller\Frontend\PublicPages\Traits\IsEmbeddable;
use App\Controller\SingleActionInterface;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class ScheduleAction implements SingleActionInterface
{
use IsEmbeddable;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
$router = $request->getRouter();
$pageClass = 'schedule station-' . $station->getShortName();
if ($this->isEmbedded($request, $params)) {
$pageClass .= ' embed';
}
$view = $request->getView();
// Add station public code.
$view->fetch(
'frontend/public/partials/station-custom',
['station' => $station]
);
return $view->renderVuePage(
response: $response
->withHeader('X-Frame-Options', '*'),
component: 'Public/Schedule',
id: 'station-schedule',
layout: 'minimal',
title: __('Schedule') . ' - ' . $station->getName(),
layoutParams: [
'page_class' => $pageClass,
'hide_footer' => true,
],
props: [
'scheduleUrl' => $router->named('api:stations:schedule', [
'station_id' => $station->getId(),
]),
'stationName' => $station->getName(),
'stationTimeZone' => $station->getTimezone(),
],
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/ScheduleAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 390 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend;
use App\Container\EntityManagerAwareTrait;
use App\Container\EnvironmentAwareTrait;
use App\Container\SettingsAwareTrait;
use App\Entity\Repository\RolePermissionRepository;
use App\Entity\User;
use App\Exception\Http\NotLoggedInException;
use App\Exception\ValidationException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\VueComponent\SettingsComponent;
use App\VueComponent\StationFormComponent;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Throwable;
final class SetupController
{
use EntityManagerAwareTrait;
use EnvironmentAwareTrait;
use SettingsAwareTrait;
public function __construct(
private readonly RolePermissionRepository $permissionRepo,
private readonly ValidatorInterface $validator,
private readonly StationFormComponent $stationFormComponent,
private readonly SettingsComponent $settingsComponent
) {
}
/**
* Setup Routing Controls
*
* @param ServerRequest $request
* @param Response $response
*/
public function indexAction(
ServerRequest $request,
Response $response
): ResponseInterface {
$currentStep = $this->getSetupStep($request);
return $response->withRedirect($request->getRouter()->named('setup:' . $currentStep));
}
/**
* Setup Step 1:
* Create Super Administrator Account
*/
public function registerAction(
ServerRequest $request,
Response $response
): ResponseInterface {
// Verify current step.
$currentStep = $this->getSetupStep($request);
if ($currentStep !== 'register' && $this->environment->isProduction()) {
return $response->withRedirect($request->getRouter()->named('setup:' . $currentStep));
}
$csrf = $request->getCsrf();
$error = null;
if ($request->isPost()) {
try {
$data = $request->getParams();
$csrf->verify($data['csrf'] ?? null, 'register');
if (empty($data['username']) || empty($data['password'])) {
throw new InvalidArgumentException('Username and password required.');
}
$role = $this->permissionRepo->ensureSuperAdministratorRole();
// Create user account.
$user = new User();
$user->setEmail($data['username']);
$user->setNewPassword($data['password']);
$user->getRoles()->add($role);
$errors = $this->validator->validate($user);
if (count($errors) > 0) {
throw ValidationException::fromValidationErrors($errors);
}
$this->em->persist($user);
$this->em->flush();
// Log in the newly created user.
$auth = $request->getAuth();
$auth->authenticate($data['username'], $data['password']);
$acl = $request->getAcl();
$acl->reload();
return $response->withRedirect($request->getRouter()->named('setup:index'));
} catch (Throwable $e) {
$error = $e->getMessage();
}
}
return $request->getView()->renderVuePage(
response: $response,
component: 'Setup/Register',
id: 'setup-register',
layout: 'minimal',
title: __('Set Up AzuraCast'),
props: [
'csrf' => $csrf->generate('register'),
'error' => $error,
]
);
}
/**
* Setup Step 2:
* Create Station and Parse Metadata
*/
public function stationAction(
ServerRequest $request,
Response $response
): ResponseInterface {
// Verify current step.
$currentStep = $this->getSetupStep($request);
if ($currentStep !== 'station' && $this->environment->isProduction()) {
return $response->withRedirect($request->getRouter()->named('setup:' . $currentStep));
}
$router = $request->getRouter();
return $request->getView()->renderVuePage(
response: $response,
component: 'Setup/Station',
id: 'setup-station',
title: __('Create a New Radio Station'),
props: array_merge(
$this->stationFormComponent->getProps($request),
[
'createUrl' => $router->named('api:admin:stations'),
'continueUrl' => $router->named('setup:settings'),
]
)
);
}
/**
* Setup Step 3:
* Set site settings.
*/
public function settingsAction(
ServerRequest $request,
Response $response
): ResponseInterface {
$router = $request->getRouter();
// Verify current step.
$currentStep = $this->getSetupStep($request);
if ($currentStep !== 'settings' && $this->environment->isProduction()) {
return $response->withRedirect($router->named('setup:' . $currentStep));
}
$router = $request->getRouter();
return $request->getView()->renderVuePage(
response: $response,
component: 'Setup/Settings',
id: 'setup-settings',
title: __('System Settings'),
props: [
...$this->settingsComponent->getProps($request),
'continueUrl' => $router->named('dashboard'),
],
);
}
/**
* Placeholder function for "setup complete" redirection.
*
* @param ServerRequest $request
* @param Response $response
*/
public function completeAction(
ServerRequest $request,
Response $response
): ResponseInterface {
$request->getFlash()->error('<b>' . __('Setup has already been completed!') . '</b>');
return $response->withRedirect($request->getRouter()->named('dashboard'));
}
/**
* Determine which step of setup is currently active.
*
* @param ServerRequest $request
*/
private function getSetupStep(ServerRequest $request): string
{
$settings = $this->readSettings();
if ($settings->isSetupComplete()) {
return 'complete';
}
// Step 1: Register
$numUsers = (int)$this->em->createQuery(
<<<'DQL'
SELECT COUNT(u.id) FROM App\Entity\User u
DQL
)->getSingleScalarResult();
if (0 === $numUsers) {
return 'register';
}
// If past "register" step, require login.
$auth = $request->getAuth();
if (!$auth->isLoggedIn()) {
throw NotLoggedInException::create($request);
}
// Step 2: Set up Station
$numStations = (int)$this->em->createQuery(
<<<'DQL'
SELECT COUNT(s.id) FROM App\Entity\Station s
DQL
)->getSingleScalarResult();
if (0 === $numStations) {
return 'station';
}
// Step 3: System Settings
return 'settings';
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/SetupController.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,535 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Controller\SingleActionInterface;
use App\Entity\Repository\CustomFieldRepository;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class RequestsAction implements SingleActionInterface
{
public function __construct(
private readonly CustomFieldRepository $customFieldRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
$router = $request->getRouter();
$customization = $request->getCustomization();
return $request->getView()->renderVuePage(
response: $response
->withHeader('X-Frame-Options', '*'),
component: 'Public/Requests',
id: 'song-requests',
layout: 'minimal',
title: __('Requests') . ' - ' . $station->getName(),
layoutParams: [
'page_class' => 'embed station-' . $station->getShortName(),
'hide_footer' => true,
],
props: [
'customFields' => $this->customFieldRepo->fetchArray(),
'showAlbumArt' => !$customization->hideAlbumArt(),
'requestListUri' => $router->named('api:requests:list', [
'station_id' => $station->getId(),
]),
],
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/RequestsAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 345 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Controller\SingleActionInterface;
use App\Entity\StationMount;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Radio\Adapters;
use Psr\Http\Message\ResponseInterface;
final class PlaylistAction implements SingleActionInterface
{
public function __construct(
private readonly Adapters $adapters,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $format */
$format = $params['format'] ?? 'pls';
$station = $request->getStation();
$streams = [];
$streamUrls = [];
$fa = $this->adapters->getFrontendAdapter($station);
if (null !== $fa) {
foreach ($station->getMounts() as $mount) {
/** @var StationMount $mount */
if (!$mount->getIsVisibleOnPublicPages()) {
continue;
}
$streamUrl = $fa->getUrlForMount($station, $mount);
$streamUrls[] = $streamUrl;
$streams[] = [
'name' => $station->getName() . ' - ' . $mount->getDisplayName(),
'url' => $streamUrl,
];
}
}
foreach ($station->getRemotes() as $remote) {
if (!$remote->getIsVisibleOnPublicPages()) {
continue;
}
$streamUrl = $this->adapters->getRemoteAdapter($remote)
->getPublicUrl($remote);
$streamUrls[] = $streamUrl;
$streams[] = [
'name' => $station->getName() . ' - ' . $remote->getDisplayName(),
'url' => $streamUrl,
];
}
if ($station->getEnableHls() && $station->getBackendType()->isEnabled()) {
$backend = $this->adapters->getBackendAdapter($station);
$backendConfig = $station->getBackendConfig();
if (null !== $backend && $backendConfig->getHlsEnableOnPublicPlayer()) {
$streamUrl = $backend->getHlsUrl($station);
$streamRow = [
'name' => $station->getName() . ' - HLS',
'url' => (string)$streamUrl,
];
if ($backendConfig->getHlsIsDefault()) {
array_unshift($streamUrls, $streamUrl);
array_unshift($streams, $streamRow);
} else {
$streamUrls[] = $streamUrl;
$streams[] = $streamRow;
}
}
}
$format = strtolower($format);
switch ($format) {
// M3U Playlist Format
case 'm3u':
$m3uFile = implode("\n", $streamUrls);
$response->getBody()->write($m3uFile);
return $response
->withHeader('Content-Type', 'audio/x-mpegurl')
->withHeader('Content-Disposition', 'attachment; filename=' . $station->getShortName() . '.m3u');
// PLS Playlist Format
case 'pls':
default:
$output = [
'[playlist]',
];
$i = 1;
foreach ($streams as $stream) {
$output[] = 'File' . $i . '=' . $stream['url'];
$output[] = 'Title' . $i . '=' . $stream['name'];
$output[] = 'Length' . $i . '=-1';
$output[] = '';
$i++;
}
$output[] = 'NumberOfEntries=' . count($streams);
$output[] = 'Version=2';
$response->getBody()->write(implode("\n", $output));
return $response
->withHeader('Content-Type', 'audio/x-scpls')
->withHeader('Content-Disposition', 'attachment; filename=' . $station->getShortName() . '.pls');
}
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/PlaylistAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 888 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Controller\SingleActionInterface;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\VueComponent\NowPlayingComponent;
use Psr\Http\Message\ResponseInterface;
final class HistoryAction implements SingleActionInterface
{
public function __construct(
private readonly NowPlayingComponent $nowPlayingComponent
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
$view = $request->getView();
// Add station public code.
$view->fetch(
'frontend/public/partials/station-custom',
['station' => $station]
);
return $view->renderVuePage(
response: $response->withHeader('X-Frame-Options', '*'),
component: 'Public/History',
id: 'song-history',
layout: 'minimal',
title: __('History') . ' - ' . $station->getName(),
layoutParams: [
'page_class' => 'embed station-' . $station->getShortName(),
'hide_footer' => true,
],
props: $this->nowPlayingComponent->getProps($request),
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/HistoryAction.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\Controller\Frontend\PublicPages;
use App\Controller\SingleActionInterface;
use App\Enums\StationFeatures;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Radio\Adapters;
use League\Plates\Template\Template;
use Psr\Http\Message\ResponseInterface;
final class WebDjAction implements SingleActionInterface
{
public function __construct(
private readonly Adapters $adapters,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
StationFeatures::Streamers->assertSupportedForStation($station);
$backend = $this->adapters->requireBackendAdapter($station);
$wssUrl = (string)$backend->getWebStreamingUrl($station, $request->getRouter()->getBaseUrl());
$view = $request->getView();
// Add station public code.
$view->fetch(
'frontend/public/partials/station-custom',
['station' => $station]
);
$view->getSections()->set(
'bodyjs',
<<<'HTML'
<script src="/static/js/taglib.js"></script>
HTML,
Template::SECTION_MODE_APPEND
);
return $view->renderVuePage(
response: $response
->withHeader('X-Frame-Options', '*')
->withHeader('X-Robots-Tag', 'index, nofollow'),
component: 'Public/WebDJ',
id: 'webdj',
layout: 'minimal',
title: __('Web DJ') . ' - ' . $station->getName(),
layoutParams: [
'page_class' => 'dj station-' . $station->getShortName(),
],
props: [
'baseUri' => $wssUrl,
],
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/WebDjAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 438 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Container\EntityManagerAwareTrait;
use App\Controller\Frontend\PublicPages\Traits\IsEmbeddable;
use App\Controller\SingleActionInterface;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class OnDemandAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
use IsEmbeddable;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
// Get list of custom fields.
/** @var array<array{id: int, short_name: string, name: string}> $customFieldsRaw */
$customFieldsRaw = $this->em->createQuery(
<<<'DQL'
SELECT cf.id, cf.short_name, cf.name
FROM App\Entity\CustomField cf ORDER BY cf.name ASC
DQL
)->getArrayResult();
$customFields = [];
foreach ($customFieldsRaw as $row) {
$customFields[] = [
'display_key' => 'custom_field_' . $row['id'],
'key' => $row['short_name'],
'label' => $row['name'],
];
}
$router = $request->getRouter();
$pageClass = 'ondemand station-' . $station->getShortName();
if ($this->isEmbedded($request, $params)) {
$pageClass .= ' embed';
}
$view = $request->getView();
// Add station public code.
$view->fetch(
'frontend/public/partials/station-custom',
['station' => $station]
);
return $view->renderVuePage(
response: $response->withHeader('X-Frame-Options', '*'),
component: 'Public/OnDemand',
id: 'station-on-demand',
layout: 'minimal',
title: __('On-Demand Media') . ' - ' . $station->getName(),
layoutParams: [
'page_class' => $pageClass,
'hide_footer' => true,
],
props: [
'listUrl' => $router->fromHere('api:stations:ondemand:list'),
'showDownloadButton' => $station->getEnableOnDemandDownload(),
'customFields' => $customFields,
'stationName' => $station->getName(),
]
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/OnDemandAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 564 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Controller\Frontend\PublicPages\Traits\IsEmbeddable;
use App\Controller\SingleActionInterface;
use App\Entity\Repository\CustomFieldRepository;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\VueComponent\NowPlayingComponent;
use Psr\Http\Message\ResponseInterface;
final class PlayerAction implements SingleActionInterface
{
use IsEmbeddable;
public function __construct(
private readonly CustomFieldRepository $customFieldRepo,
private readonly NowPlayingComponent $nowPlayingComponent
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$embed = $this->isEmbedded($request, $params);
$response = $response
->withHeader('X-Frame-Options', '*')
->withHeader('X-Robots-Tag', 'index, nofollow');
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
// Build Vue props.
$router = $request->getRouter();
$props = $this->nowPlayingComponent->getProps($request);
// Render embedded player.
if ($embed) {
$pageClasses = [];
$pageClasses[] = 'page-station-public-player-embed station-' . $station->getShortName();
$pageClasses[] = ('social' === ($params['embed'] ?? null)) ? 'embed-social' : 'embed';
$view = $request->getView();
// Add station public code.
$view->fetch(
'frontend/public/partials/station-custom',
['station' => $station]
);
return $view->renderVuePage(
response: $response,
component: 'Public/Player',
id: 'station-nowplaying',
layout: 'minimal',
title: $station->getName(),
layoutParams: [
'page_class' => implode(' ', $pageClasses),
'hide_footer' => true,
],
props: $props,
);
}
$props['downloadPlaylistUri'] = $router->named(
'public:playlist',
['station_id' => $station->getShortName(), 'format' => 'pls']
);
// Auto-redirect requests from players to the playlist (PLS) download.
$userAgent = strtolower($request->getHeaderLine('User-Agent'));
$players = ['mpv', 'player', 'vlc', 'applecoremedia'];
foreach ($players as $player) {
if (str_contains($userAgent, $player)) {
return $response->withRedirect($props['downloadPlaylistUri']);
}
}
// Render full page player.
$props['stationName'] = $station->getName();
$props['enableRequests'] = $station->getEnableRequests();
$props['requestListUri'] = $router->named(
'api:requests:list',
['station_id' => $station->getId()]
);
$props['customFields'] = $this->customFieldRepo->fetchArray();
return $request->getView()->renderToResponse(
$response,
'frontend/public/index',
[
'station' => $station,
'props' => $props,
'nowPlayingArtUri' => $router->named(
routeName: 'api:nowplaying:art',
routeParams: ['station_id' => $station->getShortName(), 'timestamp' => time()],
absolute: true
),
]
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/PlayerAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 793 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Controller\Frontend\PublicPages\Traits\IsEmbeddable;
use App\Controller\SingleActionInterface;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Utilities\Types;
use Psr\Http\Message\ResponseInterface;
final class PodcastsAction implements SingleActionInterface
{
use IsEmbeddable;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
$isEmbedded = $this->isEmbedded($request, $params);
$pageClass = 'podcasts station-' . $station->getShortName();
if ($isEmbedded) {
$pageClass .= ' embed';
}
$groupLayout = Types::string($request->getQueryParam('layout'), 'table', true);
$router = $request->getRouter();
$view = $request->getView();
// Add station public code.
$view->fetch(
'frontend/public/partials/station-custom',
['station' => $station]
);
return $view->renderVuePage(
response: $response
->withHeader('X-Frame-Options', '*')
->withHeader('X-Robots-Tag', 'index, nofollow'),
component: 'Public/Podcasts',
id: 'podcast',
layout: 'minimal',
title: 'Podcasts - ' . $station->getName(),
layoutParams: [
'page_class' => $pageClass,
'hide_footer' => $isEmbedded,
],
props: [
'baseUrl' => $router->fromHere('public:index'),
'groupLayout' => $groupLayout,
],
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/PodcastsAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 417 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Controller\SingleActionInterface;
use App\Entity\ApiGenerator\PodcastApiGenerator;
use App\Entity\ApiGenerator\PodcastEpisodeApiGenerator;
use App\Entity\PodcastCategory;
use App\Entity\PodcastEpisode;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Xml\Writer;
use Carbon\CarbonImmutable;
use Psr\Http\Message\ResponseInterface;
use Ramsey\Uuid\Uuid;
final class PodcastFeedAction implements SingleActionInterface
{
public const string PODCAST_NAMESPACE = 'ead4c236-bf58-58c6-a2c6-a6b28d128cb6';
public function __construct(
private readonly PodcastApiGenerator $podcastApiGenerator,
private readonly PodcastEpisodeApiGenerator $episodeApiGenerator
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
$podcast = $request->getPodcast();
// Fetch podcast API feed.
$podcastApi = $this->podcastApiGenerator->__invoke($podcast, $request);
$now = CarbonImmutable::now($station->getTimezoneObject());
$rss = [
'@xmlns:itunes' => 'path_to_url
'@xmlns:sy' => 'path_to_url
'@xmlns:slash' => 'path_to_url
'@xmlns:atom' => 'path_to_url
'@xmlns:podcast' => 'path_to_url
'@version' => '2.0',
];
$channel = [
'title' => $podcastApi->title,
'link' => $podcastApi->link ?? $podcastApi->links['public_episodes'],
'description' => $podcastApi->description,
'language' => $podcastApi->language,
'lastBuildDate' => $now->toRssString(),
'category' => $podcast->getCategories()->map(
function (PodcastCategory $podcastCategory) {
return (null === $podcastCategory->getSubTitle())
? $podcastCategory->getTitle()
: $podcastCategory->getSubTitle();
}
)->getValues(),
'ttl' => 5,
'image' => [
'url' => $podcastApi->art,
'title' => $podcastApi->title,
],
'itunes:author' => $podcastApi->author,
'itunes:owner' => [],
'itunes:image' => [
'@href' => $podcastApi->art,
],
'itunes:explicit' => 'false',
'itunes:category' => $podcast->getCategories()->map(
function (PodcastCategory $podcastCategory) {
return (null === $podcastCategory->getSubTitle())
? [
'@text' => $podcastCategory->getTitle(),
] : [
'@text' => $podcastCategory->getTitle(),
'itunes:category' => [
'@text' => $podcastCategory->getSubTitle(),
],
];
}
)->getValues(),
'atom:link' => [
'@rel' => 'self',
'@type' => 'application/rss+xml',
'@href' => (string)$request->getUri(),
],
'podcast:guid' => $this->buildPodcastGuid($podcastApi->links['public_feed']),
'item' => [],
];
if (null !== $podcastApi->link) {
$channel['image']['link'] = $podcastApi->link;
}
if (empty($podcastApi->author) && empty($podcastApi->email)) {
unset($channel['itunes:owner']);
} else {
$channel['itunes:owner'] = [
'itunes:name' => $podcastApi->author,
'itunes:email' => $podcastApi->email,
];
}
// Iterate through episodes.
$hasPublishedEpisode = false;
$hasExplicitEpisode = false;
/** @var PodcastEpisode $episode */
foreach ($podcast->getEpisodes() as $episode) {
if (!$episode->isPublished()) {
continue;
}
$hasPublishedEpisode = true;
if ($episode->getExplicit()) {
$hasExplicitEpisode = true;
}
$channel['item'][] = $this->buildItemForEpisode($episode, $request);
}
if (!$hasPublishedEpisode) {
throw NotFoundException::podcast();
}
if ($hasExplicitEpisode) {
$channel['itunes:explicit'] = 'true';
}
$rss['channel'] = $channel;
$response->getBody()->write(
Writer::toString($rss, 'rss')
);
return $response
->withHeader('Content-Type', 'application/rss+xml')
->withHeader('X-Robots-Tag', 'index, nofollow');
}
private function buildItemForEpisode(PodcastEpisode $episode, ServerRequest $request): array
{
$station = $request->getStation();
$episodeApi = $this->episodeApiGenerator->__invoke($episode, $request);
$publishedAt = CarbonImmutable::createFromTimestamp($episodeApi->publish_at, $station->getTimezoneObject());
$item = [
'title' => $episodeApi->title,
'link' => $episodeApi->link ?? $episodeApi->links['public'],
'description' => $episodeApi->description,
'enclosure' => [
'@url' => $episodeApi->links['download'],
],
'guid' => [
'@isPermaLink' => 'false',
'_' => $episodeApi->id,
],
'pubDate' => $publishedAt->toRssString(),
'itunes:image' => [
'@href' => $episodeApi->art,
],
'itunes:explicit' => $episodeApi->explicit ? 'true' : 'false',
];
$podcastMedia = $episode->getMedia();
if (null !== $podcastMedia) {
$item['enclosure']['@length'] = $podcastMedia->getLength();
$item['enclosure']['@type'] = $podcastMedia->getMimeType();
}
if (null !== $episodeApi->season_number) {
$item['itunes:season'] = (string)$episodeApi->season_number;
}
if (null !== $episodeApi->episode_number) {
$item['itunes:episode'] = (string)$episodeApi->episode_number;
}
return $item;
}
private function buildPodcastGuid(string $uri): string
{
$baseUri = rtrim(
str_replace(['path_to_url 'path_to_url '', $uri),
'/'
);
return (string)Uuid::uuid5(
self::PODCAST_NAMESPACE,
$baseUri
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/PodcastFeedAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,553 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages;
use App\Controller\SingleActionInterface;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Xml\Writer;
use Psr\Http\Message\ResponseInterface;
final class OEmbedAction implements SingleActionInterface
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
$format = $params['format'] ?? 'json';
$router = $request->getRouter();
$embedUrl = $router->named(
'public:index',
['station_id' => $station->getShortName(), 'embed' => 'social'],
[],
true
);
$result = [
'version' => '1.0',
'title' => $station->getName(),
'thumbnail_url' => $router->named(
routeName: 'api:nowplaying:art',
routeParams: ['station_id' => $station->getShortName(), 'timestamp' => time()],
absolute: true
),
'thumbnail_width' => 128,
'thumbnail_height' => 128,
'provider_name' => 'AzuraCast',
'provider_url' => 'path_to_url
'type' => 'rich',
'width' => 400,
'height' => 200,
'html' => <<<HTML
<iframe width="100%" height="200" sandbox="allow-same-origin allow-scripts allow-popups"
src="$embedUrl" frameborder="0" allowfullscreen/>
HTML,
];
return match ($format) {
'xml' => $response->write(Writer::toString($result, 'oembed')),
default => $response->withJson($result)
};
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/OEmbedAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 426 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\PublicPages\Traits;
use App\Http\ServerRequest;
use App\Utilities\Types;
trait IsEmbeddable
{
private function isEmbedded(
ServerRequest $request,
array $params
): bool {
$embedParam = Types::stringOrNull($params['embed'] ?? null, true);
if (null !== $embedParam) {
return true;
}
return Types::bool(
$request->getQueryParam('embed'),
false,
true
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PublicPages/Traits/IsEmbeddable.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\Controller\Frontend\Account;
use App\Controller\SingleActionInterface;
use App\Entity\Repository\UserLoginTokenRepository;
use App\Entity\Repository\UserRepository;
use App\Entity\User;
use App\Exception\Http\RateLimitExceededException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\RateLimit;
use App\Service\Mail;
use App\Utilities\Types;
use Psr\Http\Message\ResponseInterface;
final class ForgotPasswordAction implements SingleActionInterface
{
public function __construct(
private readonly UserRepository $userRepo,
private readonly UserLoginTokenRepository $loginTokenRepo,
private readonly RateLimit $rateLimit,
private readonly Mail $mail
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$flash = $request->getFlash();
$view = $request->getView();
if (!$this->mail->isEnabled()) {
return $view->renderToResponse($response, 'frontend/account/forgot_disabled');
}
if ($request->isPost()) {
try {
$this->rateLimit->checkRequestRateLimit($request, 'forgot', 30, 3);
} catch (RateLimitExceededException) {
$flash->error(
sprintf(
'<b>%s</b><br>%s',
__('Too many forgot password attempts'),
__(
'You have attempted to reset your password too many times. Please wait '
. '30 seconds and try again.'
)
),
);
return $response->withRedirect($request->getUri()->getPath());
}
$email = Types::string($request->getParsedBodyParam('email'));
$user = $this->userRepo->findByEmail($email);
if ($user instanceof User) {
$email = $this->mail->createMessage();
$email->to($user->getEmail());
$email->subject(__('Account Recovery'));
$loginToken = $this->loginTokenRepo->createToken($user);
$email->text(
$view->render(
'mail/forgot',
[
'token' => (string)$loginToken,
]
)
);
$this->mail->send($email);
}
$flash->success(
sprintf(
'<b>%s</b><br>%s',
__('Account recovery e-mail sent.'),
__(
'If the e-mail address you provided is in the system, check your inbox '
. 'for a password reset message.'
)
),
);
return $response->withRedirect($request->getRouter()->named('account:login'));
}
return $view->renderToResponse($response, 'frontend/account/forgot');
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/ForgotPasswordAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 599 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Account;
use App\Container\EntityManagerAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\Repository\UserLoginTokenRepository;
use App\Entity\User;
use App\Http\Response;
use App\Http\ServerRequest;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use Throwable;
final class RecoverAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
public function __construct(
private readonly UserLoginTokenRepository $loginTokenRepo,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
/** @var string $token */
$token = $params['token'];
$user = $this->loginTokenRepo->authenticate($token);
$flash = $request->getFlash();
if (!$user instanceof User) {
$flash->error(
sprintf(
'<b>%s</b>',
__('Invalid token specified.'),
),
);
return $response->withRedirect($request->getRouter()->named('account:login'));
}
$csrf = $request->getCsrf();
$error = null;
if ($request->isPost()) {
try {
$data = $request->getParams();
$csrf->verify($data['csrf'] ?? null, 'recover');
if (empty($data['password'])) {
throw new InvalidArgumentException('Password required.');
}
$user->setNewPassword($data['password']);
$user->setTwoFactorSecret();
$this->em->persist($user);
$this->em->flush();
$request->getAuth()->setUser($user);
$this->loginTokenRepo->revokeForUser($user);
$flash->success(
sprintf(
'<b>%s</b><br>%s',
__('Logged in using account recovery token'),
__('Your password has been updated.')
),
);
return $response->withRedirect($request->getRouter()->named('dashboard'));
} catch (Throwable $e) {
$error = $e->getMessage();
}
}
return $request->getView()->renderVuePage(
response: $response,
component: 'Recover',
id: 'account-recover',
layout: 'minimal',
title: __('Recover Account'),
props: [
'csrf' => $csrf->generate('recover'),
'error' => $error,
]
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/RecoverAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 537 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Account;
use App\Controller\SingleActionInterface;
use App\Entity\Repository\UserRepository;
use App\Entity\User;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Utilities\Types;
use Psr\Http\Message\ResponseInterface;
final class MasqueradeAction implements SingleActionInterface
{
public const string CSRF_NAMESPACE = 'user_masquerade';
public function __construct(
private readonly UserRepository $userRepo,
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$id = Types::string($params['id']);
$csrf = Types::string($params['csrf']);
$request->getCsrf()->verify($csrf, self::CSRF_NAMESPACE);
$user = $this->userRepo->find($id);
if (!($user instanceof User)) {
throw new NotFoundException(__('User not found.'));
}
$auth = $request->getAuth();
$auth->masqueradeAsUser($user);
$request->getFlash()->success(
'<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(),
);
return $response->withRedirect($request->getRouter()->named('dashboard'));
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/MasqueradeAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 293 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Account;
use App\Controller\SingleActionInterface;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class LogoutAction implements SingleActionInterface
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$auth = $request->getAuth();
$auth->logout();
return $response->withRedirect($request->getRouter()->named('account:login'));
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/LogoutAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 121 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Account;
use App\Controller\SingleActionInterface;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class EndMasqueradeAction implements SingleActionInterface
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$auth = $request->getAuth();
$auth->endMasquerade();
$router = $request->getRouter();
return $response->withRedirect($router->named('admin:users:index'));
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/EndMasqueradeAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 135 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Account;
use App\Controller\SingleActionInterface;
use App\Entity\User;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Utilities\Types;
use Psr\Http\Message\ResponseInterface;
final class TwoFactorAction implements SingleActionInterface
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$auth = $request->getAuth();
if ($request->isPost()) {
$flash = $request->getFlash();
$otp = Types::string($request->getParam('otp'));
if ($auth->verifyTwoFactor($otp)) {
/** @var User $user */
$user = $auth->getUser();
$flash->success(
'<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(),
);
$referrer = Types::stringOrNull($request->getSession()->get('login_referrer'), true);
return $response->withRedirect(
$referrer ?? $request->getRouter()->named('dashboard')
);
}
$flash->error(
'<b>' . __('Login unsuccessful') . '</b><br>' . __('Your credentials could not be verified.'),
);
return $response->withRedirect((string)$request->getUri());
}
return $request->getView()->renderToResponse($response, 'frontend/account/two_factor');
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/TwoFactorAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 317 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Account;
use App\Container\EntityManagerAwareTrait;
use App\Container\SettingsAwareTrait;
use App\Controller\SingleActionInterface;
use App\Entity\User;
use App\Exception\Http\RateLimitExceededException;
use App\Http\Response;
use App\Http\ServerRequest;
use App\RateLimit;
use App\Utilities\Types;
use Mezzio\Session\SessionCookiePersistenceInterface;
use Psr\Http\Message\ResponseInterface;
final class LoginAction implements SingleActionInterface
{
use EntityManagerAwareTrait;
use SettingsAwareTrait;
public function __construct(
private readonly RateLimit $rateLimit
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$auth = $request->getAuth();
$acl = $request->getAcl();
// Check installation completion progress.
$settings = $this->readSettings();
if (!$settings->isSetupComplete()) {
$numUsers = (int)$this->em->createQuery(
<<<'DQL'
SELECT COUNT(u.id) FROM App\Entity\User u
DQL
)->getSingleScalarResult();
if (0 === $numUsers) {
return $response->withRedirect($request->getRouter()->named('setup:index'));
}
}
if ($auth->isLoggedIn()) {
return $response->withRedirect($request->getRouter()->named('dashboard'));
}
$flash = $request->getFlash();
if ($request->isPost()) {
try {
$this->rateLimit->checkRequestRateLimit($request, 'login', 30, 5);
} catch (RateLimitExceededException) {
$flash->error(
sprintf(
'<b>%s</b><br>%s',
__('Too many login attempts'),
__('You have attempted to log in too many times. Please wait 30 seconds and try again.')
),
);
return $response->withRedirect($request->getUri()->getPath());
}
$user = $auth->authenticate(
Types::string($request->getParam('username')),
Types::string($request->getParam('password'))
);
if ($user instanceof User) {
$session = $request->getSession();
// If user selects "remember me", extend the cookie/session lifetime.
if ($session instanceof SessionCookiePersistenceInterface) {
$rememberMe = Types::bool($request->getParam('remember'), false, true);
/** @noinspection SummerTimeUnsafeTimeManipulationInspection */
$session->persistSessionFor(($rememberMe) ? 86400 * 14 : 0);
}
// Reload ACL permissions.
$acl->reload();
// Persist user as database entity.
$this->em->persist($user);
$this->em->flush();
// Redirect for 2FA.
if (!$auth->isLoginComplete()) {
return $response->withRedirect($request->getRouter()->named('account:login:2fa'));
}
// Redirect to complete setup if it's not completed yet.
if (!$settings->isSetupComplete()) {
$flash->success(
sprintf(
'<b>%s</b><br>%s',
__('Logged in successfully.'),
__('Complete the setup process to get started.')
),
);
return $response->withRedirect($request->getRouter()->named('setup:index'));
}
$flash->success(
'<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(),
);
$referrer = Types::stringOrNull($session->get('login_referrer'), true);
return $response->withRedirect(
$referrer ?? $request->getRouter()->named('dashboard')
);
}
$flash->error(
'<b>' . __('Login unsuccessful') . '</b><br>' . __('Your credentials could not be verified.'),
);
return $response->withRedirect((string)$request->getUri());
}
$customization = $request->getCustomization();
$router = $request->getRouter();
return $request->getView()->renderVuePage(
response: $response,
component: 'Login',
id: 'account-login',
layout: 'minimal',
title: __('Log In'),
layoutParams: [
'page_class' => 'login-content',
],
props: [
'hideProductName' => $customization->hideProductName(),
'instanceName' => $customization->getInstanceName(),
'forgotPasswordUrl' => $router->named('account:forgot'),
'webAuthnUrl' => $router->named('account:webauthn'),
]
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/LoginAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,019 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Account\WebAuthn;
use App\Controller\Traits\UsesWebAuthnTrait;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class GetValidationAction
{
use UsesWebAuthnTrait;
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$webAuthn = $this->getWebAuthn($request);
$getArgs = $webAuthn->getGetArgs(
[],
self::WEBAUTHN_TIMEOUT,
requireUserVerification: 'preferred'
);
$this->setChallenge($request, $webAuthn->getChallenge());
return $response->withJson($getArgs);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/WebAuthn/GetValidationAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 176 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Account\WebAuthn;
use App\Controller\Traits\UsesWebAuthnTrait;
use App\Entity\Repository\UserPasskeyRepository;
use App\Entity\UserPasskey;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Utilities\Types;
use InvalidArgumentException;
use Mezzio\Session\SessionCookiePersistenceInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;
final class PostValidationAction
{
use UsesWebAuthnTrait;
public function __construct(
private readonly UserPasskeyRepository $passkeyRepo
) {
}
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$webAuthn = $this->getWebAuthn($request);
$parsedBody = Types::array($request->getParsedBody());
$validateData = json_decode($parsedBody['validateData'] ?? '', true, 512, JSON_THROW_ON_ERROR);
$challenge = $this->getChallenge($request);
try {
$record = $this->passkeyRepo->findById(base64_decode($validateData['id']));
if (!($record instanceof UserPasskey)) {
throw new InvalidArgumentException('This passkey does not correspond to a valid user.');
}
// Validate the passkey. Exception thrown if invalid.
$webAuthn->processGet(
base64_decode($validateData['clientDataJSON'] ?? ''),
base64_decode($validateData['authenticatorData'] ?? ''),
base64_decode($validateData['signature'] ?? ''),
$record->getPasskey()->getPublicKeyPem(),
$challenge
);
} catch (Throwable $e) {
$flash = $request->getFlash();
$flash->error(
'<b>' . __('Login unsuccessful') . '</b><br>' . $e->getMessage(),
);
return $response->withRedirect($request->getRouter()->named('dashboard'));
}
$user = $record->getUser();
$auth = $request->getAuth();
$auth->setUser($user, true);
$session = $request->getSession();
if ($session instanceof SessionCookiePersistenceInterface) {
$session->persistSessionFor(86400 * 14);
}
$acl = $request->getAcl();
$acl->reload();
$flash = $request->getFlash();
$flash->success(
'<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(),
);
$referrer = $session->get('login_referrer');
return $response->withRedirect(
(!empty($referrer)) ? $referrer : $request->getRouter()->named('dashboard')
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Account/WebAuthn/PostValidationAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 594 |
```php
<?php
declare(strict_types=1);
namespace App\Controller\Frontend\Profile;
use App\Controller\SingleActionInterface;
use App\Enums\SupportedLocales;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class IndexAction implements SingleActionInterface
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$supportedLocales = [];
foreach (SupportedLocales::cases() as $supportedLocale) {
$supportedLocales[$supportedLocale->value] = $supportedLocale->getLocalName();
}
return $request->getView()->renderVuePage(
response: $response,
component: 'Account',
id: 'account',
title: __('My Account'),
props: [
'supportedLocales' => $supportedLocales,
]
);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/Profile/IndexAction.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\Controller\Frontend\PWA;
use App\Controller\SingleActionInterface;
use App\Enums\SupportedThemes;
use App\Exception\NotFoundException;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;
final class AppManifestAction implements SingleActionInterface
{
public function __invoke(
ServerRequest $request,
Response $response,
array $params
): ResponseInterface {
$station = $request->getStation();
if (!$station->getEnablePublicPage()) {
throw NotFoundException::station();
}
$customization = $request->getCustomization();
$manifest = [
'name' => $station->getName() . ' - AzuraCast',
'short_name' => $station->getName(),
'description' => $station->getDescription(),
'scope' => '/public/',
'start_url' => '.',
'display' => 'standalone',
'theme_color' => '#2196F3',
'categories' => [
'music',
],
'icons' => [
[
'src' => $customization->getBrowserIconUrl(36),
'sizes' => '36x36',
'type' => 'image/png',
'density' => '0.75',
],
[
'src' => $customization->getBrowserIconUrl(48),
'sizes' => '48x48',
'type' => 'image/png',
'density' => '1.0',
],
[
'src' => $customization->getBrowserIconUrl(72),
'sizes' => '72x72',
'type' => 'image/png',
'density' => '1.5',
],
[
'src' => $customization->getBrowserIconUrl(96),
'sizes' => '96x96',
'type' => 'image/png',
'density' => '2.0',
],
[
'src' => $customization->getBrowserIconUrl(144),
'sizes' => '144x144',
'type' => 'image/png',
'density' => '3.0',
],
[
'src' => $customization->getBrowserIconUrl(192),
'sizes' => '192x192',
'type' => 'image/png',
'density' => '4.0',
],
],
];
$customization = $request->getCustomization();
$publicTheme = $customization->getPublicTheme();
if (SupportedThemes::Browser !== $publicTheme) {
$manifest['background_color'] = match ($publicTheme) {
SupportedThemes::Dark => '#222222',
default => '#EEEEEE'
};
}
return $response
->withHeader('Content-Type', 'application/manifest+json')
->withJson($manifest);
}
}
``` | /content/code_sandbox/backend/src/Controller/Frontend/PWA/AppManifestAction.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 638 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityManagerInterface;
use IteratorAggregate;
use Traversable;
/**
* @template TKey
* @template TValue
* @implements IteratorAggregate<TKey, TValue>
*/
abstract class AbstractBatchIteratorAggregate implements IteratorAggregate
{
protected iterable $resultSet;
protected EntityManagerInterface $entityManager;
protected int $batchSize;
protected bool $clearMemoryWithFlush = true;
public static function fromQuery(
AbstractQuery $query,
int $batchSize
): static {
return new static($query->toIterable(), $query->getEntityManager(), $batchSize);
}
public static function fromArrayResult(
array $results,
EntityManagerInterface $entityManager,
int $batchSize
): static {
return new static($results, $entityManager, $batchSize);
}
public static function fromTraversableResult(
Traversable $results,
EntityManagerInterface $entityManager,
int $batchSize
): static {
return new static($results, $entityManager, $batchSize);
}
/**
* BatchIteratorAggregate constructor (private by design: use a named constructor instead).
*
* @param iterable<TKey, TValue> $resultSet
*/
final protected function __construct(
iterable $resultSet,
EntityManagerInterface $entityManager,
int $batchSize
) {
$this->resultSet = $resultSet;
$this->entityManager = $entityManager;
$this->batchSize = $batchSize;
}
public function setBatchSize(int $batchSize): void
{
$this->batchSize = $batchSize;
}
public function setClearMemoryWithFlush(bool $clearMemoryWithFlush): void
{
$this->clearMemoryWithFlush = $clearMemoryWithFlush;
}
/**
* @return Traversable<TKey, TValue>
*/
abstract public function getIterator(): Traversable;
}
``` | /content/code_sandbox/backend/src/Doctrine/AbstractBatchIteratorAggregate.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 416 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine;
use Closure;
use RuntimeException;
use Throwable;
use Traversable;
use function get_class;
use function is_array;
use function is_object;
use function key;
/**
* @template TKey
* @template TValue
* @extends AbstractBatchIteratorAggregate<TKey, TValue>
*/
final class ReadWriteBatchIteratorAggregate extends AbstractBatchIteratorAggregate
{
private ?Closure $customFetchFunction = null;
public function setCustomFetchFunction(?callable $customFetchFunction = null): void
{
$this->customFetchFunction = (null === $customFetchFunction)
? null
: $customFetchFunction(...);
}
/** @inheritDoc */
public function getIterator(): Traversable
{
$iteration = 0;
$resultSet = $this->resultSet;
$this->entityManager->beginTransaction();
try {
foreach ($resultSet as $key => $value) {
++$iteration;
yield $key => $this->getObjectFromValue($value);
$this->flushAndClearBatch($iteration);
}
} catch (Throwable $exception) {
$this->entityManager->rollback();
throw $exception;
}
$this->flushAndClearEntityManager();
$this->entityManager->commit();
}
private function getObjectFromValue(mixed $value): mixed
{
if ($this->customFetchFunction instanceof Closure) {
return ($this->customFetchFunction)($value, $this->entityManager);
}
if (is_array($value)) {
$firstKey = key($value);
if (
$firstKey !== null && is_object(
$value[$firstKey]
) && $value === [$firstKey => $value[$firstKey]]
) {
return $this->reFetchObject($value[$firstKey]);
}
}
if (!is_object($value)) {
return $value;
}
return $this->reFetchObject($value);
}
private function reFetchObject(object $object): object
{
$metadata = $this->entityManager->getClassMetadata(get_class($object));
/** @psalm-var class-string $classname */
$classname = $metadata->getName();
$freshValue = $this->entityManager->find($classname, $metadata->getIdentifierValues($object));
if (!$freshValue) {
throw new RuntimeException(
sprintf(
'Requested batch item %s#%s (of type %s) with identifier "%s" could not be found',
get_class($object),
spl_object_hash($object),
$metadata->getName(),
json_encode($metadata->getIdentifierValues($object), JSON_THROW_ON_ERROR)
)
);
}
return $freshValue;
}
private function flushAndClearBatch(int $iteration): void
{
if ($iteration % $this->batchSize) {
return;
}
$this->flushAndClearEntityManager();
}
private function flushAndClearEntityManager(): void
{
$this->entityManager->flush();
$this->entityManager->clear();
if ($this->clearMemoryWithFlush) {
gc_collect_cycles();
}
}
}
``` | /content/code_sandbox/backend/src/Doctrine/ReadWriteBatchIteratorAggregate.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 679 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine;
use Traversable;
/**
* @template TKey
* @template TValue
* @extends AbstractBatchIteratorAggregate<TKey, TValue>
*/
final class ReadOnlyBatchIteratorAggregate extends AbstractBatchIteratorAggregate
{
/** @inheritDoc */
public function getIterator(): Traversable
{
$iteration = 0;
foreach ($this->resultSet as $key => $value) {
++$iteration;
yield $key => $value;
$this->entityManager->detach($value);
$this->clearBatch($iteration);
}
$this->clearMemory();
}
private function clearBatch(int $iteration): void
{
if ($iteration % $this->batchSize) {
return;
}
$this->clearMemory();
}
private function clearMemory(): void
{
if ($this->clearMemoryWithFlush) {
gc_collect_cycles();
}
}
}
``` | /content/code_sandbox/backend/src/Doctrine/ReadOnlyBatchIteratorAggregate.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\Doctrine;
use Doctrine\ORM\EntityManagerInterface;
interface ReloadableEntityManagerInterface extends EntityManagerInterface
{
/**
* Fetch a fresh instance of an entity object, even if the EntityManager has been cleared.
*
* phpcs:disable SlevomatCodingStandard.TypeHints.ReturnTypeHint
*
* @template TEntity as object
*
* @param TEntity $entity
*
* @return TEntity
*/
public function refetch(object $entity): object;
/**
* Fetch a fresh reference to an entity object, even if the EntityManager has been cleared.
*
* phpcs:disable SlevomatCodingStandard.TypeHints.ReturnTypeHint
*
* @template TEntity as object
*
* @param TEntity $entity
*
* @return TEntity
*/
public function refetchAsReference(object $entity): object;
}
``` | /content/code_sandbox/backend/src/Doctrine/ReloadableEntityManagerInterface.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 193 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine;
use App\Entity\Interfaces\IdentifiableEntityInterface;
use Closure;
use Doctrine\ORM\Decorator\EntityManagerDecorator;
use Doctrine\ORM\ORMInvalidArgumentException;
final class DecoratedEntityManager extends EntityManagerDecorator implements ReloadableEntityManagerInterface
{
private Closure $createEm;
public function __construct(callable $createEm)
{
parent::__construct($createEm());
$this->createEm = $createEm(...);
}
/**
* Recreate the underlying EntityManager if it was closed due to a previous exception.
*/
public function open(): void
{
if (!$this->wrapped->isOpen()) {
$this->wrapped = ($this->createEm)();
}
}
/**
* Preventing a situation where duplicate rows are created.
* @see path_to_url
*
* @inheritDoc
*/
public function persist($object): void
{
if ($object instanceof IdentifiableEntityInterface) {
$oldId = $object->getId();
$this->wrapped->persist($object);
if (null !== $oldId && $oldId !== $object->getId()) {
throw ORMInvalidArgumentException::detachedEntityCannot($object, 'persisted - ID changed by Doctrine');
}
} else {
$this->wrapped->persist($object);
}
}
/**
* @inheritDoc
*
* @template TEntity as object
*
* @param TEntity $entity
*
* @return TEntity
*/
public function refetch(object $entity): object
{
// phpcs:enable
$metadata = $this->wrapped->getClassMetadata(get_class($entity));
/** @var TEntity|null $freshValue */
$freshValue = $this->wrapped->find($metadata->getName(), $metadata->getIdentifierValues($entity));
if (!$freshValue) {
throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'refetch');
}
return $freshValue;
}
/**
* @inheritDoc
*
* @template TEntity as object
*
* @param TEntity $entity
*
* @return TEntity
*/
public function refetchAsReference(object $entity): object
{
// phpcs:enable
$metadata = $this->wrapped->getClassMetadata(get_class($entity));
/** @var TEntity|null $freshValue */
$freshValue = $this->wrapped->getReference($metadata->getName(), $metadata->getIdentifierValues($entity));
if (!$freshValue) {
throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'refetch');
}
return $freshValue;
}
}
``` | /content/code_sandbox/backend/src/Doctrine/DecoratedEntityManager.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 574 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine\Paginator;
use Closure;
use Pagerfanta\Adapter\AdapterInterface;
/**
* Adapter which hydrates paginated records with a callback query.
*
* @template T
* @implements AdapterInterface<T>
*/
final class HydratingAdapter implements AdapterInterface
{
/**
* @param AdapterInterface<T> $wrapped
*/
public function __construct(
private readonly AdapterInterface $wrapped,
private readonly Closure $hydrateCallback,
) {
}
public function getNbResults(): int
{
return $this->wrapped->getNbResults();
}
public function getSlice(int $offset, int $length): iterable
{
$results = $this->wrapped->getSlice($offset, $length);
yield from ($this->hydrateCallback)($results);
}
}
``` | /content/code_sandbox/backend/src/Doctrine/Paginator/HydratingAdapter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 183 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine;
use App\Container\EntityManagerAwareTrait;
use App\Exception\NotFoundException;
use Closure;
use DI\Attribute\Inject;
use Doctrine\Persistence\ObjectRepository;
/**
* @template TEntity as object
*/
class Repository
{
use EntityManagerAwareTrait;
/** @var class-string<TEntity> */
protected string $entityClass;
/** @var ObjectRepository<TEntity> */
protected ObjectRepository $repository;
#[Inject]
public function setEntityManager(ReloadableEntityManagerInterface $em): void
{
$this->em = $em;
$this->repository = $em->getRepository($this->entityClass);
}
/**
* @return ObjectRepository<TEntity>
*/
public function getRepository(): ObjectRepository
{
return $this->repository;
}
public function getEntityManager(): ReloadableEntityManagerInterface
{
return $this->em;
}
/**
* @return TEntity|null
*/
public function find(int|string $id): ?object
{
return $this->em->find($this->entityClass, $id);
}
/**
* @return TEntity
*/
public function requireRecord(int|string $id): object
{
$record = $this->find($id);
if (null === $record) {
throw NotFoundException::generic();
}
return $record;
}
/**
* Generate an array result of all records.
*
* @param bool $cached
* @param string|null $orderBy
* @param string $orderDir
*
* @return mixed[]
*/
public function fetchArray(bool $cached = true, ?string $orderBy = null, string $orderDir = 'ASC'): array
{
$qb = $this->em->createQueryBuilder()
->select('e')
->from($this->entityClass, 'e');
if ($orderBy) {
$qb->orderBy('e.' . str_replace('e.', '', $orderBy), $orderDir);
}
return $qb->getQuery()->getArrayResult();
}
/**
* Generic dropdown builder function (can be overridden for specialized use cases).
*
* @param bool|string $addBlank
* @param Closure|NULL $display
* @param string $pk
* @param string $orderBy
*
* @return mixed[]
*/
public function fetchSelect(
bool|string $addBlank = false,
Closure $display = null,
string $pk = 'id',
string $orderBy = 'name'
): array {
$select = [];
// Specify custom text in the $add_blank parameter to override.
if ($addBlank !== false) {
$select[''] = ($addBlank === true) ? __('Select...') : $addBlank;
}
// Build query for records.
$qb = $this->em->createQueryBuilder()->from($this->entityClass, 'e');
if ($display === null) {
$qb->select('e.' . $pk)->addSelect('e.name')->orderBy('e.' . $orderBy, 'ASC');
} else {
$qb->select('e')->orderBy('e.' . $orderBy, 'ASC');
}
$results = $qb->getQuery()->getArrayResult();
// Assemble select values and, if necessary, call $display callback.
foreach ((array)$results as $result) {
$key = $result[$pk];
$select[$key] = ($display === null) ? $result['name'] : $display($result);
}
return $select;
}
}
``` | /content/code_sandbox/backend/src/Doctrine/Repository.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 784 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine\Messenger;
use App\Container\EntityManagerAwareTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Event\WorkerMessageHandledEvent;
final class ClearEntityManagerSubscriber implements EventSubscriberInterface
{
use EntityManagerAwareTrait;
/**
* @return mixed[]
*/
public static function getSubscribedEvents(): array
{
return [
WorkerMessageHandledEvent::class => 'onWorkerMessageHandled',
WorkerMessageFailedEvent::class => 'onWorkerMessageFailed',
];
}
public function onWorkerMessageHandled(): void
{
$this->clearEntityManagers();
}
public function onWorkerMessageFailed(): void
{
$this->clearEntityManagers();
}
private function clearEntityManagers(): void
{
$this->em->clear();
gc_collect_cycles();
}
}
``` | /content/code_sandbox/backend/src/Doctrine/Messenger/ClearEntityManagerSubscriber.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 206 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine\Generator;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Id\AbstractIdGenerator;
use Ramsey\Uuid\Provider\Node\RandomNodeProvider;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidFactoryInterface;
final class UuidV6Generator extends AbstractIdGenerator
{
private readonly UuidFactoryInterface $factory;
public function __construct()
{
$this->factory = clone Uuid::getFactory();
}
public function generateId(EntityManagerInterface $em, object|null $entity): mixed
{
$nodeProvider = new RandomNodeProvider();
return $this->factory->uuid6($nodeProvider->getNode())->toString();
}
}
``` | /content/code_sandbox/backend/src/Doctrine/Generator/UuidV6Generator.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 154 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine\Event;
use App\Entity\Attributes\AuditIgnore;
use App\Entity\Enums\AuditLogOperations;
use App\Entity\Station;
use App\Entity\StationHlsStream;
use App\Entity\StationMount;
use App\Entity\StationPlaylist;
use App\Entity\StationRemote;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use ReflectionObject;
/**
* A hook into Doctrine's event listener to mark a station as
* needing restart if one of its related entities is changed.
*/
final class StationRequiresRestart implements EventSubscriber
{
/**
* @inheritDoc
*/
public function getSubscribedEvents(): array
{
return [
Events::onFlush,
];
}
public function onFlush(OnFlushEventArgs $args): void
{
$em = $args->getObjectManager();
$uow = $em->getUnitOfWork();
$collectionsToCheck = [
[
AuditLogOperations::Insert,
$uow->getScheduledEntityInsertions(),
],
[
AuditLogOperations::Update,
$uow->getScheduledEntityUpdates(),
],
[
AuditLogOperations::Delete,
$uow->getScheduledEntityDeletions(),
],
];
$stationsToRestart = [];
foreach ($collectionsToCheck as [$changeType, $collection]) {
foreach ($collection as $entity) {
if (
($entity instanceof StationMount)
|| ($entity instanceof StationHlsStream)
|| ($entity instanceof StationRemote && $entity->isEditable())
|| ($entity instanceof StationPlaylist && $entity->getStation()->useManualAutoDJ())
) {
if (AuditLogOperations::Update === $changeType) {
$changes = $uow->getEntityChangeSet($entity);
// Look for the @AuditIgnore annotation on a property.
$classReflection = new ReflectionObject($entity);
foreach ($changes as $changeField => $changeset) {
$ignoreAttr = $classReflection->getProperty($changeField)->getAttributes(
AuditIgnore::class
);
if (!empty($ignoreAttr)) {
unset($changes[$changeField]);
}
}
if (empty($changes)) {
continue;
}
}
$station = $entity->getStation();
if ($station->hasLocalServices()) {
$stationsToRestart[$station->getId()] = $station;
}
}
}
}
if (count($stationsToRestart) > 0) {
foreach ($stationsToRestart as $station) {
$station->setNeedsRestart(true);
$em->persist($station);
$stationMeta = $em->getClassMetadata(Station::class);
$uow->recomputeSingleEntityChangeSet($stationMeta, $station);
}
}
}
}
``` | /content/code_sandbox/backend/src/Doctrine/Event/StationRequiresRestart.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 617 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine\Event;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Mapping\ClassMetadata;
final class SetExplicitChangeTracking implements EventSubscriber
{
/**
* @return string[]
*/
public function getSubscribedEvents(): array
{
return [
Events::loadClassMetadata,
];
}
public function loadClassMetadata(LoadClassMetadataEventArgs $args): void
{
$classMetadata = $args->getClassMetadata();
$classMetadata->setChangeTrackingPolicy(
ClassMetadata::CHANGETRACKING_DEFERRED_EXPLICIT
);
}
}
``` | /content/code_sandbox/backend/src/Doctrine/Event/SetExplicitChangeTracking.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\VueComponent;
use App\Http\ServerRequest;
interface VueComponentInterface
{
public function getProps(ServerRequest $request): array;
}
``` | /content/code_sandbox/backend/src/VueComponent/VueComponentInterface.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 42 |
```php
<?php
declare(strict_types=1);
namespace App\VueComponent;
use App\Entity\Settings;
use App\Http\ServerRequest;
use App\Version;
final class SettingsComponent implements VueComponentInterface
{
public function __construct(
private readonly Version $version,
) {
}
public function getProps(ServerRequest $request): array
{
$router = $request->getRouter();
return [
'apiUrl' => $router->named('api:admin:settings', [
'group' => Settings::GROUP_GENERAL,
]),
'testMessageUrl' => $router->named('api:admin:send-test-message'),
'acmeUrl' => $router->named('api:admin:acme'),
'releaseChannel' => $this->version->getReleaseChannelEnum()->value,
];
}
}
``` | /content/code_sandbox/backend/src/VueComponent/SettingsComponent.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 181 |
```php
<?php
declare(strict_types=1);
namespace App\VueComponent;
use App\Http\ServerRequest;
use App\Radio\Adapters;
use App\Radio\Enums\FrontendAdapters;
use App\Radio\StereoTool;
use DateTime;
use DateTimeZone;
use Symfony\Component\Intl\Countries;
final class StationFormComponent implements VueComponentInterface
{
public function __construct(
private readonly Adapters $adapters
) {
}
public function getProps(ServerRequest $request): array
{
$installedFrontends = $this->adapters->listFrontendAdapters(true);
return [
'timezones' => $this->getTimezones(),
'isShoutcastInstalled' => isset($installedFrontends[FrontendAdapters::Shoutcast->value]),
'isStereoToolInstalled' => StereoTool::isInstalled(),
'countries' => Countries::getNames(),
];
}
private function getTimezones(): array
{
$tzSelect = [
'UTC' => [
'UTC' => 'UTC',
],
];
foreach (
DateTimeZone::listIdentifiers(
(DateTimeZone::ALL ^ DateTimeZone::ANTARCTICA ^ DateTimeZone::UTC)
) as $tzIdentifier
) {
$tz = new DateTimeZone($tzIdentifier);
$tzRegion = substr($tzIdentifier, 0, strpos($tzIdentifier, '/') ?: 0) ?: $tzIdentifier;
$tzSubregion = str_replace([$tzRegion . '/', '_'], ['', ' '], $tzIdentifier) ?: $tzRegion;
$offset = $tz->getOffset(new DateTime());
$offsetPrefix = $offset < 0 ? '-' : '+';
$offsetFormatted = gmdate(($offset % 60 === 0) ? 'G' : 'G:i', abs($offset));
$prettyOffset = ($offset === 0) ? 'UTC' : 'UTC' . $offsetPrefix . $offsetFormatted;
if ($tzSubregion !== $tzRegion) {
$tzSubregion .= ' (' . $prettyOffset . ')';
}
$tzSelect[$tzRegion][$tzIdentifier] = $tzSubregion;
}
return $tzSelect;
}
}
``` | /content/code_sandbox/backend/src/VueComponent/StationFormComponent.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 483 |
```php
<?php
declare(strict_types=1);
namespace App\VueComponent;
use App\Http\ServerRequest;
use App\Service\Centrifugo;
final class NowPlayingComponent implements VueComponentInterface
{
public function __construct(
private readonly Centrifugo $centrifugo
) {
}
public function getProps(ServerRequest $request): array
{
$customization = $request->getCustomization();
$station = $request->getStation();
$backendConfig = $station->getBackendConfig();
return [
...$this->getDataProps($request),
'showAlbumArt' => !$customization->hideAlbumArt(),
'autoplay' => !empty($request->getQueryParam('autoplay')),
'showHls' => $backendConfig->getHlsEnableOnPublicPlayer(),
];
}
public function getDataProps(ServerRequest $request): array
{
$station = $request->getStation();
$customization = $request->getCustomization();
return [
'stationShortName' => $station->getShortName(),
'useStatic' => $customization->useStaticNowPlaying(),
'useSse' => $customization->useStaticNowPlaying() && $this->centrifugo->isSupported(),
];
}
}
``` | /content/code_sandbox/backend/src/VueComponent/NowPlayingComponent.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 278 |
```php
<?php
declare(strict_types=1);
namespace App\Doctrine\Event;
use App\Entity\Attributes\Auditable;
use App\Entity\Attributes\AuditIgnore;
use App\Entity\AuditLog as AuditLogEntity;
use App\Entity\Enums\AuditLogOperations;
use App\Entity\Interfaces\IdentifiableEntityInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Proxy\DefaultProxyClassNameResolver;
use Doctrine\ORM\UnitOfWork;
use ReflectionClass;
use ReflectionObject;
use Stringable;
/**
* A hook into Doctrine's event listener to write changes to "Auditable"
* entities to the audit log.
*
* Portions inspired by DataDog's audit bundle for Doctrine:
* path_to_url
*/
final class AuditLog implements EventSubscriber
{
/**
* @return string[]
*/
public function getSubscribedEvents(): array
{
return [
Events::onFlush,
];
}
public function onFlush(OnFlushEventArgs $args): void
{
$em = $args->getObjectManager();
$uow = $em->getUnitOfWork();
$singleAuditLogs = $this->handleSingleUpdates($em, $uow);
$collectionAuditLogs = $this->handleCollectionUpdates($uow);
$newAuditLogs = array_merge($singleAuditLogs, $collectionAuditLogs);
if (!empty($newAuditLogs)) {
$auditLogMetadata = $em->getClassMetadata(AuditLogEntity::class);
foreach ($newAuditLogs as $auditLog) {
$uow->persist($auditLog);
$uow->computeChangeSet($auditLogMetadata, $auditLog);
}
}
}
/** @return AuditLogEntity[] */
private function handleSingleUpdates(
EntityManagerInterface $em,
UnitOfWork $uow
): array {
$newRecords = [];
$collections = [
[
AuditLogOperations::Insert,
$uow->getScheduledEntityInsertions(),
],
[
AuditLogOperations::Update,
$uow->getScheduledEntityUpdates(),
],
[
AuditLogOperations::Delete,
$uow->getScheduledEntityDeletions(),
],
];
foreach ($collections as [$changeType, $collection]) {
foreach ($collection as $entity) {
// Check that the entity being managed is "Auditable".
$reflectionClass = new ReflectionObject($entity);
if (!$this->isAuditable($reflectionClass)) {
continue;
}
// Get the changes made to the entity.
$changesRaw = $uow->getEntityChangeSet($entity);
// Look for the @AuditIgnore annotation on properties.
$changes = [];
foreach ($changesRaw as $changeField => [$fieldPrev, $fieldNow]) {
// With new entity creation, fields left NULL are still included.
if ($fieldPrev === $fieldNow) {
continue;
}
// Ensure the property isn't ignored.
$ignoreAttr = $reflectionClass->getProperty($changeField)->getAttributes(AuditIgnore::class);
if (!empty($ignoreAttr)) {
continue;
}
// Check if either field value is an object.
if (is_object($fieldPrev) && $this->isEntity($em, $fieldPrev)) {
$fieldPrev = $this->getIdentifier($fieldPrev);
}
if (is_object($fieldNow) && $this->isEntity($em, $fieldNow)) {
$fieldNow = $this->getIdentifier($fieldNow);
}
$changes[$changeField] = [$fieldPrev, $fieldNow];
}
if (AuditLogOperations::Update === $changeType && empty($changes)) {
continue;
}
// Find the identifier method or property.
$identifier = $this->getIdentifier($entity);
$newRecords[] = new AuditLogEntity(
$changeType,
get_class($entity),
$identifier,
null,
null,
$changes
);
}
}
return $newRecords;
}
/** @return AuditLogEntity[] */
private function handleCollectionUpdates(
UnitOfWork $uow
): array {
$newRecords = [];
$associated = [];
$disassociated = [];
foreach ($uow->getScheduledCollectionUpdates() as $collection) {
$owner = $collection->getOwner();
if (null === $owner) {
continue;
}
$reflectionClass = new ReflectionObject($owner);
if (!$this->isAuditable($reflectionClass)) {
continue;
}
// Ignore inverse side or one to many relations
$mapping = $collection->getMapping();
if (!$mapping->isOwningSide() || !$mapping->isManyToMany()) {
continue;
}
$ownerIdentifier = $this->getIdentifier($owner);
foreach ($collection->getInsertDiff() as $entity) {
$targetReflectionClass = new ReflectionObject($entity);
if (!$this->isAuditable($targetReflectionClass)) {
continue;
}
$entityIdentifier = $this->getIdentifier($entity);
$associated[] = [$owner, $ownerIdentifier, $entity, $entityIdentifier];
}
foreach ($collection->getDeleteDiff() as $entity) {
$targetReflectionClass = new ReflectionObject($entity);
if (!$this->isAuditable($targetReflectionClass)) {
continue;
}
$entityIdentifier = $this->getIdentifier($entity);
$disassociated[] = [$owner, $ownerIdentifier, $entity, $entityIdentifier];
}
}
foreach ($uow->getScheduledCollectionDeletions() as $collection) {
$owner = $collection->getOwner();
if (null === $owner) {
continue;
}
$reflectionClass = new ReflectionObject($owner);
if (!$this->isAuditable($reflectionClass)) {
continue;
}
// Ignore inverse side or one to many relations
$mapping = $collection->getMapping();
if (!$mapping->isOwningSide() || !$mapping->isManyToMany()) {
continue;
}
$ownerIdentifier = $this->getIdentifier($owner);
foreach ($collection->toArray() as $entity) {
$targetReflectionClass = new ReflectionObject($entity);
if (!$this->isAuditable($targetReflectionClass)) {
continue;
}
$entityIdentifier = $this->getIdentifier($entity);
$disassociated[] = [$owner, $ownerIdentifier, $entity, $entityIdentifier];
}
}
foreach ($associated as [$owner, $ownerIdentifier, $entity, $entityIdentifier]) {
$newRecords[] = new AuditLogEntity(
AuditLogOperations::Insert,
get_class($owner),
$ownerIdentifier,
(string)get_class($entity),
$entityIdentifier,
[]
);
}
foreach ($disassociated as [$owner, $ownerIdentifier, $entity, $entityIdentifier]) {
$newRecords[] = new AuditLogEntity(
AuditLogOperations::Delete,
get_class($owner),
$ownerIdentifier,
(string)get_class($entity),
$entityIdentifier,
[]
);
}
return $newRecords;
}
private function isEntity(EntityManagerInterface $em, mixed $class): bool
{
if (is_object($class)) {
$class = DefaultProxyClassNameResolver::getClass($class);
}
if (!is_string($class)) {
return false;
}
if (!class_exists($class)) {
return false;
}
return !$em->getMetadataFactory()->isTransient($class);
}
/**
* @template TObject of object
* @param ReflectionClass<TObject> $refl
* @return bool
*/
private function isAuditable(ReflectionClass $refl): bool
{
$auditable = $refl->getAttributes(Auditable::class);
return !empty($auditable);
}
/**
* Get the identifier string for an entity, if it's set or fetchable.
*
* @param object $entity
*/
private function getIdentifier(object $entity): string
{
if ($entity instanceof Stringable) {
return (string)$entity;
}
if (method_exists($entity, 'getName')) {
return $entity->getName();
}
if ($entity instanceof IdentifiableEntityInterface) {
$entityId = $entity->getId();
if (null !== $entityId) {
return (string)$entityId;
}
}
return spl_object_hash($entity);
}
}
``` | /content/code_sandbox/backend/src/Doctrine/Event/AuditLog.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,873 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem;
use App\Entity\Repository\StorageLocationRepository;
use App\Entity\Station;
use App\Flysystem\Adapter\LocalAdapterInterface;
use App\Flysystem\Adapter\LocalFilesystemAdapter;
final class StationFilesystems
{
public const string DIR_ALBUM_ART = '.albumart';
public const string DIR_FOLDER_COVERS = '.covers';
public const string DIR_WAVEFORMS = '.waveforms';
public const array PROTECTED_DIRS = [
self::DIR_ALBUM_ART,
self::DIR_FOLDER_COVERS,
self::DIR_WAVEFORMS,
];
public function __construct(
private readonly StorageLocationRepository $storageLocationRepo
) {
}
public function getMediaFilesystem(Station $station): ExtendedFilesystemInterface
{
$mediaAdapter = $this->storageLocationRepo->getAdapter(
$station->getMediaStorageLocation()
)->getStorageAdapter();
return ($mediaAdapter instanceof LocalAdapterInterface)
? new LocalFilesystem($mediaAdapter)
: new RemoteFilesystem($mediaAdapter, $station->getRadioTempDir());
}
public function getRecordingsFilesystem(Station $station): ExtendedFilesystemInterface
{
$recordingsAdapter = $this->storageLocationRepo->getAdapter(
$station->getRecordingsStorageLocation()
)->getStorageAdapter();
return ($recordingsAdapter instanceof LocalAdapterInterface)
? new LocalFilesystem($recordingsAdapter)
: new RemoteFilesystem($recordingsAdapter, $station->getRadioTempDir());
}
public function getPodcastsFilesystem(Station $station): ExtendedFilesystemInterface
{
$podcastsAdapter = $this->storageLocationRepo->getAdapter(
$station->getPodcastsStorageLocation()
)->getStorageAdapter();
return ($podcastsAdapter instanceof LocalAdapterInterface)
? new LocalFilesystem($podcastsAdapter)
: new RemoteFilesystem($podcastsAdapter, $station->getRadioTempDir());
}
public function getPlaylistsFilesystem(Station $station): LocalFilesystem
{
return self::buildPlaylistsFilesystem($station);
}
public static function buildPlaylistsFilesystem(
Station $station
): LocalFilesystem {
return self::buildLocalFilesystemForPath($station->getRadioPlaylistsDir());
}
public function getConfigFilesystem(Station $station): LocalFilesystem
{
return self::buildConfigFilesystem($station);
}
public static function buildConfigFilesystem(
Station $station
): LocalFilesystem {
return self::buildLocalFilesystemForPath($station->getRadioConfigDir());
}
public function getTempFilesystem(Station $station): LocalFilesystem
{
return self::buildTempFilesystem($station);
}
public static function buildTempFilesystem(
Station $station
): LocalFilesystem {
return self::buildLocalFilesystemForPath($station->getRadioTempDir());
}
public static function buildLocalFilesystemForPath(
string $path
): LocalFilesystem {
return new LocalFilesystem(new LocalFilesystemAdapter($path));
}
public static function isDotFile(string $path): bool
{
$pathParts = explode('/', $path);
foreach ($pathParts as $part) {
if (str_starts_with($part, '.')) {
return true;
}
}
return false;
}
}
``` | /content/code_sandbox/backend/src/Flysystem/StationFilesystems.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 754 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem;
use App\Flysystem\Adapter\ExtendedAdapterInterface;
use League\Flysystem\PathNormalizer;
use League\Flysystem\PathPrefixer;
use RuntimeException;
final class RemoteFilesystem extends AbstractFilesystem
{
private readonly PathPrefixer $localPath;
public function __construct(
ExtendedAdapterInterface $remoteAdapter,
string $localPath = null,
array $config = [],
PathNormalizer $pathNormalizer = null
) {
$this->localPath = new PathPrefixer($localPath ?? sys_get_temp_dir());
parent::__construct($remoteAdapter, $config, $pathNormalizer);
}
/** @inheritDoc */
public function isLocal(): bool
{
return false;
}
/** @inheritDoc */
public function getLocalPath(string $path): string
{
$tempLocalPath = $this->localPath->prefixPath(
substr(md5($path), 0, 10) . '_' . basename($path),
);
$this->download($path, $tempLocalPath);
return $tempLocalPath;
}
/** @inheritDoc */
public function withLocalFile(string $path, callable $function)
{
$localPath = $this->getLocalPath($path);
try {
$returnVal = $function($localPath);
} finally {
unlink($localPath);
}
return $returnVal;
}
/** @inheritDoc */
public function upload(string $localPath, string $to): void
{
if (!is_file($localPath)) {
throw new RuntimeException(sprintf('Source upload file not found at path: %s', $localPath));
}
$stream = fopen($localPath, 'rb');
try {
$this->writeStream($to, $stream);
} finally {
if (is_resource($stream)) {
fclose($stream);
}
}
}
/** @inheritDoc */
public function download(string $from, string $localPath): void
{
if (is_file($localPath)) {
if (filemtime($localPath) >= $this->lastModified($from)) {
touch($localPath);
return;
}
unlink($localPath);
}
$stream = $this->readStream($from);
file_put_contents($localPath, $stream);
if (is_resource($stream)) {
fclose($stream);
}
}
}
``` | /content/code_sandbox/backend/src/Flysystem/RemoteFilesystem.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 538 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem;
use App\Flysystem\Adapter\ExtendedAdapterInterface;
use App\Flysystem\Normalizer\WhitespacePathNormalizer;
use League\Flysystem\Filesystem;
use League\Flysystem\PathNormalizer;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToRetrieveMetadata;
abstract class AbstractFilesystem extends Filesystem implements ExtendedFilesystemInterface
{
protected ExtendedAdapterInterface $adapter;
public function __construct(
ExtendedAdapterInterface $adapter,
array $config = [],
PathNormalizer $pathNormalizer = null
) {
$this->adapter = $adapter;
$pathNormalizer = $pathNormalizer ?: new WhitespacePathNormalizer();
parent::__construct($adapter, $config, $pathNormalizer);
}
public function getAdapter(): ExtendedAdapterInterface
{
return $this->adapter;
}
public function getMetadata(string $path): StorageAttributes
{
return $this->adapter->getMetadata($path);
}
public function isDir(string $path): bool
{
try {
return $this->getMetadata($path)->isDir();
} catch (UnableToRetrieveMetadata) {
return false;
}
}
public function isFile(string $path): bool
{
try {
return $this->getMetadata($path)->isFile();
} catch (UnableToRetrieveMetadata) {
return false;
}
}
public function uploadAndDeleteOriginal(string $localPath, string $to): void
{
$this->upload($localPath, $to);
@unlink($localPath);
}
}
``` | /content/code_sandbox/backend/src/Flysystem/AbstractFilesystem.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 364 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem;
use App\Flysystem\Adapter\ExtendedAdapterInterface;
use League\Flysystem\FilesystemOperator;
use League\Flysystem\StorageAttributes;
interface ExtendedFilesystemInterface extends FilesystemOperator
{
/**
* @return ExtendedAdapterInterface The underlying filesystem adapter.
*/
public function getAdapter(): ExtendedAdapterInterface;
/**
* @return bool Whether this filesystem is directly located on disk.
*/
public function isLocal(): bool;
/**
* @param string $path The original path of the file on the filesystem.
*
* @return string A path that will be guaranteed to be local to the filesystem.
*/
public function getLocalPath(string $path): string;
/**
* @param string $path
*
* @return StorageAttributes Metadata for the specified path.
*/
public function getMetadata(string $path): StorageAttributes;
public function isDir(string $path): bool;
public function isFile(string $path): bool;
/**
* Call a callable function with a path that is guaranteed to be a local path, even if
* this filesystem is a remote one, by copying to a temporary directory first in the
* case of remote filesystems.
*
* @param string $path
* @param callable $function
*
* @return mixed
*/
public function withLocalFile(string $path, callable $function);
/**
* @param string $localPath
* @param string $to
*/
public function uploadAndDeleteOriginal(string $localPath, string $to): void;
/**
* @param string $localPath
* @param string $to
*/
public function upload(string $localPath, string $to): void;
/**
* @param string $from
* @param string $localPath
*/
public function download(string $from, string $localPath): void;
}
``` | /content/code_sandbox/backend/src/Flysystem/ExtendedFilesystemInterface.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\Flysystem\Attributes;
use League\Flysystem\StorageAttributes;
final class DirectoryAttributes extends AbstractAttributes
{
/**
* @param string $path
* @param string|callable|null $visibility
* @param int|callable|null $lastModified
* @param array $extraMetadata
*/
public function __construct(string $path, $visibility = null, $lastModified = null, array $extraMetadata = [])
{
$this->type = StorageAttributes::TYPE_DIRECTORY;
parent::__construct($path, $visibility, $lastModified, $extraMetadata);
}
public static function fromArray(array $attributes): self
{
return new self(
$attributes[StorageAttributes::ATTRIBUTE_PATH],
$attributes[StorageAttributes::ATTRIBUTE_VISIBILITY] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_LAST_MODIFIED] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_EXTRA_METADATA] ?? [],
);
}
/**
* @inheritDoc
*/
public function jsonSerialize(): array
{
return [
StorageAttributes::ATTRIBUTE_TYPE => $this->type,
StorageAttributes::ATTRIBUTE_PATH => $this->path,
StorageAttributes::ATTRIBUTE_VISIBILITY => $this->visibility,
StorageAttributes::ATTRIBUTE_LAST_MODIFIED => $this->lastModified,
StorageAttributes::ATTRIBUTE_EXTRA_METADATA => $this->extraMetadata,
];
}
}
``` | /content/code_sandbox/backend/src/Flysystem/Attributes/DirectoryAttributes.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 305 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem;
use App\Flysystem\Adapter\LocalAdapterInterface;
use League\Flysystem\PathNormalizer;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToCreateDirectory;
use League\Flysystem\UnixVisibility\PortableVisibilityConverter;
use League\Flysystem\UnixVisibility\VisibilityConverter;
final class LocalFilesystem extends AbstractFilesystem
{
private readonly LocalAdapterInterface $localAdapter;
private readonly VisibilityConverter $visibilityConverter;
public function __construct(
LocalAdapterInterface $adapter,
array $config = [],
PathNormalizer $pathNormalizer = null,
VisibilityConverter $visibilityConverter = null
) {
$this->localAdapter = $adapter;
$this->visibilityConverter = $visibilityConverter ?? new PortableVisibilityConverter();
parent::__construct($adapter, $config, $pathNormalizer);
}
/** @inheritDoc */
public function isLocal(): bool
{
return true;
}
/** @inheritDoc */
public function getLocalPath(string $path): string
{
return $this->localAdapter->getLocalPath($path);
}
/** @inheritDoc */
public function upload(string $localPath, string $to): void
{
$destPath = $this->getLocalPath($to);
$this->ensureDirectoryExists(
dirname($destPath),
$this->visibilityConverter->defaultForDirectories()
);
if (!@copy($localPath, $destPath)) {
throw UnableToCopyFile::fromLocationTo($localPath, $destPath);
}
}
/** @inheritDoc */
public function download(string $from, string $localPath): void
{
$sourcePath = $this->getLocalPath($from);
$this->ensureDirectoryExists(
dirname($localPath),
$this->visibilityConverter->defaultForDirectories()
);
if (!@copy($sourcePath, $localPath)) {
throw UnableToCopyFile::fromLocationTo($sourcePath, $localPath);
}
}
/** @inheritDoc */
public function withLocalFile(string $path, callable $function)
{
$localPath = $this->getLocalPath($path);
return $function($localPath);
}
private function ensureDirectoryExists(string $dirname, int $visibility): void
{
if (is_dir($dirname)) {
return;
}
error_clear_last();
if (!@mkdir($dirname, $visibility, true)) {
$mkdirError = error_get_last();
}
clearstatcache(false, $dirname);
if (!is_dir($dirname)) {
$errorMessage = $mkdirError['message'] ?? '';
throw UnableToCreateDirectory::atLocation($dirname, $errorMessage);
}
}
}
``` | /content/code_sandbox/backend/src/Flysystem/LocalFilesystem.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 611 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem\Attributes;
use League\Flysystem\ProxyArrayAccessToProperties;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToRetrieveMetadata;
abstract class AbstractAttributes implements StorageAttributes
{
use ProxyArrayAccessToProperties;
protected string $type;
/**
* @param string $path
* @param string|callable|null $visibility
* @param int|callable|null $lastModified
* @param array $extraMetadata
*/
public function __construct(
protected string $path,
protected $visibility = null,
protected $lastModified = null,
protected array $extraMetadata = []
) {
}
public function path(): string
{
return $this->path;
}
public function type(): string
{
return $this->type;
}
public function visibility(): ?string
{
return (is_callable($this->visibility))
? ($this->visibility)($this->path)
: $this->visibility;
}
public function lastModified(): ?int
{
$lastModified = is_callable($this->lastModified)
? ($this->lastModified)($this->path)
: $this->lastModified;
if (null === $lastModified) {
throw UnableToRetrieveMetadata::lastModified($this->path);
}
return $lastModified;
}
public function extraMetadata(): array
{
return $this->extraMetadata;
}
public function isFile(): bool
{
return (StorageAttributes::TYPE_FILE === $this->type);
}
public function isDir(): bool
{
return (StorageAttributes::TYPE_DIRECTORY === $this->type);
}
public function withPath(string $path): StorageAttributes
{
$clone = clone $this;
$clone->path = $path;
return $clone;
}
}
``` | /content/code_sandbox/backend/src/Flysystem/Attributes/AbstractAttributes.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 423 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem\Attributes;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToRetrieveMetadata;
final class FileAttributes extends AbstractAttributes
{
/**
* @param string $path
* @param int|callable|null $fileSize
* @param string|callable|null $visibility
* @param int|callable|null $lastModified
* @param string|callable|null $mimeType
* @param array $extraMetadata
*/
public function __construct(
string $path,
private $fileSize = null,
$visibility = null,
$lastModified = null,
private $mimeType = null,
array $extraMetadata = []
) {
$this->type = StorageAttributes::TYPE_FILE;
parent::__construct($path, $visibility, $lastModified, $extraMetadata);
}
public function fileSize(): ?int
{
$fileSize = is_callable($this->fileSize)
? ($this->fileSize)($this->path)
: $this->fileSize;
if (null === $fileSize) {
throw UnableToRetrieveMetadata::fileSize($this->path);
}
return $fileSize;
}
public function mimeType(): ?string
{
$mimeType = is_callable($this->mimeType)
? ($this->mimeType)($this->path)
: $this->mimeType;
if (null === $mimeType) {
throw UnableToRetrieveMetadata::mimeType($this->path);
}
return $mimeType;
}
public static function fromArray(array $attributes): self
{
return new self(
$attributes[StorageAttributes::ATTRIBUTE_PATH],
$attributes[StorageAttributes::ATTRIBUTE_FILE_SIZE] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_VISIBILITY] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_LAST_MODIFIED] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_MIME_TYPE] ?? null,
$attributes[StorageAttributes::ATTRIBUTE_EXTRA_METADATA] ?? []
);
}
public function jsonSerialize(): array
{
return [
StorageAttributes::ATTRIBUTE_TYPE => self::TYPE_FILE,
StorageAttributes::ATTRIBUTE_PATH => $this->path,
StorageAttributes::ATTRIBUTE_FILE_SIZE => $this->fileSize,
StorageAttributes::ATTRIBUTE_VISIBILITY => $this->visibility,
StorageAttributes::ATTRIBUTE_LAST_MODIFIED => $this->lastModified,
StorageAttributes::ATTRIBUTE_MIME_TYPE => $this->mimeType,
StorageAttributes::ATTRIBUTE_EXTRA_METADATA => $this->extraMetadata,
];
}
}
``` | /content/code_sandbox/backend/src/Flysystem/Attributes/FileAttributes.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\Flysystem\Adapter;
interface LocalAdapterInterface extends ExtendedAdapterInterface
{
public function getLocalPath(string $path): string;
}
``` | /content/code_sandbox/backend/src/Flysystem/Adapter/LocalAdapterInterface.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 41 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem\Adapter;
use App\Flysystem\Attributes\DirectoryAttributes;
use App\Flysystem\Attributes\FileAttributes;
use League\Flysystem\Local\LocalFilesystemAdapter as LeagueLocalFilesystemAdapter;
use League\Flysystem\PathPrefixer;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnixVisibility\PortableVisibilityConverter;
use League\Flysystem\UnixVisibility\VisibilityConverter;
use League\MimeTypeDetection\MimeTypeDetector;
use SplFileInfo;
final class LocalFilesystemAdapter extends LeagueLocalFilesystemAdapter implements LocalAdapterInterface
{
private readonly PathPrefixer $pathPrefixer;
private readonly VisibilityConverter $visibility;
public function __construct(
string $location,
VisibilityConverter $visibility = null,
int $writeFlags = LOCK_EX,
int $linkHandling = self::DISALLOW_LINKS,
MimeTypeDetector $mimeTypeDetector = null
) {
$this->pathPrefixer = new PathPrefixer($location, DIRECTORY_SEPARATOR);
$this->visibility = $visibility ?: new PortableVisibilityConverter();
parent::__construct($location, $visibility, $writeFlags, $linkHandling, $mimeTypeDetector);
}
public function getLocalPath(string $path): string
{
return $this->pathPrefixer->prefixPath($path);
}
/** @inheritDoc */
public function getMetadata(string $path): StorageAttributes
{
$location = $this->pathPrefixer->prefixPath($path);
if (!file_exists($location)) {
throw UnableToRetrieveMetadata::create($location, 'metadata', 'File not found');
}
$fileInfo = new SplFileInfo($location);
$lastModified = $fileInfo->getMTime();
$isDirectory = $fileInfo->isDir();
$permissions = $fileInfo->getPerms();
$visibility = $isDirectory
? $this->visibility->inverseForDirectory($permissions)
: $this->visibility->inverseForFile($permissions);
return $isDirectory
? new DirectoryAttributes($path, $visibility, $lastModified)
: new FileAttributes(
$path,
$fileInfo->getSize(),
$visibility,
$lastModified,
fn() => $this->mimeType($path)->mimeType()
);
}
}
``` | /content/code_sandbox/backend/src/Flysystem/Adapter/LocalFilesystemAdapter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 518 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem\Adapter;
use App\Flysystem\Attributes\DirectoryAttributes;
use App\Flysystem\Attributes\FileAttributes;
use League\Flysystem\PathPrefixer;
use League\Flysystem\PhpseclibV3\ConnectionProvider;
use League\Flysystem\PhpseclibV3\SftpAdapter as LeagueSftpAdapter;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnixVisibility\PortableVisibilityConverter;
use League\Flysystem\UnixVisibility\VisibilityConverter;
use League\MimeTypeDetection\FinfoMimeTypeDetector;
use League\MimeTypeDetection\MimeTypeDetector;
final class SftpAdapter extends LeagueSftpAdapter implements ExtendedAdapterInterface
{
private const int NET_SFTP_TYPE_DIRECTORY = 2;
private readonly VisibilityConverter $visibilityConverter;
private readonly PathPrefixer $prefixer;
public function __construct(
private readonly ConnectionProvider $connectionProvider,
string $root,
VisibilityConverter $visibilityConverter = null,
MimeTypeDetector $mimeTypeDetector = null
) {
$this->visibilityConverter = $visibilityConverter ?: new PortableVisibilityConverter();
$this->prefixer = new PathPrefixer($root);
$mimeTypeDetector ??= new FinfoMimeTypeDetector();
parent::__construct($connectionProvider, $root, $visibilityConverter, $mimeTypeDetector);
}
/** @inheritDoc */
public function getMetadata(string $path): StorageAttributes
{
$location = $this->prefixer->prefixPath($path);
$connection = $this->connectionProvider->provideConnection();
$stat = $connection->stat($location);
if (!is_array($stat)) {
throw UnableToRetrieveMetadata::create($path, 'metadata');
}
$attributes = $this->convertListingToAttributes($path, $stat);
if (!$attributes instanceof FileAttributes) {
throw UnableToRetrieveMetadata::create($path, 'metadata', 'path is not a file');
}
return $attributes;
}
private function convertListingToAttributes(string $path, array $attributes): StorageAttributes
{
$permissions = $attributes['mode'] & 0777;
$lastModified = $attributes['mtime'] ?? null;
if ($attributes['type'] === self::NET_SFTP_TYPE_DIRECTORY) {
return new DirectoryAttributes(
ltrim($path, '/'),
$this->visibilityConverter->inverseForDirectory($permissions),
$lastModified
);
}
return new FileAttributes(
$path,
$attributes['size'],
$this->visibilityConverter->inverseForFile($permissions),
$lastModified
);
}
}
``` | /content/code_sandbox/backend/src/Flysystem/Adapter/SftpAdapter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 581 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem\Adapter;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\FilesystemException;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToRetrieveMetadata;
interface ExtendedAdapterInterface extends FilesystemAdapter
{
/**
* @throws UnableToRetrieveMetadata
* @throws FilesystemException
*/
public function getMetadata(string $path): StorageAttributes;
}
``` | /content/code_sandbox/backend/src/Flysystem/Adapter/ExtendedAdapterInterface.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 99 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem\Adapter;
use App\Flysystem\Attributes\DirectoryAttributes;
use App\Flysystem\Attributes\FileAttributes;
use App\Utilities\Types;
use Aws\Api\DateTimeResult;
use Aws\S3\S3ClientInterface;
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;
use League\Flysystem\AwsS3V3\VisibilityConverter;
use League\Flysystem\PathPrefixer;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToRetrieveMetadata;
use League\MimeTypeDetection\MimeTypeDetector;
use Throwable;
final class AwsS3Adapter extends AwsS3V3Adapter implements ExtendedAdapterInterface
{
private readonly PathPrefixer $prefixer;
public function __construct(
private readonly S3ClientInterface $client,
private readonly string $bucket,
string $prefix = '',
VisibilityConverter $visibility = null,
MimeTypeDetector $mimeTypeDetector = null,
array $options = [],
bool $streamReads = true
) {
$this->prefixer = new PathPrefixer($prefix);
parent::__construct($client, $bucket, $prefix, $visibility, $mimeTypeDetector, $options, $streamReads);
}
/** @inheritDoc */
public function getMetadata(string $path): StorageAttributes
{
$arguments = ['Bucket' => $this->bucket, 'Key' => $this->prefixer->prefixPath($path)];
$command = $this->client->getCommand('HeadObject', $arguments);
try {
$metadata = $this->client->execute($command);
} catch (Throwable $exception) {
throw UnableToRetrieveMetadata::create($path, 'metadata', '', $exception);
}
if (str_ends_with($path, '/')) {
return new DirectoryAttributes(rtrim($path, '/'));
}
$mimetype = Types::stringOrNull($metadata['ContentType'], true);
$fileSize = Types::intOrNull($metadata['ContentLength'] ?? $metadata['Size'] ?? null);
$dateTime = $metadata['LastModified'] ?? null;
$lastModified = $dateTime instanceof DateTimeResult ? $dateTime->getTimeStamp() : null;
$visibility = function ($path) {
return $this->visibility($path)->visibility();
};
return new FileAttributes(
$path,
$fileSize,
$visibility,
$lastModified,
$mimetype
);
}
}
``` | /content/code_sandbox/backend/src/Flysystem/Adapter/AwsS3Adapter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 542 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem\Adapter;
use League\Flysystem\StorageAttributes;
use League\Flysystem\UnableToRetrieveMetadata;
use Spatie\Dropbox\Exceptions\BadRequest;
use Spatie\FlysystemDropbox\DropboxAdapter as SpatieDropboxAdapter;
final class DropboxAdapter extends SpatieDropboxAdapter implements ExtendedAdapterInterface
{
/** @inheritDoc */
public function getMetadata(string $path): StorageAttributes
{
$location = $this->applyPathPrefix($path);
try {
$response = $this->client->getMetadata($location);
} catch (BadRequest $e) {
throw UnableToRetrieveMetadata::create($location, 'metadata', $e->getMessage());
}
return $this->normalizeResponse($response);
}
}
``` | /content/code_sandbox/backend/src/Flysystem/Adapter/DropboxAdapter.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 174 |
```php
<?php
declare(strict_types=1);
namespace App\Flysystem\Normalizer;
use League\Flysystem\PathNormalizer;
use League\Flysystem\PathTraversalDetected;
final class WhitespacePathNormalizer implements PathNormalizer
{
public function normalizePath(string $path): string
{
$path = str_replace('\\', '/', $path);
$path = $this->removeFunkyWhiteSpace($path);
return $this->normalizeRelativePath($path);
}
private function removeFunkyWhiteSpace(string $path): string
{
// Remove unprintable characters and invalid unicode characters.
// We do this check in a loop, since removing invalid unicode characters
// can lead to new characters being created.
//
// Customized regex for zero-width chars
// @see path_to_url
while (preg_match('#\p{C}-[\x{200C}-\x{200D}]+|^\./#u', $path)) {
$path = (string) preg_replace('#\p{C}-[\x{200C}-\x{200D}]+|^\./#u', '', $path);
}
return $path;
}
private function normalizeRelativePath(string $path): string
{
$parts = [];
foreach (explode('/', $path) as $part) {
switch ($part) {
case '':
case '.':
break;
case '..':
if (empty($parts)) {
throw PathTraversalDetected::forPath($path);
}
array_pop($parts);
break;
default:
$parts[] = $part;
break;
}
}
return implode('/', $parts);
}
}
``` | /content/code_sandbox/backend/src/Flysystem/Normalizer/WhitespacePathNormalizer.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 370 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook;
use App\Container\EnvironmentAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Service\Centrifugo;
use Symfony\Component\Filesystem\Filesystem;
use const JSON_PRETTY_PRINT;
final class LocalWebhookHandler
{
use LoggerAwareTrait;
use EnvironmentAwareTrait;
public const string NAME = 'local';
public function __construct(
private readonly Centrifugo $centrifugo
) {
}
public function dispatch(
Station $station,
NowPlaying $np,
array $triggers
): void {
$fsUtils = new Filesystem();
$staticNpDir = $this->environment->getTempDirectory() . '/nowplaying';
$fsUtils->mkdir($staticNpDir);
// Write local static file that the video stream (and other scripts) can use.
$this->logger->debug('Writing local nowplaying text file...');
$npText = implode(
' - ',
array_filter(
[
$np->now_playing->song->artist ?? null,
$np->now_playing->song->title ?? null,
]
)
);
if (empty($npText)) {
$npText = $station->getName() ?? '';
}
$configDir = $station->getRadioConfigDir();
$npFile = $configDir . '/nowplaying.txt';
$npStaticFile = $staticNpDir . '/' . $station->getShortName() . '.txt';
$fsUtils->dumpFile($npFile, $npText);
$fsUtils->dumpFile($npStaticFile, $npText);
// Write JSON file to disk so nginx can serve it without calling the PHP stack at all.
$this->logger->debug('Writing static nowplaying text file...');
$staticNpPath = $staticNpDir . '/' . $station->getShortName() . '.json';
$fsUtils->dumpFile(
$staticNpPath,
json_encode($np, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ?: ''
);
// Publish to websocket library
if ($this->centrifugo->isSupported()) {
$this->centrifugo->publishToStation($station, $np, $triggers);
}
}
}
``` | /content/code_sandbox/backend/src/Webhook/LocalWebhookHandler.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 531 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Repository\ListenerRepository;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Nginx\CustomUrls;
use GuzzleHttp\Client;
abstract class AbstractGoogleAnalyticsConnector extends AbstractConnector
{
public function __construct(
Client $httpClient,
protected readonly ListenerRepository $listenerRepo
) {
parent::__construct($httpClient);
}
protected function webhookShouldTrigger(StationWebhook $webhook, array $triggers = []): bool
{
return true;
}
protected function buildListenUrls(Station $station): array
{
$listenBaseUrl = CustomUrls::getListenUrl($station);
$hlsBaseUrl = CustomUrls::getHlsUrl($station);
$mountUrls = [];
foreach ($station->getMounts() as $mount) {
$mountUrls[$mount->getIdRequired()] = $listenBaseUrl . $mount->getName();
}
$remoteUrls = [];
foreach ($station->getRemotes() as $remote) {
$remoteUrls[$remote->getIdRequired()] = $listenBaseUrl . '/remote' . $remote->getMount();
}
$hlsUrls = [];
foreach ($station->getHlsStreams() as $hlsStream) {
$hlsUrls[$hlsStream->getIdRequired()] = $hlsBaseUrl . '/' . $hlsStream->getName();
}
return [
'mounts' => $mountUrls,
'remotes' => $remoteUrls,
'hls' => $hlsUrls,
];
}
protected function getListenUrl(
array $listener,
array $listenUrls
): ?string {
if (!empty($listener['mount_id'])) {
return $listenUrls['mounts'][$listener['mount_id']] ?? null;
}
if (!empty($listener['remote_id'])) {
return $listenUrls['remotes'][$listener['remote_id']] ?? null;
}
if (!empty($listener['hls_stream_id'])) {
return $listenUrls['hls'][$listener['hls_stream_id']] ?? null;
}
return null;
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/AbstractGoogleAnalyticsConnector.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 478 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook;
use App\Container\ContainerAwareTrait;
use App\Container\EntityManagerAwareTrait;
use App\Container\EnvironmentAwareTrait;
use App\Container\LoggerAwareTrait;
use App\Entity\ApiGenerator\NowPlayingApiGenerator;
use App\Entity\Station;
use App\Entity\StationWebhook;
use App\Http\RouterInterface;
use App\Message;
use App\Webhook\Connector\AbstractConnector;
use App\Webhook\Enums\WebhookTriggers;
use Monolog\Handler\StreamHandler;
use Monolog\Level;
use RuntimeException;
use Throwable;
final class Dispatcher
{
use LoggerAwareTrait;
use ContainerAwareTrait;
use EntityManagerAwareTrait;
use EnvironmentAwareTrait;
public function __construct(
private readonly RouterInterface $router,
private readonly LocalWebhookHandler $localHandler,
private readonly NowPlayingApiGenerator $nowPlayingApiGen
) {
}
/**
* Handle event dispatch.
*
* @param Message\AbstractMessage $message
*/
public function __invoke(Message\AbstractMessage $message): void
{
if ($message instanceof Message\DispatchWebhookMessage) {
$this->handleDispatch($message);
} elseif ($message instanceof Message\TestWebhookMessage) {
$this->testDispatch($message);
}
}
private function handleDispatch(Message\DispatchWebhookMessage $message): void
{
$station = $this->em->find(Station::class, $message->station_id);
if (!$station instanceof Station) {
return;
}
$np = $message->np;
$triggers = $message->triggers;
// Always dispatch the special "local" updater task.
try {
$this->localHandler->dispatch($station, $np, $triggers);
} catch (Throwable $e) {
$this->logger->error(
sprintf('%s L%d: %s', $e->getFile(), $e->getLine(), $e->getMessage()),
[
'exception' => $e,
]
);
}
if ($this->environment->isTesting()) {
$this->logger->notice('In testing mode; no webhooks dispatched.');
return;
}
/** @var StationWebhook[] $enabledWebhooks */
$enabledWebhooks = $station->getWebhooks()->filter(
function (StationWebhook $webhook) {
return $webhook->getIsEnabled();
}
);
$this->logger->debug('Webhook dispatch: triggering events: ' . implode(', ', $triggers));
foreach ($enabledWebhooks as $webhook) {
$webhookType = $webhook->getType();
$webhookClass = $webhookType->getClass();
if (null === $webhookClass) {
$this->logger->error(
sprintf(
'Webhook type "%s" is no longer supported. Removing this webhook is recommended.',
$webhookType->value
)
);
continue;
}
$this->logger->debug(
sprintf('Dispatching connector "%s".', $webhookType->value)
);
if (!$this->di->has($webhookClass)) {
$this->logger->error(
sprintf('Webhook class "%s" not found.', $webhookClass)
);
continue;
}
/** @var AbstractConnector $connectorObj */
$connectorObj = $this->di->get($webhookClass);
if ($connectorObj->shouldDispatch($webhook, $triggers)) {
try {
$connectorObj->dispatch($station, $webhook, $np, $triggers);
$webhook->updateLastSentTimestamp();
$this->em->persist($webhook);
} catch (Throwable $e) {
$this->logger->error(
sprintf('%s L%d: %s', $e->getFile(), $e->getLine(), $e->getMessage()),
[
'exception' => $e,
]
);
}
}
}
$this->em->flush();
}
private function testDispatch(
Message\TestWebhookMessage $message
): void {
$outputPath = $message->outputPath;
if (null !== $outputPath) {
$logHandler = new StreamHandler(
$outputPath,
Level::fromValue($message->logLevel),
true
);
$this->logger->pushHandler($logHandler);
}
try {
$webhook = $this->em->find(StationWebhook::class, $message->webhookId);
if (!($webhook instanceof StationWebhook)) {
$this->logger->error(
sprintf('Webhook ID %d not found.', $message->webhookId),
);
return;
}
$this->logger->info(sprintf('Dispatching test web hook "%s"...', $webhook->getName()));
$station = $webhook->getStation();
$np = $this->nowPlayingApiGen->currentOrEmpty($station);
$np->resolveUrls($this->router->getBaseUrl());
$np->cache = 'event';
$this->localHandler->dispatch($station, $np, []);
$webhookType = $webhook->getType();
$webhookClass = $webhookType->getClass();
if (null === $webhookClass) {
throw new RuntimeException(
'Webhook type is no longer supported. Removing this webhook is recommended.'
);
}
/** @var AbstractConnector $webhookObj */
$webhookObj = $this->di->get($webhookClass);
$webhookObj->dispatch($station, $webhook, $np, [
WebhookTriggers::SongChanged->value,
]);
$this->logger->info(sprintf('Web hook "%s" completed.', $webhook->getName()));
} catch (Throwable $e) {
$this->logger->error(
sprintf(
'%s L%d: %s',
$e->getFile(),
$e->getLine(),
$e->getMessage()
),
[
'exception' => $e,
]
);
} finally {
if (null !== $outputPath) {
$this->logger->popHandler();
}
}
}
}
``` | /content/code_sandbox/backend/src/Webhook/Dispatcher.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,366 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\Station;
use App\Entity\StationWebhook;
/*
* path_to_url#execute-webhook
*
* JSON/Form Params
* content string the message contents (up to 2000 characters) one of content, file, embeds
* username string override the default username of the webhook false
* avatar_url string override the default avatar of the webhook false
* tts bool true if this is a TTS message false
* file file contents the contents of the file being sent one of content, file, embeds
* embeds array of embed objects embedded rich content one of content, file, embeds
*
* Embed Structure
* title string title of embed
* type string type of embed (always "rich" for webhook embeds)
* description string description of embed
* url string url of embed
* timestamp ISO8601 timestamp timestamp of embed content
* color integer color code of the embed
* footer embed footer object footer information
* image embed image object image information
* thumbnail embed thumbnail object thumbnail information
* video embed video object video information
* provider embed provider object provider information
* author embed author object author information
* fields array of embed field objects fields information
*
* Embed Footer Structure
* text string footer text
* icon_url string url of footer icon (only supports http(s) and attachments)
* proxy_icon_url string a proxied url of footer icon
*
* Embed Thumbnail Structure
* url string source url of thumbnail (only supports http(s) and attachments)
* proxy_url string a proxied url of the thumbnail
* height integer height of thumbnail
* width integer width of thumbnail
*
* Embed Provider Structure
* name string name of provider
* url string url of provider
*
* Embed Footer Structure
* text string footer text
* icon_url string url of footer icon (only supports http(s) and attachments)
* proxy_icon_url string a proxied url of footer icon
*
* Embed Field Structure
* name string name of the field
* value string value of the field
* inline bool whether or not this field should display inline
*/
final class Discord extends AbstractConnector
{
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
$webhookUrl = $this->getValidUrl($config['webhook_url']);
if (empty($webhookUrl)) {
throw $this->incompleteConfigException($webhook);
}
$rawVars = [
'content' => $config['content'] ?? '',
'title' => $config['title'] ?? '',
'description' => $config['description'] ?? '',
'url' => $config['url'] ?? '',
'author' => $config['author'] ?? '',
'thumbnail' => $config['thumbnail'] ?? '',
'footer' => $config['footer'] ?? '',
];
$vars = $this->replaceVariables($rawVars, $np);
// Compose webhook
$embed = array_filter(
[
'title' => $vars['title'] ?? '',
'description' => $vars['description'] ?? '',
'url' => $this->getValidUrl($vars['url']) ?? '',
'color' => 2201331, // #2196f3
]
);
if (!empty($vars['author'])) {
$embed['author'] = [
'name' => $vars['author'],
];
}
if (!empty($vars['thumbnail']) && $this->getImageUrl($vars['thumbnail'])) {
$embed['thumbnail'] = [
'url' => $this->getImageUrl($vars['thumbnail']),
];
}
if (!empty($vars['footer'])) {
$embed['footer'] = [
'text' => $vars['footer'],
];
}
$webhookBody = [];
$webhookBody['content'] = $vars['content'] ?? '';
// Don't include an embed if all relevant fields are empty.
if (count($embed) > 1) {
$webhookBody['embeds'] = [$embed];
}
// Dispatch webhook
$this->logger->debug('Dispatching Discord webhook...');
$response = $this->httpClient->request(
'POST',
$webhookUrl,
[
'headers' => [
'Content-Type' => 'application/json',
],
'json' => $webhookBody,
]
);
$this->logHttpResponse(
$webhook,
$response,
$webhookBody
);
}
/** @noinspection HttpUrlsUsage */
private function getImageUrl(?string $url = null): ?string
{
$url = $this->getValidUrl($url);
if (null !== $url) {
return str_replace('path_to_url 'path_to_url $url);
}
return null;
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/Discord.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,125 |
```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;
final class Generic extends AbstractConnector
{
/**
* @inheritDoc
*/
public function dispatch(
Station $station,
StationWebhook $webhook,
NowPlaying $np,
array $triggers
): void {
$config = $webhook->getConfig();
$webhookUrl = $this->getValidUrl($config['webhook_url']);
if (empty($webhookUrl)) {
throw $this->incompleteConfigException($webhook);
}
$requestOptions = [
'headers' => [
'Content-Type' => 'application/json',
],
'json' => $np,
'timeout' => Types::floatOrNull($config['timeout']) ?? 5.0,
];
if (!empty($config['basic_auth_username']) && !empty($config['basic_auth_password'])) {
$requestOptions['auth'] = [
$config['basic_auth_username'],
$config['basic_auth_password'],
];
}
$response = $this->httpClient->request('POST', $webhookUrl, $requestOptions);
$this->logHttpResponse(
$webhook,
$response
);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/Generic.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 302 |
```php
<?php
declare(strict_types=1);
namespace App\Webhook\Connector;
use App\Container\LoggerAwareTrait;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\Entity\StationWebhook;
use App\Utilities\Arrays;
use App\Utilities\Types;
use App\Utilities\Urls;
use GuzzleHttp\Client;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
abstract class AbstractConnector implements ConnectorInterface
{
use LoggerAwareTrait;
public function __construct(
protected Client $httpClient
) {
}
/**
* @inheritDoc
*/
public function shouldDispatch(StationWebhook $webhook, array $triggers = []): bool
{
if (!$this->webhookShouldTrigger($webhook, $triggers)) {
$this->logger->debug(
sprintf(
'Webhook "%s" will not run for triggers: %s; skipping...',
$webhook->getName(),
implode(', ', $triggers)
)
);
return false;
}
$rateLimitTime = $this->getRateLimitTime($webhook);
if (null !== $rateLimitTime && !$webhook->checkRateLimit($rateLimitTime)) {
$this->logger->notice(
sprintf(
'Webhook "%s" has run less than %d seconds ago; skipping...',
$webhook->getName(),
$rateLimitTime
)
);
return false;
}
return true;
}
/**
* @param StationWebhook $webhook
* @param array<string> $triggers
*
*/
protected function webhookShouldTrigger(StationWebhook $webhook, array $triggers = []): bool
{
if (!$webhook->hasTriggers()) {
return true;
}
foreach ($triggers as $trigger) {
if ($webhook->hasTrigger($trigger)) {
return true;
}
}
return false;
}
protected function getRateLimitTime(StationWebhook $webhook): ?int
{
return 10;
}
/**
* Replace variables in the format {{ blah }} with the flattened contents of the NowPlaying API array.
*
* @param array $rawVars
* @param NowPlaying $np
*
* @return array
*/
public function replaceVariables(array $rawVars, NowPlaying $np): array
{
$values = Arrays::flattenArray($np);
$vars = [];
foreach ($rawVars as $varKey => $varValue) {
// Replaces {{ var.name }} with the flattened $values['var.name']
$vars[$varKey] = preg_replace_callback(
"/\{\{(\s*)([a-zA-Z\d\-_.]+)(\s*)}}/",
static function (array $matches) use ($values): string {
$innerValue = strtolower(trim($matches[2]));
return Types::string($values[$innerValue] ?? '');
},
$varValue
);
}
return $vars;
}
/**
* Determine if a passed URL is valid and return it if so, or return null otherwise.
*/
protected function getValidUrl(mixed $urlString = null): ?string
{
$urlString = Types::stringOrNull($urlString, true);
$uri = Urls::tryParseUserUrl(
$urlString,
'Webhook'
);
if (null === $uri) {
return null;
}
return (string)$uri;
}
protected function incompleteConfigException(StationWebhook $webhook): InvalidArgumentException
{
return new InvalidArgumentException(
sprintf(
'Webhook "%s" (type "%s") is missing necessary configuration. Skipping...',
$webhook->getName(),
$webhook->getType()->value
),
);
}
protected function logHttpResponse(
StationWebhook $webhook,
ResponseInterface $response,
mixed $requestBody = null
): void {
$responseStatus = $response->getStatusCode();
if ($responseStatus >= 400) {
$this->logger->error(
sprintf(
'Webhook "%s" returned unsuccessful response code %d.',
$webhook->getName(),
$responseStatus
)
);
}
$debugLogInfo = [];
if ($requestBody) {
$debugLogInfo['message_sent'] = $requestBody;
}
$debugLogInfo['response_body'] = $response->getBody()->getContents();
$this->logger->debug(
sprintf(
'Webhook "%s" returned response code %d',
$webhook->getName(),
$response->getStatusCode()
),
$debugLogInfo
);
}
}
``` | /content/code_sandbox/backend/src/Webhook/Connector/AbstractConnector.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,025 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.