text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```php <?php declare(strict_types=1); namespace App\Entity; use App\Enums\PermissionInterface; use Doctrine\ORM\Mapping as ORM; use JsonSerializable; #[ ORM\Entity(readOnly: true), ORM\Table(name: 'role_permissions'), ORM\UniqueConstraint(name: 'role_permission_unique_idx', columns: ['role_id', 'action_name', 'station_id']) ] class RolePermission implements JsonSerializable, Interfaces\StationCloneAwareInterface, Interfaces\IdentifiableEntityInterface { use Traits\HasAutoIncrementId; #[ORM\ManyToOne(inversedBy: 'permissions')] #[ORM\JoinColumn(name: 'role_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected Role $role; #[ORM\Column(insertable: false, updatable: false)] protected int $role_id; #[ORM\Column(length: 50)] protected string $action_name; #[ORM\ManyToOne(inversedBy: 'permissions')] #[ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?Station $station = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $station_id = null; public function __construct( Role $role, Station $station = null, string|PermissionInterface|null $actionName = null ) { $this->role = $role; $this->station = $station; if (null !== $actionName) { $this->setActionName($actionName); } } public function getRole(): Role { return $this->role; } public function getStation(): ?Station { return $this->station; } public function setStation(?Station $station): void { $this->station = $station; } public function hasStation(): bool { return (null !== $this->station); } public function getActionName(): string { return $this->action_name; } public function setActionName(string|PermissionInterface $actionName): void { if ($actionName instanceof PermissionInterface) { $actionName = $actionName->getValue(); } $this->action_name = $actionName; } /** * @return mixed[] */ public function jsonSerialize(): array { return [ 'action' => $this->action_name, 'station_id' => $this->station_id, ]; } } ```
/content/code_sandbox/backend/src/Entity/RolePermission.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
557
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use DateTimeZone; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; #[ OA\Schema(type: "object"), ORM\Entity, ORM\Table(name: 'station_schedules'), Attributes\Auditable ] class StationSchedule implements IdentifiableEntityInterface { use Traits\HasAutoIncrementId; #[ ORM\ManyToOne(inversedBy: 'schedule_items'), ORM\JoinColumn(name: 'playlist_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE') ] protected ?StationPlaylist $playlist = null; #[ ORM\ManyToOne(inversedBy: 'schedule_items'), ORM\JoinColumn(name: 'streamer_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE') ] protected ?StationStreamer $streamer = null; #[ OA\Property(example: 900), ORM\Column(type: 'smallint') ] protected int $start_time = 0; #[ OA\Property(example: 2200), ORM\Column(type: 'smallint') ] protected int $end_time = 0; #[ORM\Column(length: 10, nullable: true)] protected ?string $start_date = null; #[ORM\Column(length: 10, nullable: true)] protected ?string $end_date = null; #[ OA\Property( description: "Array of ISO-8601 days (1 for Monday, 7 for Sunday)", example: "0,1,2,3" ), ORM\Column(length: 50, nullable: true) ] protected ?string $days = null; #[ OA\Property(example: false), ORM\Column ] protected bool $loop_once = false; public function __construct(StationPlaylist|StationStreamer $relation) { if ($relation instanceof StationPlaylist) { $this->playlist = $relation; } else { $this->streamer = $relation; } } public function getPlaylist(): ?StationPlaylist { return $this->playlist; } public function setPlaylist(StationPlaylist $playlist): void { $this->playlist = $playlist; $this->streamer = null; } public function getStreamer(): ?StationStreamer { return $this->streamer; } public function setStreamer(StationStreamer $streamer): void { $this->streamer = $streamer; $this->playlist = null; } public function getStartTime(): int { return $this->start_time; } public function setStartTime(int $startTime): void { $this->start_time = $startTime; } public function getEndTime(): int { return $this->end_time; } public function setEndTime(int $endTime): void { $this->end_time = $endTime; } /** * @return int Get the duration of scheduled play time in seconds (used for remote URLs of indeterminate length). */ public function getDuration(): int { $now = CarbonImmutable::now(new DateTimeZone('UTC')); $startTime = self::getDateTime($this->start_time, $now) ->getTimestamp(); $endTime = self::getDateTime($this->end_time, $now) ->getTimestamp(); if ($startTime > $endTime) { /** @noinspection SummerTimeUnsafeTimeManipulationInspection */ return 86400 - ($startTime - $endTime); } return $endTime - $startTime; } public function getStartDate(): ?string { return $this->start_date; } public function setStartDate(?string $startDate): void { $this->start_date = $startDate; } public function getEndDate(): ?string { return $this->end_date; } public function setEndDate(?string $endDate): void { $this->end_date = $endDate; } /** * @return int[] */ public function getDays(): array { if (empty($this->days)) { return []; } $days = []; foreach (explode(',', $this->days) as $day) { $days[] = (int)$day; } return $days; } public function setDays(array $days): void { $this->days = implode(',', $days); } public function getLoopOnce(): bool { return $this->loop_once; } public function setLoopOnce(bool $loopOnce): void { $this->loop_once = $loopOnce; } public function __toString(): string { $parts = []; $startTimeText = self::displayTimeCode($this->start_time); $endTimeText = self::displayTimeCode($this->end_time); if ($this->start_time === $this->end_time) { $parts[] = $startTimeText; } else { $parts[] = $startTimeText . ' to ' . $endTimeText; } if (!empty($this->start_date) || !empty($this->end_date)) { if ($this->start_date === $this->end_date) { $parts[] = $this->start_date; } elseif (empty($this->start_date)) { $parts[] = 'Until ' . $this->end_date; } elseif (empty($this->end_date)) { $parts[] = 'After ' . $this->start_date; } else { $parts[] = $this->start_date . ' to ' . $this->end_date; } } $days = $this->getDays(); $daysOfWeek = [ 1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat', 7 => 'Sun', ]; if ([] !== $days) { $displayDays = []; foreach ($days as $day) { $displayDays[] = $daysOfWeek[$day]; } $parts[] = implode('/', $displayDays); } return implode(', ', $parts); } /** * Return a \DateTime object (or null) for a given time code, by default in the UTC time zone. * * @param int|string $timeCode * @param CarbonInterface $now The current date/time. Note that this time MUST be using the station's timezone * for this function to be accurate. * @return CarbonInterface The current date/time, with the time set to the time code specified. */ public static function getDateTime(int|string $timeCode, CarbonInterface $now): CarbonInterface { $timeCode = str_pad((string)$timeCode, 4, '0', STR_PAD_LEFT); return $now->setTime( (int)substr($timeCode, 0, 2), (int)substr($timeCode, 2) ); } public static function displayTimeCode(string|int $timeCode): string { $timeCode = str_pad((string)$timeCode, 4, '0', STR_PAD_LEFT); $hours = (int)substr($timeCode, 0, 2); $mins = substr($timeCode, 2); return $hours . ':' . $mins; } } ```
/content/code_sandbox/backend/src/Entity/StationSchedule.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,668
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\EntityGroupsInterface; use App\Entity\Interfaces\IdentifiableEntityInterface; use App\Security\SplitToken; use Azura\Normalizer\Attributes\DeepNormalize; use Doctrine\ORM\Mapping as ORM; use Stringable; use Symfony\Component\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation\Groups; #[ Attributes\Auditable, ORM\Table(name: 'api_keys'), ORM\Entity(readOnly: true) ] class ApiKey implements Stringable, IdentifiableEntityInterface { use Traits\HasSplitTokenFields; use Traits\TruncateStrings; #[ORM\ManyToOne(targetEntity: User::class, fetch: 'EAGER', inversedBy: 'api_keys')] #[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] #[Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL])] #[DeepNormalize(true)] #[Serializer\MaxDepth(1)] protected User $user; #[ORM\Column(length: 255, nullable: false)] #[Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])] protected string $comment = ''; public function __construct(User $user, SplitToken $token) { $this->user = $user; $this->setFromToken($token); } public function getUser(): User { return $this->user; } public function getComment(): string { return $this->comment; } public function setComment(string $comment): void { $this->comment = $this->truncateString($comment); } public function __toString(): string { return $this->comment; } } ```
/content/code_sandbox/backend/src/Entity/ApiKey.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
387
```php <?php declare(strict_types=1); namespace App\Entity; use App\Utilities\Strings; use App\Utilities\Types; use LogicException; class StationFrontendConfiguration extends AbstractStationConfiguration { public function __construct(array $elements = []) { // Generate defaults if not set. $autoAssignPasswords = [ self::SOURCE_PASSWORD, self::ADMIN_PASSWORD, self::RELAY_PASSWORD, self::STREAMER_PASSWORD, ]; foreach ($autoAssignPasswords as $autoAssignPassword) { if (empty($elements[$autoAssignPassword])) { $elements[$autoAssignPassword] = Strings::generatePassword(); } } parent::__construct($elements); } public const string CUSTOM_CONFIGURATION = 'custom_config'; public function getCustomConfiguration(): ?string { return Types::stringOrNull($this->get(self::CUSTOM_CONFIGURATION), true); } public function setCustomConfiguration(?string $config): void { $this->set(self::CUSTOM_CONFIGURATION, $config); } public const string SOURCE_PASSWORD = 'source_pw'; public function getSourcePassword(): string { return Types::stringOrNull($this->get(self::SOURCE_PASSWORD), true) ?? throw new LogicException('Password not generated'); } public function setSourcePassword(string $pw): void { $this->set(self::SOURCE_PASSWORD, $pw); } public const string ADMIN_PASSWORD = 'admin_pw'; public function getAdminPassword(): string { return Types::stringOrNull($this->get(self::ADMIN_PASSWORD), true) ?? throw new LogicException('Password not generated'); } public function setAdminPassword(string $pw): void { $this->set(self::ADMIN_PASSWORD, $pw); } public const string RELAY_PASSWORD = 'relay_pw'; public function getRelayPassword(): string { return Types::stringOrNull($this->get(self::RELAY_PASSWORD), true) ?? throw new LogicException('Password not generated'); } public function setRelayPassword(string $pw): void { $this->set(self::RELAY_PASSWORD, $pw); } public const string STREAMER_PASSWORD = 'streamer_pw'; public function getStreamerPassword(): string { return Types::stringOrNull($this->get(self::STREAMER_PASSWORD)) ?? throw new LogicException('Password not generated'); } public function setStreamerPassword(string $pw): void { $this->set(self::STREAMER_PASSWORD, $pw); } public const string PORT = 'port'; public function getPort(): ?int { return Types::intOrNull($this->get(self::PORT)); } public function setPort(int|string $port = null): void { $this->set(self::PORT, $port); } public const string MAX_LISTENERS = 'max_listeners'; public function getMaxListeners(): ?int { return Types::intOrNull($this->get(self::MAX_LISTENERS)); } public function setMaxListeners(int|string $listeners = null): void { $this->set(self::MAX_LISTENERS, $listeners); } public const string BANNED_IPS = 'banned_ips'; public function getBannedIps(): ?string { return Types::stringOrNull($this->get(self::BANNED_IPS), true); } public function setBannedIps(?string $ips): void { $this->set(self::BANNED_IPS, $ips); } public const string BANNED_USER_AGENTS = 'banned_user_agents'; public function getBannedUserAgents(): ?string { return Types::stringOrNull($this->get(self::BANNED_USER_AGENTS), true); } public function setBannedUserAgents(?string $userAgents): void { $this->set(self::BANNED_USER_AGENTS, $userAgents); } public const string BANNED_COUNTRIES = 'banned_countries'; public function getBannedCountries(): ?array { return Types::arrayOrNull($this->get(self::BANNED_COUNTRIES)); } public function setBannedCountries(?array $countries): void { $this->set(self::BANNED_COUNTRIES, $countries); } public const string ALLOWED_IPS = 'allowed_ips'; public function getAllowedIps(): ?string { return Types::stringOrNull($this->get(self::ALLOWED_IPS), true); } public function setAllowedIps(?string $ips): void { $this->set(self::ALLOWED_IPS, $ips); } public const string SC_LICENSE_ID = 'sc_license_id'; { return Types::stringOrNull($this->get(self::SC_LICENSE_ID), true); } { $this->set(self::SC_LICENSE_ID, $licenseId); } public const string SC_USER_ID = 'sc_user_id'; public function getScUserId(): ?string { return Types::stringOrNull($this->get(self::SC_USER_ID), true); } public function setScUserId(?string $userId): void { $this->set(self::SC_USER_ID, $userId); } } ```
/content/code_sandbox/backend/src/Entity/StationFrontendConfiguration.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,170
```php <?php declare(strict_types=1); namespace App\Entity; use Doctrine\Inflector\Inflector; use Doctrine\Inflector\InflectorFactory; use JsonSerializable; use ReflectionClass; use ReflectionClassConstant; /** * @phpstan-type ConfigData array<string, mixed> */ abstract class AbstractStationConfiguration implements JsonSerializable { /** @var ConfigData */ protected array $data = []; protected readonly Inflector $inflector; /** * @param ConfigData $data */ public function __construct( array $data = [] ) { $this->inflector = InflectorFactory::create()->build(); $this->fromArray($data); } /** * @param AbstractStationConfiguration|ConfigData|array<array-key, mixed> $data * @return $this */ public function fromArray( array|self $data ): static { if ($data instanceof self) { $data = $data->toArray(); } foreach ($data as $dataKey => $dataVal) { $methodName = $this->inflector->camelize('set_' . $dataKey); if (method_exists($this, $methodName)) { $this->$methodName($dataVal); } else { $this->set($dataKey, $dataVal); } } return $this; } /** * @return ConfigData */ public function toArray(): array { $return = []; foreach (self::getFields() as $dataKey) { $getMethodName = $this->inflector->camelize('get_' . $dataKey); $methodName = $this->inflector->camelize($dataKey); $return[$dataKey] = match (true) { method_exists($this, $getMethodName) => $this->$getMethodName(), method_exists($this, $methodName) => $this->$methodName(), default => $this->get($dataKey) }; } ksort($return); return $return; } public function jsonSerialize(): array|object { $result = $this->toArray(); return (0 !== count($result)) ? $result : (object)[]; } protected function get(string $key, mixed $default = null): mixed { return $this->data[$key] ?? $default; } protected function set(string $key, mixed $value): static { $this->data[$key] = $value; return $this; } public static function getFields(): array { $reflClass = new ReflectionClass(static::class); return $reflClass->getConstants(ReflectionClassConstant::IS_PUBLIC); } } ```
/content/code_sandbox/backend/src/Entity/AbstractStationConfiguration.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
601
```php <?php declare(strict_types=1); namespace App\Entity; use App\OpenApi; use App\Validator\Constraints\UniqueEntity; use Azura\Normalizer\Attributes\DeepNormalize; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; use Stringable; use Symfony\Component\Serializer\Annotation as Serializer; use Symfony\Component\Validator\Constraints as Assert; use const PASSWORD_ARGON2ID; #[ OA\Schema( description: 'Station streamers (DJ accounts) allowed to broadcast to a station.', type: "object" ), ORM\Entity, ORM\Table(name: 'station_streamers'), ORM\UniqueConstraint(name: 'username_unique_idx', columns: ['station_id', 'streamer_username']), ORM\HasLifecycleCallbacks, UniqueEntity(fields: ['station', 'streamer_username']), Attributes\Auditable ] class StationStreamer implements Stringable, Interfaces\StationCloneAwareInterface, Interfaces\IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; #[ ORM\ManyToOne(inversedBy: 'streamers'), ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE') ] protected Station $station; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $station_id; #[ OA\Property(example: "dj_test"), ORM\Column(length: 50), Assert\NotBlank ] protected string $streamer_username; #[ OA\Property(example: ""), ORM\Column(length: 255), Assert\NotBlank, Attributes\AuditIgnore ] protected string $streamer_password; #[ OA\Property(example: "Test DJ"), ORM\Column(length: 255, nullable: true) ] protected ?string $display_name = null; #[ OA\Property(example: "This is a test DJ account."), ORM\Column(type: 'text', nullable: true) ] protected ?string $comments = null; #[ OA\Property(example: true), ORM\Column ] protected bool $is_active = true; #[ OA\Property(example: false), ORM\Column ] protected bool $enforce_schedule = false; #[ OA\Property(example: OpenApi::SAMPLE_TIMESTAMP), ORM\Column(nullable: true), Attributes\AuditIgnore ] protected ?int $reactivate_at = null; #[ ORM\Column, Attributes\AuditIgnore ] protected int $art_updated_at = 0; /** @var Collection<int, StationSchedule> */ #[ OA\Property(type: "array", items: new OA\Items()), ORM\OneToMany(targetEntity: StationSchedule::class, mappedBy: 'streamer'), DeepNormalize(true), Serializer\MaxDepth(1) ] protected Collection $schedule_items; /** @var Collection<int, StationStreamerBroadcast> */ #[ ORM\OneToMany(targetEntity: StationStreamerBroadcast::class, mappedBy: 'streamer'), DeepNormalize(true) ] protected Collection $broadcasts; public function __construct(Station $station) { $this->station = $station; $this->schedule_items = new ArrayCollection(); $this->broadcasts = new ArrayCollection(); } public function getStation(): Station { return $this->station; } public function setStation(Station $station): void { $this->station = $station; } public function getStreamerUsername(): string { return $this->streamer_username; } public function setStreamerUsername(string $streamerUsername): void { $this->streamer_username = $this->truncateString($streamerUsername, 50); } public function getStreamerPassword(): string { return ''; } public function setStreamerPassword(?string $streamerPassword): void { $streamerPassword = trim($streamerPassword ?? ''); if (!empty($streamerPassword)) { $this->streamer_password = password_hash($streamerPassword, PASSWORD_ARGON2ID); } } public function authenticate(string $password): bool { return password_verify($password, $this->streamer_password); } public function getDisplayName(): string { return (!empty($this->display_name)) ? $this->display_name : $this->streamer_username; } public function setDisplayName(?string $displayName): void { $this->display_name = $this->truncateNullableString($displayName); } public function getComments(): ?string { return $this->comments; } public function setComments(string $comments = null): void { $this->comments = $comments; } public function getIsActive(): bool { return $this->is_active; } public function setIsActive(bool $isActive): void { $this->is_active = $isActive; // Automatically set the "reactivate_at" flag to null if the DJ is for any reason reactivated. if (true === $isActive) { $this->reactivate_at = null; } } public function enforceSchedule(): bool { return $this->enforce_schedule; } public function setEnforceSchedule(bool $enforceSchedule): void { $this->enforce_schedule = $enforceSchedule; } public function getReactivateAt(): ?int { return $this->reactivate_at; } public function setReactivateAt(?int $reactivateAt): void { $this->reactivate_at = $reactivateAt; } public function deactivateFor(int $seconds): void { $this->is_active = false; $this->reactivate_at = time() + $seconds; } public function getArtUpdatedAt(): int { return $this->art_updated_at; } public function setArtUpdatedAt(int $artUpdatedAt): self { $this->art_updated_at = $artUpdatedAt; return $this; } /** * @return Collection<int, StationSchedule> */ public function getScheduleItems(): Collection { return $this->schedule_items; } public function __toString(): string { return $this->getStation() . ' Streamer: ' . $this->getDisplayName(); } public function __clone() { $this->reactivate_at = null; } public static function getArtworkPath(int|string $streamerId): string { return 'streamer_' . $streamerId . '.jpg'; } } ```
/content/code_sandbox/backend/src/Entity/StationStreamer.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,488
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Attributes\Auditable; use App\Validator\Constraints\UniqueEntity; use Doctrine\ORM\Mapping as ORM; use Exception; use OpenApi\Attributes as OA; use phpseclib3\Crypt\PublicKeyLoader; use Symfony\Component\Validator\Constraints as Assert; use const PASSWORD_ARGON2ID; #[ OA\Schema(type: "object"), ORM\Entity, ORM\Table(name: 'sftp_user'), ORM\UniqueConstraint(name: 'username_idx', columns: ['username']), UniqueEntity(fields: ['username']), Auditable ] class SftpUser implements Interfaces\IdentifiableEntityInterface, Interfaces\StationAwareInterface { use Traits\HasAutoIncrementId; #[ ORM\ManyToOne(inversedBy: 'sftp_users'), ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE') ] protected Station $station; #[ OA\Property, ORM\Column(length: 32), Assert\Length(min: 1, max: 32), Assert\NotBlank, Assert\Regex(pattern: '/^[a-zA-Z0-9-_.~]+$/') ] protected string $username; #[ OA\Property, ORM\Column(length: 255), Assert\NotBlank ] protected string $password; #[ OA\Property, ORM\Column(name: 'public_keys', type: 'text', nullable: true) ] protected ?string $publicKeys = null; public function __construct(Station $station) { $this->station = $station; } public function getStation(): Station { return $this->station; } public function getUsername(): string { return $this->username; } public function setUsername(string $username): void { $this->username = $username; } public function getPassword(): string { return ''; } public function setPassword(?string $password): void { if (!empty($password)) { $this->password = password_hash($password, PASSWORD_ARGON2ID); } } public function getPublicKeys(): ?string { return $this->publicKeys; } /** * @return string[] */ public function getPublicKeysArray(): array { if (null === $this->publicKeys) { return []; } $pubKeysRaw = trim($this->publicKeys); if (!empty($pubKeysRaw)) { return array_filter( array_map([$this, 'cleanPublicKey'], explode("\n", $pubKeysRaw)) ); } return []; } public function setPublicKeys(?string $publicKeys): void { $this->publicKeys = $publicKeys; } public function authenticate(?string $password = null, ?string $pubKey = null): bool { if (!empty($password)) { return password_verify($password, $this->password); } if (!empty($pubKey)) { $pubKeys = $this->getPublicKeysArray(); return in_array($this->cleanPublicKey($pubKey), $pubKeys, true); } return false; } public function cleanPublicKey(string $pubKeyRaw): ?string { try { $pkObj = PublicKeyLoader::loadPublicKey(trim($pubKeyRaw)); return trim($pkObj->toString('OpenSSH', ['comment' => ''])); } catch (Exception) { return null; } } } ```
/content/code_sandbox/backend/src/Entity/SftpUser.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
788
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Enums\PlaylistOrders; use App\Entity\Enums\PlaylistRemoteTypes; use App\Entity\Enums\PlaylistSources; use App\Entity\Enums\PlaylistTypes; use App\Utilities\File; use Azura\Normalizer\Attributes\DeepNormalize; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; use Stringable; use Symfony\Component\Serializer\Annotation as Serializer; use Symfony\Component\Validator\Constraints as Assert; #[ OA\Schema(type: "object"), ORM\Entity, ORM\Table(name: 'station_playlists'), ORM\HasLifecycleCallbacks, Attributes\Auditable ] class StationPlaylist implements Stringable, Interfaces\StationCloneAwareInterface, Interfaces\IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; public const int DEFAULT_WEIGHT = 3; public const int DEFAULT_REMOTE_BUFFER = 20; public const string OPTION_INTERRUPT_OTHER_SONGS = 'interrupt'; public const string OPTION_PLAY_SINGLE_TRACK = 'single_track'; public const string OPTION_MERGE = 'merge'; #[ ORM\ManyToOne(inversedBy: 'playlists'), ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE') ] protected Station $station; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $station_id; #[ OA\Property(example: "Test Playlist"), ORM\Column(length: 200), Assert\NotBlank ] protected string $name; #[ OA\Property(example: "default"), ORM\Column(type: 'string', length: 50, enumType: PlaylistTypes::class) ] protected PlaylistTypes $type; #[ OA\Property(example: "songs"), ORM\Column(type: 'string', length: 50, enumType: PlaylistSources::class) ] protected PlaylistSources $source; #[ OA\Property(example: "shuffle"), ORM\Column(name: 'playback_order', type: 'string', length: 50, enumType: PlaylistOrders::class) ] protected PlaylistOrders $order; #[ OA\Property(example: "path_to_url"), ORM\Column(length: 255, nullable: true) ] protected ?string $remote_url = null; #[ OA\Property(example: "stream"), ORM\Column(type: 'string', length: 25, nullable: true, enumType: PlaylistRemoteTypes::class) ] protected ?PlaylistRemoteTypes $remote_type; #[ OA\Property( description: "The total time (in seconds) that Liquidsoap should buffer remote URL streams.", example: 0 ), ORM\Column(name: 'remote_timeout', type: 'smallint') ] protected int $remote_buffer = 0; #[ OA\Property(example: true), ORM\Column ] protected bool $is_enabled = true; #[ OA\Property( description: "If yes, do not send jingle metadata to AutoDJ or trigger web hooks.", example: false ), ORM\Column ] protected bool $is_jingle = false; #[ OA\Property(example: 5), ORM\Column(type: 'smallint') ] protected int $play_per_songs = 0; #[ OA\Property(example: 120), ORM\Column(type: 'smallint') ] protected int $play_per_minutes = 0; #[ OA\Property(example: 15), ORM\Column(type: 'smallint') ] protected int $play_per_hour_minute = 0; #[ OA\Property(example: 3), ORM\Column(type: 'smallint') ] protected int $weight = self::DEFAULT_WEIGHT; #[ OA\Property(example: true), ORM\Column ] protected bool $include_in_requests = true; #[ OA\Property( description: "Whether this playlist's media is included in 'on demand' download/streaming if enabled.", example: true ), ORM\Column ] protected bool $include_in_on_demand = false; #[ OA\Property(example: "interrupt,loop_once,single_track,merge"), ORM\Column(length: 255, nullable: true) ] protected ?string $backend_options = ''; #[ OA\Property(example: true), ORM\Column ] protected bool $avoid_duplicates = true; #[ ORM\Column, Attributes\AuditIgnore ] protected int $played_at = 0; #[ ORM\Column, Attributes\AuditIgnore ] protected int $queue_reset_at = 0; /** @var Collection<int, StationPlaylistMedia> */ #[ ORM\OneToMany(targetEntity: StationPlaylistMedia::class, mappedBy: 'playlist', fetch: 'EXTRA_LAZY'), ORM\OrderBy(['weight' => 'ASC']) ] protected Collection $media_items; /** @var Collection<int, StationPlaylistFolder> */ #[ ORM\OneToMany(targetEntity: StationPlaylistFolder::class, mappedBy: 'playlist', fetch: 'EXTRA_LAZY') ] protected Collection $folders; /** @var Collection<int, StationSchedule> */ #[ OA\Property(type: "array", items: new OA\Items()), ORM\OneToMany(targetEntity: StationSchedule::class, mappedBy: 'playlist', fetch: 'EXTRA_LAZY'), DeepNormalize(true), Serializer\MaxDepth(1) ] protected Collection $schedule_items; /** @var Collection<int, Podcast> */ #[ OA\Property(type: "array", items: new OA\Items()), ORM\OneToMany(targetEntity: Podcast::class, mappedBy: 'playlist', fetch: 'EXTRA_LAZY'), DeepNormalize(true), Serializer\MaxDepth(1) ] protected Collection $podcasts; public function __construct(Station $station) { $this->station = $station; $this->type = PlaylistTypes::default(); $this->source = PlaylistSources::Songs; $this->order = PlaylistOrders::Shuffle; $this->remote_type = PlaylistRemoteTypes::Stream; $this->media_items = new ArrayCollection(); $this->folders = new ArrayCollection(); $this->schedule_items = new ArrayCollection(); $this->podcasts = new ArrayCollection(); } public function getStation(): Station { return $this->station; } public function setStation(Station $station): void { $this->station = $station; } public function getName(): string { return $this->name; } public function setName(string $name): void { $this->name = $this->truncateString($name, 200); } public function getShortName(): string { return self::generateShortName($this->name); } public function getType(): PlaylistTypes { return $this->type; } public function setType(PlaylistTypes $type): void { $this->type = $type; } public function getSource(): PlaylistSources { return $this->source; } public function setSource(PlaylistSources $source): void { $this->source = $source; if (PlaylistSources::RemoteUrl === $source) { $this->type = PlaylistTypes::Standard; } } public function getOrder(): PlaylistOrders { return $this->order; } public function setOrder(PlaylistOrders $order): void { $this->order = $order; } public function getRemoteUrl(): ?string { return $this->remote_url; } public function setRemoteUrl(?string $remoteUrl): void { $this->remote_url = $remoteUrl; } public function getRemoteType(): ?PlaylistRemoteTypes { return $this->remote_type; } public function setRemoteType(?PlaylistRemoteTypes $remoteType): void { $this->remote_type = $remoteType; } public function getRemoteBuffer(): int { return $this->remote_buffer; } public function setRemoteBuffer(int $remoteBuffer): void { $this->remote_buffer = $remoteBuffer; } public function getIsEnabled(): bool { return $this->is_enabled; } public function setIsEnabled(bool $isEnabled): void { $this->is_enabled = $isEnabled; } public function getIsJingle(): bool { return $this->is_jingle; } public function setIsJingle(bool $isJingle): void { $this->is_jingle = $isJingle; } public function getWeight(): int { if ($this->weight < 1) { return self::DEFAULT_WEIGHT; } return $this->weight; } public function setWeight(int $weight): void { $this->weight = $weight; } public function getIncludeInRequests(): bool { return $this->include_in_requests; } public function setIncludeInRequests(bool $includeInRequests): void { $this->include_in_requests = $includeInRequests; } public function getIncludeInOnDemand(): bool { return $this->include_in_on_demand; } public function setIncludeInOnDemand(bool $includeInOnDemand): void { $this->include_in_on_demand = $includeInOnDemand; } /** * Indicates whether this playlist can be used as a valid source of requestable media. */ public function isRequestable(): bool { return ($this->is_enabled && $this->include_in_requests); } public function getAvoidDuplicates(): bool { return $this->avoid_duplicates; } public function setAvoidDuplicates(bool $avoidDuplicates): void { $this->avoid_duplicates = $avoidDuplicates; } public function getPlayedAt(): int { return $this->played_at; } public function setPlayedAt(int $playedAt): void { $this->played_at = $playedAt; } public function getQueueResetAt(): int { return $this->queue_reset_at; } public function setQueueResetAt(int $queueResetAt): void { $this->queue_reset_at = $queueResetAt; } /** * @return Collection<int, StationPlaylistMedia> */ public function getMediaItems(): Collection { return $this->media_items; } /** * @return Collection<int, StationPlaylistFolder> */ public function getFolders(): Collection { return $this->folders; } /** * @return Collection<int, StationSchedule> */ public function getScheduleItems(): Collection { return $this->schedule_items; } /** * @return Collection<int, Podcast> */ public function getPodcasts(): Collection { return $this->podcasts; } /** * Indicates whether a playlist is enabled and has content which can be scheduled by an AutoDJ scheduler. * * @param bool $interrupting Whether determining "playability" for an interrupting queue or a regular one. */ public function isPlayable(bool $interrupting = false): bool { if (!$this->is_enabled) { return false; } if ($interrupting !== $this->backendInterruptOtherSongs()) { return false; } if (PlaylistSources::Songs === $this->getSource()) { return $this->media_items->count() > 0; } // Remote stream playlists aren't supported by the AzuraCast AutoDJ. return PlaylistRemoteTypes::Playlist === $this->getRemoteType(); } /** * @return string[] */ public function getBackendOptions(): array { return explode(',', $this->backend_options ?? ''); } /** * @param array $backendOptions */ public function setBackendOptions(array $backendOptions): void { $this->backend_options = implode(',', $backendOptions); } public function backendInterruptOtherSongs(): bool { $backendOptions = $this->getBackendOptions(); return in_array(self::OPTION_INTERRUPT_OTHER_SONGS, $backendOptions, true); } public function backendMerge(): bool { $backendOptions = $this->getBackendOptions(); return in_array(self::OPTION_MERGE, $backendOptions, true); } public function backendPlaySingleTrack(): bool { $backendOptions = $this->getBackendOptions(); return in_array(self::OPTION_PLAY_SINGLE_TRACK, $backendOptions, true); } public function getPlayPerHourMinute(): int { return $this->play_per_hour_minute; } public function setPlayPerHourMinute(int $playPerHourMinute): void { if ($playPerHourMinute > 59 || $playPerHourMinute < 0) { $playPerHourMinute = 0; } $this->play_per_hour_minute = $playPerHourMinute; } public function getPlayPerSongs(): int { return $this->play_per_songs; } public function setPlayPerSongs(int $playPerSongs): void { $this->play_per_songs = $playPerSongs; } public function getPlayPerMinutes(): int { return $this->play_per_minutes; } public function setPlayPerMinutes( int $playPerMinutes ): void { $this->play_per_minutes = $playPerMinutes; } public function __clone() { $this->played_at = 0; $this->queue_reset_at = 0; } public function __toString(): string { return $this->getStation() . ' Playlist: ' . $this->getName(); } public static function generateShortName(string $str): string { $str = File::sanitizeFileName($str); return (is_numeric($str)) ? 'playlist_' . $str : $str; } } ```
/content/code_sandbox/backend/src/Entity/StationPlaylist.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
3,177
```php <?php declare(strict_types=1); namespace App\Entity; use App\Radio\Enums\AdapterTypeInterface; use App\Radio\Enums\FrontendAdapters; use App\Radio\Enums\StreamFormats; use App\Radio\Enums\StreamProtocols; use App\Radio\Frontend\AbstractFrontend; use App\Utilities\Urls; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; use Psr\Http\Message\UriInterface; use Stringable; use Symfony\Component\Validator\Constraints as Assert; #[ OA\Schema(type: "object"), ORM\Entity, ORM\Table(name: 'station_mounts'), Attributes\Auditable ] class StationMount implements Stringable, Interfaces\StationMountInterface, Interfaces\StationCloneAwareInterface, Interfaces\IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; use Traits\TruncateInts; #[ ORM\ManyToOne(inversedBy: 'mounts'), ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE') ] protected Station $station; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $station_id; #[ OA\Property(example: "/radio.mp3"), ORM\Column(length: 100), Assert\NotBlank ] protected string $name = ''; #[ OA\Property(example: "128kbps MP3"), ORM\Column(length: 255, nullable: true) ] protected ?string $display_name = null; #[ OA\Property(example: true), ORM\Column ] protected bool $is_visible_on_public_pages = true; #[ OA\Property(example: false), ORM\Column ] protected bool $is_default = false; #[ OA\Property(example: false), ORM\Column ] protected bool $is_public = false; #[ OA\Property(example: "/error.mp3"), ORM\Column(length: 100, nullable: true) ] protected ?string $fallback_mount = null; #[ OA\Property(example: "path_to_url"), ORM\Column(length: 255, nullable: true) ] protected ?string $relay_url = null; #[ OA\Property(example: ""), ORM\Column(length: 255, nullable: true) ] protected ?string $authhash = null; #[ OA\Property(example: 43200), ORM\Column(type: 'integer', nullable: false) ] protected int $max_listener_duration = 0; #[ OA\Property(example: true), ORM\Column ] protected bool $enable_autodj = true; #[ OA\Property(example: "mp3"), ORM\Column(type: 'string', length: 10, nullable: true, enumType: StreamFormats::class) ] protected ?StreamFormats $autodj_format = StreamFormats::Mp3; #[ OA\Property(example: 128), ORM\Column(type: 'smallint', nullable: true) ] protected ?int $autodj_bitrate = 128; #[ OA\Property(example: "path_to_url"), ORM\Column(length: 255, nullable: true) ] protected ?string $custom_listen_url = null; #[ORM\Column(length: 255, nullable: true)] protected ?string $intro_path = null; #[ OA\Property(type: "array", items: new OA\Items()), ORM\Column(type: 'text', nullable: true) ] protected ?string $frontend_config = null; #[ OA\Property( description: "The most recent number of unique listeners.", example: 10 ), ORM\Column, Attributes\AuditIgnore ] protected int $listeners_unique = 0; #[ OA\Property( description: "The most recent number of total (non-unique) listeners.", example: 12 ), ORM\Column, Attributes\AuditIgnore ] protected int $listeners_total = 0; public function __construct(Station $station) { $this->station = $station; } public function getStation(): Station { return $this->station; } public function setStation(Station $station): void { $this->station = $station; } public function getName(): string { return $this->name; } public function setName(string $newName): void { // Ensure all mount point names start with a leading slash. $this->name = $this->truncateString('/' . ltrim($newName, '/'), 100); } public function getDisplayName(): string { if (!empty($this->display_name)) { return $this->display_name; } if ($this->enable_autodj) { $format = $this->getAutodjFormat(); return (null !== $format) ? $this->name . ' (' . $format->formatBitrate($this->autodj_bitrate) . ')' : $this->name; } return $this->name; } public function setDisplayName(?string $displayName): void { $this->display_name = $this->truncateNullableString($displayName); } public function getIsVisibleOnPublicPages(): bool { return $this->is_visible_on_public_pages; } public function setIsVisibleOnPublicPages(bool $isVisibleOnPublicPages): void { $this->is_visible_on_public_pages = $isVisibleOnPublicPages; } public function getIsDefault(): bool { return $this->is_default; } public function setIsDefault(bool $isDefault): void { $this->is_default = $isDefault; } public function getIsPublic(): bool { return $this->is_public; } public function setIsPublic(bool $isPublic): void { $this->is_public = $isPublic; } public function getFallbackMount(): ?string { return $this->fallback_mount; } public function setFallbackMount(?string $fallbackMount = null): void { $this->fallback_mount = $fallbackMount; } public function getRelayUrl(): ?string { return $this->relay_url; } public function getRelayUrlAsUri(): ?UriInterface { $relayUri = Urls::tryParseUserUrl( $this->relay_url, 'Mount Point ' . $this->__toString() . ' Relay URL' ); if (null !== $relayUri) { // Relays need port explicitly provided. $port = $relayUri->getPort(); if ($port === null && '' !== $relayUri->getScheme()) { $relayUri = $relayUri->withPort( ('https' === $relayUri->getScheme()) ? 443 : 80 ); } } return $relayUri; } public function setRelayUrl(?string $relayUrl = null): void { $this->relay_url = $this->truncateNullableString($relayUrl); } public function getAuthhash(): ?string { return $this->authhash; } public function setAuthhash(?string $authhash = null): void { $this->authhash = $this->truncateNullableString($authhash); } public function getMaxListenerDuration(): int { return $this->max_listener_duration; } public function setMaxListenerDuration(int $maxListenerDuration): void { $this->max_listener_duration = $this->truncateInt($maxListenerDuration); } public function getEnableAutodj(): bool { return $this->enable_autodj; } public function setEnableAutodj(bool $enableAutodj): void { $this->enable_autodj = $enableAutodj; } public function getAutodjFormat(): ?StreamFormats { return $this->autodj_format; } public function setAutodjFormat(?StreamFormats $autodjFormat = null): void { $this->autodj_format = $autodjFormat; } public function getAutodjBitrate(): ?int { return $this->autodj_bitrate; } public function setAutodjBitrate(?int $autodjBitrate = null): void { $this->autodj_bitrate = $autodjBitrate; } public function getCustomListenUrl(): ?string { return $this->custom_listen_url; } public function getCustomListenUrlAsUri(): ?UriInterface { return Urls::tryParseUserUrl( $this->custom_listen_url, 'Mount Point ' . $this->__toString() . ' Listen URL' ); } public function setCustomListenUrl(?string $customListenUrl = null): void { $this->custom_listen_url = $this->truncateNullableString($customListenUrl); } public function getFrontendConfig(): ?string { return $this->frontend_config; } public function setFrontendConfig(?string $frontendConfig = null): void { $this->frontend_config = $frontendConfig; } public function getListenersUnique(): int { return $this->listeners_unique; } public function setListenersUnique(int $listenersUnique): void { $this->listeners_unique = $listenersUnique; } public function getListenersTotal(): int { return $this->listeners_total; } public function setListenersTotal(int $listenersTotal): void { $this->listeners_total = $listenersTotal; } public function getIntroPath(): ?string { return $this->intro_path; } public function setIntroPath(?string $introPath): void { $this->intro_path = $introPath; } public function getAutodjHost(): ?string { return '127.0.0.1'; } public function getAutodjPort(): ?int { return $this->getStation()->getFrontendConfig()->getPort(); } public function getAutodjProtocol(): ?StreamProtocols { return match ($this->getAutodjAdapterType()) { FrontendAdapters::Shoutcast => StreamProtocols::Icy, default => null }; } public function getAutodjUsername(): ?string { return ''; } public function getAutodjPassword(): ?string { return $this->getStation()->getFrontendConfig()->getSourcePassword(); } public function getAutodjMount(): ?string { return $this->getName(); } public function getAutodjAdapterType(): AdapterTypeInterface { return $this->getStation()->getFrontendType(); } public function getIsShoutcast(): bool { return match ($this->getAutodjAdapterType()) { FrontendAdapters::Shoutcast => true, default => false }; } /** * Retrieve the API version of the object/array. * * @param AbstractFrontend $fa * @param UriInterface|null $baseUrl */ public function api( AbstractFrontend $fa, UriInterface $baseUrl = null ): Api\NowPlaying\StationMount { $response = new Api\NowPlaying\StationMount(); $response->id = $this->getIdRequired(); $response->name = $this->getDisplayName(); $response->path = $this->getName(); $response->is_default = $this->is_default; $response->url = $fa->getUrlForMount($this->station, $this, $baseUrl); $response->listeners = new Api\NowPlaying\Listeners( total: $this->listeners_total, unique: $this->listeners_unique ); if ($this->enable_autodj) { $response->bitrate = (int)$this->autodj_bitrate; $response->format = $this->autodj_format?->value; } return $response; } public function __toString(): string { return $this->getStation() . ' Mount: ' . $this->getDisplayName(); } } ```
/content/code_sandbox/backend/src/Entity/StationMount.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,794
```php <?php declare(strict_types=1); namespace App\Entity; use App\Utilities\Types; use Doctrine\ORM\Mapping as ORM; use JsonSerializable; #[ORM\Embeddable] class ListenerLocation implements JsonSerializable { #[ORM\Column(length: 255, nullable: false)] protected string $description = 'Unknown'; #[ORM\Column(length: 150, nullable: true)] protected ?string $region = null; #[ORM\Column(length: 150, nullable: true)] protected ?string $city = null; #[ORM\Column(length: 2, nullable: true)] protected ?string $country = null; #[ORM\Column(type: 'decimal', precision: 10, scale: 6, nullable: true)] protected ?string $lat = null; #[ORM\Column(type: 'decimal', precision: 10, scale: 6, nullable: true)] protected ?string $lon = null; public function getDescription(): string { return $this->description; } public function getRegion(): ?string { return $this->region; } public function getCity(): ?string { return $this->city; } public function getCountry(): ?string { return $this->country; } public function getLat(): ?float { return Types::floatOrNull($this->lat); } public function getLon(): ?float { return Types::floatOrNull($this->lon); } public function jsonSerialize(): array { return [ 'description' => $this->description, 'region' => $this->region, 'city' => $this->city, 'country' => $this->country, 'lat' => $this->lat, 'lon' => $this->lon, ]; } } ```
/content/code_sandbox/backend/src/Entity/ListenerLocation.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
403
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use Doctrine\ORM\Mapping as ORM; use JsonSerializable; #[ ORM\Entity, ORM\Table(name: 'station_playlist_media') ] class StationPlaylistMedia implements JsonSerializable, IdentifiableEntityInterface { use Traits\HasAutoIncrementId; #[ORM\ManyToOne(fetch: 'EAGER', inversedBy: 'media_items')] #[ORM\JoinColumn(name: 'playlist_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected StationPlaylist $playlist; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $playlist_id; #[ORM\ManyToOne(fetch: 'EAGER', inversedBy: 'playlists')] #[ORM\JoinColumn(name: 'media_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected StationMedia $media; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $media_id; #[ORM\Column] protected int $weight = 0; #[ORM\Column] protected bool $is_queued = true; #[ORM\Column] protected int $last_played = 0; public function __construct(StationPlaylist $playlist, StationMedia $media) { $this->playlist = $playlist; $this->media = $media; } public function getPlaylist(): StationPlaylist { return $this->playlist; } public function setPlaylist(StationPlaylist $playlist): void { $this->playlist = $playlist; } public function getMedia(): StationMedia { return $this->media; } public function getWeight(): int { return $this->weight; } public function setWeight(int $weight): void { $this->weight = $weight; } public function getLastPlayed(): int { return $this->last_played; } public function requeue(): void { $this->is_queued = true; } public function played(int $timestamp = null): void { $this->last_played = $timestamp ?? time(); $this->is_queued = false; } /** * @inheritDoc */ public function jsonSerialize(): array { return [ 'id' => $this->playlist->getId(), 'name' => $this->playlist->getName(), 'weight' => $this->weight, ]; } public function __clone() { $this->last_played = 0; $this->is_queued = false; } } ```
/content/code_sandbox/backend/src/Entity/StationPlaylistMedia.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
595
```php <?php declare(strict_types=1); namespace App\Entity; use App\Utilities\Types; use App\Utilities\Urls; use Psr\Http\Message\UriInterface; class StationBrandingConfiguration extends AbstractStationConfiguration { public const string DEFAULT_ALBUM_ART_URL = 'default_album_art_url'; public function getDefaultAlbumArtUrl(): ?string { return Types::stringOrNull($this->get(self::DEFAULT_ALBUM_ART_URL), true); } public function getDefaultAlbumArtUrlAsUri(): ?UriInterface { return Urls::tryParseUserUrl( $this->getDefaultAlbumArtUrl(), 'Station Default Album Art URL', false ); } public function setDefaultAlbumArtUrl(?string $defaultAlbumArtUrl): void { $this->set(self::DEFAULT_ALBUM_ART_URL, $defaultAlbumArtUrl); } public const string PUBLIC_CUSTOM_CSS = 'public_custom_css'; public function getPublicCustomCss(): ?string { return Types::stringOrNull($this->get(self::PUBLIC_CUSTOM_CSS), true); } public function setPublicCustomCss(?string $css): void { $this->set(self::PUBLIC_CUSTOM_CSS, $css); } public const string PUBLIC_CUSTOM_JS = 'public_custom_js'; public function getPublicCustomJs(): ?string { return Types::stringOrNull($this->get(self::PUBLIC_CUSTOM_JS), true); } public function setPublicCustomJs(?string $js): void { $this->set(self::PUBLIC_CUSTOM_JS, $js); } public const string OFFLINE_TEXT = 'offline_text'; public function getOfflineText(): ?string { return Types::stringOrNull($this->get(self::OFFLINE_TEXT), true); } public function setOfflineText(?string $message): void { $this->set(self::OFFLINE_TEXT, $message); } } ```
/content/code_sandbox/backend/src/Entity/StationBrandingConfiguration.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
421
```php <?php declare(strict_types=1); namespace App\Entity; use Doctrine\ORM\Mapping as ORM; #[ ORM\Entity, ORM\Table(name: 'station_queue'), ORM\Index(name: 'idx_is_played', columns: ['is_played']), ORM\Index(name: 'idx_timestamp_played', columns: ['timestamp_played']), ORM\Index(name: 'idx_sent_to_autodj', columns: ['sent_to_autodj']), ORM\Index(name: 'idx_timestamp_cued', columns: ['timestamp_cued']) ] class StationQueue implements Interfaces\SongInterface, Interfaces\IdentifiableEntityInterface, Interfaces\StationAwareInterface { use Traits\HasAutoIncrementId; use Traits\TruncateInts; use Traits\HasSongFields; public const int DAYS_TO_KEEP = 7; public const int QUEUE_LOG_TTL = 86400; #[ORM\ManyToOne(inversedBy: 'history')] #[ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected Station $station; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $station_id; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'playlist_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?StationPlaylist $playlist = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $playlist_id = null; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'media_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?StationMedia $media = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $media_id = null; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'playlist_media_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?StationPlaylistMedia $playlistMedia = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $playlist_media_id = null; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'request_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?StationRequest $request = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $request_id = null; #[ORM\Column] protected bool $sent_to_autodj = false; #[ORM\Column] protected bool $is_played = false; #[ORM\Column] protected bool $is_visible = true; #[ORM\Column(length: 255, nullable: true)] protected ?string $autodj_custom_uri = null; #[ORM\Column] protected int $timestamp_cued; #[ORM\Column] protected int $timestamp_played; #[ORM\Column(nullable: true)] protected ?int $duration = null; public function __construct(Station $station, Interfaces\SongInterface $song) { $this->setSong($song); $this->station = $station; $this->timestamp_cued = time(); $this->timestamp_played = time(); } public function getStation(): Station { return $this->station; } public function getPlaylist(): ?StationPlaylist { return $this->playlist; } public function setPlaylist(StationPlaylist $playlist = null): void { $this->playlist = $playlist; } public function getMedia(): ?StationMedia { return $this->media; } public function setMedia(?StationMedia $media = null): void { $this->media = $media; if (null !== $media) { $this->setDuration($media->getCalculatedLength()); } } public function getRequest(): ?StationRequest { return $this->request; } public function setRequest(?StationRequest $request): void { $this->request = $request; } public function getPlaylistMedia(): ?StationPlaylistMedia { return $this->playlistMedia; } public function setPlaylistMedia(?StationPlaylistMedia $playlistMedia): void { $this->playlistMedia = $playlistMedia; } public function getAutodjCustomUri(): ?string { return $this->autodj_custom_uri; } public function setAutodjCustomUri(?string $autodjCustomUri): void { $this->autodj_custom_uri = $autodjCustomUri; } public function getTimestampCued(): int { return $this->timestamp_cued; } public function setTimestampCued(int $timestampCued): void { $this->timestamp_cued = $timestampCued; } public function getDuration(): ?int { return $this->duration; } public function setDuration(?int $duration): void { $this->duration = $duration; } public function getSentToAutodj(): bool { return $this->sent_to_autodj; } public function setSentToAutodj(bool $newValue = true): void { $this->sent_to_autodj = $newValue; } public function getIsPlayed(): bool { return $this->is_played; } public function setIsPlayed(bool $newValue = true): void { if ($newValue) { $this->sent_to_autodj = true; $this->setTimestampPlayed(time()); } $this->is_played = $newValue; } public function getIsVisible(): bool { return $this->is_visible; } public function setIsVisible(bool $isVisible): void { $this->is_visible = $isVisible; } public function updateVisibility(): void { $this->is_visible = !($this->playlist instanceof StationPlaylist) || !$this->playlist->getIsJingle(); } public function getTimestampPlayed(): int { return $this->timestamp_played; } public function setTimestampPlayed(int $timestampPlayed): void { $this->timestamp_played = $timestampPlayed; } public function __toString(): string { return (null !== $this->media) ? (string)$this->media : (string)(new Song($this)); } public static function fromMedia(Station $station, StationMedia $media): self { $sq = new self($station, $media); $sq->setMedia($media); return $sq; } public static function fromRequest(StationRequest $request): self { $sq = new self($request->getStation(), $request->getTrack()); $sq->setRequest($request); $sq->setMedia($request->getTrack()); return $sq; } } ```
/content/code_sandbox/backend/src/Entity/StationQueue.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,554
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use JsonSerializable; use OpenApi\Attributes as OA; use Stringable; use Symfony\Component\Validator\Constraints as Assert; #[ OA\Schema(type: "object"), ORM\Entity, ORM\Table(name: 'role'), Attributes\Auditable ] class Role implements JsonSerializable, Stringable, IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; #[ OA\Property(example: "Super Administrator"), ORM\Column(length: 100), Assert\NotBlank ] protected string $name; /** @var Collection<int, User> */ #[ORM\ManyToMany(targetEntity: User::class, mappedBy: 'roles')] protected Collection $users; /** @var Collection<int, RolePermission> */ #[ OA\Property(type: "array", items: new OA\Items()), ORM\OneToMany(targetEntity: RolePermission::class, mappedBy: 'role') ] protected Collection $permissions; public function __construct() { $this->users = new ArrayCollection(); $this->permissions = new ArrayCollection(); } public function getName(): string { return $this->name; } public function setName(string $name): void { $this->name = $this->truncateString($name, 100); } /** * @return Collection<int, User> */ public function getUsers(): Collection { return $this->users; } /** * @return Collection<int, RolePermission> */ public function getPermissions(): Collection { return $this->permissions; } /** * @return mixed[] */ public function jsonSerialize(): array { $return = [ 'id' => $this->id, 'name' => $this->name, 'permissions' => [ 'global' => [], 'station' => [], ], ]; foreach ($this->permissions as $permission) { /** @var RolePermission $permission */ $station = $permission->getStation(); if (null !== $station) { $return['permissions']['station'][$station->getIdRequired()][] = $permission->getActionName(); } else { $return['permissions']['global'][] = $permission->getActionName(); } } return $return; } public function __toString(): string { return $this->name; } } ```
/content/code_sandbox/backend/src/Entity/Role.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
571
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use App\Entity\Interfaces\PathAwareInterface; use Doctrine\ORM\Mapping as ORM; #[ ORM\Entity, ORM\Table(name: 'unprocessable_media'), ORM\UniqueConstraint(name: 'path_unique_idx', columns: ['path', 'storage_location_id']) ] class UnprocessableMedia implements PathAwareInterface, IdentifiableEntityInterface { use Traits\HasAutoIncrementId; public const int REPROCESS_THRESHOLD_MINIMUM = 604800; // One week #[ORM\ManyToOne(inversedBy: 'unprocessable_media')] #[ORM\JoinColumn(name: 'storage_location_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected StorageLocation $storage_location; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $storage_location_id; #[ORM\Column(length: 500)] protected string $path; #[ORM\Column(nullable: false)] protected int $mtime = 0; #[ORM\Column(type: 'text', nullable: true)] protected ?string $error = null; public function __construct(StorageLocation $storageLocation, string $path) { $this->storage_location = $storageLocation; $this->setPath($path); } public function getStorageLocation(): StorageLocation { return $this->storage_location; } public function getPath(): string { return $this->path; } public function setPath(string $path): void { $this->path = $path; } public function getMtime(): int { return $this->mtime; } public function setMtime(int $mtime): void { $this->mtime = $mtime; } public function getError(): ?string { return $this->error; } public function setError(?string $error): void { $this->error = $error; } public static function needsReprocessing(int $fileModifiedTime = 0, int $dbModifiedTime = 0): bool { if ($fileModifiedTime > $dbModifiedTime) { return true; } $threshold = $dbModifiedTime + self::REPROCESS_THRESHOLD_MINIMUM + random_int(0, 86400); return time() > $threshold; } } ```
/content/code_sandbox/backend/src/Entity/UnprocessableMedia.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
526
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; #[ ORM\Entity, ORM\Table(name: 'podcast_category'), Attributes\Auditable ] class PodcastCategory implements IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; public const string CATEGORY_SEPARATOR = '|'; #[ORM\ManyToOne(inversedBy: 'categories')] #[ORM\JoinColumn(name: 'podcast_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected Podcast $podcast; #[ORM\Column(length: 255)] #[Assert\NotBlank] protected string $category; public function __construct(Podcast $podcast, string $category) { $this->podcast = $podcast; $this->category = $this->truncateString($category); } public function getPodcast(): Podcast { return $this->podcast; } public function getCategory(): string { return $this->category; } public function getTitle(): string { return (explode(self::CATEGORY_SEPARATOR, $this->category))[0]; } public function getSubTitle(): ?string { return (str_contains($this->category, self::CATEGORY_SEPARATOR)) ? (explode(self::CATEGORY_SEPARATOR, $this->category))[1] : null; } /** * @return mixed[] */ public static function getAvailableCategories(): array { $categories = [ 'Arts' => [ 'Books', 'Design', 'Fashion & Beauty', 'Food', 'Performing Arts', 'Visual Arts', ], 'Business' => [ 'Careers', 'Entrepreneurship', 'Investing', 'Management', 'Marketing', 'Non-Profit', ], 'Comedy' => [ 'Comedy Interviews', 'Improv', 'Stand-Up', ], 'Education' => [ 'Courses', 'How To', 'Language Learning', 'Self-Improvement', ], 'Fiction' => [ 'Comedy Fiction', 'Drama', 'Science Fiction', ], 'Government' => [ '', ], 'History' => [ '', ], 'Health & Fitness' => [ 'Alternative Health', 'Fitness', 'Medicine', 'Mental Health', 'Nutrition', 'Sexuality', ], 'Kids & Family' => [ 'Parenting', 'Pets & Animals', 'Stories for Kids', ], 'Leisure' => [ 'Animation & Manga', 'Automotive', 'Aviation', 'Crafts', 'Games', 'Hobbies', 'Home & Garden', 'Video Games', ], 'Music' => [ 'Music Commentary', 'Music History', 'Music Interviews', ], 'News' => [ 'Business News', 'Daily News', 'Entertainment News', 'News Commentary', 'Politics', 'Sports News', 'Tech News', ], 'Religion & Spirituality' => [ 'Buddhism', 'Christianity', 'Hinduism', 'Islam', 'Judaism', 'Religion', 'Spirituality', ], 'Science' => [ 'Astronomy', 'Chemistry', 'Earth Sciences', 'Life Sciences', 'Mathematics', 'Natural Sciences', 'Nature', 'Physics', 'Social Sciences', ], 'Society & Culture' => [ 'Documentary', 'Personal Journals', 'Philosophy', 'Places & Travel', 'Relationships', ], 'Sports' => [ 'Baseball', 'Basketball', 'Cricket', 'Fantasy Sports', 'Football', 'Golf', 'Hockey', 'Rugby', 'Running', 'Soccer', 'Swimming', 'Tennis', 'Volleyball', 'Wilderness', 'Wrestling', ], 'Technology' => [ '', ], 'True Crime' => [ '', ], 'TV & Film' => [ 'After Shows', 'Film History', 'Film Interviews', 'Film Reviews', 'TV Reviews', ], ]; $categorySelect = []; foreach ($categories as $categoryName => $subTitles) { foreach ($subTitles as $subTitle) { if ('' === $subTitle) { $categorySelect[$categoryName] = $categoryName; } else { $selectKey = $categoryName . self::CATEGORY_SEPARATOR . $subTitle; $categorySelect[$selectKey] = $categoryName . ' > ' . $subTitle; } } } return $categorySelect; } } ```
/content/code_sandbox/backend/src/Entity/PodcastCategory.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,106
```php <?php declare(strict_types=1); namespace App\Entity; use App\Doctrine\Generator\UuidV6Generator; use App\Entity\Enums\AnalyticsLevel; use App\Entity\Enums\IpSources; use App\Enums\SupportedThemes; use App\OpenApi; use App\Service\Avatar; use App\Utilities\Types; use App\Utilities\Urls; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UriInterface; use RuntimeException; use Stringable; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; #[ OA\Schema(schema: "Settings", type: "object"), ORM\Entity, ORM\Table(name: 'settings'), Attributes\Auditable ] class Settings implements Stringable { use Traits\TruncateStrings; use Traits\TruncateInts; // Sorting groups for settings, as used in Symfony serialization. public const string GROUP_GENERAL = 'general'; public const string GROUP_BRANDING = 'branding'; public const string GROUP_BACKUP = 'backup'; public const string GROUP_GEO_IP = 'geo_ip'; public const array VALID_GROUPS = [ self::GROUP_GENERAL, self::GROUP_BRANDING, self::GROUP_BACKUP, self::GROUP_GEO_IP, ]; #[ OA\Property, ORM\Column(type: 'guid', unique: true), ORM\Id, ORM\GeneratedValue(strategy: 'CUSTOM'), ORM\CustomIdGenerator(UuidV6Generator::class) ] protected string $app_unique_identifier; public function getAppUniqueIdentifier(): string { if (!isset($this->app_unique_identifier)) { throw new RuntimeException('Application Unique ID not generated yet.'); } return $this->app_unique_identifier; } #[ OA\Property(description: "Site Base URL", example: "path_to_url"), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $base_url = ''; public function getBaseUrl(): ?string { return $this->base_url; } public function getBaseUrlAsUri(): ?UriInterface { return Urls::tryParseUserUrl( $this->base_url, 'System Base URL', ); } public function setBaseUrl(?string $baseUrl): void { if (empty($baseUrl)) { $this->base_url = null; return; } // Filter the base URL to avoid trailing slashes and other problems. $baseUri = Urls::parseUserUrl( $baseUrl, 'System Base URL' ); $this->base_url = $this->truncateNullableString((string)$baseUri); } #[ OA\Property(description: "AzuraCast Instance Name", example: "My AzuraCast Instance"), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $instance_name = null; public function getInstanceName(): ?string { return $this->instance_name; } public function setInstanceName(?string $instanceName): void { $this->instance_name = $this->truncateNullableString($instanceName); } #[ OA\Property(description: "Prefer Browser URL (If Available)", example: "false"), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $prefer_browser_url = true; public function getPreferBrowserUrl(): bool { return $this->prefer_browser_url; } public function setPreferBrowserUrl(bool $preferBrowserUrl): void { $this->prefer_browser_url = $preferBrowserUrl; } #[ OA\Property(description: "Use Web Proxy for Radio", example: "false"), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $use_radio_proxy = true; public function getUseRadioProxy(): bool { return $this->use_radio_proxy; } public function setUseRadioProxy(bool $useRadioProxy): void { $this->use_radio_proxy = $useRadioProxy; } #[ OA\Property(description: "Days of Playback History to Keep"), ORM\Column(type: 'smallint'), Assert\Choice([0, 14, 30, 60, 365, 730]), Groups(self::GROUP_GENERAL) ] protected int $history_keep_days = SongHistory::DEFAULT_DAYS_TO_KEEP; public function getHistoryKeepDays(): int { return $this->history_keep_days; } public function setHistoryKeepDays(int $historyKeepDays): void { $this->history_keep_days = $this->truncateSmallInt($historyKeepDays); } #[ OA\Property(description: "Always Use HTTPS", example: "false"), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $always_use_ssl = false; public function getAlwaysUseSsl(): bool { return $this->always_use_ssl; } public function setAlwaysUseSsl(bool $alwaysUseSsl): void { $this->always_use_ssl = $alwaysUseSsl; } #[ OA\Property(description: "API 'Access-Control-Allow-Origin' header", example: "*"), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $api_access_control = ''; public function getApiAccessControl(): string { return $this->api_access_control ?? ''; } public function setApiAccessControl(?string $apiAccessControl): void { $this->api_access_control = $this->truncateNullableString($apiAccessControl); } #[ OA\Property( description: "Whether to use high-performance static JSON for Now Playing data updates.", example: "false" ), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $enable_static_nowplaying = false; public function getEnableStaticNowPlaying(): bool { return $this->enable_static_nowplaying; } public function setEnableStaticNowPlaying(bool $enableStaticNowplaying): void { $this->enable_static_nowplaying = $enableStaticNowplaying; } #[ OA\Property(description: "Listener Analytics Collection"), ORM\Column(type: 'string', length: 50, nullable: true, enumType: AnalyticsLevel::class), Groups(self::GROUP_GENERAL) ] protected ?AnalyticsLevel $analytics = null; public function getAnalytics(): AnalyticsLevel { return $this->analytics ?? AnalyticsLevel::default(); } public function isAnalyticsEnabled(): bool { return AnalyticsLevel::None !== $this->getAnalytics(); } public function setAnalytics(?AnalyticsLevel $analytics): void { $this->analytics = $analytics; } #[ OA\Property(description: "Check for Updates and Announcements", example: "true"), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $check_for_updates = true; public function getCheckForUpdates(): bool { return $this->check_for_updates; } public function setCheckForUpdates(bool $checkForUpdates): void { $this->check_for_updates = $checkForUpdates; } /** * @var mixed[]|null */ #[ OA\Property(description: "Results of the latest update check.", example: ""), ORM\Column(type: 'json', nullable: true), Attributes\AuditIgnore ] protected ?array $update_results = null; /** * @return mixed[]|null */ public function getUpdateResults(): ?array { return $this->update_results; } public function setUpdateResults(?array $updateResults): void { $this->update_results = $updateResults; } #[ OA\Property( description: "The UNIX timestamp when updates were last checked.", example: OpenApi::SAMPLE_TIMESTAMP ), ORM\Column, Attributes\AuditIgnore ] protected int $update_last_run = 0; public function getUpdateLastRun(): int { return $this->update_last_run; } public function setUpdateLastRun(int $updateLastRun): void { $this->update_last_run = $updateLastRun; } public function updateUpdateLastRun(): void { $this->setUpdateLastRun(time()); } #[ OA\Property(description: "Base Theme for Public Pages", example: "light"), ORM\Column(type: 'string', length: 50, nullable: true, enumType: SupportedThemes::class), Groups(self::GROUP_BRANDING) ] protected ?SupportedThemes $public_theme = null; public function getPublicTheme(): ?SupportedThemes { return $this->public_theme; } public function setPublicTheme(?SupportedThemes $publicTheme): void { $this->public_theme = $publicTheme; } #[ OA\Property(description: "Hide Album Art on Public Pages", example: "false"), ORM\Column, Groups(self::GROUP_BRANDING) ] protected bool $hide_album_art = false; public function getHideAlbumArt(): bool { return $this->hide_album_art; } public function setHideAlbumArt(bool $hideAlbumArt): void { $this->hide_album_art = $hideAlbumArt; } #[ OA\Property(description: "Homepage Redirect URL", example: "path_to_url"), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_BRANDING) ] protected ?string $homepage_redirect_url = null; public function getHomepageRedirectUrl(): ?string { return Types::stringOrNull($this->homepage_redirect_url, true); } public function setHomepageRedirectUrl(?string $homepageRedirectUrl): void { $this->homepage_redirect_url = $this->truncateNullableString( Types::stringOrNull($homepageRedirectUrl) ); } #[ OA\Property(description: "Default Album Art URL", example: "path_to_url"), ORM\Column(nullable: true), Groups(self::GROUP_BRANDING) ] protected ?string $default_album_art_url = null; public function getDefaultAlbumArtUrl(): ?string { return Types::stringOrNull($this->default_album_art_url); } public function getDefaultAlbumArtUrlAsUri(): ?UriInterface { return Urls::tryParseUserUrl( $this->getDefaultAlbumArtUrl(), 'Default Album Art URL', false ); } public function setDefaultAlbumArtUrl(?string $defaultAlbumArtUrl): void { $this->default_album_art_url = $this->truncateNullableString( Types::stringOrNull($defaultAlbumArtUrl) ); } #[ OA\Property( description: "Attempt to fetch album art from external sources when processing media.", example: "false" ), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $use_external_album_art_when_processing_media = false; public function getUseExternalAlbumArtWhenProcessingMedia(): bool { return $this->use_external_album_art_when_processing_media; } public function setUseExternalAlbumArtWhenProcessingMedia(bool $useExternalAlbumArtWhenProcessingMedia): void { $this->use_external_album_art_when_processing_media = $useExternalAlbumArtWhenProcessingMedia; } #[ OA\Property( description: "Attempt to fetch album art from external sources in API requests.", example: "false" ), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $use_external_album_art_in_apis = false; public function getUseExternalAlbumArtInApis(): bool { return $this->use_external_album_art_in_apis; } public function setUseExternalAlbumArtInApis(bool $useExternalAlbumArtInApis): void { $this->use_external_album_art_in_apis = $useExternalAlbumArtInApis; } #[ OA\Property( description: "An API key to connect to Last.fm services, if provided.", example: "SAMPLE-API-KEY" ), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $last_fm_api_key = null; public function getLastFmApiKey(): ?string { return Types::stringOrNull($this->last_fm_api_key, true); } public function setLastFmApiKey(?string $lastFmApiKey): void { $this->last_fm_api_key = $this->truncateNullableString( Types::stringOrNull($lastFmApiKey, true) ); } #[ OA\Property(description: "Hide AzuraCast Branding on Public Pages", example: "false"), ORM\Column, Groups(self::GROUP_BRANDING) ] protected bool $hide_product_name = false; public function getHideProductName(): bool { return $this->hide_product_name; } public function setHideProductName(bool $hideProductName): void { $this->hide_product_name = $hideProductName; } #[ OA\Property(description: "Custom CSS for Public Pages", example: ""), ORM\Column(type: 'text', nullable: true), Groups(self::GROUP_BRANDING) ] protected ?string $public_custom_css = null; public function getPublicCustomCss(): ?string { return Types::stringOrNull($this->public_custom_css, true); } public function setPublicCustomCss(?string $publicCustomCss): void { $this->public_custom_css = Types::stringOrNull($publicCustomCss, true); } #[ OA\Property(description: "Custom JS for Public Pages", example: ""), ORM\Column(type: 'text', nullable: true), Groups(self::GROUP_BRANDING) ] protected ?string $public_custom_js = null; public function getPublicCustomJs(): ?string { return Types::stringOrNull($this->public_custom_js, true); } public function setPublicCustomJs(?string $publicCustomJs): void { $this->public_custom_js = Types::stringOrNull($publicCustomJs, true); } #[ OA\Property(description: "Custom CSS for Internal Pages", example: ""), ORM\Column(type: 'text', nullable: true), Groups(self::GROUP_BRANDING) ] protected ?string $internal_custom_css = null; public function getInternalCustomCss(): ?string { return Types::stringOrNull($this->internal_custom_css, true); } public function setInternalCustomCss(?string $internalCustomCss): void { $this->internal_custom_css = Types::stringOrNull($internalCustomCss, true); } #[ OA\Property(description: "Whether backup is enabled.", example: "false"), ORM\Column, Groups(self::GROUP_BACKUP) ] protected bool $backup_enabled = false; public function getBackupEnabled(): bool { return $this->backup_enabled; } public function setBackupEnabled(bool $backupEnabled): void { $this->backup_enabled = $backupEnabled; } #[ OA\Property( description: "The timecode (i.e. 400 for 4:00AM) when automated backups should run.", example: 400 ), ORM\Column(length: 4, nullable: true), Groups(self::GROUP_BACKUP) ] protected ?string $backup_time_code = null; public function getBackupTimeCode(): ?string { return Types::stringOrNull($this->backup_time_code, true); } public function setBackupTimeCode(?string $backupTimeCode): void { $this->backup_time_code = Types::stringOrNull($backupTimeCode, true); } #[ OA\Property(description: "Whether to exclude media in automated backups.", example: "false"), ORM\Column, Groups(self::GROUP_BACKUP) ] protected bool $backup_exclude_media = false; public function getBackupExcludeMedia(): bool { return $this->backup_exclude_media; } public function setBackupExcludeMedia(bool $backupExcludeMedia): void { $this->backup_exclude_media = $backupExcludeMedia; } #[ OA\Property(description: "Number of backups to keep, or infinite if zero/null.", example: 2), ORM\Column(type: 'smallint'), Groups(self::GROUP_BACKUP) ] protected int $backup_keep_copies = 0; public function getBackupKeepCopies(): int { return $this->backup_keep_copies; } public function setBackupKeepCopies(int $backupKeepCopies): void { $this->backup_keep_copies = $this->truncateSmallInt($backupKeepCopies); } #[ OA\Property(description: "The storage location ID for automated backups.", example: 1), ORM\Column(nullable: true), Groups(self::GROUP_BACKUP) ] protected ?int $backup_storage_location = null; public function getBackupStorageLocation(): ?int { return $this->backup_storage_location; } public function setBackupStorageLocation(?int $backupStorageLocation): void { $this->backup_storage_location = $backupStorageLocation; } #[ OA\Property(description: "The output format for the automated backup.", example: 'zip'), ORM\Column(nullable: true), Groups(self::GROUP_BACKUP) ] protected ?string $backup_format = null; public function getBackupFormat(): ?string { return Types::stringOrNull($this->backup_format, true); } public function setBackupFormat(?string $backupFormat): void { $this->backup_format = Types::stringOrNull($backupFormat, true); } #[ OA\Property( description: "The UNIX timestamp when automated backup was last run.", example: OpenApi::SAMPLE_TIMESTAMP ), ORM\Column, Attributes\AuditIgnore, Groups(self::GROUP_BACKUP) ] protected int $backup_last_run = 0; public function getBackupLastRun(): int { return $this->backup_last_run; } public function setBackupLastRun(int $backupLastRun): void { $this->backup_last_run = $backupLastRun; } public function updateBackupLastRun(): void { $this->setBackupLastRun(time()); } #[ OA\Property(description: "The output of the latest automated backup task.", example: ""), ORM\Column(type: 'text', nullable: true), Attributes\AuditIgnore, Groups(self::GROUP_BACKUP) ] protected ?string $backup_last_output = null; public function getBackupLastOutput(): ?string { return $this->backup_last_output; } public function setBackupLastOutput(?string $backupLastOutput): void { $this->backup_last_output = $backupLastOutput; } #[ OA\Property( description: "The UNIX timestamp when setup was last completed.", example: OpenApi::SAMPLE_TIMESTAMP ), ORM\Column ] protected int $setup_complete_time = 0; public function getSetupCompleteTime(): int { return $this->setup_complete_time; } public function isSetupComplete(): bool { return (0 !== $this->setup_complete_time); } public function setSetupCompleteTime(int $setupCompleteTime): void { $this->setup_complete_time = $setupCompleteTime; } public function updateSetupComplete(): void { $this->setSetupCompleteTime(time()); } #[ OA\Property(description: "Temporarily disable all sync tasks.", example: "false"), ORM\Column, Attributes\AuditIgnore ] protected bool $sync_disabled = false; public function getSyncDisabled(): bool { return $this->sync_disabled; } public function setSyncDisabled(bool $syncDisabled): void { $this->sync_disabled = $syncDisabled; } #[ OA\Property( description: "The last run timestamp for the unified sync task.", example: OpenApi::SAMPLE_TIMESTAMP ), ORM\Column, Attributes\AuditIgnore ] protected int $sync_last_run = 0; public function updateSyncLastRun(): void { $this->sync_last_run = time(); } public function getSyncLastRun(): int { return $this->sync_last_run; } #[ OA\Property(description: "This installation's external IP.", example: "192.168.1.1"), ORM\Column(length: 45, nullable: true), Attributes\AuditIgnore ] protected ?string $external_ip = null; public function getExternalIp(): ?string { return $this->external_ip; } public function setExternalIp(?string $externalIp): void { $this->external_ip = $externalIp; } #[ OA\Property(description: "The license key for the Maxmind Geolite download.", example: ""), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GEO_IP) ] protected ?string $geolite_license_key = null; { return (null === $this->geolite_license_key) ? null : trim($this->geolite_license_key); } { } #[ OA\Property( description: "The UNIX timestamp when the Maxmind Geolite was last downloaded.", example: OpenApi::SAMPLE_TIMESTAMP ), ORM\Column, Attributes\AuditIgnore, Groups(self::GROUP_GEO_IP) ] protected int $geolite_last_run = 0; public function getGeoliteLastRun(): int { return $this->geolite_last_run; } public function setGeoliteLastRun(int $geoliteLastRun): void { $this->geolite_last_run = $geoliteLastRun; } public function updateGeoliteLastRun(): void { $this->setGeoliteLastRun(time()); } #[ OA\Property( description: "Whether to enable 'advanced' functionality in the system that is intended for power users.", example: false ), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $enable_advanced_features = false; public function getEnableAdvancedFeatures(): bool { return $this->enable_advanced_features; } public function setEnableAdvancedFeatures(bool $enableAdvancedFeatures): void { $this->enable_advanced_features = $enableAdvancedFeatures; } #[ OA\Property(description: "Enable e-mail delivery across the application.", example: "true"), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $mail_enabled = false; public function getMailEnabled(): bool { return $this->mail_enabled; } public function setMailEnabled(bool $mailEnabled): void { $this->mail_enabled = $mailEnabled; } #[ OA\Property(description: "The name of the sender of system e-mails.", example: "AzuraCast"), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $mail_sender_name = ''; public function getMailSenderName(): string { return $this->mail_sender_name ?? ''; } public function setMailSenderName(?string $mailSenderName): void { $this->mail_sender_name = $mailSenderName; } #[ OA\Property( description: "The e-mail address of the sender of system e-mails.", example: "example@example.com" ), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $mail_sender_email = ''; public function getMailSenderEmail(): string { return $this->mail_sender_email ?? ''; } public function setMailSenderEmail(?string $mailSenderEmail): void { $this->mail_sender_email = $mailSenderEmail; } #[ OA\Property(description: "The host to send outbound SMTP mail.", example: "smtp.example.com"), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $mail_smtp_host = ''; public function getMailSmtpHost(): string { return $this->mail_smtp_host ?? ''; } public function setMailSmtpHost(?string $mailSmtpHost): void { $this->mail_smtp_host = $mailSmtpHost; } #[ OA\Property(description: "The port for sending outbound SMTP mail.", example: 465), ORM\Column(type: 'smallint'), Groups(self::GROUP_GENERAL) ] protected int $mail_smtp_port = 0; public function getMailSmtpPort(): int { return $this->mail_smtp_port; } public function setMailSmtpPort(int $mailSmtpPort): void { $this->mail_smtp_port = $this->truncateSmallInt($mailSmtpPort); } #[ OA\Property(description: "The username when connecting to SMTP mail.", example: "username"), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $mail_smtp_username = ''; public function getMailSmtpUsername(): string { return $this->mail_smtp_username ?? ''; } public function setMailSmtpUsername(?string $mailSmtpUsername): void { $this->mail_smtp_username = $this->truncateNullableString($mailSmtpUsername); } #[ OA\Property(description: "The password when connecting to SMTP mail.", example: "password"), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $mail_smtp_password = ''; public function getMailSmtpPassword(): string { return $this->mail_smtp_password ?? ''; } public function setMailSmtpPassword(?string $mailSmtpPassword): void { $this->mail_smtp_password = $mailSmtpPassword; } #[ OA\Property(description: "Whether to use a secure (TLS) connection when sending SMTP mail.", example: "true"), ORM\Column, Groups(self::GROUP_GENERAL) ] protected bool $mail_smtp_secure = true; public function getMailSmtpSecure(): bool { return $this->mail_smtp_secure; } public function setMailSmtpSecure(bool $mailSmtpSecure): void { $this->mail_smtp_secure = $mailSmtpSecure; } #[ OA\Property(description: "The external avatar service to use when fetching avatars.", example: "libravatar"), ORM\Column(length: 25, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $avatar_service = null; public function getAvatarService(): string { return $this->avatar_service ?? Avatar::DEFAULT_SERVICE; } public function setAvatarService(?string $avatarService): void { $this->avatar_service = $this->truncateNullableString($avatarService, 25); } #[ OA\Property(description: "The default avatar URL.", example: ""), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $avatar_default_url = null; public function getAvatarDefaultUrl(): string { return $this->avatar_default_url ?? Avatar::DEFAULT_AVATAR; } public function setAvatarDefaultUrl(?string $avatarDefaultUrl): void { $this->avatar_default_url = $avatarDefaultUrl; } #[ OA\Property(description: "ACME (LetsEncrypt) e-mail address.", example: ""), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $acme_email = null; public function getAcmeEmail(): ?string { return $this->acme_email; } public function setAcmeEmail(?string $acmeEmail): void { $this->acme_email = $acmeEmail; } #[ OA\Property(description: "ACME (LetsEncrypt) domain name(s).", example: ""), ORM\Column(length: 255, nullable: true), Groups(self::GROUP_GENERAL) ] protected ?string $acme_domains = null; public function getAcmeDomains(): ?string { return Types::stringOrNull($this->acme_domains, true); } public function setAcmeDomains(?string $acmeDomains): void { $acmeDomains = Types::stringOrNull($acmeDomains, true); if (null !== $acmeDomains) { $acmeDomains = implode( ', ', array_map( static function ($str) { $str = trim($str); $str = trim($str, '/'); $str = str_replace(['path_to_url 'path_to_url '', $str); return $str; }, explode(',', $acmeDomains) ) ); } $this->acme_domains = $acmeDomains; } #[ OA\Property(description: "IP Address Source"), ORM\Column(type: 'string', length: 50, nullable: true, enumType: IpSources::class), Groups(self::GROUP_GENERAL) ] protected ?IpSources $ip_source = null; public function getIpSource(): IpSources { return $this->ip_source ?? IpSources::default(); } public function getIp(ServerRequestInterface $request): string { return $this->getIpSource()->getIp($request); } public function setIpSource(?IpSources $ipSource): void { $this->ip_source = $ipSource; } public function __toString(): string { return 'Settings'; } } ```
/content/code_sandbox/backend/src/Entity/Settings.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
6,744
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Enums\AnalyticsIntervals; use App\Entity\Interfaces\IdentifiableEntityInterface; use Carbon\CarbonImmutable; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Doctrine\ORM\Mapping as ORM; use RuntimeException; #[ ORM\Entity(readOnly: true), ORM\Table(name: 'analytics'), ORM\Index(name: 'search_idx', columns: ['type', 'moment']), ORM\UniqueConstraint(name: 'stats_unique_idx', columns: ['station_id', 'type', 'moment']) ] class Analytics implements IdentifiableEntityInterface { use Traits\HasAutoIncrementId; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?Station $station = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $station_id = null; #[ORM\Column(type: 'string', length: 15, enumType: AnalyticsIntervals::class)] protected AnalyticsIntervals $type; #[ORM\Column(type: 'datetime_immutable')] protected DateTimeImmutable $moment; #[ORM\Column] protected int $number_min; #[ORM\Column] protected int $number_max; #[ORM\Column(type: 'decimal', precision: 10, scale: 2)] protected string $number_avg; #[ORM\Column(nullable: true)] protected ?int $number_unique = null; public function __construct( DateTimeInterface $moment, ?Station $station = null, AnalyticsIntervals $type = AnalyticsIntervals::Daily, int $numberMin = 0, int $numberMax = 0, float $numberAvg = 0, ?int $numberUnique = null ) { $utc = new DateTimeZone('UTC'); $this->moment = CarbonImmutable::parse($moment, $utc)->shiftTimezone($utc); $this->station = $station; $this->type = $type; $this->number_min = $numberMin; $this->number_max = $numberMax; $this->number_avg = (string)round($numberAvg, 2); $this->number_unique = $numberUnique; } public function getStation(): ?Station { return $this->station; } public function getType(): AnalyticsIntervals { return $this->type; } public function getMoment(): CarbonImmutable { return CarbonImmutable::instance($this->moment); } public function getMomentInStationTimeZone(): CarbonImmutable { if (null === $this->station) { throw new RuntimeException('Cannot get moment in station timezone; no station associated.'); } $tz = $this->station->getTimezoneObject(); return CarbonImmutable::instance($this->moment)->shiftTimezone($tz); } public function getNumberMin(): int { return $this->number_min; } public function getNumberMax(): int { return $this->number_max; } public function getNumberAvg(): float { return round((float)$this->number_avg, 2); } public function getNumberUnique(): ?int { return $this->number_unique; } } ```
/content/code_sandbox/backend/src/Entity/Analytics.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
731
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\EntityGroupsInterface; use App\Entity\Interfaces\IdentifiableEntityInterface; use App\Entity\Traits\TruncateStrings; use App\Security\WebAuthnPasskey; use Doctrine\ORM\Mapping as ORM; use InvalidArgumentException; use Symfony\Component\Serializer\Annotation\Groups; #[ ORM\Entity(readOnly: true), ORM\Table(name: 'user_passkeys') ] class UserPasskey implements IdentifiableEntityInterface { use TruncateStrings; #[ORM\Column(length: 64)] #[ORM\Id] #[Groups([ EntityGroupsInterface::GROUP_ID, EntityGroupsInterface::GROUP_ALL, ])] protected string $id; #[ORM\ManyToOne(fetch: 'EAGER', inversedBy: 'passkeys')] #[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected User $user; #[ORM\Column] #[Groups([ EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL, ])] protected int $created_at; #[ORM\Column(length: 255)] #[Groups([ EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL, ])] protected string $name; #[ORM\Column(type: 'text')] protected string $full_id; #[ORM\Column(type: 'text')] protected string $public_key_pem; public function __construct(User $user, string $name, WebAuthnPasskey $passkey) { $this->user = $user; $this->name = $this->truncateString($name); $this->id = $passkey->getHashedId(); $this->full_id = base64_encode($passkey->getId()); $this->public_key_pem = $passkey->getPublicKeyPem(); $this->created_at = time(); } public function getId(): string { return $this->id; } public function getIdRequired(): int|string { return $this->id; } public function getUser(): User { return $this->user; } public function getCreatedAt(): int { return $this->created_at; } public function getName(): string { return $this->name; } public function getPasskey(): WebAuthnPasskey { return new WebAuthnPasskey( base64_decode($this->full_id), $this->public_key_pem ); } public function verifyFullId(string $fullId): void { if (!hash_equals($this->getPasskey()->getId(), $fullId)) { throw new InvalidArgumentException('Full ID does not match passkey.'); } } } ```
/content/code_sandbox/backend/src/Entity/UserPasskey.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
609
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\SongInterface; use App\Utilities\Types; use Doctrine\ORM\Mapping as ORM; #[ ORM\Entity, ORM\Table(name: 'song_history'), ORM\Index(name: 'idx_is_visible', columns: ['is_visible']), ORM\Index(name: 'idx_timestamp_start', columns: ['timestamp_start']), ORM\Index(name: 'idx_timestamp_end', columns: ['timestamp_end']) ] class SongHistory implements Interfaces\SongInterface, Interfaces\IdentifiableEntityInterface, Interfaces\StationAwareInterface { use Traits\HasAutoIncrementId; use Traits\TruncateInts; use Traits\HasSongFields; /** @var int The expected delay between when a song history record is registered and when listeners hear it. */ public const int PLAYBACK_DELAY_SECONDS = 5; /** @var int */ public const int DEFAULT_DAYS_TO_KEEP = 60; #[ORM\ManyToOne(inversedBy: 'history')] #[ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected Station $station; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $station_id; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'playlist_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')] protected ?StationPlaylist $playlist = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $playlist_id = null; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'streamer_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')] protected ?StationStreamer $streamer = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $streamer_id = null; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'media_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')] protected ?StationMedia $media = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $media_id = null; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'request_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')] protected ?StationRequest $request = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $request_id = null; #[ORM\Column] protected int $timestamp_start = 0; #[ORM\Column(nullable: true)] protected ?int $duration = null; #[ORM\Column(nullable: true)] protected ?int $listeners_start = null; #[ORM\Column] protected int $timestamp_end = 0; #[ORM\Column(nullable: true)] protected ?int $listeners_end = 0; #[ORM\Column(nullable: true)] protected ?int $unique_listeners = 0; #[ORM\Column] protected int $delta_total = 0; #[ORM\Column] protected int $delta_positive = 0; #[ORM\Column] protected int $delta_negative = 0; #[ORM\Column(type: 'json', nullable: true)] protected mixed $delta_points = null; #[ORM\Column] protected bool $is_visible = true; public function __construct( Station $station, SongInterface $song ) { $this->setSong($song); $this->station = $station; } public function getStation(): Station { return $this->station; } public function getPlaylist(): ?StationPlaylist { return $this->playlist; } public function setPlaylist(StationPlaylist $playlist = null): void { $this->playlist = $playlist; } public function getStreamer(): ?StationStreamer { return $this->streamer; } public function setStreamer(?StationStreamer $streamer): void { $this->streamer = $streamer; } public function getMedia(): ?StationMedia { return $this->media; } public function setMedia(?StationMedia $media = null): void { $this->media = $media; if (null !== $media) { $this->setDuration($media->getCalculatedLength()); } } public function getRequest(): ?StationRequest { return $this->request; } public function setRequest(?StationRequest $request): void { $this->request = $request; } public function getTimestampStart(): int { return $this->timestamp_start; } public function setTimestampStart(int $timestampStart): void { $this->timestamp_start = $timestampStart; } public function getDuration(): ?int { return $this->duration; } public function setDuration(?int $duration): void { $this->duration = $duration; } public function getListenersStart(): ?int { return $this->listeners_start; } public function setListenersStart(?int $listenersStart): void { $this->listeners_start = $listenersStart; } public function getTimestampEnd(): int { return $this->timestamp_end; } public function setTimestampEnd(int $timestampEnd): void { $this->timestamp_end = $timestampEnd; if (!$this->duration) { $this->duration = $timestampEnd - $this->timestamp_start; } } public function getTimestamp(): int { return $this->timestamp_start; } public function getListenersEnd(): ?int { return $this->listeners_end; } public function setListenersEnd(?int $listenersEnd): void { $this->listeners_end = $listenersEnd; } public function getUniqueListeners(): ?int { return $this->unique_listeners; } public function setUniqueListeners(?int $uniqueListeners): void { $this->unique_listeners = $uniqueListeners; } public function getListeners(): int { return (int)$this->listeners_start; } public function getDeltaTotal(): int { return $this->delta_total; } public function setDeltaTotal(int $deltaTotal): void { $this->delta_total = $this->truncateSmallInt($deltaTotal); } public function getDeltaPositive(): int { return $this->delta_positive; } public function setDeltaPositive(int $deltaPositive): void { $this->delta_positive = $this->truncateSmallInt($deltaPositive); } public function getDeltaNegative(): int { return $this->delta_negative; } public function setDeltaNegative(int $deltaNegative): void { $this->delta_negative = $this->truncateSmallInt($deltaNegative); } /** * @return int[] */ public function getDeltaPoints(): array { return Types::array($this->delta_points); } public function addDeltaPoint(int $deltaPoint): void { $deltaPoints = $this->getDeltaPoints(); if (0 === count($deltaPoints)) { $this->setListenersStart($deltaPoint); } $deltaPoints[] = $deltaPoint; $this->delta_points = $deltaPoints; } public function setListenersFromLastSong(?SongHistory $lastSong): void { if (null === $lastSong) { $this->addDeltaPoint(0); return; } $deltaPoints = $lastSong->getDeltaPoints(); $lastDeltaPoint = array_pop($deltaPoints); if (null !== $lastDeltaPoint) { $this->addDeltaPoint($lastDeltaPoint); } } public function getIsVisible(): bool { return $this->is_visible; } public function setIsVisible(bool $isVisible): void { $this->is_visible = $isVisible; } public function updateVisibility(): void { $this->is_visible = !($this->playlist instanceof StationPlaylist) || !$this->playlist->getIsJingle(); } /** * @return bool Whether the record should be shown in APIs (i.e. is not a jingle) */ public function showInApis(): bool { if ($this->playlist instanceof StationPlaylist) { return !$this->playlist->getIsJingle(); } return true; } public function playbackEnded(): void { $this->setTimestampEnd(time()); $deltaPoints = (array)$this->getDeltaPoints(); if (0 !== count($deltaPoints)) { $this->setListenersEnd(end($deltaPoints)); reset($deltaPoints); $deltaPositive = 0; $deltaNegative = 0; $deltaTotal = 0; $previousDelta = null; foreach ($deltaPoints as $currentDelta) { if (null !== $previousDelta) { $deltaDelta = $currentDelta - $previousDelta; $deltaTotal += $deltaDelta; if ($deltaDelta > 0) { $deltaPositive += $deltaDelta; } elseif ($deltaDelta < 0) { $deltaNegative += (int)abs($deltaDelta); } } $previousDelta = $currentDelta; } $this->setDeltaPositive((int)$deltaPositive); $this->setDeltaNegative((int)$deltaNegative); $this->setDeltaTotal((int)$deltaTotal); } else { $this->setListenersEnd(0); $this->setDeltaPositive(0); $this->setDeltaNegative(0); $this->setDeltaTotal(0); } } public function __toString(): string { if ($this->media instanceof StationMedia) { return (string)$this->media; } return (string)(new Song($this)); } public static function fromQueue(StationQueue $queue): self { $sh = new self($queue->getStation(), $queue); $sh->setMedia($queue->getMedia()); $sh->setRequest($queue->getRequest()); $sh->setPlaylist($queue->getPlaylist()); $sh->setDuration($queue->getDuration()); $sh->updateVisibility(); return $sh; } } ```
/content/code_sandbox/backend/src/Entity/SongHistory.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,330
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use App\Entity\Interfaces\PathAwareInterface; use App\Entity\Interfaces\ProcessableMediaInterface; use App\Entity\Interfaces\SongInterface; use App\Flysystem\StationFilesystems; use App\Media\Metadata; use App\Media\MetadataInterface; use App\Utilities\Types; use Azura\Normalizer\Attributes\DeepNormalize; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Serializer\Annotation as Serializer; #[ ORM\Entity, ORM\Table(name: 'station_media'), ORM\Index(name: 'search_idx', columns: ['title', 'artist', 'album']), ORM\UniqueConstraint(name: 'path_unique_idx', columns: ['path', 'storage_location_id']) ] class StationMedia implements SongInterface, ProcessableMediaInterface, PathAwareInterface, IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\HasSongFields; public const int UNIQUE_ID_LENGTH = 24; #[ ORM\ManyToOne(inversedBy: 'media'), ORM\JoinColumn(name: 'storage_location_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE') ] protected StorageLocation $storage_location; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $storage_location_id; #[ORM\Column(length: 25, nullable: false)] protected string $unique_id; #[ORM\Column(length: 200, nullable: true)] protected ?string $album = null; #[ORM\Column(length: 255, nullable: true)] protected ?string $genre = null; #[ORM\Column(type: 'text', nullable: true)] protected ?string $lyrics = null; #[ORM\Column(length: 15, nullable: true)] protected ?string $isrc = null; #[ORM\Column(type: 'decimal', precision: 7, scale: 2, nullable: false)] protected string $length = '0.00'; #[ORM\Column(length: 500)] protected string $path; #[ORM\Column(nullable: false)] protected int $mtime; #[ORM\Column(nullable: false)] protected int $uploaded_at; #[ORM\Column] protected int $art_updated_at = 0; #[ORM\Column(type: 'json', nullable: true)] protected ?array $extra_metadata = null; /** @var Collection<int, StationPlaylistMedia> */ #[ ORM\OneToMany(targetEntity: StationPlaylistMedia::class, mappedBy: 'media'), DeepNormalize(true), Serializer\MaxDepth(1) ] protected Collection $playlists; /** @var Collection<int, StationMediaCustomField> */ #[ORM\OneToMany(targetEntity: StationMediaCustomField::class, mappedBy: 'media')] protected Collection $custom_fields; /** @var Collection<int, PodcastEpisode> */ #[ORM\OneToMany(targetEntity: PodcastEpisode::class, mappedBy: 'playlist_media')] protected Collection $podcast_episodes; public function __construct(StorageLocation $storageLocation, string $path) { $this->storage_location = $storageLocation; $this->playlists = new ArrayCollection(); $this->custom_fields = new ArrayCollection(); $this->podcast_episodes = new ArrayCollection(); $this->mtime = $this->uploaded_at = time(); $this->generateUniqueId(); $this->setPath($path); } public function getUniqueId(): string { return $this->unique_id; } public function generateUniqueId(bool $forceNew = false): void { if (!isset($this->unique_id) || $forceNew) { $this->unique_id = bin2hex(random_bytes(12)); } } public function getStorageLocation(): StorageLocation { return $this->storage_location; } public function getAlbum(): ?string { return $this->album; } public function setAlbum(?string $album = null): void { $this->album = $this->truncateNullableString($album, 200); } public function getGenre(): ?string { return $this->genre; } public function setGenre(?string $genre = null): void { $this->genre = $this->truncateNullableString($genre); } public function getLyrics(): ?string { return $this->lyrics; } public function setLyrics(?string $lyrics = null): void { $this->lyrics = $lyrics; } /** * @return string[] */ public function getRelatedFilePaths(): array { return [ self::getArtPath($this->getUniqueId()), self::getWaveformPath($this->getUniqueId()), ]; } public function getIsrc(): ?string { return $this->isrc; } public function setIsrc(?string $isrc = null): void { $this->isrc = $this->truncateNullableString($isrc, 15); } public function getLength(): float { return Types::float($this->length); } public function setLength(float $length): void { $this->length = (string)$length; } public function getPath(): string { return $this->path; } public function setPath(string $path): void { $this->path = $path; } public function getMtime(): int { return $this->mtime; } public function setMtime(int $mtime): void { $this->mtime = $mtime; } public function getUploadedAt(): int { return $this->uploaded_at; } public function getArtUpdatedAt(): int { return $this->art_updated_at; } public function setArtUpdatedAt(int $artUpdatedAt): void { $this->art_updated_at = $artUpdatedAt; } public function getExtraMetadata(): StationMediaMetadata { return new StationMediaMetadata((array)$this->extra_metadata); } public function setExtraMetadata( StationMediaMetadata|array $metadata ): void { $this->extra_metadata = $this->getExtraMetadata() ->fromArray($metadata) ->toArray(); } public function clearExtraMetadata(): void { $this->extra_metadata = (new StationMediaMetadata([]))->toArray(); } /** * Get the length with cue-in and cue-out points included. */ public function getCalculatedLength(): int { $length = $this->getLength(); $extraMeta = $this->getExtraMetadata(); $cueOut = $extraMeta->getLiqCueOut(); if ($cueOut > 0) { $lengthRemoved = $length - $cueOut; $length -= $lengthRemoved; } $cueIn = $extraMeta->getLiqCueIn(); if ($cueIn > 0) { $length -= $cueIn; } return (int)floor($length); } /** * @return Collection<int, StationMediaCustomField> */ public function getCustomFields(): Collection { return $this->custom_fields; } /** * @param Collection<int, StationMediaCustomField> $customFields */ public function setCustomFields(Collection $customFields): void { $this->custom_fields = $customFields; } /** * @return Collection<int, PodcastEpisode> */ public function getPodcastEpisodes(): Collection { return $this->podcast_episodes; } /** * Indicates whether this media is a part of any "requestable" playlists. */ public function isRequestable(): bool { foreach ($this->getPlaylists() as $playlistItem) { $playlist = $playlistItem->getPlaylist(); /** @var StationPlaylist $playlist */ if ($playlist->isRequestable()) { return true; } } return false; } /** * @return Collection<int, StationPlaylistMedia> */ public function getPlaylists(): Collection { return $this->playlists; } public function fromMetadata(MetadataInterface $metadata): void { $this->setLength($metadata->getDuration()); $tags = $metadata->getKnownTags(); if (isset($tags['title'])) { $this->setTitle(Types::stringOrNull($tags['title'])); } if (isset($tags['artist'])) { $this->setArtist(Types::stringOrNull($tags['artist'])); } if (isset($tags['album'])) { $this->setAlbum(Types::stringOrNull($tags['album'])); } if (isset($tags['genre'])) { $this->setGenre(Types::stringOrNull($tags['genre'])); } if (isset($tags['unsynchronised_lyric'])) { $this->setLyrics(Types::stringOrNull($tags['unsynchronised_lyric'])); } if (isset($tags['isrc'])) { $this->setIsrc(Types::stringOrNull($tags['isrc'])); } $this->setExtraMetadata($metadata->getExtraTags()); $this->updateSongId(); } public function toMetadata(): MetadataInterface { $metadata = new Metadata(); $metadata->setDuration($this->getLength()); $tags = array_filter( [ 'title' => $this->getTitle(), 'artist' => $this->getArtist(), 'album' => $this->getAlbum(), 'genre' => $this->getGenre(), 'unsynchronised_lyric' => $this->getLyrics(), 'isrc' => $this->getIsrc(), ] ); $metadata->setKnownTags($tags); $metadata->setExtraTags($this->getExtraMetadata()->toArray()); return $metadata; } public function __toString(): string { return 'StationMedia ' . $this->id . ': ' . $this->artist . ' - ' . $this->title; } public static function needsReprocessing(int $fileModifiedTime = 0, int $dbModifiedTime = 0): bool { return $fileModifiedTime > $dbModifiedTime; } public static function getArtPath(string $uniqueId): string { return StationFilesystems::DIR_ALBUM_ART . '/' . $uniqueId . '.jpg'; } public static function getFolderArtPath(string $folderHash): string { return StationFilesystems::DIR_FOLDER_COVERS . '/' . $folderHash . '.jpg'; } public static function getFolderHashForPath(string $path): string { $folder = dirname($path); return (!empty($folder)) ? md5($folder) : 'base'; } public static function getWaveformPath(string $uniqueId): string { return StationFilesystems::DIR_WAVEFORMS . '/' . $uniqueId . '.json'; } } ```
/content/code_sandbox/backend/src/Entity/StationMedia.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,480
```php <?php declare(strict_types=1); namespace App\Entity; use App\Radio\Enums\StreamFormats; use App\Utilities\Strings; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; use Stringable; use Symfony\Component\Validator\Constraints as Assert; #[ OA\Schema(type: "object"), ORM\Entity, ORM\Table(name: 'station_hls_streams'), Attributes\Auditable ] class StationHlsStream implements Stringable, Interfaces\StationCloneAwareInterface, Interfaces\IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; use Traits\TruncateInts; #[ ORM\ManyToOne(inversedBy: 'hls_streams'), ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE') ] protected Station $station; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $station_id; #[ OA\Property(example: "aac_lofi"), ORM\Column(length: 100), Assert\NotBlank ] protected string $name = ''; #[ OA\Property(example: "aac"), ORM\Column(type: 'string', length: 10, nullable: true, enumType: StreamFormats::class) ] protected ?StreamFormats $format = StreamFormats::Aac; #[ OA\Property(example: 128), ORM\Column(type: 'smallint', nullable: true) ] protected ?int $bitrate = 128; #[ ORM\Column, Attributes\AuditIgnore ] protected int $listeners = 0; public function __construct(Station $station) { $this->station = $station; } public function getStation(): Station { return $this->station; } public function setStation(Station $station): void { $this->station = $station; } public function getName(): string { return $this->name; } public function setName(string $newName): void { // Ensure all mount point names start with a leading slash. $this->name = $this->truncateString(Strings::getProgrammaticString($newName), 100); } public function getFormat(): ?StreamFormats { return $this->format; } public function setFormat(?StreamFormats $format): void { $this->format = $format; } public function getBitrate(): ?int { return $this->bitrate; } public function setBitrate(?int $bitrate): void { $this->bitrate = $bitrate; } public function getListeners(): int { return $this->listeners; } public function setListeners(int $listeners): void { $this->listeners = $listeners; } public function __toString(): string { return $this->getStation() . ' HLS Stream: ' . $this->getName(); } } ```
/content/code_sandbox/backend/src/Entity/StationHlsStream.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
680
```php <?php declare(strict_types=1); namespace App\Entity; use App\Utilities\Types; class PodcastBrandingConfiguration extends AbstractStationConfiguration { public const string PUBLIC_CUSTOM_HTML = 'public_custom_html'; public function getPublicCustomHtml(): ?string { return Types::stringOrNull($this->get(self::PUBLIC_CUSTOM_HTML), true); } public function setPublicCustomHtml(?string $html): void { $this->set(self::PUBLIC_CUSTOM_HTML, $html); } } ```
/content/code_sandbox/backend/src/Entity/PodcastBrandingConfiguration.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
111
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Enums\PodcastSources; use App\Entity\Interfaces\IdentifiableEntityInterface; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; #[ ORM\Entity, ORM\Table(name: 'podcast_episode'), Attributes\Auditable ] class PodcastEpisode implements IdentifiableEntityInterface { use Traits\HasUniqueId; use Traits\TruncateStrings; public const string DIR_PODCAST_EPISODE_ARTWORK = '.podcast_episode_art'; #[ORM\ManyToOne(inversedBy: 'episodes')] #[ORM\JoinColumn(name: 'podcast_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected Podcast $podcast; #[ORM\ManyToOne(inversedBy: 'podcast_episodes')] #[ORM\JoinColumn(name: 'playlist_media_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?StationMedia $playlist_media = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $playlist_media_id = null; #[ORM\OneToOne(mappedBy: 'episode')] protected ?PodcastMedia $media = null; #[ORM\Column(length: 255)] #[Assert\NotBlank] protected string $title; #[ORM\Column(length: 255, nullable: true)] protected ?string $link = null; #[ORM\Column(type: 'text')] #[Assert\NotBlank] protected string $description; #[ORM\Column] protected int $publish_at; #[ORM\Column] protected bool $explicit; #[ORM\Column(nullable: true)] protected ?int $season_number; #[ORM\Column(nullable: true)] protected ?int $episode_number; #[ORM\Column] protected int $created_at; #[ORM\Column] #[Attributes\AuditIgnore] protected int $art_updated_at = 0; public function __construct(Podcast $podcast) { $this->podcast = $podcast; $this->created_at = time(); $this->publish_at = time(); } public function getPodcast(): Podcast { return $this->podcast; } public function setMedia(?PodcastMedia $media): void { $this->media = $media; } public function getMedia(): ?PodcastMedia { return $this->media; } public function getPlaylistMedia(): ?StationMedia { return $this->playlist_media; } public function setPlaylistMedia(?StationMedia $playlist_media): void { $this->playlist_media = $playlist_media; } public function getTitle(): string { return $this->title; } public function setTitle(string $title): self { $this->title = $this->truncateString($title); return $this; } public function getLink(): ?string { return $this->link; } public function setLink(?string $link): self { $this->link = $this->truncateNullableString($link); return $this; } public function getDescription(): string { return $this->description; } public function setDescription(string $description): self { $this->description = $this->truncateString($description, 4000); return $this; } public function getPublishAt(): int { return $this->publish_at; } public function setPublishAt(?int $publishAt): self { $this->publish_at = $publishAt ?? $this->created_at; return $this; } public function getExplicit(): bool { return $this->explicit; } public function setExplicit(bool $explicit): self { $this->explicit = $explicit; return $this; } public function getSeasonNumber(): ?int { return $this->season_number; } public function setSeasonNumber(?int $season_number): self { $this->season_number = $season_number; return $this; } public function getEpisodeNumber(): ?int { return $this->episode_number; } public function setEpisodeNumber(?int $episode_number): self { $this->episode_number = $episode_number; return $this; } public function getCreatedAt(): int { return $this->created_at; } public function setCreatedAt(int $createdAt): self { $this->created_at = $createdAt; return $this; } public function getArtUpdatedAt(): int { return $this->art_updated_at; } public function setArtUpdatedAt(int $artUpdatedAt): self { $this->art_updated_at = $artUpdatedAt; return $this; } public static function getArtPath(string $uniqueId): string { return self::DIR_PODCAST_EPISODE_ARTWORK . '/' . $uniqueId . '.jpg'; } public function isPublished(): bool { if ($this->getPublishAt() > time()) { return false; } return match ($this->getPodcast()->getSource()) { PodcastSources::Manual => ($this->getMedia() !== null), PodcastSources::Playlist => ($this->getPlaylistMedia() !== null) }; } } ```
/content/code_sandbox/backend/src/Entity/PodcastEpisode.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,193
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use App\OpenApi; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; #[ OA\Schema(type: "object"), ORM\Entity, ORM\Table(name: 'relays'), ORM\HasLifecycleCallbacks ] class Relay implements IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; #[ OA\Property(example: "path_to_url"), ORM\Column(length: 255) ] protected string $base_url; #[ OA\Property(example: "Relay"), ORM\Column(length: 100, nullable: true) ] protected ?string $name = 'Relay'; #[ OA\Property(example: true), ORM\Column ] protected bool $is_visible_on_public_pages = true; #[ OA\Property(example: OpenApi::SAMPLE_TIMESTAMP), ORM\Column ] protected int $created_at; #[ OA\Property(example: OpenApi::SAMPLE_TIMESTAMP), ORM\Column ] protected int $updated_at; /** @var Collection<int, StationRemote> */ #[ORM\OneToMany(targetEntity: StationRemote::class, mappedBy: 'relay')] protected Collection $remotes; public function __construct(string $baseUrl) { $this->base_url = $this->truncateString($baseUrl); $this->created_at = time(); $this->updated_at = time(); $this->remotes = new ArrayCollection(); } #[ORM\PreUpdate] public function preUpdate(): void { $this->updated_at = time(); } public function getBaseUrl(): string { return $this->base_url; } public function getName(): ?string { return $this->name; } public function setName(?string $name): void { $this->name = $this->truncateNullableString($name, 100); } public function getIsVisibleOnPublicPages(): bool { return $this->is_visible_on_public_pages; } public function setIsVisibleOnPublicPages(bool $isVisibleOnPublicPages): void { $this->is_visible_on_public_pages = $isVisibleOnPublicPages; } public function getCreatedAt(): int { return $this->created_at; } public function setCreatedAt(int $createdAt): void { $this->created_at = $createdAt; } public function getUpdatedAt(): int { return $this->updated_at; } public function setUpdatedAt(int $updatedAt): void { $this->updated_at = $updatedAt; } /** * @return Collection<int, StationRemote> */ public function getRemotes(): Collection { return $this->remotes; } } ```
/content/code_sandbox/backend/src/Entity/Relay.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
649
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Enums\AuditLogOperations; use App\Entity\Interfaces\IdentifiableEntityInterface; use Doctrine\ORM\Mapping as ORM; #[ ORM\Entity(readOnly: true), ORM\Table(name: 'audit_log'), ORM\Index(name: 'idx_search', columns: ['class', 'user', 'identifier']) ] class AuditLog implements IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; protected static ?string $currentUser = null; #[ORM\Column] protected int $timestamp; #[ORM\Column(type: 'smallint', enumType: AuditLogOperations::class)] protected AuditLogOperations $operation; #[ORM\Column(length: 255)] protected string $class; #[ORM\Column(length: 255)] protected string $identifier; #[ORM\Column(name: 'target_class', length: 255, nullable: true)] protected ?string $targetClass; #[ORM\Column(length: 255, nullable: true)] protected ?string $target; #[ORM\Column(type: 'json')] protected array $changes; #[ORM\Column(length: 255, nullable: true)] protected ?string $user; public function __construct( AuditLogOperations $operation, string $class, string $identifier, ?string $targetClass, ?string $target, array $changes ) { $this->timestamp = time(); $this->user = self::$currentUser; $this->operation = $operation; $this->class = $this->filterClassName($class) ?? ''; $this->identifier = $identifier; $this->targetClass = $this->filterClassName($targetClass); $this->target = $target; $this->changes = $changes; } /** * @param string|null $class The FQDN for a class * * @return string|null The non-namespaced class name */ protected function filterClassName(?string $class): ?string { if (empty($class)) { return null; } $classNameParts = explode('\\', $class); return array_pop($classNameParts); } /** * Set the current user for this request (used when creating new entries). * * @param User|null $user */ public static function setCurrentUser(?User $user = null): void { self::$currentUser = (null !== $user) ? (string)$user : null; } public function getTimestamp(): int { return $this->timestamp; } public function getOperation(): AuditLogOperations { return $this->operation; } public function getClass(): string { return $this->class; } public function getIdentifier(): string { return $this->identifier; } public function getTargetClass(): ?string { return $this->targetClass; } public function getTarget(): ?string { return $this->target; } /** * @return mixed[] */ public function getChanges(): array { return $this->changes; } public function getUser(): ?string { return $this->user; } } ```
/content/code_sandbox/backend/src/Entity/AuditLog.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
726
```php <?php declare(strict_types=1); namespace App\Entity; use App\Auth; use App\Entity\Interfaces\EntityGroupsInterface; use App\Entity\Interfaces\IdentifiableEntityInterface; use App\OpenApi; use App\Utilities\Strings; use App\Validator\Constraints\UniqueEntity; use Azura\Normalizer\Attributes\DeepNormalize; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; use OTPHP\Factory; use Stringable; use Symfony\Component\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; #[ OA\Schema(type: "object"), ORM\Entity, ORM\Table(name: 'users'), ORM\HasLifecycleCallbacks, ORM\UniqueConstraint(name: 'email_idx', columns: ['email']), Attributes\Auditable, UniqueEntity(fields: ['email']) ] class User implements Stringable, IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; #[ OA\Property(example: "demo@azuracast.com"), ORM\Column(length: 100, nullable: false), Assert\NotBlank, Assert\Email, Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL]) ] protected string $email; #[ ORM\Column(length: 255, nullable: false), Attributes\AuditIgnore ] protected string $auth_password = ''; #[ OA\Property(example: ""), Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL]) ] protected ?string $new_password = null; #[ OA\Property(example: "Demo Account"), ORM\Column(length: 100, nullable: true), Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL]) ] protected ?string $name = null; #[ OA\Property(example: "en_US"), ORM\Column(length: 25, nullable: true), Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL]) ] protected ?string $locale = null; #[ OA\Property(example: true), ORM\Column(nullable: true), Attributes\AuditIgnore, Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL]) ] protected ?bool $show_24_hour_time = null; #[ OA\Property(example: "A1B2C3D4"), ORM\Column(length: 255, nullable: true), Attributes\AuditIgnore, Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL]) ] protected ?string $two_factor_secret = null; #[ OA\Property(example: OpenApi::SAMPLE_TIMESTAMP), ORM\Column, Attributes\AuditIgnore, Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL]) ] protected int $created_at; #[ OA\Property(example: OpenApi::SAMPLE_TIMESTAMP), ORM\Column, Attributes\AuditIgnore, Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL]) ] protected int $updated_at; /** @var Collection<int, Role> */ #[ OA\Property(type: "array", items: new OA\Items()), ORM\ManyToMany(targetEntity: Role::class, inversedBy: 'users', fetch: 'EAGER'), ORM\JoinTable(name: 'user_has_role'), ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', onDelete: 'CASCADE'), ORM\InverseJoinColumn(name: 'role_id', referencedColumnName: 'id', onDelete: 'CASCADE'), Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL]), DeepNormalize(true), Serializer\MaxDepth(1) ] protected Collection $roles; /** @var Collection<int, ApiKey> */ #[ ORM\OneToMany(targetEntity: ApiKey::class, mappedBy: 'user'), Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL]), DeepNormalize(true) ] protected Collection $api_keys; /** @var Collection<int, UserPasskey> */ #[ ORM\OneToMany(targetEntity: UserPasskey::class, mappedBy: 'user'), Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL]), DeepNormalize(true) ] protected Collection $passkeys; /** @var Collection<int, UserLoginToken> */ #[ ORM\OneToMany(targetEntity: UserLoginToken::class, mappedBy: 'user'), Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL]), DeepNormalize(true) ] protected Collection $login_tokens; public function __construct() { $this->created_at = time(); $this->updated_at = time(); $this->roles = new ArrayCollection(); $this->api_keys = new ArrayCollection(); $this->login_tokens = new ArrayCollection(); } #[ORM\PreUpdate] public function preUpdate(): void { $this->updated_at = time(); } public function getName(): ?string { return $this->name; } public function getDisplayName(): string { return $this->name ?? $this->email; } public function setName(?string $name = null): void { $this->name = $this->truncateNullableString($name, 100); } public function getEmail(): string { return $this->email; } public function setEmail(string $email): void { $this->email = $this->truncateString($email, 100); } public function verifyPassword(string $password): bool { if (password_verify($password, $this->auth_password)) { if (password_needs_rehash($this->auth_password, PASSWORD_ARGON2ID)) { $this->setNewPassword($password); } return true; } return false; } public function setNewPassword(?string $password): void { if (null !== $password && trim($password)) { $this->auth_password = password_hash($password, PASSWORD_ARGON2ID); } } public function generateRandomPassword(): void { $this->setNewPassword(Strings::generatePassword()); } public function getLocale(): ?string { return $this->locale; } public function setLocale(?string $locale = null): void { $this->locale = $locale; } public function getShow24HourTime(): ?bool { return $this->show_24_hour_time; } public function setShow24HourTime(?bool $show24HourTime): void { $this->show_24_hour_time = $show24HourTime; } public function getTwoFactorSecret(): ?string { return $this->two_factor_secret; } public function setTwoFactorSecret(?string $twoFactorSecret = null): void { $this->two_factor_secret = $twoFactorSecret; } public function verifyTwoFactor(string $otp): bool { if (empty($this->two_factor_secret)) { return true; } if (empty($otp)) { return false; } return Factory::loadFromProvisioningUri($this->two_factor_secret)->verify($otp, null, Auth::TOTP_WINDOW); } public function getCreatedAt(): int { return $this->created_at; } public function getUpdatedAt(): int { return $this->updated_at; } /** * @return Collection<int, Role> */ public function getRoles(): Collection { return $this->roles; } /** * @return Collection<int, ApiKey> */ public function getApiKeys(): Collection { return $this->api_keys; } /** * @return Collection<int, UserPasskey> */ public function getPasskeys(): Collection { return $this->passkeys; } public function __toString(): string { return $this->getName() . ' (' . $this->getEmail() . ')'; } } ```
/content/code_sandbox/backend/src/Entity/User.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,802
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use App\Utilities\File; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use OpenApi\Attributes as OA; use Stringable; use Symfony\Component\Validator\Constraints as Assert; #[ OA\Schema(type: 'object'), ORM\Entity, ORM\Table(name: 'custom_field'), Attributes\Auditable ] class CustomField implements Stringable, IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; #[ OA\Property, ORM\Column(length: 255), Assert\NotBlank ] protected string $name; #[ OA\Property( description: "The programmatic name for the field. Can be auto-generated from the full name." ), ORM\Column(length: 100, nullable: false) ] protected string $short_name; #[ OA\Property( description: "An ID3v2 field to automatically assign to this value, if it exists in the media file." ), ORM\Column(length: 100, nullable: true) ] protected ?string $auto_assign = null; /** @var Collection<int, StationMediaCustomField> */ #[ORM\OneToMany(targetEntity: StationMediaCustomField::class, mappedBy: 'field')] protected Collection $media_fields; public function __construct() { $this->media_fields = new ArrayCollection(); } public function getName(): string { return $this->name; } public function setName(string $name): void { $this->name = $this->truncateString($name); if (empty($this->short_name) && !empty($name)) { $this->setShortName(self::generateShortName($name)); } } public function getShortName(): string { return (!empty($this->short_name)) ? $this->short_name : self::generateShortName($this->name); } public function setShortName(string $shortName): void { $shortName = trim($shortName); if (!empty($shortName)) { $this->short_name = $this->truncateString($shortName, 100); } } public function getAutoAssign(): ?string { return $this->auto_assign; } public function hasAutoAssign(): bool { return !empty($this->auto_assign); } public function setAutoAssign(?string $autoAssign): void { $this->auto_assign = $autoAssign; } public function __toString(): string { return $this->short_name; } public static function generateShortName(string $str): string { $str = File::sanitizeFileName($str); return (is_numeric($str)) ? 'custom_field_' . $str : $str; } } ```
/content/code_sandbox/backend/src/Entity/CustomField.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
656
```php <?php declare(strict_types=1); namespace App\Entity; use App\Media\Metadata; use App\Utilities\Time; use App\Utilities\Types; use ReflectionObject; class StationMediaMetadata extends AbstractStationConfiguration { public const string AMPLIFY = 'liq_amplify'; public function getLiqAmplify(): ?float { return Types::floatOrNull($this->get(self::AMPLIFY)); } public function setLiqAmplify(float|string $amplify = null): void { $this->set(self::AMPLIFY, self::getNumericValue($amplify)); } public const string CROSS_START_NEXT = 'liq_cross_start_next'; public function getLiqCrossStartNext(): ?float { return Types::floatOrNull($this->get(self::CROSS_START_NEXT)); } public function setLiqCrossStartNext(string|int|float $startNext = null): void { $this->set(self::CROSS_START_NEXT, self::getNumericValue($startNext)); } public const string FADE_IN = 'liq_fade_in'; public function getLiqFadeIn(): ?float { return Types::floatOrNull($this->get(self::FADE_IN)); } public function setLiqFadeIn(string|int|float $fadeIn = null): void { $this->set(self::FADE_IN, self::getNumericValue($fadeIn)); } public const string FADE_OUT = 'liq_fade_out'; public function getLiqFadeOut(): ?float { return Types::floatOrNull($this->get(self::FADE_OUT)); } public function setLiqFadeOut(string|int|float $fadeOut = null): void { $this->set(self::FADE_OUT, $fadeOut); } public const string CUE_IN = 'liq_cue_in'; public function getLiqCueIn(): ?float { return Types::floatOrNull($this->get(self::CUE_IN)); } public function setLiqCueIn(string|int|float $cueIn = null): void { $this->set(self::CUE_IN, self::getNumericValue($cueIn)); } public const string CUE_OUT = 'liq_cue_out'; public function getLiqCueOut(): ?float { return Types::floatOrNull($this->get(self::CUE_OUT)); } public function setLiqCueOut(string|int|float $cueOut = null): void { $this->set(self::CUE_OUT, self::getNumericValue($cueOut)); } public function fromArray( array|AbstractStationConfiguration $data ): static { if ($data instanceof AbstractStationConfiguration) { $data = $data->toArray(); } $reflClass = new ReflectionObject($this); // Only accept hashmap-style data, not lists. if (array_is_list($data)) { return $this; } foreach ($data as $dataKey => $dataVal) { if (is_int($dataKey)) { continue; } $dataKey = mb_strtolower($dataKey); if (!$reflClass->hasConstant($dataKey) && !self::isLiquidsoapAnnotation($dataKey)) { continue; } if (is_string($dataVal) && ($sepPos = strpos($dataVal, Metadata::MULTI_VALUE_SEPARATOR)) !== false) { $dataVal = substr($dataVal, 0, $sepPos); } $methodName = $this->inflector->camelize('set_' . $dataKey); if (method_exists($this, $methodName)) { $this->$methodName($dataVal); } else { $this->set($dataKey, self::normalizeLiquidsoapValue($dataVal)); } } return $this; } public function toArray(): array { $return = []; foreach ($this->data as $dataKey => $dataVal) { $getMethodName = $this->inflector->camelize('get_' . $dataKey); $methodName = $this->inflector->camelize($dataKey); $return[$dataKey] = match (true) { method_exists($this, $getMethodName) => $this->$getMethodName(), method_exists($this, $methodName) => $this->$methodName(), default => $this->get($dataKey) }; } ksort($return); return $return; } public static function getNumericValue(string|int|float $annotation = null): ?float { if (is_string($annotation)) { if (str_contains($annotation, ':')) { $annotation = Time::displayTimeToSeconds($annotation); } else { preg_match('/([+-]?\d*\.?\d+)/', $annotation, $matches); $annotation = $matches[1] ?? null; } } return Types::floatOrNull($annotation); } public static function normalizeLiquidsoapValue(mixed $dataVal = null): mixed { return match (true) { 'true' === $dataVal || 'false' === $dataVal => Types::bool($dataVal, false, true), is_numeric($dataVal) => Types::float($dataVal), default => $dataVal }; } public static function isLiquidsoapAnnotation(string $key): bool { $key = mb_strtolower($key); return str_starts_with($key, 'liq_') || str_starts_with($key, 'replaygain_'); } } ```
/content/code_sandbox/backend/src/Entity/StationMediaMetadata.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,253
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Enums\PodcastSources; use Azura\Normalizer\Attributes\DeepNormalize; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; #[ ORM\Entity, ORM\Table(name: 'podcast'), Attributes\Auditable ] class Podcast implements Interfaces\IdentifiableEntityInterface { use Traits\HasUniqueId; use Traits\TruncateStrings; public const string DIR_PODCAST_ARTWORK = '.podcast_art'; #[ORM\ManyToOne(targetEntity: StorageLocation::class)] #[ORM\JoinColumn(name: 'storage_location_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected StorageLocation $storage_location; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $storage_location_id; #[DeepNormalize(true)] #[ORM\ManyToOne(inversedBy: 'podcasts')] #[ORM\JoinColumn(name: 'playlist_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?StationPlaylist $playlist = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $playlist_id = null; #[ORM\Column(type: 'string', length: 50, enumType: PodcastSources::class)] protected PodcastSources $source = PodcastSources::Manual; #[ORM\Column(length: 255)] #[Assert\NotBlank] protected string $title; #[ORM\Column(length: 255, nullable: true)] protected ?string $link = null; #[ORM\Column(type: 'text')] #[Assert\NotBlank] protected string $description; #[ORM\Column] protected bool $is_enabled = true; #[ORM\Column(type: 'json', nullable: true)] protected ?array $branding_config = null; #[ORM\Column(length: 2)] #[Assert\NotBlank] protected string $language; #[ORM\Column(length: 255)] protected string $author; #[ORM\Column(length: 255)] #[Assert\Email] protected string $email; #[ORM\Column] #[Attributes\AuditIgnore] protected int $art_updated_at = 0; #[ORM\Column] protected bool $playlist_auto_publish = true; /** @var Collection<int, PodcastCategory> */ #[ORM\OneToMany(targetEntity: PodcastCategory::class, mappedBy: 'podcast')] protected Collection $categories; /** @var Collection<int, PodcastEpisode> */ #[ORM\OneToMany(targetEntity: PodcastEpisode::class, mappedBy: 'podcast', fetch: 'EXTRA_LAZY')] protected Collection $episodes; public function __construct(StorageLocation $storageLocation) { $this->storage_location = $storageLocation; $this->categories = new ArrayCollection(); $this->episodes = new ArrayCollection(); } public function getStorageLocation(): StorageLocation { return $this->storage_location; } public function getPlaylist(): ?StationPlaylist { return $this->playlist; } public function setPlaylist(?StationPlaylist $playlist): void { $this->playlist = $playlist; } public function getSource(): PodcastSources { return $this->source; } public function setSource(PodcastSources $source): void { $this->source = $source; } public function getTitle(): string { return $this->title; } public function setTitle(string $title): self { $this->title = $this->truncateString($title); return $this; } public function getLink(): ?string { return $this->link; } public function setLink(?string $link): self { $this->link = $this->truncateNullableString($link); return $this; } public function getDescription(): string { return $this->description; } public function setDescription(string $description): self { $this->description = $this->truncateString($description, 4000); return $this; } public function isEnabled(): bool { return $this->is_enabled; } public function setIsEnabled(bool $is_enabled): void { $this->is_enabled = $is_enabled; } public function getBrandingConfig(): PodcastBrandingConfiguration { return new PodcastBrandingConfiguration((array)$this->branding_config); } public function setBrandingConfig( PodcastBrandingConfiguration|array $brandingConfig ): void { $this->branding_config = $this->getBrandingConfig() ->fromArray($brandingConfig) ->toArray(); } public function getLanguage(): string { return $this->language; } public function setLanguage(string $language): self { $this->language = $this->truncateString($language); return $this; } public function getAuthor(): string { return $this->author; } public function setAuthor(string $author): self { $this->author = $this->truncateString($author); return $this; } public function getEmail(): string { return $this->email; } public function setEmail(string $email): self { $this->email = $this->truncateString($email); return $this; } public function getArtUpdatedAt(): int { return $this->art_updated_at; } public function setArtUpdatedAt(int $artUpdatedAt): self { $this->art_updated_at = $artUpdatedAt; return $this; } public function playlistAutoPublish(): bool { return $this->playlist_auto_publish; } public function setPlaylistAutoPublish(bool $playlist_auto_publish): void { $this->playlist_auto_publish = $playlist_auto_publish; } /** * @return Collection<int, PodcastCategory> */ public function getCategories(): Collection { return $this->categories; } /** * @return Collection<int, PodcastEpisode> */ public function getEpisodes(): Collection { return $this->episodes; } public static function getArtPath(string $uniqueId): string { return self::DIR_PODCAST_ARTWORK . '/' . $uniqueId . '.jpg'; } } ```
/content/code_sandbox/backend/src/Entity/Podcast.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,421
```php <?php declare(strict_types=1); namespace App\Entity; use App\Radio\Enums\AdapterTypeInterface; use App\Radio\Enums\RemoteAdapters; use App\Radio\Enums\StreamFormats; use App\Radio\Enums\StreamProtocols; use App\Radio\Remote\AbstractRemote; use App\Utilities; use Doctrine\ORM\Mapping as ORM; use Psr\Http\Message\UriInterface; use Stringable; #[ ORM\Entity, ORM\Table(name: 'station_remotes'), Attributes\Auditable ] class StationRemote implements Stringable, Interfaces\StationMountInterface, Interfaces\StationCloneAwareInterface, Interfaces\IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; #[ORM\ManyToOne(inversedBy: 'remotes')] #[ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected Station $station; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $station_id; #[ORM\ManyToOne(inversedBy: 'remotes')] #[ORM\JoinColumn(name: 'relay_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')] protected ?Relay $relay = null; #[ORM\Column(nullable: true, insertable: false, updatable: false)] protected ?int $relay_id = null; #[ORM\Column(length: 255, nullable: true)] protected ?string $display_name = null; #[ORM\Column] protected bool $is_visible_on_public_pages = true; #[ORM\Column(type: 'string', length: 50, enumType: RemoteAdapters::class)] protected RemoteAdapters $type; #[ORM\Column] protected bool $enable_autodj = false; #[ORM\Column(type: 'string', length: 10, nullable: true, enumType: StreamFormats::class)] protected ?StreamFormats $autodj_format = null; #[ORM\Column(type: 'smallint', nullable: true)] protected ?int $autodj_bitrate = null; #[ORM\Column(length: 255, nullable: true)] protected ?string $custom_listen_url = null; #[ORM\Column(length: 255, nullable: false)] protected string $url = ''; #[ORM\Column(length: 150, nullable: true)] protected ?string $mount = null; #[ORM\Column(length: 100, nullable: true)] protected ?string $admin_password = null; #[ORM\Column(type: 'smallint', nullable: true, options: ['unsigned' => true])] protected ?int $source_port = null; #[ORM\Column(length: 150, nullable: true)] protected ?string $source_mount = null; #[ORM\Column(length: 100, nullable: true)] protected ?string $source_username = null; #[ORM\Column(length: 100, nullable: true)] protected ?string $source_password = null; #[ORM\Column] protected bool $is_public = false; #[ORM\Column] #[Attributes\AuditIgnore] protected int $listeners_unique = 0; #[ORM\Column] #[Attributes\AuditIgnore] protected int $listeners_total = 0; public function __construct(Station $station) { $this->station = $station; } public function getStation(): Station { return $this->station; } public function setStation(Station $station): void { $this->station = $station; } public function getRelay(): ?Relay { return $this->relay; } public function setRelay(?Relay $relay): void { $this->relay = $relay; } public function getIsVisibleOnPublicPages(): bool { return $this->is_visible_on_public_pages; } public function setIsVisibleOnPublicPages(bool $isVisibleOnPublicPages): void { $this->is_visible_on_public_pages = $isVisibleOnPublicPages; } public function getEnableAutodj(): bool { return $this->enable_autodj; } public function setEnableAutodj(bool $enableAutodj): void { $this->enable_autodj = $enableAutodj; } public function getAutodjFormat(): ?StreamFormats { return $this->autodj_format; } public function setAutodjFormat(?StreamFormats $autodjFormat = null): void { $this->autodj_format = $autodjFormat; } public function getAutodjBitrate(): ?int { return $this->autodj_bitrate; } public function setAutodjBitrate(int $autodjBitrate = null): void { $this->autodj_bitrate = $autodjBitrate; } public function getCustomListenUrl(): ?string { return $this->custom_listen_url; } public function setCustomListenUrl(?string $customListenUrl = null): void { $this->custom_listen_url = $this->truncateNullableString($customListenUrl); } public function getAutodjUsername(): ?string { return $this->getSourceUsername(); } public function getSourceUsername(): ?string { return $this->source_username; } public function setSourceUsername(?string $sourceUsername): void { $this->source_username = $this->truncateNullableString($sourceUsername, 100); } public function getAutodjPassword(): ?string { $password = $this->getSourcePassword(); if (RemoteAdapters::Shoutcast2 === $this->getType()) { $mount = $this->getSourceMount(); if (empty($mount)) { $mount = $this->getMount(); } if (!empty($mount)) { $password .= ':#' . $mount; } } return $password; } public function getSourcePassword(): ?string { return $this->source_password; } public function setSourcePassword(?string $sourcePassword): void { $this->source_password = $this->truncateNullableString($sourcePassword, 100); } public function getType(): RemoteAdapters { return $this->type; } public function setType(RemoteAdapters $type): void { $this->type = $type; } public function getSourceMount(): ?string { return $this->source_mount; } public function setSourceMount(?string $sourceMount): void { $this->source_mount = $this->truncateNullableString($sourceMount, 150); } public function getMount(): ?string { return $this->mount; } public function setMount(?string $mount): void { $this->mount = $this->truncateNullableString($mount, 150); } public function getAdminPassword(): ?string { return $this->admin_password; } public function setAdminPassword(?string $adminPassword): void { $this->admin_password = $adminPassword; } public function getAutodjMount(): ?string { if (RemoteAdapters::Icecast !== $this->getType()) { return null; } $mount = $this->getSourceMount(); if (!empty($mount)) { return $mount; } return $this->getMount(); } public function getAutodjHost(): ?string { return $this->getUrlAsUri()->getHost(); } public function getUrl(): string { return $this->url; } public function getUrlAsUri(): UriInterface { return Utilities\Urls::parseUserUrl( $this->url, 'Remote Relay ' . $this->__toString() . ' URL' ); } public function setUrl(string $url): void { if (empty($url)) { $this->url = ''; } else { $uri = Utilities\Urls::parseUserUrl( $url, 'Remote Relay URL' ); $this->url = $this->truncateString((string)$uri); } } /* * StationMountInterface compliance methods */ public function getAutodjPort(): ?int { return $this->getSourcePort() ?? $this->getUrlAsUri()->getPort(); } public function getSourcePort(): ?int { return $this->source_port; } public function setSourcePort(?int $sourcePort): void { if ((int)$sourcePort === 0) { $sourcePort = null; } $this->source_port = $sourcePort; } public function getAutodjProtocol(): ?StreamProtocols { $urlScheme = $this->getUrlAsUri()->getScheme(); return match ($this->getAutodjAdapterType()) { RemoteAdapters::Shoutcast1, RemoteAdapters::Shoutcast2 => StreamProtocols::Icy, default => ('https' === $urlScheme) ? StreamProtocols::Https : StreamProtocols::Http }; } public function getAutodjAdapterType(): AdapterTypeInterface { return $this->getType(); } public function getIsPublic(): bool { return $this->is_public; } public function setIsPublic(bool $isPublic): void { $this->is_public = $isPublic; } public function getListenersUnique(): int { return $this->listeners_unique; } public function setListenersUnique(int $listenersUnique): void { $this->listeners_unique = $listenersUnique; } public function getListenersTotal(): int { return $this->listeners_total; } public function setListenersTotal(int $listenersTotal): void { $this->listeners_total = $listenersTotal; } /** * @return bool Whether this remote relay can be hand-edited. */ public function isEditable(): bool { return (RemoteAdapters::AzuraRelay !== $this->getType()); } public function getIsShoutcast(): bool { return match ($this->getAutodjAdapterType()) { RemoteAdapters::Shoutcast1, RemoteAdapters::Shoutcast2 => true, default => false, }; } /** * Retrieve the API version of the object/array. * * @param AbstractRemote $adapter */ public function api( AbstractRemote $adapter ): Api\NowPlaying\StationRemote { $response = new Api\NowPlaying\StationRemote(); $response->id = $this->getIdRequired(); $response->name = $this->getDisplayName(); $response->url = $adapter->getPublicUrl($this); $response->listeners = new Api\NowPlaying\Listeners( total: $this->listeners_total, unique: $this->listeners_unique ); if ($this->enable_autodj || (RemoteAdapters::AzuraRelay === $this->getType())) { $response->bitrate = (int)$this->autodj_bitrate; $response->format = $this->autodj_format?->value; } return $response; } public function getDisplayName(): string { if (!empty($this->display_name)) { return $this->display_name; } if ($this->enable_autodj) { $format = $this->getAutodjFormat(); if (null !== $format) { return $format->formatBitrate($this->autodj_bitrate); } } return Utilities\Strings::truncateUrl($this->url); } /** * @param string|null $displayName */ public function setDisplayName(?string $displayName): void { $this->display_name = $this->truncateNullableString($displayName); } public function __toString(): string { return $this->getStation() . ' Relay: ' . $this->getDisplayName(); } } ```
/content/code_sandbox/backend/src/Entity/StationRemote.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
2,719
```php <?php declare(strict_types=1); namespace App\Entity; use App\Security\SplitToken; use Doctrine\ORM\Mapping as ORM; #[ ORM\Entity(readOnly: true), ORM\Table(name: 'user_login_tokens') ] class UserLoginToken { use Traits\HasSplitTokenFields; #[ORM\ManyToOne(fetch: 'EAGER', inversedBy: 'login_tokens')] #[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected User $user; #[ORM\Column] protected int $created_at; public function __construct(User $user, SplitToken $token) { $this->user = $user; $this->setFromToken($token); $this->created_at = time(); } public function getUser(): User { return $this->user; } } ```
/content/code_sandbox/backend/src/Entity/UserLoginToken.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
190
```php <?php declare(strict_types=1); namespace App\Entity; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use DateTimeZone; use Doctrine\ORM\Mapping as ORM; #[ ORM\Entity, ORM\Table(name: 'station_requests') ] class StationRequest implements Interfaces\IdentifiableEntityInterface, Interfaces\StationAwareInterface { use Traits\HasAutoIncrementId; #[ORM\ManyToOne(inversedBy: 'requests')] #[ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected Station $station; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $station_id; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'track_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected StationMedia $track; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $track_id; #[ORM\Column] protected int $timestamp; #[ORM\Column] protected bool $skip_delay = false; #[ORM\Column] protected int $played_at = 0; #[ORM\Column(length: 40)] protected string $ip; public function __construct( Station $station, StationMedia $track, string $ip = null, bool $skipDelay = false ) { $this->station = $station; $this->track = $track; $this->timestamp = time(); $this->skip_delay = $skipDelay; $this->ip = $ip ?? $_SERVER['REMOTE_ADDR']; } public function getStation(): Station { return $this->station; } public function getTrack(): StationMedia { return $this->track; } public function getTimestamp(): int { return $this->timestamp; } public function skipDelay(): bool { return $this->skip_delay; } public function getPlayedAt(): int { return $this->played_at; } public function setPlayedAt(int $playedAt): void { $this->played_at = $playedAt; } public function getIp(): string { return $this->ip; } public function shouldPlayNow(CarbonInterface $now = null): bool { if ($this->skip_delay) { return true; } $station = $this->station; $stationTz = new DateTimeZone($station->getTimezone()); if (null === $now) { $now = CarbonImmutable::now($stationTz); } $thresholdMins = (int)$station->getRequestDelay(); $thresholdMins += random_int(0, $thresholdMins); $cued = CarbonImmutable::createFromTimestamp($this->timestamp); return $now->subMinutes($thresholdMins)->gt($cued); } } ```
/content/code_sandbox/backend/src/Entity/StationRequest.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
647
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\SongInterface; use InvalidArgumentException; use NowPlaying\Result\CurrentSong; class Song implements SongInterface { use Traits\HasSongFields; public final const string OFFLINE_SONG_ID = '5a6a865199cf5df73b1417326d2ff24f'; public function __construct(?SongInterface $song = null) { if (null !== $song) { $this->setSong($song); } } public function __toString(): string { return 'Song ' . $this->song_id . ': ' . $this->artist . ' - ' . $this->title; } public static function getSongHash(Song|array|string|CurrentSong $songText): string { // Handle various input types. if ($songText instanceof self) { return self::getSongHash($songText->getText() ?? ''); } if ($songText instanceof CurrentSong) { return self::getSongHash($songText->text); } if (is_array($songText)) { return self::getSongHash($songText['text'] ?? ''); } if (!is_string($songText)) { throw new InvalidArgumentException( sprintf( '$songText parameter must be a string, array, or instance of %s or %s.', self::class, CurrentSong::class ) ); } $songText = mb_substr($songText, 0, 150, 'UTF-8'); // Strip out characters that are likely to not be properly translated or relayed through the radio. $removeChars = [ ' ', '-', '"', '\'', "\n", "\t", "\r", ]; $songText = str_replace($removeChars, '', $songText); if (empty($songText)) { return self::OFFLINE_SONG_ID; } $hashBase = mb_strtolower($songText, 'UTF-8'); return md5($hashBase); } public static function createFromApiSong(Api\Song $apiSong): self { $song = new self(); $song->setText($apiSong->text); $song->setTitle($apiSong->title); $song->setArtist($apiSong->artist); $song->updateSongId(); return $song; } public static function createFromNowPlayingSong(CurrentSong $currentSong): self { $song = new self(); $song->setText($currentSong->text); $song->setTitle($currentSong->title); $song->setArtist($currentSong->artist); $song->updateSongId(); return $song; } public static function createFromArray(array $songRow): self { $currentSong = new CurrentSong( $songRow['text'] ?? '', $songRow['title'] ?? '', $songRow['artist'] ?? '' ); return self::createFromNowPlayingSong($currentSong); } public static function createFromText(string $songText): self { $currentSong = new CurrentSong($songText); return self::createFromNowPlayingSong($currentSong); } public static function createOffline(?string $text = null): self { $song = self::createFromText($text ?? 'Station Offline'); $song->setSongId(self::OFFLINE_SONG_ID); return $song; } } ```
/content/code_sandbox/backend/src/Entity/Song.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
774
```php <?php declare(strict_types=1); namespace App\Entity; use App\Entity\Interfaces\IdentifiableEntityInterface; use Doctrine\ORM\Mapping as ORM; #[ ORM\Entity, ORM\Table(name: 'station_media_custom_field') ] class StationMediaCustomField implements IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; #[ORM\ManyToOne(inversedBy: 'custom_fields')] #[ORM\JoinColumn(name: 'media_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected StationMedia $media; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $media_id; #[ORM\ManyToOne(inversedBy: 'media_fields')] #[ORM\JoinColumn(name: 'field_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected CustomField $field; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $field_id; #[ORM\Column(name: 'field_value', length: 255, nullable: true)] protected ?string $value = null; public function __construct(StationMedia $media, CustomField $field) { $this->media = $media; $this->field = $field; } public function getMedia(): StationMedia { return $this->media; } public function getField(): CustomField { return $this->field; } public function getValue(): ?string { return $this->value; } public function setValue(?string $value = null): void { $this->value = $this->truncateNullableString($value); } } ```
/content/code_sandbox/backend/src/Entity/StationMediaCustomField.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
375
```php <?php declare(strict_types=1); namespace App\Entity; use Doctrine\ORM\Mapping as ORM; #[ ORM\Entity, ORM\Table(name: 'station_playlist_folders') ] class StationPlaylistFolder implements Interfaces\PathAwareInterface, Interfaces\StationCloneAwareInterface, Interfaces\IdentifiableEntityInterface { use Traits\HasAutoIncrementId; use Traits\TruncateStrings; #[ORM\ManyToOne] #[ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected Station $station; #[ORM\ManyToOne(fetch: 'EAGER', inversedBy: 'folders')] #[ORM\JoinColumn(name: 'playlist_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected StationPlaylist $playlist; #[ORM\Column(nullable: false, insertable: false, updatable: false)] protected int $playlist_id; #[ORM\Column(length: 500)] protected string $path; public function __construct(Station $station, StationPlaylist $playlist, string $path) { $this->station = $station; $this->playlist = $playlist; $this->path = $path; } public function getStation(): Station { return $this->station; } public function setStation(Station $station): void { $this->station = $station; } public function getPlaylist(): StationPlaylist { return $this->playlist; } public function setPlaylist(StationPlaylist $playlist): void { $this->playlist = $playlist; } public function getPath(): string { return $this->path; } public function setPath(string $path): void { $this->path = $this->truncateString($path, 500); } } ```
/content/code_sandbox/backend/src/Entity/StationPlaylistFolder.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
402
```php <?php declare(strict_types=1); namespace App\Entity\Attributes; use Attribute; /** * Mark a database migration as the last migration before a stable version was tagged. */ #[Attribute(Attribute::TARGET_CLASS | ATTRIBUTE::IS_REPEATABLE)] final class StableMigration { public function __construct( public string $version ) { } } ```
/content/code_sandbox/backend/src/Entity/Attributes/StableMigration.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
74
```php <?php declare(strict_types=1); namespace App\Entity\Attributes; use Attribute; /** * Mark an individual property as one where changes should be ignored. */ #[Attribute(Attribute::TARGET_PROPERTY)] final class AuditIgnore { } ```
/content/code_sandbox/backend/src/Entity/Attributes/AuditIgnore.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
48
```php <?php declare(strict_types=1); namespace App\Entity\Attributes; use Attribute; /** * Marks a class as one whose changes should be logged via the Audit Log. */ #[Attribute(Attribute::TARGET_CLASS)] final class Auditable { } ```
/content/code_sandbox/backend/src/Entity/Attributes/Auditable.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
51
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20170510082607 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD radio_media_dir VARCHAR(255) DEFAULT NULL, ADD radio_playlists_dir VARCHAR(255) DEFAULT NULL, ADD radio_config_dir VARCHAR(255) DEFAULT NULL'); } public function postup(Schema $schema): void { foreach ($this->connection->fetchAllAssociative('SELECT * FROM station') as $station) { $this->connection->update( 'station', [ 'radio_media_dir' => $station['radio_base_dir'] . '/media', 'radio_playlists_dir' => $station['radio_base_dir'] . '/playlists', 'radio_config_dir' => $station['radio_base_dir'] . '/config', ], [ 'id' => $station['id'], ] ); } } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station DROP radio_media_dir, DROP radio_playlists_dir, DROP radio_config_dir'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170510082607.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
299
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Add relay URL to mountpoint table, update Shoutcast 2 stations to have one default mount point. */ final class Version20170412210654 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_mounts ADD relay_url VARCHAR(255) DEFAULT NULL'); } public function postup(Schema $schema): void { $allStations = $this->connection->fetchAllAssociative( "SELECT * FROM station WHERE frontend_type='shoutcast2'" ); foreach ($allStations as $station) { $this->connection->insert('station_mounts', [ 'station_id' => $station['id'], 'name' => '/radio.mp3', 'is_default' => 1, 'fallback_mount' => '/autodj.mp3', 'enable_streamers' => 1, 'enable_autodj' => 1, 'autodj_format' => 'mp3', 'autodj_bitrate' => 128, ]); } } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_mounts DROP relay_url'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170412210654.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
316
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use App\Entity\Attributes\StableMigration; use Doctrine\DBAL\Schema\Schema; #[ StableMigration('0.18.1'), StableMigration('0.18.0') ] final class Version20230410210554 extends AbstractMigration { public function getDescription(): string { return 'Add new Dropbox-related keys.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE storage_location ADD dropbox_app_key VARCHAR(50) DEFAULT NULL, ADD dropbox_app_secret VARCHAR(150) DEFAULT NULL, ADD dropbox_refresh_token VARCHAR(255) DEFAULT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE storage_location DROP dropbox_app_key, DROP dropbox_app_secret, DROP dropbox_refresh_token'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20230410210554.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20210105061553 extends AbstractMigration { public function getDescription(): string { return 'Add a separate setting for showing/hiding the "Download" button in On-Demand streaming.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD enable_on_demand_download TINYINT(1) NOT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station DROP enable_on_demand_download'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20210105061553.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
139
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Move all playlists that were previously "random" into the new "shuffled" type. */ final class Version20180830003036 extends AbstractMigration { public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('-- "Ignore Migration"'); } public function postup(Schema $schema): void { $this->connection->update('station_playlists', [ 'playback_order' => 'shuffle', ], [ 'playback_order' => 'random', ]); } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('-- "Ignore Migration"'); } public function postdown(Schema $schema): void { $this->connection->update('station_playlists', [ 'playback_order' => 'random', ], [ 'playback_order' => 'shuffle', ]); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20180830003036.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
252
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20220530010809 extends AbstractMigration { public function getDescription(): string { return 'Add artwork file to StationStreamer'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_streamers ADD art_updated_at INT NOT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_streamers DROP art_updated_at'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20220530010809.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20201204043539 extends AbstractMigration { public function getDescription(): string { return 'Settings migration'; } public function preUp(Schema $schema): void { $settingsRaw = $this->connection->fetchAllAssociative('SELECT * FROM settings WHERE setting_value IS NOT NULL'); $settings = []; foreach ($settingsRaw as $row) { $settings[$row['setting_key']] = json_decode($row['setting_value'], true, 512, JSON_THROW_ON_ERROR); } $newSettings = array_filter( [ 'baseUrl' => $settings['base_url'] ?? null, 'instanceName' => $settings['instance_name'] ?? null, 'preferBrowserUrl' => $this->toBool($settings['prefer_browser_url'] ?? null), 'useRadioProxy' => $this->toBool($settings['use_radio_proxy'] ?? null), 'historyKeepDays' => $this->toInt($settings['history_keep_days'] ?? null), 'alwaysUseSsl' => $this->toBool($settings['always_use_ssl'] ?? null), 'apiAccessControl' => $settings['api_access_control'] ?? null, 'enableWebsockets' => $this->toBool($settings['nowplaying_use_websockets'] ?? null), 'analytics' => $settings['analytics'] ?? null, 'checkForUpdates' => $this->toBool($settings['central_updates_channel'] ?? null), 'appUniqueIdentifier' => $settings['central_app_uuid'] ?? null, 'updateResults' => $settings['central_update_results'] ?? null, 'updateLastRun' => $this->toInt($settings['central_update_last_run'] ?? null), 'hideAlbumArt' => $this->toBool($settings['hide_album_art'] ?? null), 'homepageRedirectUrl' => $settings['homepage_redirect_url'] ?? null, 'defaultAlbumArtUrl' => $settings['default_album_art_url'] ?? null, 'hideProductName' => $this->toBool($settings['hide_product_name'] ?? null), 'publicTheme' => $settings['public_theme'] ?? null, 'publicCustomCss' => $settings['custom_css_public'] ?? null, 'publicCustomJs' => $settings['custom_js_public'] ?? null, 'internalCustomCss' => $settings['custom_css_internal'] ?? null, 'backupEnabled' => $this->toBool($settings['backup_enabled'] ?? null), 'backupTimeCode' => $settings['backup_time'] ?? null, 'backupExcludeMedia' => $this->toBool($settings['backup_exclude_media'] ?? null), 'backupKeepCopies' => $settings['backup_keep_copies'] ?? null, 'backupStorageLocation' => $this->toInt($settings['backup_storage_location'] ?? null), 'backupLastRun' => $this->toInt($settings['backup_last_run'] ?? null), 'backupLastResult' => $settings['backup_last_result'] ?? null, 'backupLastOutput' => $settings['backup_last_output'] ?? null, 'setupCompleteTime' => $this->toInt($settings['setup_complete'] ?? null), 'nowplaying' => $settings['nowplaying'] ?? null, 'syncNowplayingLastRun' => $this->toInt( $settings['nowplaying_last_run'] ?? null ), 'syncShortLastRun' => $this->toInt($settings['sync_fast_last_run'] ?? null), 'syncMediumLastRun' => $this->toInt($settings['sync_last_run'] ?? null), 'syncLongLastRun' => $this->toInt($settings['sync_slow_last_run'] ?? null), 'externalIp' => $settings['external_ip'] ?? null, 'geoliteLastRun' => $this->toInt($settings['geolite_last_run'] ?? null), ], static function ($value) { return null !== $value; } ); $this->connection->executeStatement( <<<'SQL' DELETE FROM settings SQL ); foreach ($newSettings as $settingKey => $settingValue) { $this->connection->insert('settings', [ 'setting_key' => $settingKey, 'setting_value' => json_encode($settingValue, JSON_THROW_ON_ERROR), ]); } } private function toInt(mixed $value): ?int { return (null === $value) ? null : (int)$value; } private function toBool(mixed $value): ?bool { return (null === $value) ? null : (bool)$value; } public function up(Schema $schema): void { $this->addSql('-- "No Query"'); } public function down(Schema $schema): void { $this->addSql('-- "No Query"'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20201204043539.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,100
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20190429025906 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists ADD backend_options VARCHAR(255) DEFAULT NULL'); } public function postup(Schema $schema): void { $playlists = $this->connection->fetchAllAssociative('SELECT sp.* FROM station_playlists AS sp'); foreach ($playlists as $playlist) { $backendOptions = []; if ($playlist['interrupt_other_songs']) { $backendOptions[] = 'interrupt'; } if ($playlist['loop_playlist_once']) { $backendOptions[] = 'loop_once'; } if ($playlist['play_single_track']) { $backendOptions[] = 'single_track'; } $this->connection->update('station_playlists', [ 'backend_options' => implode(',', $backendOptions), ], [ 'id' => $playlist['id'], ]); } } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists DROP backend_options'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20190429025906.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
280
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Make media length an INT instead of SMALLINT for songs longer than 9 hours (!) */ final class Version20180716185805 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_media CHANGE length length INT NOT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_media CHANGE length length SMALLINT NOT NULL'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20180716185805.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20200417082209 extends AbstractMigration { public function getDescription(): string { return 'Expand indices for improved performance.'; } public function up(Schema $schema): void { $this->addSql('DROP INDEX update_idx ON listener'); $this->addSql('DROP INDEX search_idx ON listener'); $this->addSql('CREATE INDEX idx_timestamps ON listener (timestamp_end, timestamp_start)'); $this->addSql('DROP INDEX history_idx ON song_history'); $this->addSql('CREATE INDEX idx_timestamp_cued ON song_history (timestamp_cued)'); $this->addSql('CREATE INDEX idx_timestamp_start ON song_history (timestamp_start)'); $this->addSql('CREATE INDEX idx_timestamp_end ON song_history (timestamp_end)'); $this->addSql('CREATE INDEX idx_short_name ON station (short_name)'); } public function down(Schema $schema): void { $this->addSql('DROP INDEX idx_timestamps ON listener'); $this->addSql('CREATE INDEX update_idx ON listener (listener_hash)'); $this->addSql('CREATE INDEX search_idx ON listener (listener_uid, timestamp_end)'); $this->addSql('DROP INDEX idx_timestamp_cued ON song_history'); $this->addSql('DROP INDEX idx_timestamp_start ON song_history'); $this->addSql('DROP INDEX idx_timestamp_end ON song_history'); $this->addSql('CREATE INDEX history_idx ON song_history (timestamp_start, timestamp_end, listeners_start)'); $this->addSql('DROP INDEX idx_short_name ON station'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20200417082209.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
382
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20170502202418 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE settings CHANGE setting_value setting_value LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:json_array)\''); $this->addSql('ALTER TABLE song_history CHANGE delta_points delta_points LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:json_array)\''); $this->addSql('ALTER TABLE station CHANGE frontend_config frontend_config LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:json_array)\', CHANGE backend_config backend_config LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:json_array)\', CHANGE nowplaying_data nowplaying_data LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:json_array)\', CHANGE automation_settings automation_settings LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:json_array)\''); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE settings CHANGE setting_value setting_value LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci COMMENT \'(DC2Type:json)\''); $this->addSql('ALTER TABLE song_history CHANGE delta_points delta_points LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci COMMENT \'(DC2Type:json)\''); $this->addSql('ALTER TABLE station CHANGE frontend_config frontend_config LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci COMMENT \'(DC2Type:json)\', CHANGE backend_config backend_config LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci COMMENT \'(DC2Type:json)\', CHANGE nowplaying_data nowplaying_data LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci COMMENT \'(DC2Type:json)\', CHANGE automation_settings automation_settings LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci COMMENT \'(DC2Type:json)\''); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170502202418.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
445
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20161122035237 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('DROP INDEX path_unique_idx ON station_media'); $this->addSql('CREATE UNIQUE INDEX path_unique_idx ON station_media (path, station_id)'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('DROP INDEX path_unique_idx ON station_media'); $this->addSql('CREATE UNIQUE INDEX path_unique_idx ON station_media (path)'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20161122035237.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20190429040410 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists DROP interrupt_other_songs, DROP loop_playlist_once, DROP play_single_track'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists ADD interrupt_other_songs TINYINT(1) NOT NULL, ADD loop_playlist_once TINYINT(1) NOT NULL, ADD play_single_track TINYINT(1) NOT NULL'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20190429040410.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
159
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20201027130404 extends AbstractMigration { public function getDescription(): string { return 'Song storage consolidation, part 1.'; } public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('CREATE TABLE IF NOT EXISTS storage_location(id INT AUTO_INCREMENT NOT NULL, type VARCHAR(50) NOT NULL, adapter VARCHAR(50) NOT NULL, path VARCHAR(255) DEFAULT NULL, s3_credential_key VARCHAR(255) DEFAULT NULL, s3_credential_secret VARCHAR(255) DEFAULT NULL, s3_region VARCHAR(150) DEFAULT NULL, s3_version VARCHAR(150) DEFAULT NULL, s3_bucket VARCHAR(255) DEFAULT NULL, s3_endpoint VARCHAR(255) DEFAULT NULL, storage_quota BIGINT DEFAULT NULL, storage_used BIGINT DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_general_ci` ENGINE = InnoDB'); $this->addSql('ALTER TABLE station ADD media_storage_location_id INT DEFAULT NULL, ADD recordings_storage_location_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE station ADD CONSTRAINT FK_9F39F8B1C896ABC5 FOREIGN KEY (media_storage_location_id) REFERENCES storage_location (id) ON DELETE SET NULL'); $this->addSql('ALTER TABLE station ADD CONSTRAINT FK_9F39F8B15C7361BE FOREIGN KEY (recordings_storage_location_id) REFERENCES storage_location (id) ON DELETE SET NULL'); $this->addSql('CREATE INDEX IDX_9F39F8B1C896ABC5 ON station (media_storage_location_id)'); $this->addSql('CREATE INDEX IDX_9F39F8B15C7361BE ON station (recordings_storage_location_id)'); $this->addSql('ALTER TABLE station_media DROP FOREIGN KEY FK_32AADE3A21BDB235'); $this->addSql('DROP INDEX IDX_32AADE3A21BDB235 ON station_media'); $this->addSql('DROP INDEX path_unique_idx ON station_media'); $this->addSql('ALTER TABLE station_media ADD storage_location_id INT NOT NULL'); } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('ALTER TABLE station DROP FOREIGN KEY FK_9F39F8B1C896ABC5'); $this->addSql('ALTER TABLE station DROP FOREIGN KEY FK_9F39F8B15C7361BE'); $this->addSql('DROP INDEX IDX_9F39F8B1C896ABC5 ON station'); $this->addSql('DROP INDEX IDX_9F39F8B15C7361BE ON station'); $this->addSql('DROP TABLE storage_location'); $this->addSql('ALTER TABLE station DROP media_storage_location_id, DROP recordings_storage_location_id'); $this->addSql('DROP INDEX IDX_32AADE3ACDDD8AF ON station_media'); $this->addSql('DROP INDEX path_unique_idx ON station_media'); $this->addSql('ALTER TABLE station_media DROP storage_location_id'); $this->addSql('ALTER TABLE station_media CHANGE storage_location_id station_id INT NOT NULL'); $this->addSql('ALTER TABLE station_media ADD CONSTRAINT FK_32AADE3A21BDB235 FOREIGN KEY (station_id) REFERENCES station (id) ON DELETE CASCADE'); $this->addSql('CREATE INDEX IDX_32AADE3A21BDB235 ON station_media (station_id)'); $this->addSql('CREATE UNIQUE INDEX path_unique_idx ON station_media (path, station_id)'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20201027130404.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
837
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20170622223025 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD nowplaying LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:array)\', DROP nowplaying_data'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station ADD nowplaying_data LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci COMMENT \'(DC2Type:json_array)\', DROP nowplaying'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170622223025.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20190402224811 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists ADD play_single_track TINYINT(1) NOT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists DROP play_single_track'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20190402224811.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20220415093355 extends AbstractMigration { public function getDescription(): string { return 'Add device and location metadata to Listeners table.'; } public function up(Schema $schema): void { $this->addSql( 'ALTER TABLE listener ADD location_description VARCHAR(255) NOT NULL, ADD location_region VARCHAR(150) DEFAULT NULL, ADD location_city VARCHAR(150) DEFAULT NULL, ADD location_country VARCHAR(2) DEFAULT NULL, ADD location_lat NUMERIC(10, 6) DEFAULT NULL, ADD location_lon NUMERIC(10, 6) DEFAULT NULL, ADD device_client VARCHAR(255) NOT NULL, ADD device_is_browser TINYINT(1) NOT NULL, ADD device_is_mobile TINYINT(1) NOT NULL, ADD device_is_bot TINYINT(1) NOT NULL, ADD device_browser_family VARCHAR(150) NOT NULL, ADD device_os_family VARCHAR(150) NOT NULL' ); $this->addSql('CREATE INDEX idx_statistics_country ON listener (location_country)'); $this->addSql('CREATE INDEX idx_statistics_os ON listener (device_os_family)'); $this->addSql('CREATE INDEX idx_statistics_browser ON listener (device_browser_family)'); } public function down(Schema $schema): void { $this->addSql('DROP INDEX idx_statistics_country ON listener'); $this->addSql('DROP INDEX idx_statistics_os ON listener'); $this->addSql('DROP INDEX idx_statistics_browser ON listener'); $this->addSql( 'ALTER TABLE listener DROP location_description, DROP location_region, DROP location_city, DROP location_country, DROP location_lat, DROP location_lon, DROP device_client, DROP device_is_browser, DROP device_is_mobile, DROP device_is_bot, DROP device_browser_family, DROP device_os_family' ); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20220415093355.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
411
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20170606173152 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD has_started TINYINT(1) NOT NULL'); $this->addSql('UPDATE station SET has_started=1'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station DROP has_started'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170606173152.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Add request threshold to Station entity. */ final class Version20170414205418 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD request_threshold INT DEFAULT NULL'); } public function postup(Schema $schema): void { $this->connection->update('station', [ 'request_threshold' => 15, ], [ 'enable_requests' => 1, ]); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station DROP request_threshold'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170414205418.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
180
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20220102033308 extends AbstractMigration { public function getDescription(): string { return 'New Settings columns for new sync process.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE settings ADD sync_disabled TINYINT(1) NOT NULL, ADD sync_last_run INT NOT NULL, DROP nowplaying, DROP sync_nowplaying_last_run, DROP sync_short_last_run, DROP sync_medium_last_run, DROP sync_long_last_run'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE settings ADD nowplaying LONGTEXT CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci` COMMENT \'(DC2Type:json)\', ADD sync_short_last_run INT NOT NULL, ADD sync_medium_last_run INT NOT NULL, ADD sync_long_last_run INT NOT NULL, DROP sync_disabled, CHANGE sync_last_run sync_nowplaying_last_run INT NOT NULL'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20220102033308.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
234
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20201215175111 extends AbstractMigration { public function getDescription(): string { return 'Expand the possible length of various cue and fade values in StationMedia.'; } public function up(Schema $schema): void { $this->addSql( 'ALTER TABLE station_media CHANGE amplify amplify NUMERIC(6, 1) DEFAULT NULL, CHANGE fade_overlap fade_overlap NUMERIC(6, 1) DEFAULT NULL, CHANGE fade_in fade_in NUMERIC(6, 1) DEFAULT NULL, CHANGE fade_out fade_out NUMERIC(6, 1) DEFAULT NULL, CHANGE cue_in cue_in NUMERIC(6, 1) DEFAULT NULL, CHANGE cue_out cue_out NUMERIC(6, 1) DEFAULT NULL' ); } public function down(Schema $schema): void { $this->addSql( 'ALTER TABLE station_media CHANGE amplify amplify NUMERIC(3, 1) DEFAULT NULL, CHANGE fade_overlap fade_overlap NUMERIC(3, 1) DEFAULT NULL, CHANGE fade_in fade_in NUMERIC(3, 1) DEFAULT NULL, CHANGE fade_out fade_out NUMERIC(3, 1) DEFAULT NULL, CHANGE cue_in cue_in NUMERIC(5, 1) DEFAULT NULL, CHANGE cue_out cue_out NUMERIC(5, 1) DEFAULT NULL' ); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20201215175111.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
312
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20211230194621 extends AbstractMigration { public function getDescription(): string { return 'Add "is_visible" field to queue items to optimize queries.'; } public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('ALTER TABLE station_queue ADD is_visible TINYINT(1) NOT NULL'); } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('ALTER TABLE station_queue DROP is_visible'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20211230194621.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
165
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use App\Entity\Attributes\StableMigration; use Doctrine\DBAL\Schema\Schema; #[ StableMigration('0.20.0') ] final class Version20240511123636 extends AbstractMigration { public function getDescription(): string { return 'Remove DB cache.'; } public function up(Schema $schema): void { $this->addSql('DROP TABLE cache_items'); } public function down(Schema $schema): void { $this->addSql('CREATE TABLE cache_items (item_id VARBINARY(255) NOT NULL, item_data MEDIUMBLOB NOT NULL, item_lifetime INT UNSIGNED DEFAULT NULL, item_time INT UNSIGNED NOT NULL, PRIMARY KEY(item_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_general_ci` ENGINE = InnoDB COMMENT = \'\' '); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20240511123636.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
196
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20170510091820 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD radio_base_dir VARCHAR(255) DEFAULT NULL, DROP radio_playlists_dir, DROP radio_config_dir'); } public function postup(Schema $schema): void { foreach ($this->connection->fetchAllAssociative('SELECT * FROM station') as $station) { $this->connection->update( 'station', [ 'radio_base_dir' => str_replace('/media', '', $station['radio_media_dir']), ], [ 'id' => $station['id'], ] ); } } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station ADD radio_config_dir VARCHAR(255) DEFAULT NULL COLLATE utf8_unicode_ci, CHANGE radio_base_dir radio_playlists_dir VARCHAR(255) DEFAULT NULL COLLATE utf8_unicode_ci'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170510091820.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
273
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20170524090814 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_media ADD isrc VARCHAR(15) DEFAULT NULL'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_media DROP isrc'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170524090814.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
139
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use App\Entity\Migration\Traits\UpdateAllRecords; use Doctrine\DBAL\Schema\Schema; final class Version20180412055024 extends AbstractMigration { use UpdateAllRecords; public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists ADD source VARCHAR(50) NOT NULL, ADD include_in_requests TINYINT(1) NOT NULL'); } public function postup(Schema $schema): void { $this->updateAllRecords('station_playlists', [ 'include_in_requests' => '1', ]); $this->updateAllRecords('station_playlists', [ 'source' => 'default', ]); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists DROP source, DROP include_in_requests'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20180412055024.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
199
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20190331215627 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists ADD remote_timeout SMALLINT NOT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists DROP remote_timeout'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20190331215627.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
115
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20190818003805 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists ADD queue LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:array)\''); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists DROP queue'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20190818003805.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
123
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Manually re-shuffle any "shuffled" playlists via their weights in the DB. */ final class Version20181016144143 extends AbstractMigration { public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('-- "Ignore Migration"'); } public function postup(Schema $schema): void { $shuffledPlaylists = $this->connection->fetchAllAssociative( 'SELECT sp.* FROM station_playlists AS sp WHERE sp.playback_order = :order', [ 'order' => 'shuffle', ] ); foreach ($shuffledPlaylists as $playlist) { $allMedia = $this->connection->fetchAllAssociative( 'SELECT spm.* FROM station_playlist_media AS spm WHERE spm.playlist_id = :playlist_id ORDER BY RAND()', [ 'playlist_id' => $playlist['id'], ] ); $weight = 1; foreach ($allMedia as $row) { $this->connection->update('station_playlist_media', [ 'weight' => $weight, ], [ 'id' => $row['id'], ]); $weight++; } } } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('-- "Ignore Migration"'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20181016144143.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
341
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20201109203951 extends AbstractMigration { public function getDescription(): string { return 'Add unique constraint for analytics.'; } public function preUp(Schema $schema): void { $analytics = $this->connection->fetchAllAssociative('SELECT id, station_id, type, moment FROM analytics ORDER BY id ASC'); $rows = []; foreach ($analytics as $row) { $rowKey = ($row['station_id'] ?? 'all') . '_' . $row['type'] . '_' . $row['moment']; if (isset($rows[$rowKey])) { $this->connection->delete('analytics', [ 'id' => $row['id'], ], [ 'id' => ParameterType::INTEGER, ]); } else { $rows[$rowKey] = $row['id']; } } } public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('CREATE UNIQUE INDEX stats_unique_idx ON analytics (station_id, type, moment)'); } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('DROP INDEX stats_unique_idx ON analytics'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20201109203951.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
337
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20181120100629 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists ADD remote_type VARCHAR(25) DEFAULT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists DROP remote_type'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20181120100629.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
117
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20201125220258 extends AbstractMigration { public function getDescription(): string { return 'Expand the length of the "text" field.'; } public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('ALTER TABLE song_history CHANGE text text VARCHAR(303) DEFAULT NULL'); $this->addSql('ALTER TABLE station_media CHANGE text text VARCHAR(303) DEFAULT NULL'); $this->addSql('ALTER TABLE station_queue CHANGE text text VARCHAR(303) DEFAULT NULL'); } public function postUp(Schema $schema): void { $this->connection->executeQuery('UPDATE station_media SET text=CONCAT(artist, \' - \', title)'); } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('ALTER TABLE song_history CHANGE text text VARCHAR(150) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci`'); $this->addSql('ALTER TABLE station_media CHANGE text text VARCHAR(150) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci`'); $this->addSql('ALTER TABLE station_queue CHANGE text text VARCHAR(150) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci`'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20201125220258.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
352
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use App\Entity\Station; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20171208093239 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD short_name VARCHAR(100) DEFAULT NULL'); } public function postup(Schema $schema): void { foreach ($this->connection->fetchAllAssociative('SELECT * FROM station') as $record) { $this->connection->update( 'station', [ 'short_name' => Station::generateShortName($record['name']), ], [ 'id' => $record['id'], ] ); } } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station DROP short_name'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20171208093239.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
205
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\ArrayParameterType; use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20191024185005 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_media ADD art_updated_at INT NOT NULL'); } public function postUp(Schema $schema): void { foreach ($this->connection->fetchAllAssociative('SELECT s.* FROM station AS s') as $station) { $this->write('Migrating album art for station "' . $station['name'] . '"...'); $baseDir = $station['radio_base_dir']; $artDir = $baseDir . '/album_art'; $getMediaQuery = $this->connection->executeQuery( 'SELECT unique_id FROM station_media WHERE station_id = ?', [$station['id']], [ParameterType::INTEGER] ); $mediaRowsTotal = 0; $mediaRowsToUpdate = []; while ($row = $getMediaQuery->fetchAssociative()) { $mediaRowsTotal++; $artPath = $artDir . '/' . $row['unique_id'] . '.jpg'; if (file_exists($artPath)) { $mediaRowsToUpdate[] = $row['unique_id']; } } $this->write('Album art exists for ' . count($mediaRowsToUpdate) . ' of ' . $mediaRowsTotal . ' media.'); $this->connection->executeStatement( 'UPDATE station_media SET art_updated_at=UNIX_TIMESTAMP() WHERE unique_id IN (?)', [$mediaRowsToUpdate], [ArrayParameterType::STRING] ); } } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_media DROP art_updated_at'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20191024185005.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
424
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20210419043231 extends AbstractMigration { public function getDescription(): string { return 'Settings entity migration, part 2'; } public function preUp(Schema $schema): void { $oldSettings = []; $oldSettingsRaw = $this->connection->fetchAllAssociative( 'SELECT setting_key, setting_value FROM old_settings' ); foreach ($oldSettingsRaw as $row) { $key = $row['setting_key']; $key = mb_strtolower(preg_replace('~(?<=\\w)([A-Z])~u', '_$1', $key)); $value = $row['setting_value']; $value = ($value === null || $value === '') ? null : json_decode($value, true, 512, JSON_THROW_ON_ERROR); $oldSettings[$key] = $value; } $newSettings = []; $appUniqueIdentifier = $oldSettings['app_unique_identifier'] ?? null; if (empty($appUniqueIdentifier)) { $appUniqueIdentifier = $this->connection->executeQuery('SELECT UUID()')->fetchOne(); } $newSettings['app_unique_identifier'] = $appUniqueIdentifier; $textFields = [ 'public_custom_css', 'public_custom_js', 'internal_custom_css', 'backup_last_result', 'backup_last_output', ]; $stringFields = [ 'base_url' => 255, 'instance_name' => 255, 'api_access_control' => 255, 'analytics' => 50, 'public_theme' => 50, 'homepage_redirect_url' => 255, 'default_album_art_url' => 255, 'last_fm_api_key' => 255, 'backup_time_code' => 4, 'external_ip' => 45, 'geolite_license_key' => 255, 'mail_sender_name' => 255, 'mail_sender_email' => 255, 'mail_smtp_host' => 255, 'mail_smtp_username' => 255, 'mail_smtp_password' => 255, 'avatar_service' => 25, 'avatar_default_url' => 255, ]; $boolFields = [ 'prefer_browser_url', 'use_radio_proxy', 'always_use_ssl', 'enable_websockets', 'check_for_updates', 'hide_album_art', 'use_external_album_art_when_processing_media', 'use_external_album_art_in_apis', 'hide_product_name', 'backup_enabled', 'backup_exclude_media', 'enable_advanced_features', 'mail_enabled', 'mail_smtp_secure', ]; $smallIntFields = [ 'history_keep_days', 'backup_keep_copies', 'mail_smtp_port', ]; $intFields = [ 'update_last_run', 'backup_storage_location', 'backup_last_run', 'setup_complete_time', 'sync_nowplaying_last_run', 'sync_short_last_run', 'sync_medium_last_run', 'sync_long_last_run', 'geolite_last_run', ]; foreach ($textFields as $field) { $value = $oldSettings[$field] ?? null; if (null === $value) { continue; } $newSettings[$field] = $value; } foreach ($stringFields as $field => $length) { $value = $oldSettings[$field] ?? null; if (null === $value) { continue; } $newSettings[$field] = mb_substr((string)$value, 0, $length, 'UTF-8'); } foreach ($boolFields as $field) { $value = $oldSettings[$field] ?? null; if (null === $value) { $newSettings[$field] = 0; continue; } $newSettings[$field] = $value ? 1 : 0; } foreach ($smallIntFields as $field) { $value = $oldSettings[$field] ?? null; if (null === $value) { $newSettings[$field] = 0; continue; } $value = (int)$value; if ($value > 32767) { $value = 32767; } $newSettings[$field] = $value; } foreach ($intFields as $field) { $value = $oldSettings[$field] ?? null; if (null === $value) { $value = 0; } $newSettings[$field] = (int)$value; } $this->connection->executeQuery('DELETE FROM new_settings'); $this->connection->insert('new_settings', $newSettings); } public function up(Schema $schema): void { $this->addSql('RENAME TABLE new_settings TO settings'); $this->addSql('DROP TABLE old_settings'); } public function down(Schema $schema): void { $this->addSql('RENAME TABLE settings TO new_settings'); $this->addSql('CREATE TABLE old_settings (setting_key VARCHAR(64) CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_general_ci`, setting_value LONGTEXT CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci` COMMENT \'(DC2Type:json)\', PRIMARY KEY(setting_key)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB COMMENT = \'\' '); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20210419043231.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,251
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20221008015609 extends AbstractMigration { public function getDescription(): string { return 'Support App Key and App Secret for Dropbox Storage Locations'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE storage_location ADD dropbox_app_key VARCHAR(255) DEFAULT NULL, ADD dropbox_app_secret VARCHAR(255) DEFAULT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE storage_location DROP dropbox_app_key, DROP dropbox_app_secret'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20221008015609.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
149
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20240319115513 extends AbstractMigration { public function getDescription(): string { return 'Make Podcast Episode publish date always have a value.'; } public function up(Schema $schema): void { $this->addSql( <<<'SQL' UPDATE podcast_episode SET publish_at = created_at WHERE publish_at IS NULL SQL ); $this->addSql('ALTER TABLE podcast_episode CHANGE publish_at publish_at INT NOT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE podcast_episode CHANGE publish_at publish_at INT DEFAULT NULL'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20240319115513.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
167
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Schema\Schema; use RuntimeException; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20181202180617 extends AbstractMigration { public function preup(Schema $schema): void { foreach ($this->connection->fetchAllAssociative('SELECT s.* FROM station AS s') as $station) { $this->write('Migrating album art for station "' . $station['name'] . '"...'); $baseDir = $station['radio_base_dir']; $artDir = $baseDir . '/album_art'; if (!mkdir($artDir) && !is_dir($artDir)) { throw new RuntimeException(sprintf('Directory "%s" was not created', $artDir)); } $stmt = $this->connection->executeQuery( 'SELECT sm.unique_id, sma.art FROM station_media AS sm JOIN station_media_art sma on sm.id = sma.media_id WHERE sm.station_id = ?', [$station['id']], [ParameterType::INTEGER] ); while ($artRow = $stmt->fetchAssociative()) { $artPath = $artDir . '/' . $artRow['unique_id'] . '.jpg'; file_put_contents($artPath, $artRow['art']); } } } public function up(Schema $schema): void { $this->addSql('DROP TABLE station_media_art'); } public function down(Schema $schema): void { $this->addSql('CREATE TABLE station_media_art (id INT AUTO_INCREMENT NOT NULL, media_id INT NOT NULL, art LONGBLOB DEFAULT NULL, UNIQUE INDEX UNIQ_35E0CAB2EA9FDD75 (media_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('ALTER TABLE station_media_art ADD CONSTRAINT FK_35E0CAB2EA9FDD75 FOREIGN KEY (media_id) REFERENCES station_media (id) ON DELETE CASCADE'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20181202180617.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
469
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20161117161959 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_mounts ADD frontend_config LONGTEXT DEFAULT NULL'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_mounts DROP frontend_config'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20161117161959.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
139
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20180425050351 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->changeCharset('utf8mb4_bin'); } private function changeCharset(string $collate): void { $sqlLines = [ 'ALTER TABLE `station_media` DROP FOREIGN KEY FK_32AADE3AA0BDB2F3', 'ALTER TABLE `song_history` DROP FOREIGN KEY FK_2AD16164A0BDB2F3', 'ALTER TABLE `station_media` CONVERT TO CHARACTER SET utf8mb4 COLLATE ' . $collate, 'ALTER TABLE `song_history` CONVERT TO CHARACTER SET utf8mb4 COLLATE ' . $collate, 'ALTER TABLE `songs` CONVERT TO CHARACTER SET utf8mb4 COLLATE ' . $collate, 'ALTER TABLE `song_history` ADD CONSTRAINT FK_2AD16164A0BDB2F3 FOREIGN KEY (song_id) REFERENCES songs (id) ON DELETE CASCADE', 'ALTER TABLE `station_media` ADD CONSTRAINT FK_32AADE3AA0BDB2F3 FOREIGN KEY (song_id) REFERENCES songs (id) ON DELETE SET NULL', ]; foreach ($sqlLines as $sql) { $this->addSql($sql); } } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->changeCharset('utf8mb4_unicode_ci'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20180425050351.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
373
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20180320052444 extends AbstractMigration { public function preup(Schema $schema): void { // Avoid FK errors with station art $this->connection->executeStatement( 'DELETE FROM station_media_art WHERE media_id NOT IN (SELECT id FROM station_media)' ); } public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_media_art ADD CONSTRAINT FK_35E0CAB2EA9FDD75 FOREIGN KEY (media_id) REFERENCES station_media (id)'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_media_art DROP FOREIGN KEY FK_35E0CAB2EA9FDD75'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20180320052444.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
202
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use App\Entity\Attributes\StableMigration; use Doctrine\DBAL\Schema\Schema; #[StableMigration('0.17.1')] final class Version20220611123923 extends AbstractMigration { public function getDescription(): string { return 'Add current_song relation to Station.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD current_song_id INT DEFAULT NULL'); $this->addSql( 'ALTER TABLE station ADD CONSTRAINT FK_9F39F8B1AB03776 FOREIGN KEY (current_song_id) REFERENCES song_history (id) ON DELETE SET NULL' ); $this->addSql('CREATE INDEX IDX_9F39F8B1AB03776 ON station (current_song_id)'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station DROP FOREIGN KEY FK_9F39F8B1AB03776'); $this->addSql('DROP INDEX IDX_9F39F8B1AB03776 ON station'); $this->addSql('ALTER TABLE station DROP current_song_id'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20220611123923.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
265
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Update the index on song_history. */ final class Version20180826011103 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('DROP INDEX sort_idx ON song_history'); $this->addSql('CREATE INDEX history_idx ON song_history (timestamp_start, timestamp_end, listeners_start)'); } public function down(Schema $schema): void { $this->addSql('DROP INDEX history_idx ON song_history'); $this->addSql('CREATE INDEX sort_idx ON song_history (timestamp_start)'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20180826011103.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
148
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20200124183957 extends AbstractMigration { public function getDescription(): string { return 'Add "amplify" metadata to associate with station media.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_media ADD amplify NUMERIC(3, 1) DEFAULT NULL AFTER mtime'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_media DROP amplify'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20200124183957.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
147
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20170823204230 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists ADD schedule_days VARCHAR(50) DEFAULT NULL, ADD play_once_days VARCHAR(50) DEFAULT NULL'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_playlists DROP schedule_days, DROP play_once_days'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170823204230.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
157
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use App\Entity\Attributes\StableMigration; use Doctrine\DBAL\Schema\Schema; #[StableMigration('0.17.5')] final class Version20221102125558 extends AbstractMigration { public function getDescription(): string { return 'Add user-level 24-hour time setting.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE users ADD show_24_hour_time TINYINT(1) DEFAULT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE users DROP show_24_hour_time'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20221102125558.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
152
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20220626024436 extends AbstractMigration { public function getDescription(): string { return 'Add listeners to HLS streams.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_hls_streams ADD listeners INT NOT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_hls_streams DROP listeners'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20220626024436.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20210528180443 extends AbstractMigration { public function getDescription(): string { return 'Correct many tables having incorrectly nullable relation tables.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE api_keys CHANGE user_id user_id INT NOT NULL'); $this->addSql('ALTER TABLE podcast CHANGE storage_location_id storage_location_id INT NOT NULL'); $this->addSql('ALTER TABLE podcast_category CHANGE podcast_id podcast_id CHAR(36) NOT NULL COMMENT \'(DC2Type:guid)\''); $this->addSql('ALTER TABLE podcast_episode CHANGE podcast_id podcast_id CHAR(36) NOT NULL COMMENT \'(DC2Type:guid)\''); $this->addSql('ALTER TABLE podcast_media CHANGE storage_location_id storage_location_id INT NOT NULL'); $this->addSql('ALTER TABLE settings CHANGE app_unique_identifier app_unique_identifier CHAR(36) NOT NULL COMMENT \'(DC2Type:guid)\''); $this->addSql('ALTER TABLE sftp_user CHANGE station_id station_id INT NOT NULL'); $this->addSql('ALTER TABLE station_playlist_folders CHANGE station_id station_id INT NOT NULL, CHANGE playlist_id playlist_id INT NOT NULL'); $this->addSql('ALTER TABLE station_streamer_broadcasts CHANGE station_id station_id INT NOT NULL, CHANGE streamer_id streamer_id INT NOT NULL'); $this->addSql('ALTER TABLE user_login_tokens CHANGE user_id user_id INT NOT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE api_keys CHANGE user_id user_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE podcast CHANGE storage_location_id storage_location_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE podcast_category CHANGE podcast_id podcast_id CHAR(36) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci` COMMENT \'(DC2Type:guid)\''); $this->addSql('ALTER TABLE podcast_episode CHANGE podcast_id podcast_id CHAR(36) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci` COMMENT \'(DC2Type:guid)\''); $this->addSql('ALTER TABLE podcast_media CHANGE storage_location_id storage_location_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE settings CHANGE app_unique_identifier app_unique_identifier CHAR(36) CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_general_ci` COMMENT \'(DC2Type:uuid)\''); $this->addSql('ALTER TABLE sftp_user CHANGE station_id station_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE station_playlist_folders CHANGE station_id station_id INT DEFAULT NULL, CHANGE playlist_id playlist_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE station_streamer_broadcasts CHANGE station_id station_id INT DEFAULT NULL, CHANGE streamer_id streamer_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE user_login_tokens CHANGE user_id user_id INT DEFAULT NULL'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20210528180443.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
675
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20210419033245 extends AbstractMigration { public function getDescription(): string { return 'Settings entity migration, part 1'; } public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('CREATE TABLE new_settings (app_unique_identifier CHAR(36) NOT NULL COMMENT \'(DC2Type:uuid)\', base_url VARCHAR(255) DEFAULT NULL, instance_name VARCHAR(255) DEFAULT NULL, prefer_browser_url TINYINT(1) NOT NULL, use_radio_proxy TINYINT(1) NOT NULL, history_keep_days SMALLINT NOT NULL, always_use_ssl TINYINT(1) NOT NULL, api_access_control VARCHAR(255) DEFAULT NULL, enable_websockets TINYINT(1) NOT NULL, analytics VARCHAR(50) DEFAULT NULL, check_for_updates TINYINT(1) NOT NULL, update_results LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:json)\', update_last_run INT NOT NULL, public_theme VARCHAR(50) DEFAULT NULL, hide_album_art TINYINT(1) NOT NULL, homepage_redirect_url VARCHAR(255) DEFAULT NULL, default_album_art_url VARCHAR(255) DEFAULT NULL, use_external_album_art_when_processing_media TINYINT(1) NOT NULL, use_external_album_art_in_apis TINYINT(1) NOT NULL, last_fm_api_key VARCHAR(255) DEFAULT NULL, hide_product_name TINYINT(1) NOT NULL, public_custom_css LONGTEXT DEFAULT NULL, public_custom_js LONGTEXT DEFAULT NULL, internal_custom_css LONGTEXT DEFAULT NULL, backup_enabled TINYINT(1) NOT NULL, backup_time_code VARCHAR(4) DEFAULT NULL, backup_exclude_media TINYINT(1) NOT NULL, backup_keep_copies SMALLINT NOT NULL, backup_storage_location INT DEFAULT NULL, backup_last_run INT NOT NULL, backup_last_result LONGTEXT DEFAULT NULL, backup_last_output LONGTEXT DEFAULT NULL, setup_complete_time INT NOT NULL, nowplaying LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:json)\', sync_nowplaying_last_run INT NOT NULL, sync_short_last_run INT NOT NULL, sync_medium_last_run INT NOT NULL, sync_long_last_run INT NOT NULL, external_ip VARCHAR(45) DEFAULT NULL, geolite_license_key VARCHAR(255) DEFAULT NULL, geolite_last_run INT NOT NULL, enable_advanced_features TINYINT(1) NOT NULL, mail_enabled TINYINT(1) NOT NULL, mail_sender_name VARCHAR(255) DEFAULT NULL, mail_sender_email VARCHAR(255) DEFAULT NULL, mail_smtp_host VARCHAR(255) DEFAULT NULL, mail_smtp_port SMALLINT NOT NULL, mail_smtp_username VARCHAR(255) DEFAULT NULL, mail_smtp_password VARCHAR(255) DEFAULT NULL, mail_smtp_secure TINYINT(1) NOT NULL, avatar_service VARCHAR(25) DEFAULT NULL, avatar_default_url VARCHAR(255) DEFAULT NULL, PRIMARY KEY(app_unique_identifier)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_general_ci` ENGINE = InnoDB'); $this->addSql('RENAME TABLE settings TO old_settings'); } public function down(Schema $schema): void { $this->addSql('DROP TABLE new_settings'); $this->addSql('RENAME TABLE old_settings TO settings'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20210419033245.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
742
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20181126073334 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('ALTER TABLE station ADD genre VARCHAR(150) DEFAULT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE station DROP genre'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20181126073334.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
111
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\Migrations\AbstractMigration as DoctrineAbstractMigration; abstract class AbstractMigration extends DoctrineAbstractMigration { public function isTransactional(): bool { return false; } } ```
/content/code_sandbox/backend/src/Entity/Migration/AbstractMigration.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
52
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use App\Entity\Attributes\StableMigration; use Doctrine\DBAL\Schema\Schema; #[ StableMigration('0.19.6'), StableMigration('0.19.7') ] final class Version20240425151151 extends AbstractMigration { public function getDescription(): string { return 'Add is_enabled flag for podcasts.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE podcast ADD is_enabled TINYINT(1) NOT NULL AFTER description'); $this->addSql(<<<'SQL' UPDATE podcast SET is_enabled=1 SQL); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE podcast DROP is_enabled'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20240425151151.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\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20171103075821 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_media ADD lyrics LONGTEXT DEFAULT NULL, ADD art LONGBLOB DEFAULT NULL'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE station_media DROP lyrics, DROP art'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20171103075821.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
147
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20200711002451 extends AbstractMigration { public function getDescription(): string { return 'Add Messenger messages table.'; } public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('CREATE TABLE messenger_messages (id BIGINT AUTO_INCREMENT NOT NULL, body LONGTEXT NOT NULL, headers LONGTEXT NOT NULL, queue_name VARCHAR(190) NOT NULL, created_at DATETIME NOT NULL, available_at DATETIME NOT NULL, delivered_at DATETIME DEFAULT NULL, INDEX IDX_75EA56E0FB7336F0 (queue_name), INDEX IDX_75EA56E0E3BD61CE (available_at), INDEX IDX_75EA56E016BA31DB (delivered_at), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_general_ci` ENGINE = InnoDB'); } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('DROP TABLE messenger_messages'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20200711002451.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
282
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20201231011833 extends AbstractMigration { public function getDescription(): string { return 'Make paths across the system consistent.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE station_media CHANGE path path VARCHAR(500) NOT NULL'); $this->addSql('ALTER TABLE station_playlist_folders CHANGE path path VARCHAR(500) NOT NULL'); $this->addSql('ALTER TABLE unprocessable_media CHANGE path path VARCHAR(500) NOT NULL'); } public function down(Schema $schema): void { $this->addSql( 'ALTER TABLE station_media CHANGE path path VARCHAR(500) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci`' ); $this->addSql( 'ALTER TABLE station_playlist_folders CHANGE path path VARCHAR(255) CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_general_ci`' ); $this->addSql( 'ALTER TABLE unprocessable_media CHANGE path path VARCHAR(500) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_general_ci`' ); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20201231011833.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
277
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20240221151753 extends AbstractMigration { public function getDescription(): string { return 'Add ability for podcasts to sync from playlists.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE podcast ADD playlist_id INT DEFAULT NULL, ADD source VARCHAR(50) NOT NULL, ADD playlist_auto_publish TINYINT(1) NOT NULL'); $this->addSql('ALTER TABLE podcast ADD CONSTRAINT FK_D7E805BD6BBD148 FOREIGN KEY (playlist_id) REFERENCES station_playlists (id) ON DELETE CASCADE'); $this->addSql('CREATE INDEX IDX_D7E805BD6BBD148 ON podcast (playlist_id)'); $this->addSql('ALTER TABLE podcast_episode ADD playlist_media_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE podcast_episode ADD CONSTRAINT FK_77EB2BD017421B18 FOREIGN KEY (playlist_media_id) REFERENCES station_media (id) ON DELETE CASCADE'); $this->addSql('CREATE UNIQUE INDEX UNIQ_77EB2BD017421B18 ON podcast_episode (playlist_media_id)'); $this->addSql( <<<'SQL' UPDATE podcast SET source='manual' SQL ); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE podcast DROP FOREIGN KEY FK_D7E805BD6BBD148'); $this->addSql('DROP INDEX IDX_D7E805BD6BBD148 ON podcast'); $this->addSql('ALTER TABLE podcast DROP playlist_id, DROP source, DROP playlist_auto_publish'); $this->addSql('ALTER TABLE podcast_episode DROP FOREIGN KEY FK_77EB2BD017421B18'); $this->addSql('DROP INDEX UNIQ_77EB2BD017421B18 ON podcast_episode'); $this->addSql('ALTER TABLE podcast_episode DROP playlist_media_id'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20240221151753.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
439
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20191101065730 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('CREATE TABLE station_playlist_schedules (id INT AUTO_INCREMENT NOT NULL, playlist_id INT DEFAULT NULL, start_time SMALLINT NOT NULL, end_time SMALLINT NOT NULL, start_date VARCHAR(10) DEFAULT NULL, end_date VARCHAR(10) DEFAULT NULL, days VARCHAR(50) DEFAULT NULL, INDEX IDX_C61009BA6BBD148 (playlist_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ENGINE = InnoDB'); $this->addSql('ALTER TABLE station_playlist_schedules ADD CONSTRAINT FK_C61009BA6BBD148 FOREIGN KEY (playlist_id) REFERENCES station_playlists (id) ON DELETE CASCADE'); } public function postUp(Schema $schema): void { $playlists = $this->connection->fetchAllAssociative( 'SELECT sp.* FROM station_playlists AS sp WHERE sp.type = ?', ['scheduled'], [ParameterType::STRING] ); foreach ($playlists as $row) { $this->connection->insert('station_playlist_schedules', [ 'playlist_id' => $row['id'], 'start_time' => $row['schedule_start_time'], 'end_time' => $row['schedule_end_time'], 'days' => $row['schedule_days'], ]); $this->connection->update('station_playlists', [ 'type' => 'default', ], [ 'id' => $row['id'], ]); } } public function down(Schema $schema): void { $this->addSql('DROP TABLE station_playlist_schedules'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20191101065730.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
419
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20170618013019 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema): void { $this->addSql('ALTER TABLE song_history ADD media_id INT DEFAULT NULL, ADD duration INT DEFAULT NULL'); $this->addSql('ALTER TABLE song_history ADD CONSTRAINT FK_2AD16164EA9FDD75 FOREIGN KEY (media_id) REFERENCES station_media (id) ON DELETE CASCADE'); $this->addSql('CREATE INDEX IDX_2AD16164EA9FDD75 ON song_history (media_id)'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->addSql('ALTER TABLE song_history DROP FOREIGN KEY FK_2AD16164EA9FDD75'); $this->addSql('DROP INDEX IDX_2AD16164EA9FDD75 ON song_history'); $this->addSql('ALTER TABLE song_history DROP media_id, DROP duration'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20170618013019.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
262
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; final class Version20201211164613 extends AbstractMigration { public function getDescription(): string { return 'Improve indexing on audit log records and clean up spurious settings records.'; } public function up(Schema $schema): void { $this->addSql('CREATE INDEX idx_search ON audit_log (class, user, identifier)'); } public function postUp(Schema $schema): void { $this->connection->delete( 'audit_log', [ 'class' => 'SettingsTable', 'user' => null, ] ); } public function down(Schema $schema): void { $this->addSql('DROP INDEX idx_search ON audit_log'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20201211164613.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
182
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use App\Entity\Attributes\StableMigration; use Doctrine\DBAL\Schema\Schema; #[StableMigration('0.17.0')] final class Version20220605052847 extends AbstractMigration { public function getDescription(): string { return 'Add selectable automatic backup format.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE settings ADD backup_format VARCHAR(255) DEFAULT NULL'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE settings DROP backup_format'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20220605052847.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
141
```php <?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20180428062526 extends AbstractMigration { public function up(Schema $schema): void { $this->addSql('CREATE TABLE station_playlist_media (id INT AUTO_INCREMENT NOT NULL, playlist_id INT NOT NULL, media_id INT NOT NULL, weight SMALLINT NOT NULL, last_played INT NOT NULL, INDEX IDX_EA70D7796BBD148 (playlist_id), INDEX IDX_EA70D779EA9FDD75 (media_id), UNIQUE INDEX idx_playlist_media (playlist_id, media_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); $this->addSql('ALTER TABLE station_playlist_media ADD CONSTRAINT FK_EA70D7796BBD148 FOREIGN KEY (playlist_id) REFERENCES station_playlists (id) ON DELETE CASCADE'); $this->addSql('ALTER TABLE station_playlist_media ADD CONSTRAINT FK_EA70D779EA9FDD75 FOREIGN KEY (media_id) REFERENCES station_media (id) ON DELETE CASCADE'); $this->addSql('INSERT INTO station_playlist_media (playlist_id, media_id, weight, last_played) SELECT playlists_id, media_id, \'0\', \'0\' FROM station_playlist_has_media'); $this->addSql('DROP TABLE station_playlist_has_media'); } public function down(Schema $schema): void { $this->addSql('CREATE TABLE station_playlist_has_media (media_id INT NOT NULL, playlists_id INT NOT NULL, INDEX IDX_668E6486EA9FDD75 (media_id), INDEX IDX_668E64869F70CF56 (playlists_id), PRIMARY KEY(media_id, playlists_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('ALTER TABLE station_playlist_has_media ADD CONSTRAINT FK_668E64869F70CF56 FOREIGN KEY (playlists_id) REFERENCES station_playlists (id) ON DELETE CASCADE'); $this->addSql('ALTER TABLE station_playlist_has_media ADD CONSTRAINT FK_668E6486EA9FDD75 FOREIGN KEY (media_id) REFERENCES station_media (id) ON DELETE CASCADE'); $this->addSql('INSERT INTO station_playlist_has_media (playlists_id, media_id) SELECT playlist_id, media_id FROM station_playlist_media'); $this->addSql('DROP TABLE station_playlist_media'); } } ```
/content/code_sandbox/backend/src/Entity/Migration/Version20180428062526.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
543