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
/*
* Install unused checker with:
* composer global require insolita/unused-scanner
*
* Invoke with:
* php ~/.composer/vendor/bin/unused_scanner util/unused.php
*/
/**
* Set $projectPath = getcwd(); if your put it under project root
**/
$projectPath = dirname(__DIR__);
/**
* Array of full directories path for scan;
* Scan will be recursive
* Put directories with most intensive imports in top of list for more quick result
* @see path_to_url#method_in
**/
$scanDirectories = [
$projectPath . '/config/',
$projectPath . '/src/',
$projectPath . '/templates',
];
$scanFiles = [
];
/**
* Names relative to ones of scanDirectories
*
* @see path_to_url#method_exclude
**/
$excludeDirectories = [
];
return [
/**
* Required params
**/
'composerJsonPath' => $projectPath . '/composer.json',
'vendorPath' => $projectPath . '/vendor/',
'scanDirectories' => $scanDirectories,
/**
* Optional params
**/
'excludeDirectories' => $excludeDirectories,
'scanFiles' => $scanFiles,
'extensions' => ['*.php'],
'requireDev' => false, //Check composer require-dev section, default false
/**
* Optional, custom logic for check is file contains definitions of package
*
* @example
* 'customMatch'=> function($definition, $packageName, \Symfony\Component\Finder\SplFileInfo $file):bool{
* $isPresent = false;
* if($packageName === 'phpunit/phpunit'){
* $isPresent = true;
* }
* if($file->getExtension()==='twig'){
* $isPresent = customCheck();
* }
* return $isPresent;
* }
**/
'customMatch' => null,
/**
* Report mode options
* Report mode enabled, when reportPath value is valid directory path
* !!!Note!!! The scanning time and memory usage will be increased when report mode enabled,
* it sensitive especially for big projects and when requireDev option enabled
**/
'reportPath' => __DIR__, //path in directory, where usage report will be stores;
/**
* Optional custom formatter (by default report stored as json)
* $report array format
* [
* 'packageName'=> [
* 'definition'=>['fileNames',...]
* ....
* ]
* ...
* ]
*
* @example
* 'reportFormatter'=>function(array $report):string{
* return print_r($report, true);
* }
**/
'reportFormatter' => null,
'reportExtension' => null, //by default - json, set own, if use custom formatter
];
``` | /content/code_sandbox/util/unused.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 624 |
```php
<?php
declare(strict_types=1);
use App\Environment;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LogLevel;
require dirname(__DIR__) . '/vendor/autoload.php';
$app = App\AppFactory::createApp(
[
App\Environment::LOG_LEVEL => LogLevel::DEBUG,
]
);
$di = $app->getContainer();
$env = $di->get(Environment::class);
App\Enums\SupportedLocales::createForCli($env);
$em = $di->get(EntityManagerInterface::class);
``` | /content/code_sandbox/util/psysh.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 110 |
```shell
#!/usr/bin/env bash
# Functions to manage .env files
__dotenv=
__dotenv_file=
__dotenv_cmd=.env
.env() {
REPLY=()
[[ $__dotenv_file || ${1-} == -* ]] || .env.--file .env || return
if declare -F -- ".env.${1-}" >/dev/null; then
.env."$@"
return
fi
return 64
}
.env.-f() { .env.--file "$@"; }
.env.get() {
.env::arg "get requires a key" "$@" &&
[[ "$__dotenv" =~ ^(.*(^|$'\n'))([ ]*)"$1="(.*)$ ]] &&
REPLY=${BASH_REMATCH[4]%%$'\n'*} && REPLY=${REPLY%"${REPLY##*[![:space:]]}"}
}
.env.parse() {
local line key
while IFS= read -r line; do
line=${line#"${line%%[![:space:]]*}"} # trim leading whitespace
line=${line%"${line##*[![:space:]]}"} # trim trailing whitespace
if [[ ! "$line" || "$line" == '#'* ]]; then continue; fi
if (($#)); then
for key; do
if [[ $key == "${line%%=*}" ]]; then
REPLY+=("$line")
break
fi
done
else
REPLY+=("$line")
fi
done <<<"$__dotenv"
((${#REPLY[@]}))
}
.env.export() { ! .env.parse "$@" || export "${REPLY[@]}"; }
.env.set() {
.env::file load || return
local key saved=$__dotenv
while (($#)); do
key=${1#+}
key=${key%%=*}
if .env.get "$key"; then
REPLY=()
if [[ $1 == +* ]]; then
shift
continue # skip if already found
elif [[ $1 == *=* ]]; then
__dotenv=${BASH_REMATCH[1]}${BASH_REMATCH[3]}$1$'\n'${BASH_REMATCH[4]#*$'\n'}
else
__dotenv=${BASH_REMATCH[1]}${BASH_REMATCH[4]#*$'\n'}
continue # delete all occurrences
fi
elif [[ $1 == *=* ]]; then
__dotenv+="${1#+}"$'\n'
fi
shift
done
[[ $__dotenv == "$saved" ]] || .env::file save
}
.env.puts() { echo "${1-}" >>"$__dotenv_file" && __dotenv+="$1"$'\n'; }
.env.generate() {
.env::arg "key required for generate" "$@" || return
.env.get "$1" && return || REPLY=$("${@:2}") || return
.env::one "generate: ouptut of '${*:2}' has more than one line" "$REPLY" || return
.env.puts "$1=$REPLY"
}
.env.--file() {
.env::arg "filename required for --file" "$@" || return
__dotenv_file=$1
.env::file load || return
(($# < 2)) || .env "${@:2}"
}
.env::arg() { [[ "${2-}" ]] || {
echo "$__dotenv_cmd: $1" >&2
return 64
}; }
.env::one() { [[ "$2" != *$'\n'* ]] || .env::arg "$1"; }
.env::file() {
local REPLY=$__dotenv_file
case "$1" in
load)
__dotenv=
! [[ -f "$REPLY" ]] || __dotenv="$(<"$REPLY")"$'\n' || return
;;
save)
if [[ -L "$REPLY" ]] && declare -F -- realpath.resolved >/dev/null; then
realpath.resolved "$REPLY"
fi
{ [[ ! -f "$REPLY" ]] || cp -p "$REPLY" "$REPLY.bak"; } &&
printf %s "$__dotenv" >"$REPLY.bak" && mv "$REPLY.bak" "$REPLY"
;;
esac
}
# Ensure we're in the same directory as this script.
cd "$( dirname "${BASH_SOURCE[0]}" )" || exit
cd ..
# Download mkcert
curl -JLO "path_to_url"
chmod +x mkcert-v*-linux-amd64
sudo cp mkcert-v*-linux-amd64 /usr/local/bin/mkcert
# Use mkcert to generate a working SSL cert for this install.
GITPOD_URL=$(gp url 443)
mkcrt "$GITPOD_URL" -cert-file ./util/local_ssl/default.crt -key-file ./util/local_ssl/default.key
# Update env file to provision this URL as the base URL for AzuraCast.
.env --file azuracast.env set INIT_BASE_URL="$GITPOD_URL"
# Set up SSH key from remote env.
if [[ -z "$SSH_PUBLIC_KEY" ]]; then
mkdir -p ~/.ssh
echo $SSH_PUBLIC_KEY > ~/.ssh/id_ed25519.pub
chmod 644 ~/.ssh/id_ed25519.pub
echo $SSH_PRIVATE_KEY > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
git config --global commit.gpgsign true
git config --global gpg.format "ssh"
git config --global user.signingkey "~/.ssh/id_ed25519"
fi
``` | /content/code_sandbox/util/setup_gitpod.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,223 |
```php
<?php
/**
* PHPStan Bootstrap File
*/
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
ini_set('display_errors', 1);
require dirname(__DIR__) . '/vendor/autoload.php';
const AZURACAST_VERSION = App\Version::STABLE_VERSION;
const AZURACAST_API_URL = 'path_to_url
const AZURACAST_API_NAME = 'Testing API';
$tempDir = sys_get_temp_dir();
$app = App\AppFactory::createCli(
[
App\Environment::TEMP_DIR => $tempDir,
App\Environment::UPLOADS_DIR => $tempDir,
]
);
return $app;
``` | /content/code_sandbox/util/phpstan.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 137 |
```shell
#!/bin/bash
set -e
set -x
export DEBIAN_FRONTEND=noninteractive
apt-get update
# Install common scripts
# cp -rT /bd_build/supervisor/scripts/ /usr/local/bin
# cp -rT /bd_build/supervisor/startup_scripts/. /etc/my_init.d/
# cp -rT /bd_build/supervisor/service.minimal/. /etc/supervisor/minimal.conf.d/
# cp -rT /bd_build/supervisor/service.full/. /etc/supervisor/full.conf.d/
# Run service setup for all setup scripts
for f in /bd_build/supervisor/setup/*.sh; do
bash "$f" -H
done
``` | /content/code_sandbox/util/docker/supervisor/setup.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 153 |
```shell
#!/bin/bash
set -e
set -x
apt-get install -y --no-install-recommends python3-minimal python3-pip
pip3 install --no-cache-dir --break-system-packages setuptools supervisor \
git+path_to_url
# apt-get install -y --no-install-recommends supervisor
mkdir -p /etc/supervisor
mkdir -p /etc/supervisor/full.conf.d/
mkdir -p /etc/supervisor/minimal.conf.d/
cp /bd_build/supervisor/supervisor/supervisord*.conf /etc/supervisor/
``` | /content/code_sandbox/util/docker/supervisor/setup/supervisor.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 125 |
```shell
#!/bin/bash
set -e
set -x
apt-get -y autoremove
apt-get clean
rm -rf /var/lib/apt/lists/*
rm -rf /tmp/tmp*
chmod -R a+x /usr/local/bin
chmod -R +x /etc/my_init.d
``` | /content/code_sandbox/util/docker/common/cleanup.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 62 |
```shell
#!/bin/bash
set -e
set -x
chown -R azuracast:azuracast /var/azuracast
``` | /content/code_sandbox/util/docker/common/chown_dirs.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 34 |
```shell
#!/bin/bash
set -e
set -x
apt-get install -y --no-install-recommends sudo
# Workaround for sudo errors in containers, see: path_to_url
echo "Set disable_coredump false" >> /etc/sudo.conf
adduser --home /var/azuracast --disabled-password --gecos "" azuracast
usermod -aG www-data azuracast
mkdir -p /var/azuracast/www /var/azuracast/stations /var/azuracast/www_tmp \
/var/azuracast/docs \
/var/azuracast/backups \
/var/azuracast/dbip \
/var/azuracast/storage/uploads \
/var/azuracast/storage/shoutcast2 \
/var/azuracast/storage/stereo_tool \
/var/azuracast/storage/geoip \
/var/azuracast/storage/sftpgo \
/var/azuracast/storage/acme
chown -R azuracast:azuracast /var/azuracast
chmod -R 777 /var/azuracast/www_tmp
echo 'azuracast ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
``` | /content/code_sandbox/util/docker/common/add_user.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 289 |
```shell
#!/bin/bash
set -e
set -x
## Prevent initramfs updates from trying to run grub and lilo.
## path_to_url
## path_to_url
export INITRD=no
export DEBIAN_FRONTEND=noninteractive
# Enable contrib and nonfree repos
sed -i 's/^Components: main$/& contrib non-free non-free-firmware/' /etc/apt/sources.list.d/debian.sources
echo "deb path_to_url bookworm-backports main" > /etc/apt/sources.list.d/backports.list
apt-get update
## Fix some issues with APT packages.
## See path_to_url
dpkg-divert --local --rename --add /sbin/initctl
ln -sf /bin/true /sbin/initctl
# Add default timezone.
echo "UTC" > /etc/timezone
## Replace the 'ischroot' tool to make it always return true.
## Prevent initscripts updates from breaking /dev/shm.
## path_to_url
## path_to_url
dpkg-divert --local --rename --add /usr/bin/ischroot
ln -sf /bin/true /usr/bin/ischroot
## Install HTTPS support for APT.
apt-get install -y --no-install-recommends apt-utils apt-transport-https ca-certificates
## Upgrade all packages.
apt-get dist-upgrade -y --no-install-recommends -o Dpkg::Options::="--force-confold"
## Fix locale.
apt-get install -y --no-install-recommends locales
echo "en_US.UTF-8 UTF-8" > /etc/locale.gen
locale-gen
dpkg-reconfigure locales
# Make init folders
mkdir -p /etc/my_init.d
# Install other common scripts.
apt-get install -y --no-install-recommends \
lsb-release tini gosu curl wget tar zip unzip xz-utils git rsync tzdata gnupg gpg-agent openssh-client
# Add scripts
cp -rT /bd_build/scripts/ /usr/local/bin
chmod -R a+x /usr/local/bin
``` | /content/code_sandbox/util/docker/common/prepare.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 437 |
```shell
#!/bin/bash
set -e
set -x
export DEBIAN_FRONTEND=noninteractive
apt-get update
# Install common scripts
cp -rT /bd_build/dev/scripts/ /usr/local/bin
cp -rT /bd_build/dev/startup_scripts/. /etc/my_init.d/
# cp -rT /bd_build/dev/service.minimal/. /etc/supervisor/minimal.conf.d/
cp -rT /bd_build/dev/service.full/. /etc/supervisor/full.conf.d/
# Run service setup for all setup scripts
for f in /bd_build/dev/setup/*.sh; do
bash "$f" -H
done
``` | /content/code_sandbox/util/docker/dev/setup.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 140 |
```shell
#!/bin/bash
# Set up permissions
cd /var/azuracast/www
chown -R azuracast:azuracast .
chmod 777 ./vendor/ ./node_modules/ ./web/static/
# If the Composer directory is empty, run composer install at this point.
if [ $(find ./vendor/ -maxdepth 1 -printf x | wc -c) -lt 10 ]; then
gosu azuracast composer install
fi
``` | /content/code_sandbox/util/docker/dev/startup_scripts/50_ensure_dev_setup.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 102 |
```shell
#!/bin/bash
set -e
set -x
curl -fsSL path_to_url | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
NODE_MAJOR=20
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] path_to_url nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
apt-get update
apt-get install -y --no-install-recommends nodejs
``` | /content/code_sandbox/util/docker/dev/setup/node.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 101 |
```shell
#!/bin/bash
set -e
set -x
# Install dev PHP stuff
install-php-extensions xdebug spx
rm -rf /usr/local/etc/php-fpm.d/*
``` | /content/code_sandbox/util/docker/dev/setup/php.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 40 |
```shell
#!/bin/bash
set -e
set -x
export DEBIAN_FRONTEND=noninteractive
apt-get update
# Install common scripts
# cp -rT /bd_build/stations/scripts/ /usr/local/bin
# cp -rT /bd_build/stations/startup_scripts/. /etc/my_init.d/
# cp -rT /bd_build/stations/service.minimal/. /etc/supervisor/minimal.conf.d/
# cp -rT /bd_build/stations/service.full/. /etc/supervisor/full.conf.d/
# Run service setup for all setup scripts
for f in /bd_build/stations/setup/*.sh; do
bash "$f" -H
done
``` | /content/code_sandbox/util/docker/stations/setup.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 148 |
```shell
#!/bin/bash
set -e
set -x
apt-get install -y --no-install-recommends python3-minimal python3-pip
pip3 install --no-cache-dir --break-system-packages mutagen
mkdir -p /tmp/autocue
mkdir -p /var/azuracast/autocue
cd /tmp/autocue
wget -O autocue.tar.gz "path_to_url"
tar -xvf autocue.tar.gz --strip-components=1
# git clone path_to_url .
# git checkout integrate-with-liquidsoap
mv ./cue_file /usr/local/bin/cue_file
chmod a+x /usr/local/bin/cue_file
mv ./autocue.cue_file.liq /var/azuracast/autocue/autocue.liq
chown -R azuracast:azuracast /var/azuracast/autocue
cd /var/azuracast/autocue
rm -rf /tmp/autocue
``` | /content/code_sandbox/util/docker/stations/setup/autocue.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 221 |
```shell
#!/bin/bash
set -e
set -x
mkdir -p /tmp/master_me
cd /tmp/master_me
# Per-architecture LS installs
ARCHITECTURE=x86_64
if [[ "$(uname -m)" = "aarch64" ]]; then
ARCHITECTURE=arm64
fi
wget -O master_me.tar.xz "path_to_url{ARCHITECTURE}.tar.xz"
tar -xvf master_me.tar.xz --strip-components=1
mkdir -p /usr/lib/ladspa
mkdir -p /usr/lib/lv2
mv ./master_me-easy-presets.lv2 /usr/lib/lv2
mv ./master_me.lv2 /usr/lib/lv2
mv ./master_me-ladspa.so /usr/lib/ladspa/master_me.so
cd /tmp
rm -rf /tmp/master_me
``` | /content/code_sandbox/util/docker/stations/setup/master_me.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 184 |
```shell
#!/bin/bash
set -e
set -x
# Packages required by Liquidsoap
apt-get install -y --no-install-recommends \
libao4 libfaad2 libfdk-aac2 libgd3 liblo7 libmad0 libmagic1 libportaudio2 \
libsdl2-image-2.0-0 libsdl2-ttf-2.0-0 libsoundtouch1 libxpm4 \
libasound2 libavcodec59 libavdevice59 libavfilter8 libavformat59 libavutil57 \
libpulse0 libsamplerate0 libswresample4 libswscale6 libtag1v5 \
libsrt1.5-openssl bubblewrap ffmpeg liblilv-0-0 libjemalloc2 libpcre3
# Audio Post-processing
apt-get install -y --no-install-recommends ladspa-sdk
# Per-architecture LS installs
ARCHITECTURE=amd64
if [[ "$(uname -m)" = "aarch64" ]]; then
ARCHITECTURE=arm64
fi
# wget -O /tmp/liquidsoap.deb "path_to_url{ARCHITECTURE}.deb"
wget -O /tmp/liquidsoap.deb "path_to_url{ARCHITECTURE}.deb"
dpkg -i /tmp/liquidsoap.deb
apt-get install -y -f --no-install-recommends
rm -f /tmp/liquidsoap.deb
ln -s /usr/bin/liquidsoap /usr/local/bin/liquidsoap
``` | /content/code_sandbox/util/docker/stations/setup/liquidsoap.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 327 |
```shell
#!/bin/bash
set -e
set -x
# Audio library dependencies used by Php-Getid3
apt-get install -q -y --no-install-recommends \
vorbis-tools flac
``` | /content/code_sandbox/util/docker/stations/setup/getid3.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 46 |
```shell
#!/bin/bash
set -e
set -x
# Icecast is built and imported in its own Docker container.
apt-get install -q -y --no-install-recommends libxml2 libxslt1.1 openssl
``` | /content/code_sandbox/util/docker/stations/setup/icecast.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 50 |
```shell
#!/bin/bash
set -e
set -x
export DEBIAN_FRONTEND=noninteractive
apt-get update
# Install common scripts
# cp -rT /bd_build/redis/scripts/ /usr/local/bin
cp -rT /bd_build/redis/startup_scripts/. /etc/my_init.d/
cp -rT /bd_build/redis/service.minimal/. /etc/supervisor/minimal.conf.d/
# cp -rT /bd_build/redis/service.full/. /etc/supervisor/full.conf.d/
# Run service setup for all setup scripts
for f in /bd_build/redis/setup/*.sh; do
bash "$f" -H
done
``` | /content/code_sandbox/util/docker/redis/setup.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 146 |
```shell
#!/bin/bash
bool() {
case "$1" in
Y* | y* | true | TRUE | 1) return 0 ;;
esac
return 1
}
# If Redis is expressly disabled or the host is anything but localhost, disable Redis on this container.
ENABLE_REDIS=${ENABLE_REDIS:-true}
if [ "$REDIS_HOST" != "localhost" ] || ! bool "$ENABLE_REDIS"; then
echo "Redis is disabled or host is not localhost; disabling Redis..."
rm -rf /etc/supervisor/minimal.conf.d/redis.conf
fi
``` | /content/code_sandbox/util/docker/redis/startup_scripts/00_disable_redis.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 127 |
```shell
#!/bin/bash
set -e
set -x
apt-get install -y --no-install-recommends redict-server/bookworm-backports redict-tools/bookworm-backports
cp /bd_build/redis/redis/redis.conf /etc/redict/redict.conf
chown redict:redict /etc/redict/redict.conf
mkdir -p /run/redis
chown redict:redict /run/redis
``` | /content/code_sandbox/util/docker/redis/setup/redis.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 91 |
```shell
#!/bin/bash
set -e
set -x
export DEBIAN_FRONTEND=noninteractive
apt-get update
# Install common scripts
cp -rT /bd_build/web/scripts/ /usr/local/bin
cp -rT /bd_build/web/startup_scripts/. /etc/my_init.d/
# cp -rT /bd_build/web/service.minimal/. /etc/supervisor/minimal.conf.d/
cp -rT /bd_build/web/service.full/. /etc/supervisor/full.conf.d/
# Run service setup for all setup scripts
for f in /bd_build/web/setup/*.sh; do
bash "$f" -H
done
``` | /content/code_sandbox/util/docker/web/setup.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 140 |
```shell
#!/bin/bash
export DEBIAN_FRONTEND=noninteractive
INSTALL_PACKAGES_ON_STARTUP=${INSTALL_PACKAGES_ON_STARTUP:-""}
if [ ! -z "$INSTALL_PACKAGES_ON_STARTUP" ]; then
echo "Installing extra packages..."
apt-get update
apt-get install -y --no-install-recommends $INSTALL_PACKAGES_ON_STARTUP
apt-get clean
rm -rf /var/lib/apt/lists/*
rm -rf /tmp/tmp*
fi
``` | /content/code_sandbox/util/docker/web/startup_scripts/02_install_extra_packages.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 104 |
```shell
#!/bin/bash
dockerize -template "/usr/local/etc/php/php.ini.tmpl:/usr/local/etc/php/php.ini" \
-template "/usr/local/etc/php-fpm.conf.tmpl:/usr/local/etc/php-fpm.conf"
``` | /content/code_sandbox/util/docker/web/startup_scripts/06_php_conf.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 49 |
```shell
#!/bin/bash
if [[ ! -f /var/azuracast/storage/sftpgo/id_rsa ]]; then
ssh-keygen -t rsa -b 4096 -f /var/azuracast/storage/sftpgo/id_rsa -q -N ""
fi
if [[ ! -f /var/azuracast/storage/sftpgo/id_ecdsa ]]; then
ssh-keygen -t ecdsa -b 521 -f /var/azuracast/storage/sftpgo/id_ecdsa -q -N ""
fi
if [[ ! -f /var/azuracast/storage/sftpgo/id_ed25519 ]]; then
ssh-keygen -t ed25519 -f /var/azuracast/storage/sftpgo/id_ed25519 -q -N ""
fi
echo "SFTPGO_SFTPD__BINDINGS__0__PORT=${AZURACAST_SFTP_PORT:-2022}" > /var/azuracast/sftpgo/env.d/sftpd.env
chown -R azuracast:azuracast /var/azuracast/storage/sftpgo
``` | /content/code_sandbox/util/docker/web/startup_scripts/07_sftpgo_conf.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 245 |
```shell
#!/bin/bash
if [ -z "$ACME_DIR" ]; then
if [ -d "/var/azuracast/acme" ]; then
export ACME_DIR="/var/azuracast/acme"
else
export ACME_DIR="/var/azuracast/storage/acme"
fi
fi
mkdir -p "$ACME_DIR/challenges" || true
# If the final cert path is a symlink (working or otherwise), remove it to re-establish it in the next step.
if [ ! -e "$ACME_DIR/ssl.crt" ] || [ -L "$ACME_DIR/ssl.crt" ]; then
rm -rf "$ACME_DIR/ssl.key" || true
rm -rf "$ACME_DIR/ssl.crt" || true
fi
if [ ! -f "$ACME_DIR/ssl.crt" ]; then
if [ -f "$ACME_DIR/custom.crt" ]; then
ln -s "$ACME_DIR/custom.key" "$ACME_DIR/ssl.key"
ln -s "$ACME_DIR/custom.crt" "$ACME_DIR/ssl.crt"
elif [ -f "$ACME_DIR/acme.crt" ]; then
ln -s "$ACME_DIR/acme.key" "$ACME_DIR/ssl.key"
ln -s "$ACME_DIR/acme.crt" "$ACME_DIR/ssl.crt"
else
# Always generate a new self-signed cert if it's in use.
rm -rf "$ACME_DIR/default.key" || true
rm -rf "$ACME_DIR/default.crt" || true
if [ ! -f "$ACME_DIR/default.crt" ]; then
echo "Generating self-signed certificate..."
openssl req -new -nodes -x509 -subj "/C=US/ST=Texas/L=Austin/O=IT/CN=localhost" \
-days 365 -extensions v3_ca \
-keyout "$ACME_DIR/default.key" \
-out "$ACME_DIR/default.crt"
fi
ln -s "$ACME_DIR/default.key" "$ACME_DIR/ssl.key"
ln -s "$ACME_DIR/default.crt" "$ACME_DIR/ssl.crt"
fi
fi
chown -R azuracast:azuracast "$ACME_DIR" || true
chmod -R u=rwX,go=rX "$ACME_DIR" || true
``` | /content/code_sandbox/util/docker/web/startup_scripts/01_self_signed_ssl.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 518 |
```shell
#!/bin/bash
export DEBIAN_FRONTEND=noninteractive
echo "Creating persist directories..."
mkdir -p /var/azuracast/storage/uploads \
/var/azuracast/storage/shoutcast2 \
/var/azuracast/storage/stereo_tool \
/var/azuracast/storage/geoip \
/var/azuracast/storage/sftpgo \
/var/azuracast/storage/acme
``` | /content/code_sandbox/util/docker/web/startup_scripts/03_persist_dir.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 99 |
```shell
#!/bin/bash
ENABLE_REDIS=${ENABLE_REDIS:-true}
export ENABLE_REDIS
dockerize -template "/var/azuracast/centrifugo/config.toml.tmpl:/var/azuracast/centrifugo/config.toml"
``` | /content/code_sandbox/util/docker/web/startup_scripts/05_centrifugo_conf.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 55 |
```shell
#!/bin/bash
AZURACAST_PUID="${AZURACAST_PUID:-1000}"
AZURACAST_PGID="${AZURACAST_PGID:-1000}"
PUID="${PUID:-$AZURACAST_PUID}"
PGID="${PGID:-$AZURACAST_PGID}"
groupmod -o -g "$PGID" azuracast
usermod -o -u "$PUID" azuracast
echo "Docker 'azuracast' User UID: $(id -u azuracast)"
echo "Docker 'azuracast' User GID: $(id -g azuracast)"
``` | /content/code_sandbox/util/docker/web/startup_scripts/00_setup_user.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 142 |
```shell
#!/bin/bash
shopt -s dotglob
rm -rf /var/azuracast/www_tmp/*
``` | /content/code_sandbox/util/docker/web/startup_scripts/10_clear_temp.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 25 |
```shell
#!/bin/bash
# Determine the current uploads dir for the installation.
if [ -z "$UPLOADS_DIR" ]; then
if [ -d "/var/azuracast/uploads" ]; then
export UPLOADS_DIR="/var/azuracast/uploads"
else
export UPLOADS_DIR="/var/azuracast/storage/uploads"
fi
fi
if [ -z "$ACME_DIR" ]; then
if [ -d "/var/azuracast/acme" ]; then
export ACME_DIR="/var/azuracast/acme"
else
export ACME_DIR="/var/azuracast/storage/acme"
fi
fi
# Copy the nginx template to its destination.
dockerize -template "/etc/nginx/nginx.conf.tmpl:/etc/nginx/nginx.conf" \
-template "/etc/nginx/azuracast.conf.tmpl:/etc/nginx/sites-available/default"
``` | /content/code_sandbox/util/docker/web/startup_scripts/05_nginx_conf.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 198 |
```shell
#!/bin/bash
set -e
set -x
# Per-architecture LS installs
ARCHITECTURE=amd64
if [[ "$(uname -m)" = "aarch64" ]]; then
ARCHITECTURE=arm64
fi
wget -O /tmp/sftpgo.deb "path_to_url{ARCHITECTURE}.deb"
dpkg -i /tmp/sftpgo.deb
apt-get install -y -f --no-install-recommends
rm -f /tmp/sftpgo.deb
mkdir -p /var/azuracast/sftpgo/persist \
/var/azuracast/sftpgo/backups \
/var/azuracast/sftpgo/env.d
cp /bd_build/web/sftpgo/sftpgo.json /var/azuracast/sftpgo/sftpgo.json
touch /var/azuracast/sftpgo/sftpgo.db
chown -R azuracast:azuracast /var/azuracast/sftpgo
# Create sftpgo temp dir
mkdir -p /tmp/sftpgo_temp
touch /tmp/sftpgo_temp/.tmpreaper
chmod -R 777 /tmp/sftpgo_temp
``` | /content/code_sandbox/util/docker/web/setup/sftpgo.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 264 |
```shell
#!/bin/bash
set -e
set -x
# Per-architecture LS installs
ARCHITECTURE=amd64
if [[ "$(uname -m)" = "aarch64" ]]; then
ARCHITECTURE=arm64
fi
apt-get install -y --no-install-recommends \
libid3tag0 libboost-program-options1.74.0 libboost-filesystem1.74.0 libboost-regex1.74.0
wget -O /tmp/audiowaveform.deb "path_to_url{ARCHITECTURE}.deb"
dpkg -i /tmp/audiowaveform.deb
apt-get install -y -f --no-install-recommends
rm -f /tmp/audiowaveform.deb
``` | /content/code_sandbox/util/docker/web/setup/audiowaveform.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 163 |
```shell
#!/bin/bash
set -e
set -x
mkdir -p /etc/cron.d/
cp -r /bd_build/web/cron/. /etc/cron.d/
``` | /content/code_sandbox/util/docker/web/setup/cron.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 38 |
```shell
#!/bin/bash
set -e
set -x
# Group up several package installations here to reduce overall build time
apt-get update
apt-get install -y --no-install-recommends nginx-light openssl tmpreaper zstd
``` | /content/code_sandbox/util/docker/web/setup/00_packages.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 50 |
```shell
#!/bin/bash
set -e
set -x
cd /tmp
YEAR=$(date +'%Y')
MONTH=$(date +'%m')
wget --quiet -O dbip-city-lite.mmdb.gz "path_to_url{YEAR}-${MONTH}.mmdb.gz"
gunzip dbip-city-lite.mmdb.gz
mv dbip-city-lite.mmdb /var/azuracast/dbip/
chown -R azuracast:azuracast /var/azuracast/dbip
``` | /content/code_sandbox/util/docker/web/setup/dbip.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 106 |
```shell
#!/bin/bash
set -e
set -x
install-php-extensions @composer \
gd curl xml zip \
gmp pdo_mysql mbstring intl \
redis maxminddb \
ffi sockets
rm -rf /usr/local/etc/php-fpm.d/*
cp /bd_build/web/php/php.ini.tmpl /usr/local/etc/php/php.ini.tmpl
cp /bd_build/web/php/www.conf.tmpl /usr/local/etc/php-fpm.conf.tmpl
# Enable FFI (for StereoTool inspection)
echo 'ffi.enable="true"' >> /usr/local/etc/php/conf.d/ffi.ini
``` | /content/code_sandbox/util/docker/web/setup/php.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 127 |
```shell
#!/bin/bash
set -e
set -x
# Package installation handled in 00_packages.sh
# Install nginx and configuration
cp /bd_build/web/nginx/proxy_params.conf /etc/nginx/proxy_params
cp /bd_build/web/nginx/nginx.conf.tmpl /etc/nginx/nginx.conf.tmpl
cp /bd_build/web/nginx/azuracast.conf.tmpl /etc/nginx/azuracast.conf.tmpl
# Change M3U8 MIME type to "application/x-mpegurl" for broader compatibility.
sed -i 's#application/vnd.apple.mpegurl#application/x-mpegurl#' /etc/nginx/mime.types
mkdir -p /etc/nginx/azuracast.conf.d/
# Create nginx temp dirs
mkdir -p /tmp/nginx_client \
/tmp/nginx_fastcgi \
/tmp/nginx_cache
touch /tmp/nginx_client/.tmpreaper
touch /tmp/nginx_fastcgi/.tmpreaper
touch /tmp/nginx_cache/.tmpreaper
chmod -R 777 /tmp/nginx_*
``` | /content/code_sandbox/util/docker/web/setup/nginx.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 218 |
```shell
#!/bin/bash
set -e
set -x
mkdir -p /var/azuracast/centrifugo
cp /bd_build/web/centrifugo/config.toml.tmpl /var/azuracast/centrifugo/config.toml.tmpl
``` | /content/code_sandbox/util/docker/web/setup/centrifugo.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 59 |
```shell
#!/bin/bash
set -e
set -x
export DEBIAN_FRONTEND=noninteractive
apt-get update
# Install common scripts
cp -rT /bd_build/mariadb/scripts/ /usr/local/bin
cp -rT /bd_build/mariadb/startup_scripts/. /etc/my_init.d/
cp -rT /bd_build/mariadb/service.minimal/. /etc/supervisor/minimal.conf.d/
# cp -rT /bd_build/mariadb/service.full/. /etc/supervisor/full.conf.d/
# Run service setup for all setup scripts
for f in /bd_build/mariadb/setup/*.sh; do
bash "$f" -H
done
``` | /content/code_sandbox/util/docker/mariadb/setup.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 150 |
```shell
#!/bin/bash
if [ ! -f /etc/supervisor/minimal.conf.d/mariadb.conf ]; then
echo "MariaDB disabled. Skipping DB initialization..."
exit 0
fi
dockerize -template /etc/mysql/db.cnf.tmpl:/etc/mysql/conf.d/db.cnf
``` | /content/code_sandbox/util/docker/mariadb/startup_scripts/04_mariadb_conf.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 65 |
```shell
#!/bin/bash
# If the MariaDB host is anything but localhost, disable MariaDB on this container.
if [ "$MYSQL_HOST" != "localhost" ]; then
echo "MariaDB host is not localhost; disabling MariaDB..."
rm -rf /etc/supervisor/minimal.conf.d/mariadb.conf
fi
``` | /content/code_sandbox/util/docker/mariadb/startup_scripts/00_disable_mariadb.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 70 |
```shell
#!/bin/bash
if [ ! -f /etc/supervisor/minimal.conf.d/mariadb.conf ]; then
echo "MariaDB disabled. Skipping DB initialization..."
exit 0
fi
export MARIADB_AUTO_UPGRADE=1
source /usr/local/bin/db_entrypoint.sh
set -- mariadbd
mysql_note "Initial DB setup..."
mysql_check_config "$@"
# Load various environment variables
docker_setup_env "$@"
# Create DB directories
mkdir -p "$DATADIR"
if [ "$(id -u)" = "0" ]; then
# this will cause less disk access than `chown -R`
find "$DATADIR" \! -user mysql -exec chown mysql: '{}' +
# See path_to_url
find "${SOCKET%/*}" -maxdepth 0 \! -user mysql -exec chown mysql: '{}' \;
fi
# If container is started as root user, restart as dedicated mysql user
if [ "$(id -u)" = "0" ]; then
mysql_note "Switching to dedicated user 'mysql'"
exec gosu mysql "${BASH_SOURCE[0]}" "$@"
fi
# there's no database, so it needs to be initialized
if [ -z "$DATABASE_ALREADY_EXISTS" ]; then
docker_verify_minimum_env
docker_mariadb_init "$@"
# MDEV-27636 mariadb_upgrade --check-if-upgrade-is-needed cannot be run offline
#elif mysql_upgrade --check-if-upgrade-is-needed; then
elif _check_if_upgrade_is_needed; then
docker_mariadb_upgrade "$@"
fi
``` | /content/code_sandbox/util/docker/mariadb/startup_scripts/05_setup_db.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 341 |
```shell
#!/bin/bash
set -e
set -x
curl -LsS path_to_url | bash -s -- \
--mariadb-server-version=11.2
{ \
echo "mariadb-server" mysql-server/root_password password 'unused'; \
echo "mariadb-server" mysql-server/root_password_again password 'unused'; \
} | debconf-set-selections
apt-get update
apt-get install -q -y --no-install-recommends \
mariadb-server mariadb-backup mariadb-client \
ca-certificates gpg gpgv libjemalloc2 pwgen tzdata xz-utils zstd
rm -rf /var/lib/mysql
mkdir -p /var/lib/mysql /var/run/mysqld
chown -R mysql:mysql /var/lib/mysql /var/run/mysqld
# ensure that /var/run/mysqld (used for socket and lock files) is writable regardless of the UID our mysqld instance ends up having at runtime
chmod 777 /var/run/mysqld
# comment out a few problematic configuration values
find /etc/mysql/ -name '*.cnf' -print0 \
| xargs -0 grep -lZE '^(bind-address|log|user\s)' \
| xargs -rt -0 sed -Ei 's/^(bind-address|log|user\s)/#&/';
# don't reverse lookup hostnames, they are usually another container
printf "[mariadb]\nhost-cache-size=0\nskip-name-resolve\n" > /etc/mysql/mariadb.conf.d/05-skipcache.cnf;
mkdir /docker-entrypoint-initdb.d
cp /bd_build/mariadb/mariadb/db.sql /docker-entrypoint-initdb.d/00-azuracast.sql
cp /bd_build/mariadb/mariadb/db.cnf.tmpl /etc/mysql/db.cnf.tmpl
``` | /content/code_sandbox/util/docker/mariadb/setup/mariadb.sh | shell | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 407 |
```sqlpl
-- MySQL dump 10.17 Distrib 10.3.22-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: mariadb Database: azuracast
-- ------------------------------------------------------
-- Server version 10.4.13-MariaDB-1:10.4.13+maria~bionic-log
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES UTF8MB4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `azuracast`;
USE `azuracast`;
ALTER DATABASE `azuracast` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
--
-- Table structure for table `analytics`
--
DROP TABLE IF EXISTS `analytics`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analytics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) DEFAULT NULL,
`type` varchar(15) NOT NULL,
`timestamp` int(11) NOT NULL,
`number_min` int(11) NOT NULL,
`number_max` int(11) NOT NULL,
`number_avg` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_EAC2E68821BDB235` (`station_id`),
KEY `search_idx` (`type`,`timestamp`),
CONSTRAINT `FK_EAC2E68821BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `api_keys`
--
DROP TABLE IF EXISTS `api_keys`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `api_keys` (
`id` varchar(16) NOT NULL,
`user_id` int(11) NOT NULL,
`verifier` varchar(128) NOT NULL,
`comment` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_9579321FA76ED395` (`user_id`),
CONSTRAINT `FK_9579321FA76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`uid`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `app_migrations`
--
DROP TABLE IF EXISTS `app_migrations`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `app_migrations` (
`version` varchar(191) NOT NULL,
`executed_at` datetime DEFAULT NULL,
`execution_time` int(11) DEFAULT NULL,
PRIMARY KEY (`version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `app_migrations`
--
LOCK TABLES `app_migrations` WRITE;
/*!40000 ALTER TABLE `app_migrations` DISABLE KEYS */;
INSERT INTO `app_migrations` VALUES ('App\\Entity\\Migration\\Version20161003041904',NULL,NULL),('App\\Entity\\Migration\\Version20161006030903',NULL,NULL),('App\\Entity\\Migration\\Version20161007021719',NULL,NULL),('App\\Entity\\Migration\\Version20161007195027',NULL,NULL),('App\\Entity\\Migration\\Version20161117000718',NULL,NULL),('App\\Entity\\Migration\\Version20161117161959',NULL,NULL),('App\\Entity\\Migration\\Version20161120032434',NULL,NULL),('App\\Entity\\Migration\\Version20161122035237',NULL,NULL),('App\\Entity\\Migration\\Version20170412210654',NULL,NULL),('App\\Entity\\Migration\\Version20170414205418',NULL,NULL),('App\\Entity\\Migration\\Version20170423202805',NULL,NULL),('App\\Entity\\Migration\\Version20170424042111',NULL,NULL),('App\\Entity\\Migration\\Version20170502202418',NULL,NULL),('App\\Entity\\Migration\\Version20170510082607',NULL,NULL),('App\\Entity\\Migration\\Version20170510085226',NULL,NULL),('App\\Entity\\Migration\\Version20170510091820',NULL,NULL),('App\\Entity\\Migration\\Version20170512023527',NULL,NULL),('App\\Entity\\Migration\\Version20170512082741',NULL,NULL),('App\\Entity\\Migration\\Version20170512094523',NULL,NULL),('App\\Entity\\Migration\\Version20170516073708',NULL,NULL),('App\\Entity\\Migration\\Version20170516205418',NULL,NULL),('App\\Entity\\Migration\\Version20170516214120',NULL,NULL),('App\\Entity\\Migration\\Version20170516215536',NULL,NULL),('App\\Entity\\Migration\\Version20170518100549',NULL,NULL),('App\\Entity\\Migration\\Version20170522052114',NULL,NULL),('App\\Entity\\Migration\\Version20170524090814',NULL,NULL),('App\\Entity\\Migration\\Version20170606173152',NULL,NULL),('App\\Entity\\Migration\\Version20170618013019',NULL,NULL),('App\\Entity\\Migration\\Version20170619044014',NULL,NULL),('App\\Entity\\Migration\\Version20170619171323',NULL,NULL),('App\\Entity\\Migration\\Version20170622223025',NULL,NULL),('App\\Entity\\Migration\\Version20170719045113',NULL,NULL),('App\\Entity\\Migration\\Version20170803050109',NULL,NULL),('App\\Entity\\Migration\\Version20170823204230',NULL,NULL),('App\\Entity\\Migration\\Version20170829030442',NULL,NULL),('App\\Entity\\Migration\\Version20170906080352',NULL,NULL),('App\\Entity\\Migration\\Version20170917175534',NULL,NULL),('App\\Entity\\Migration\\Version20171022005913',NULL,NULL),('App\\Entity\\Migration\\Version20171103075821',NULL,NULL),('App\\Entity\\Migration\\Version20171104014701',NULL,NULL),('App\\Entity\\Migration\\Version20171124184831',NULL,NULL),('App\\Entity\\Migration\\Version20171128121012',NULL,NULL),('App\\Entity\\Migration\\Version20171208093239',NULL,NULL),('App\\Entity\\Migration\\Version20171214104226',NULL,NULL),('App\\Entity\\Migration\\Version20180203201032',NULL,NULL),('App\\Entity\\Migration\\Version20180203203751',NULL,NULL),('App\\Entity\\Migration\\Version20180203214656',NULL,NULL),('App\\Entity\\Migration\\Version20180204210633',NULL,NULL),('App\\Entity\\Migration\\Version20180206105454',NULL,NULL),('App\\Entity\\Migration\\Version20180211192448',NULL,NULL),('App\\Entity\\Migration\\Version20180320052444',NULL,NULL),('App\\Entity\\Migration\\Version20180320061801',NULL,NULL),('App\\Entity\\Migration\\Version20180320070100',NULL,NULL),('App\\Entity\\Migration\\Version20180320163622',NULL,NULL),('App\\Entity\\Migration\\Version20180320171318',NULL,NULL),('App\\Entity\\Migration\\Version20180324053351',NULL,NULL),('App\\Entity\\Migration\\Version20180412055024',NULL,NULL),('App\\Entity\\Migration\\Version20180415235105',NULL,NULL),('App\\Entity\\Migration\\Version20180417041534',NULL,NULL),('App\\Entity\\Migration\\Version20180425025237',NULL,NULL),('App\\Entity\\Migration\\Version20180425050351',NULL,NULL),('App\\Entity\\Migration\\Version20180428062526',NULL,NULL),('App\\Entity\\Migration\\Version20180429013130',NULL,NULL),('App\\Entity\\Migration\\Version20180506022642',NULL,NULL),('App\\Entity\\Migration\\Version20180608130900',NULL,NULL),('App\\Entity\\Migration\\Version20180716185805',NULL,NULL),('App\\Entity\\Migration\\Version20180818223558',NULL,NULL),('App\\Entity\\Migration\\Version20180826011103',NULL,NULL),('App\\Entity\\Migration\\Version20180826043500',NULL,NULL),('App\\Entity\\Migration\\Version20180830003036',NULL,NULL),('App\\Entity\\Migration\\Version20180909035413',NULL,NULL),('App\\Entity\\Migration\\Version20180909060758',NULL,NULL),('App\\Entity\\Migration\\Version20180909174026',NULL,NULL),('App\\Entity\\Migration\\Version20181016144143',NULL,NULL),('App\\Entity\\Migration\\Version20181025232600',NULL,NULL),('App\\Entity\\Migration\\Version20181120100629',NULL,NULL),('App\\Entity\\Migration\\Version20181126073334',NULL,NULL),('App\\Entity\\Migration\\Version20181202180617',NULL,NULL),('App\\Entity\\Migration\\Version20181211220707',NULL,NULL),('App\\Entity\\Migration\\Version20190124132556',NULL,NULL),('App\\Entity\\Migration\\Version20190128035353',NULL,NULL),('App\\Entity\\Migration\\Version20190314074747',NULL,NULL),('App\\Entity\\Migration\\Version20190314203550',NULL,NULL),('App\\Entity\\Migration\\Version20190315002523',NULL,NULL),('App\\Entity\\Migration\\Version20190324040155',NULL,NULL),('App\\Entity\\Migration\\Version20190326051220',NULL,NULL),('App\\Entity\\Migration\\Version20190331215627','2020-06-09 02:19:27',NULL),('App\\Entity\\Migration\\Version20190402224811','2020-06-09 02:19:27',NULL),('App\\Entity\\Migration\\Version20190429025906','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190429040410','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190513163051','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190517122806','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190624135222','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190715231530','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190719220017','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190810234058','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190813210707','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190818003805','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20190930201744','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20191024185005','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20191101065730','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20191101075303','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200105190343','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200123004338','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200124183957','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200127071620','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200129010322','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200130094654','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200213052842','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200216121137','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200217114139','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200310204315','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200321174535','2020-06-09 02:19:28',NULL),('App\\Entity\\Migration\\Version20200402212036','2020-06-09 02:19:29',NULL),('App\\Entity\\Migration\\Version20200417082209','2020-06-09 02:19:29',NULL),('App\\Entity\\Migration\\Version20200503005148','2020-06-09 02:19:29',NULL),('App\\Entity\\Migration\\Version20200514061004','2020-06-09 02:19:29',NULL),('App\\Entity\\Migration\\Version20200604073027','2020-06-09 02:19:29',NULL),('App\\Entity\\Migration\\Version20200604075356','2020-07-04 17:05:25',137);
/*!40000 ALTER TABLE `app_migrations` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `audit_log`
--
DROP TABLE IF EXISTS `audit_log`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `audit_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` int(11) NOT NULL,
`operation` smallint(6) NOT NULL,
`class` varchar(255) NOT NULL,
`identifier` varchar(255) NOT NULL,
`target_class` varchar(255) DEFAULT NULL,
`target` varchar(255) DEFAULT NULL,
`changes` longtext NOT NULL COMMENT '(DC2Type:array)',
`user` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `custom_field`
--
DROP TABLE IF EXISTS `custom_field`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `custom_field` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`short_name` varchar(100) DEFAULT NULL,
`auto_assign` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `listener`
--
DROP TABLE IF EXISTS `listener`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `listener` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) NOT NULL,
`listener_uid` int(11) NOT NULL,
`listener_ip` varchar(45) NOT NULL,
`listener_user_agent` varchar(255) NOT NULL,
`timestamp_start` int(11) NOT NULL,
`timestamp_end` int(11) NOT NULL,
`listener_hash` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_959C342221BDB235` (`station_id`),
KEY `idx_timestamps` (`timestamp_end`,`timestamp_start`),
CONSTRAINT `FK_959C342221BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `relays`
--
DROP TABLE IF EXISTS `relays`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `relays` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`base_url` varchar(255) NOT NULL,
`name` varchar(100) DEFAULT NULL,
`is_visible_on_public_pages` tinyint(1) NOT NULL,
`nowplaying` longtext DEFAULT NULL COMMENT '(DC2Type:array)',
`created_at` int(11) NOT NULL,
`updated_at` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `role`
--
DROP TABLE IF EXISTS `role`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `role_permissions`
--
DROP TABLE IF EXISTS `role_permissions`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `role_permissions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_id` int(11) NOT NULL,
`station_id` int(11) DEFAULT NULL,
`action_name` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `role_permission_unique_idx` (`role_id`,`action_name`,`station_id`),
KEY `IDX_1FBA94E6D60322AC` (`role_id`),
KEY `IDX_1FBA94E621BDB235` (`station_id`),
CONSTRAINT `FK_1FBA94E621BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_1FBA94E6D60322AC` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `settings`
--
DROP TABLE IF EXISTS `settings`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `settings` (
`setting_key` varchar(64) NOT NULL,
`setting_value` longtext DEFAULT NULL COMMENT '(DC2Type:json_array)',
PRIMARY KEY (`setting_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sftp_user`
--
DROP TABLE IF EXISTS `sftp_user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sftp_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) DEFAULT NULL,
`username` varchar(32) NOT NULL,
`password` varchar(255) NOT NULL,
`public_keys` longtext DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username_idx` (`username`),
KEY `IDX_3C32EA3421BDB235` (`station_id`),
CONSTRAINT `FK_3C32EA3421BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `song_history`
--
DROP TABLE IF EXISTS `song_history`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `song_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`song_id` varchar(50) NOT NULL,
`station_id` int(11) NOT NULL,
`timestamp_start` int(11) NOT NULL,
`listeners_start` int(11) DEFAULT NULL,
`timestamp_end` int(11) NOT NULL,
`listeners_end` smallint(6) DEFAULT NULL,
`delta_total` smallint(6) NOT NULL,
`delta_positive` smallint(6) NOT NULL,
`delta_negative` smallint(6) NOT NULL,
`delta_points` longtext DEFAULT NULL COMMENT '(DC2Type:json_array)',
`playlist_id` int(11) DEFAULT NULL,
`timestamp_cued` int(11) DEFAULT NULL,
`request_id` int(11) DEFAULT NULL,
`unique_listeners` smallint(6) DEFAULT NULL,
`media_id` int(11) DEFAULT NULL,
`duration` int(11) DEFAULT NULL,
`sent_to_autodj` tinyint(1) NOT NULL,
`autodj_custom_uri` varchar(255) DEFAULT NULL,
`streamer_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_2AD16164A0BDB2F3` (`song_id`),
KEY `IDX_2AD1616421BDB235` (`station_id`),
KEY `IDX_2AD161646BBD148` (`playlist_id`),
KEY `IDX_2AD16164EA9FDD75` (`media_id`),
KEY `IDX_2AD1616425F432AD` (`streamer_id`),
KEY `IDX_2AD16164427EB8A5` (`request_id`),
KEY `idx_timestamp_cued` (`timestamp_cued`),
KEY `idx_timestamp_start` (`timestamp_start`),
KEY `idx_timestamp_end` (`timestamp_end`),
CONSTRAINT `FK_2AD1616421BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_2AD1616425F432AD` FOREIGN KEY (`streamer_id`) REFERENCES `station_streamers` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_2AD16164427EB8A5` FOREIGN KEY (`request_id`) REFERENCES `station_requests` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_2AD161646BBD148` FOREIGN KEY (`playlist_id`) REFERENCES `station_playlists` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_2AD16164A0BDB2F3` FOREIGN KEY (`song_id`) REFERENCES `songs` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_2AD16164EA9FDD75` FOREIGN KEY (`media_id`) REFERENCES `station_media` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `songs`
--
DROP TABLE IF EXISTS `songs`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `songs` (
`id` varchar(50) NOT NULL,
`text` varchar(150) DEFAULT NULL,
`artist` varchar(150) DEFAULT NULL,
`title` varchar(150) DEFAULT NULL,
`created` int(11) NOT NULL,
`play_count` int(11) NOT NULL,
`last_played` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `search_idx` (`text`,`artist`,`title`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station`
--
DROP TABLE IF EXISTS `station`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`frontend_type` varchar(100) DEFAULT NULL,
`frontend_config` longtext DEFAULT NULL COMMENT '(DC2Type:json_array)',
`backend_type` varchar(100) DEFAULT NULL,
`backend_config` longtext DEFAULT NULL COMMENT '(DC2Type:json_array)',
`description` longtext DEFAULT NULL,
`automation_settings` longtext DEFAULT NULL COMMENT '(DC2Type:json_array)',
`automation_timestamp` int(11) DEFAULT NULL,
`enable_requests` tinyint(1) NOT NULL,
`request_delay` int(11) DEFAULT NULL,
`enable_streamers` tinyint(1) NOT NULL,
`needs_restart` tinyint(1) NOT NULL,
`request_threshold` int(11) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
`radio_media_dir` varchar(255) DEFAULT NULL,
`radio_base_dir` varchar(255) DEFAULT NULL,
`has_started` tinyint(1) NOT NULL,
`nowplaying` longtext DEFAULT NULL COMMENT '(DC2Type:array)',
`adapter_api_key` varchar(150) DEFAULT NULL,
`nowplaying_timestamp` int(11) DEFAULT NULL,
`enable_public_page` tinyint(1) NOT NULL,
`short_name` varchar(100) DEFAULT NULL,
`current_streamer_id` int(11) DEFAULT NULL,
`is_streamer_live` tinyint(1) NOT NULL,
`is_enabled` tinyint(1) NOT NULL,
`api_history_items` smallint(6) NOT NULL,
`disconnect_deactivate_streamer` int(11) DEFAULT 0,
`genre` varchar(150) DEFAULT NULL,
`storage_quota` bigint(20) DEFAULT NULL,
`storage_used` bigint(20) DEFAULT NULL,
`timezone` varchar(100) DEFAULT NULL,
`default_album_art_url` varchar(255) DEFAULT NULL,
`enable_on_demand` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_9F39F8B19B209974` (`current_streamer_id`),
KEY `idx_short_name` (`short_name`),
CONSTRAINT `FK_9F39F8B19B209974` FOREIGN KEY (`current_streamer_id`) REFERENCES `station_streamers` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_media`
--
DROP TABLE IF EXISTS `station_media`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_media` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) NOT NULL,
`song_id` varchar(50) DEFAULT NULL,
`title` varchar(200) DEFAULT NULL,
`artist` varchar(200) DEFAULT NULL,
`album` varchar(200) DEFAULT NULL,
`length` int(11) NOT NULL,
`length_text` varchar(10) DEFAULT NULL,
`path` varchar(500) DEFAULT NULL,
`mtime` int(11) DEFAULT NULL,
`amplify` decimal(3,1) DEFAULT NULL,
`fade_overlap` decimal(3,1) DEFAULT NULL,
`fade_in` decimal(3,1) DEFAULT NULL,
`fade_out` decimal(3,1) DEFAULT NULL,
`cue_in` decimal(5,1) DEFAULT NULL,
`cue_out` decimal(5,1) DEFAULT NULL,
`isrc` varchar(15) DEFAULT NULL,
`lyrics` longtext DEFAULT NULL,
`unique_id` varchar(25) DEFAULT NULL,
`art_updated_at` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `path_unique_idx` (`path`,`station_id`),
KEY `IDX_32AADE3A21BDB235` (`station_id`),
KEY `IDX_32AADE3AA0BDB2F3` (`song_id`),
KEY `search_idx` (`title`,`artist`,`album`),
CONSTRAINT `FK_32AADE3A21BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_32AADE3AA0BDB2F3` FOREIGN KEY (`song_id`) REFERENCES `songs` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_media_custom_field`
--
DROP TABLE IF EXISTS `station_media_custom_field`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_media_custom_field` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`media_id` int(11) NOT NULL,
`field_id` int(11) NOT NULL,
`field_value` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_35DC02AAEA9FDD75` (`media_id`),
KEY `IDX_35DC02AA443707B0` (`field_id`),
CONSTRAINT `FK_35DC02AA443707B0` FOREIGN KEY (`field_id`) REFERENCES `custom_field` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_35DC02AAEA9FDD75` FOREIGN KEY (`media_id`) REFERENCES `station_media` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_mounts`
--
DROP TABLE IF EXISTS `station_mounts`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_mounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`is_default` tinyint(1) NOT NULL,
`fallback_mount` varchar(100) DEFAULT NULL,
`enable_autodj` tinyint(1) NOT NULL,
`autodj_format` varchar(10) DEFAULT NULL,
`autodj_bitrate` smallint(6) DEFAULT NULL,
`frontend_config` longtext DEFAULT NULL,
`relay_url` varchar(255) DEFAULT NULL,
`is_public` tinyint(1) NOT NULL,
`authhash` varchar(255) DEFAULT NULL,
`custom_listen_url` varchar(255) DEFAULT NULL,
`display_name` varchar(255) DEFAULT NULL,
`is_visible_on_public_pages` tinyint(1) NOT NULL,
`listeners_unique` int(11) NOT NULL,
`listeners_total` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_4DDF64AD21BDB235` (`station_id`),
CONSTRAINT `FK_4DDF64AD21BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_playlist_folders`
--
DROP TABLE IF EXISTS `station_playlist_folders`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_playlist_folders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) DEFAULT NULL,
`playlist_id` int(11) DEFAULT NULL,
`path` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_15190AE921BDB235` (`station_id`),
KEY `IDX_15190AE96BBD148` (`playlist_id`),
CONSTRAINT `FK_15190AE921BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_15190AE96BBD148` FOREIGN KEY (`playlist_id`) REFERENCES `station_playlists` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_playlist_media`
--
DROP TABLE IF EXISTS `station_playlist_media`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_playlist_media` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`playlist_id` int(11) NOT NULL,
`media_id` int(11) NOT NULL,
`weight` int(11) NOT NULL,
`last_played` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_EA70D7796BBD148` (`playlist_id`),
KEY `IDX_EA70D779EA9FDD75` (`media_id`),
CONSTRAINT `FK_EA70D7796BBD148` FOREIGN KEY (`playlist_id`) REFERENCES `station_playlists` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_EA70D779EA9FDD75` FOREIGN KEY (`media_id`) REFERENCES `station_media` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_playlists`
--
DROP TABLE IF EXISTS `station_playlists`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_playlists` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`type` varchar(50) NOT NULL,
`is_enabled` tinyint(1) NOT NULL,
`play_per_songs` smallint(6) NOT NULL,
`play_per_minutes` smallint(6) NOT NULL,
`weight` smallint(6) NOT NULL,
`include_in_automation` tinyint(1) NOT NULL,
`source` varchar(50) NOT NULL,
`include_in_requests` tinyint(1) NOT NULL,
`playback_order` varchar(50) NOT NULL,
`remote_url` varchar(255) DEFAULT NULL,
`remote_type` varchar(25) DEFAULT NULL,
`is_jingle` tinyint(1) NOT NULL,
`play_per_hour_minute` smallint(6) NOT NULL,
`remote_timeout` smallint(6) NOT NULL,
`backend_options` varchar(255) DEFAULT NULL,
`played_at` int(11) NOT NULL,
`queue` longtext DEFAULT NULL COMMENT '(DC2Type:array)',
`include_in_on_demand` tinyint(1) NOT NULL,
`avoid_duplicates` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_DC827F7421BDB235` (`station_id`),
CONSTRAINT `FK_DC827F7421BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_remotes`
--
DROP TABLE IF EXISTS `station_remotes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_remotes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) NOT NULL,
`type` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`enable_autodj` tinyint(1) NOT NULL,
`autodj_format` varchar(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`autodj_bitrate` smallint(6) DEFAULT NULL,
`custom_listen_url` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`url` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`mount` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`source_username` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`source_password` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`source_port` smallint(5) unsigned DEFAULT NULL,
`source_mount` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`is_public` tinyint(1) NOT NULL,
`display_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`is_visible_on_public_pages` tinyint(1) NOT NULL,
`relay_id` int(11) DEFAULT NULL,
`listeners_unique` int(11) NOT NULL,
`listeners_total` int(11) NOT NULL,
`admin_password` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_779D0E8A21BDB235` (`station_id`),
KEY `IDX_779D0E8A68A482E` (`relay_id`),
CONSTRAINT `FK_779D0E8A21BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_779D0E8A68A482E` FOREIGN KEY (`relay_id`) REFERENCES `relays` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_requests`
--
DROP TABLE IF EXISTS `station_requests`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_requests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) NOT NULL,
`track_id` int(11) NOT NULL,
`timestamp` int(11) NOT NULL,
`played_at` int(11) NOT NULL,
`ip` varchar(40) NOT NULL,
`skip_delay` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_F71F0C0721BDB235` (`station_id`),
KEY `IDX_F71F0C075ED23C43` (`track_id`),
CONSTRAINT `FK_F71F0C0721BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_F71F0C075ED23C43` FOREIGN KEY (`track_id`) REFERENCES `station_media` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_schedules`
--
DROP TABLE IF EXISTS `station_schedules`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_schedules` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`playlist_id` int(11) DEFAULT NULL,
`streamer_id` int(11) DEFAULT NULL,
`start_time` smallint(6) NOT NULL,
`end_time` smallint(6) NOT NULL,
`start_date` varchar(10) DEFAULT NULL,
`end_date` varchar(10) DEFAULT NULL,
`days` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_B3BFB2956BBD148` (`playlist_id`),
KEY `IDX_B3BFB29525F432AD` (`streamer_id`),
CONSTRAINT `FK_B3BFB29525F432AD` FOREIGN KEY (`streamer_id`) REFERENCES `station_streamers` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_B3BFB2956BBD148` FOREIGN KEY (`playlist_id`) REFERENCES `station_playlists` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_streamer_broadcasts`
--
DROP TABLE IF EXISTS `station_streamer_broadcasts`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_streamer_broadcasts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) DEFAULT NULL,
`streamer_id` int(11) DEFAULT NULL,
`timestamp_start` int(11) NOT NULL,
`timestamp_end` int(11) NOT NULL,
`recording_path` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_76169D6621BDB235` (`station_id`),
KEY `IDX_76169D6625F432AD` (`streamer_id`),
CONSTRAINT `FK_76169D6621BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_76169D6625F432AD` FOREIGN KEY (`streamer_id`) REFERENCES `station_streamers` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_streamers`
--
DROP TABLE IF EXISTS `station_streamers`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_streamers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) NOT NULL,
`streamer_username` varchar(50) NOT NULL,
`streamer_password` varchar(255) NOT NULL,
`comments` longtext DEFAULT NULL,
`is_active` tinyint(1) NOT NULL,
`display_name` varchar(255) DEFAULT NULL,
`reactivate_at` int(11) DEFAULT NULL,
`enforce_schedule` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username_unique_idx` (`station_id`,`streamer_username`),
KEY `IDX_5170063E21BDB235` (`station_id`),
CONSTRAINT `FK_5170063E21BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `station_webhooks`
--
DROP TABLE IF EXISTS `station_webhooks`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `station_webhooks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`station_id` int(11) NOT NULL,
`type` varchar(100) NOT NULL,
`is_enabled` tinyint(1) NOT NULL,
`triggers` longtext DEFAULT NULL COMMENT '(DC2Type:json_array)',
`config` longtext DEFAULT NULL COMMENT '(DC2Type:json_array)',
`name` varchar(100) DEFAULT NULL,
`metadata` longtext DEFAULT NULL COMMENT '(DC2Type:json_array)',
PRIMARY KEY (`id`),
KEY `IDX_1516958B21BDB235` (`station_id`),
CONSTRAINT `FK_1516958B21BDB235` FOREIGN KEY (`station_id`) REFERENCES `station` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `user_has_role`
--
DROP TABLE IF EXISTS `user_has_role`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_has_role` (
`user_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`role_id`),
KEY `IDX_EAB8B535A76ED395` (`user_id`),
KEY `IDX_EAB8B535D60322AC` (`role_id`),
CONSTRAINT `FK_EAB8B535A76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`uid`) ON DELETE CASCADE,
CONSTRAINT `FK_EAB8B535D60322AC` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(100) DEFAULT NULL,
`auth_password` varchar(255) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`locale` varchar(25) DEFAULT NULL,
`created_at` int(11) NOT NULL,
`updated_at` int(11) NOT NULL,
`theme` varchar(25) DEFAULT NULL,
`two_factor_secret` varchar(255) DEFAULT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `email_idx` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2020-07-07 20:12:22
``` | /content/code_sandbox/util/docker/mariadb/mariadb/db.sql | sqlpl | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 10,568 |
```php
<?php
declare(strict_types=1);
use App\CallableEventDispatcherInterface;
use App\Environment;
use App\Event;
use App\Middleware;
return static function (CallableEventDispatcherInterface $dispatcher) {
$dispatcher->addListener(
Event\BuildConsoleCommands::class,
function (Event\BuildConsoleCommands $event) {
call_user_func(include(__DIR__ . '/cli.php'), $event);
}
);
$dispatcher->addListener(
Event\BuildRoutes::class,
function (Event\BuildRoutes $event) {
$app = $event->getApp();
// Load app-specific route configuration.
$container = $event->getContainer();
/** @var Environment $environment */
$environment = $container->get(Environment::class);
call_user_func(include(__DIR__ . '/routes.php'), $app);
if (file_exists(__DIR__ . '/routes.dev.php')) {
call_user_func(include(__DIR__ . '/routes.dev.php'), $app);
}
$app->add(Middleware\WrapExceptionsWithRequestData::class);
$app->add(Middleware\EnforceSecurity::class);
// Request injection middlewares.
$app->add(Middleware\InjectRouter::class);
$app->add(Middleware\InjectRateLimit::class);
// System middleware for routing and body parsing.
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
// Redirects and updates that should happen before system middleware.
$app->add(new Middleware\Cache\SetDefaultCache());
$app->add(new Middleware\RemoveSlashes());
$app->add(new Middleware\ApplyXForwarded());
// Add an error handler for most in-controller/task situations.
$errorMiddleware = $app->addErrorMiddleware(
$environment->showDetailedErrors(),
true,
true,
$container->get(Psr\Log\LoggerInterface::class)
);
$errorMiddleware->setDefaultErrorHandler(Slim\Interfaces\ErrorHandlerInterface::class);
}
);
// Build default menus
$dispatcher->addListener(
App\Event\GetSyncTasks::class,
function (App\Event\GetSyncTasks $e) {
$e->addTasks([
App\Sync\Task\CheckFolderPlaylistsTask::class,
App\Sync\Task\CheckMediaTask::class,
App\Sync\Task\CheckPodcastPlaylistsTask::class,
App\Sync\Task\CheckRequestsTask::class,
App\Sync\Task\CheckUpdatesTask::class,
App\Sync\Task\CleanupHistoryTask::class,
App\Sync\Task\CleanupLoginTokensTask::class,
App\Sync\Task\CleanupRelaysTask::class,
App\Sync\Task\CleanupStorageTask::class,
App\Sync\Task\EnforceBroadcastTimesTask::class,
App\Sync\Task\MoveBroadcastsTask::class,
App\Sync\Task\QueueInterruptingTracks::class,
App\Sync\Task\ReactivateStreamerTask::class,
App\Sync\Task\RenewAcmeCertTask::class,
App\Sync\Task\RotateLogsTask::class,
App\Sync\Task\RunAnalyticsTask::class,
App\Sync\Task\RunBackupTask::class,
App\Sync\Task\UpdateGeoLiteTask::class,
App\Sync\Task\UpdateStorageLocationSizesTask::class,
]);
}
);
// Other event subscribers from across the application.
$dispatcher->addCallableListener(
Event\GetNotifications::class,
App\Notification\Check\BaseUrlCheck::class
);
$dispatcher->addCallableListener(
Event\GetNotifications::class,
App\Notification\Check\UpdateCheck::class
);
$dispatcher->addCallableListener(
Event\GetNotifications::class,
App\Notification\Check\RecentBackupCheck::class
);
$dispatcher->addCallableListener(
Event\GetNotifications::class,
App\Notification\Check\SyncTaskCheck::class
);
$dispatcher->addCallableListener(
Event\GetNotifications::class,
App\Notification\Check\ProfilerAdvisorCheck::class
);
$dispatcher->addCallableListener(
Event\GetNotifications::class,
App\Notification\Check\DonateAdvisorCheck::class
);
$dispatcher->addCallableListener(
Event\GetNotifications::class,
App\Notification\Check\ServiceCheck::class
);
$dispatcher->addCallableListener(
Event\Media\GetAlbumArt::class,
App\Media\AlbumArtHandler\LastFmAlbumArtHandler::class,
priority: 10
);
$dispatcher->addCallableListener(
Event\Media\GetAlbumArt::class,
App\Media\AlbumArtHandler\MusicBrainzAlbumArtHandler::class,
priority: -10
);
$dispatcher->addCallableListener(
Event\Media\ReadMetadata::class,
App\Media\Metadata\Reader\PhpReader::class,
);
$dispatcher->addCallableListener(
Event\Media\ReadMetadata::class,
App\Media\Metadata\Reader\FfprobeReader::class,
priority: -10
);
$dispatcher->addCallableListener(
Event\Media\WriteMetadata::class,
App\Media\Metadata\Writer::class
);
$dispatcher->addServiceSubscriber(
[
App\Console\ErrorHandler::class,
App\Nginx\ConfigWriter::class,
App\Radio\AutoDJ\QueueBuilder::class,
App\Radio\AutoDJ\Annotations::class,
App\Radio\Backend\Liquidsoap\ConfigWriter::class,
App\Radio\Backend\Liquidsoap\PlaylistFileWriter::class,
App\Sync\NowPlaying\Task\NowPlayingTask::class,
]
);
};
``` | /content/code_sandbox/backend/config/events.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,262 |
```php
<?php
declare(strict_types=1);
use App\Middleware;
use Slim\App;
use Slim\Routing\RouteCollectorProxy;
return static function (App $app) {
$app->group(
'',
function (RouteCollectorProxy $group) {
call_user_func(include(__DIR__ . '/routes/public.php'), $group);
}
)->add(Middleware\Auth\PublicAuth::class);
$app->group(
'',
function (RouteCollectorProxy $group) {
call_user_func(include(__DIR__ . '/routes/base.php'), $group);
}
)->add(Middleware\Auth\StandardAuth::class)
->add(Middleware\InjectSession::class);
$app->group(
'/api',
function (RouteCollectorProxy $group) {
$group->group(
'',
function (RouteCollectorProxy $group) {
call_user_func(include(__DIR__ . '/routes/api_public.php'), $group);
}
)->add(Middleware\Module\Api::class)
->add(Middleware\Auth\PublicAuth::class);
$group->group(
'',
function (RouteCollectorProxy $group) {
call_user_func(include(__DIR__ . '/routes/api_internal.php'), $group);
call_user_func(include(__DIR__ . '/routes/api_admin.php'), $group);
call_user_func(include(__DIR__ . '/routes/api_frontend.php'), $group);
call_user_func(include(__DIR__ . '/routes/api_station.php'), $group);
}
)
->add(Middleware\Module\Api::class)
->add(Middleware\Auth\ApiAuth::class)
->add(Middleware\InjectSession::class);
}
);
};
``` | /content/code_sandbox/backend/config/routes.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 354 |
```php
<?php
declare(strict_types=1);
// An array of message queue types and the DI classes responsible for handling them.
use App\Message;
use App\Radio\Backend\Liquidsoap;
use App\Sync\Task;
use Symfony\Component\Mailer;
return [
Message\AddNewMediaMessage::class => App\Media\MediaProcessor::class,
Message\ReprocessMediaMessage::class => App\Media\MediaProcessor::class,
Message\ProcessCoverArtMessage::class => App\Media\MediaProcessor::class,
Message\WritePlaylistFileMessage::class => Liquidsoap\PlaylistFileWriter::class,
Message\BackupMessage::class => Task\RunBackupTask::class,
Message\GenerateAcmeCertificate::class => App\Service\Acme::class,
Message\DispatchWebhookMessage::class => App\Webhook\Dispatcher::class,
Message\TestWebhookMessage::class => App\Webhook\Dispatcher::class,
Mailer\Messenger\SendEmailMessage::class => Mailer\Messenger\MessageHandler::class,
];
``` | /content/code_sandbox/backend/config/messagequeue.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 221 |
```php
<?php
/**
* PHP-DI Services
*/
declare(strict_types=1);
use App\Environment;
use App\Event;
use Psr\Container\ContainerInterface;
return [
// Slim interface
Slim\Interfaces\RouteCollectorInterface::class => static fn(Slim\App $app) => $app->getRouteCollector(),
Slim\Interfaces\RouteParserInterface::class => static fn(
Slim\Interfaces\RouteCollectorInterface $routeCollector
) => $routeCollector->getRouteParser(),
// URL Router helper
App\Http\RouterInterface::class => DI\Get(App\Http\Router::class),
// Error handler
Slim\Interfaces\ErrorHandlerInterface::class => DI\Get(App\Http\ErrorHandler::class),
// HTTP client
App\Service\GuzzleFactory::class => static function (Psr\Log\LoggerInterface $logger) {
$stack = GuzzleHttp\HandlerStack::create();
$stack->unshift(
function (callable $handler) {
return static function (Psr\Http\Message\RequestInterface $request, array $options) use ($handler) {
$options[GuzzleHttp\RequestOptions::VERIFY] = Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(
);
return $handler($request, $options);
};
},
'ssl_verify'
);
$stack->push(
GuzzleHttp\Middleware::log(
$logger,
new GuzzleHttp\MessageFormatter('HTTP client {method} call to {uri} produced response {code}'),
Psr\Log\LogLevel::DEBUG
)
);
return new App\Service\GuzzleFactory(
[
'handler' => $stack,
GuzzleHttp\RequestOptions::HTTP_ERRORS => false,
GuzzleHttp\RequestOptions::TIMEOUT => 3.0,
]
);
},
GuzzleHttp\Client::class => static fn(App\Service\GuzzleFactory $guzzleFactory) => $guzzleFactory->buildClient(),
// DBAL
Doctrine\DBAL\Connection::class => static function (
Environment $environment,
Psr\Cache\CacheItemPoolInterface $psr6Cache,
) {
$dbSettings = $environment->getDatabaseSettings();
if (isset($dbSettings['unix_socket'])) {
unset($dbSettings['host'], $dbSettings['port']);
}
$connectionOptions = [
...$dbSettings,
'driver' => 'pdo_mysql',
'charset' => 'utf8mb4',
'defaultTableOptions' => [
'charset' => 'utf8mb4',
'collate' => 'utf8mb4_general_ci',
],
'driverOptions' => [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4 COLLATE utf8mb4_general_ci; '
. 'SET sql_mode=(SELECT REPLACE(@@sql_mode, "ONLY_FULL_GROUP_BY", ""))',
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
],
];
// Specify MariaDB version for local Docker installs. Let non-local ones auto-detect via Doctrine.
if (isset($connectionOptions['unix_socket']) || $environment->isTesting()) {
$connectionOptions['serverVersion'] = '11.2.3-MariaDB-1';
}
$config = new Doctrine\DBAL\Configuration();
$config->setResultCache($psr6Cache);
/** @phpstan-ignore-next-line */
return Doctrine\DBAL\DriverManager::getConnection($connectionOptions, $config);
},
// Doctrine Entity Manager
App\Doctrine\DecoratedEntityManager::class => static function (
Doctrine\DBAL\Connection $connection,
Psr\Cache\CacheItemPoolInterface $psr6Cache,
Environment $environment,
App\Doctrine\Event\StationRequiresRestart $eventRequiresRestart,
App\Doctrine\Event\AuditLog $eventAuditLog,
App\Doctrine\Event\SetExplicitChangeTracking $eventChangeTracking,
Psr\EventDispatcher\EventDispatcherInterface $dispatcher
) {
if ($environment->isCli()) {
$psr6Cache = new Symfony\Component\Cache\Adapter\ArrayAdapter();
} else {
$psr6Cache = new Symfony\Component\Cache\Adapter\ProxyAdapter($psr6Cache, 'doctrine.');
}
$mappingClassesPaths = [$environment->getBackendDirectory() . '/src/Entity'];
$buildDoctrineMappingPathsEvent = new Event\BuildDoctrineMappingPaths(
$mappingClassesPaths,
$environment->getBaseDirectory()
);
$dispatcher->dispatch($buildDoctrineMappingPathsEvent);
$mappingClassesPaths = $buildDoctrineMappingPathsEvent->getMappingClassesPaths();
// Fetch and store entity manager.
$config = Doctrine\ORM\ORMSetup::createAttributeMetadataConfiguration(
$mappingClassesPaths,
!$environment->isProduction(),
$environment->getTempDirectory() . '/proxies',
$psr6Cache
);
$config->setAutoGenerateProxyClasses(
Doctrine\ORM\Proxy\ProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS_OR_CHANGED
);
// Debug mode:
// $config->setSQLLogger(new Doctrine\DBAL\Logging\EchoSQLLogger);
$config->addCustomNumericFunction('RAND', DoctrineExtensions\Query\Mysql\Rand::class);
$config->addCustomStringFunction('FIELD', DoctrineExtensions\Query\Mysql\Field::class);
$eventManager = new Doctrine\Common\EventManager();
$eventManager->addEventSubscriber($eventRequiresRestart);
$eventManager->addEventSubscriber($eventAuditLog);
$eventManager->addEventSubscriber($eventChangeTracking);
return new App\Doctrine\DecoratedEntityManager(
fn() => new Doctrine\ORM\EntityManager($connection, $config, $eventManager)
);
},
App\Doctrine\ReloadableEntityManagerInterface::class => DI\Get(App\Doctrine\DecoratedEntityManager::class),
Doctrine\ORM\EntityManagerInterface::class => DI\Get(App\Doctrine\DecoratedEntityManager::class),
Symfony\Contracts\Cache\CacheInterface::class => static function (
Environment $environment,
Psr\Log\LoggerInterface $logger,
App\Service\RedisFactory $redisFactory
) {
if ($environment->isTesting()) {
$cacheInterface = new Symfony\Component\Cache\Adapter\ArrayAdapter();
} elseif ($redisFactory->isSupported()) {
$cacheInterface = new Symfony\Component\Cache\Adapter\RedisAdapter(
$redisFactory->getInstance(),
marshaller: new Symfony\Component\Cache\Marshaller\DefaultMarshaller(
$environment->isProduction() ? null : false
)
);
} else {
$tempDir = $environment->getTempDirectory() . DIRECTORY_SEPARATOR . 'cache';
$cacheInterface = new Symfony\Component\Cache\Adapter\FilesystemAdapter(
'',
0,
$tempDir
);
}
$cacheInterface->setLogger($logger);
return $cacheInterface;
},
Symfony\Component\Cache\Adapter\AdapterInterface::class => DI\get(
Symfony\Contracts\Cache\CacheInterface::class
),
Psr\Cache\CacheItemPoolInterface::class => DI\get(
Symfony\Contracts\Cache\CacheInterface::class
),
Psr\SimpleCache\CacheInterface::class => static fn(
Psr\Cache\CacheItemPoolInterface $cache
) => new Symfony\Component\Cache\Psr16Cache($cache),
// Symfony Lock adapter
Symfony\Component\Lock\PersistingStoreInterface::class => static fn(
Environment $environment,
App\Service\RedisFactory $redisFactory
) => ($redisFactory->isSupported())
? new Symfony\Component\Lock\Store\RedisStore($redisFactory->getInstance())
: new Symfony\Component\Lock\Store\FlockStore($environment->getTempDirectory()),
// Console
App\Console\Application::class => static function (
DI\Container $di,
App\CallableEventDispatcherInterface $dispatcher,
App\Version $version,
Environment $environment,
Doctrine\ORM\EntityManagerInterface $em
) {
$console = new App\Console\Application(
$environment->getAppName() . ' Command Line Tools ('
. $environment->getAppEnvironmentEnum()->getName() . ')',
$version->getVersion()
);
$console->setDispatcher($dispatcher);
// Doctrine ORM/DBAL
Doctrine\ORM\Tools\Console\ConsoleRunner::addCommands(
$console,
new Doctrine\ORM\Tools\Console\EntityManagerProvider\SingleManagerProvider($em)
);
// Add Doctrine Migrations
$migrationConfigurations = [
'migrations_paths' => [
'App\Entity\Migration' => $environment->getBackendDirectory() . '/src/Entity/Migration',
],
'table_storage' => [
'table_name' => 'app_migrations',
'version_column_length' => 191,
],
'custom_template' => $environment->getBaseDirectory() . '/util/doctrine_migration.php.tmpl',
];
$buildMigrationConfigurationsEvent = new Event\BuildMigrationConfigurationArray(
$migrationConfigurations,
$environment->getBaseDirectory()
);
$dispatcher->dispatch($buildMigrationConfigurationsEvent);
$migrationConfigurations = $buildMigrationConfigurationsEvent->getMigrationConfigurations();
$migrateConfig = new Doctrine\Migrations\Configuration\Migration\ConfigurationArray(
$migrationConfigurations
);
$migrateFactory = Doctrine\Migrations\DependencyFactory::fromEntityManager(
$migrateConfig,
new Doctrine\Migrations\Configuration\EntityManager\ExistingEntityManager($em)
);
Doctrine\Migrations\Tools\Console\ConsoleRunner::addCommands($console, $migrateFactory);
// Trigger an event for the core app and all plugins to build their CLI commands.
$event = new Event\BuildConsoleCommands($console, $di, $environment);
$dispatcher->dispatch($event);
$commandLoader = new Symfony\Component\Console\CommandLoader\ContainerCommandLoader(
$di,
$event->getAliases()
);
$console->setCommandLoader($commandLoader);
return $console;
},
// Event Dispatcher
App\CallableEventDispatcherInterface::class => static function (
DI\Container $di,
App\Plugins $plugins
) {
$dispatcher = new App\CallableEventDispatcher();
$dispatcher->setContainer($di);
// Register application default events.
if (file_exists(__DIR__ . '/events.php')) {
call_user_func(include(__DIR__ . '/events.php'), $dispatcher);
}
// Register plugin-provided events.
$plugins->registerEvents($dispatcher);
return $dispatcher;
},
Psr\EventDispatcher\EventDispatcherInterface::class => DI\get(
App\CallableEventDispatcherInterface::class
),
// Monolog Logger
Monolog\Logger::class => static function (Environment $environment) {
$logger = new Monolog\Logger($environment->getAppName());
$loggingLevel = $environment->getLogLevel();
if ($environment->isCli() || $environment->isDocker()) {
$logStderr = new Monolog\Handler\StreamHandler('php://stderr', $loggingLevel, true);
$logger->pushHandler($logStderr);
}
$logFile = new Monolog\Handler\RotatingFileHandler(
$environment->getTempDirectory() . '/app.log',
5,
$loggingLevel,
true
);
$logger->pushHandler($logFile);
return $logger;
},
Psr\Log\LoggerInterface::class => DI\get(Monolog\Logger::class),
// Symfony Serializer
Symfony\Component\Serializer\Serializer::class => static function (
App\Doctrine\ReloadableEntityManagerInterface $em
) {
$classMetaFactory = new Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory(
new Symfony\Component\Serializer\Mapping\Loader\AttributeLoader()
);
$normalizers = [
new Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer(),
new Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer(),
new Azura\Normalizer\DoctrineEntityNormalizer(
$em,
classMetadataFactory: $classMetaFactory
),
new Symfony\Component\Serializer\Normalizer\ObjectNormalizer(
classMetadataFactory: $classMetaFactory
),
];
$encoders = [
new Symfony\Component\Serializer\Encoder\JsonEncoder(),
];
return new Symfony\Component\Serializer\Serializer($normalizers, $encoders);
},
// Symfony Validator
Symfony\Component\Validator\Validator\ValidatorInterface::class => static function (
Symfony\Component\Validator\ContainerConstraintValidatorFactory $constraintValidatorFactory
) {
$builder = new Symfony\Component\Validator\ValidatorBuilder();
$builder->setConstraintValidatorFactory($constraintValidatorFactory);
$builder->enableAttributeMapping();
return $builder->getValidator();
},
App\MessageQueue\QueueManagerInterface::class => static function (
App\Service\RedisFactory $redisFactory
) {
return ($redisFactory->isSupported())
? new App\MessageQueue\QueueManager($redisFactory)
: new App\MessageQueue\TestQueueManager();
},
Symfony\Component\Messenger\MessageBus::class => static function (
App\MessageQueue\QueueManager $queueManager,
App\Lock\LockFactory $lockFactory,
Monolog\Logger $logger,
ContainerInterface $di,
App\Plugins $plugins,
App\Service\RedisFactory $redisFactory,
Environment $environment
) {
$loggingLevel = $environment->getLogLevel();
$busLogger = new Psr\Log\NullLogger();
// Configure message handling middleware
$handlers = [];
$receivers = require __DIR__ . '/messagequeue.php';
// Register plugin-provided message queue receivers
$receivers = $plugins->registerMessageQueueReceivers($receivers);
/**
* @var class-string $messageClass
* @var class-string $handlerClass
*/
foreach ($receivers as $messageClass => $handlerClass) {
$handlers[$messageClass][] = static function ($message) use ($handlerClass, $di) {
/** @var callable $obj */
$obj = $di->get($handlerClass);
return $obj($message);
};
}
$handlersLocator = new Symfony\Component\Messenger\Handler\HandlersLocator($handlers);
$handleMessageMiddleware = new Symfony\Component\Messenger\Middleware\HandleMessageMiddleware(
$handlersLocator,
true
);
$handleMessageMiddleware->setLogger($busLogger);
// On testing, messages are handled directly when called
if (!$redisFactory->isSupported()) {
return new Symfony\Component\Messenger\MessageBus(
[
$handleMessageMiddleware,
]
);
}
// Add unique protection middleware
$uniqueMiddleware = new App\MessageQueue\HandleUniqueMiddleware($lockFactory);
// Configure message sending middleware
$sendMessageMiddleware = new Symfony\Component\Messenger\Middleware\SendMessageMiddleware($queueManager);
$sendMessageMiddleware->setLogger($busLogger);
// Compile finished message bus.
return new Symfony\Component\Messenger\MessageBus(
[
$sendMessageMiddleware,
$uniqueMiddleware,
$handleMessageMiddleware,
]
);
},
Symfony\Component\Messenger\MessageBusInterface::class => DI\get(
Symfony\Component\Messenger\MessageBus::class
),
// Mail functionality
Symfony\Component\Mailer\Transport\TransportInterface::class => static function (
App\Entity\Repository\SettingsRepository $settingsRepo,
Psr\EventDispatcher\EventDispatcherInterface $eventDispatcher,
Monolog\Logger $logger
) {
$settings = $settingsRepo->readSettings();
if ($settings->getMailEnabled()) {
$requiredSettings = [
'mailSenderEmail' => $settings->getMailSenderEmail(),
'mailSmtpHost' => $settings->getMailSmtpHost(),
'mailSmtpPort' => $settings->getMailSmtpPort(),
];
$hasAllSettings = true;
foreach ($requiredSettings as $setting) {
if (empty($setting)) {
$hasAllSettings = false;
break;
}
}
if ($hasAllSettings) {
$transport = new Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport(
$settings->getMailSmtpHost(),
$settings->getMailSmtpPort(),
$settings->getMailSmtpSecure(),
$eventDispatcher,
$logger
);
if (!empty($settings->getMailSmtpUsername())) {
$transport->setUsername($settings->getMailSmtpUsername());
$transport->setPassword($settings->getMailSmtpPassword());
}
return $transport;
}
}
return new Symfony\Component\Mailer\Transport\NullTransport(
$eventDispatcher,
$logger
);
},
Symfony\Component\Mailer\Mailer::class => static fn(
Symfony\Component\Mailer\Transport\TransportInterface $transport,
Symfony\Component\Messenger\MessageBus $messageBus,
Psr\EventDispatcher\EventDispatcherInterface $eventDispatcher
) => new Symfony\Component\Mailer\Mailer($transport, $messageBus, $eventDispatcher),
Symfony\Component\Mailer\MailerInterface::class => DI\get(
Symfony\Component\Mailer\Mailer::class
),
// Supervisor manager
Supervisor\SupervisorInterface::class => static fn(
Environment $environment,
Psr\Log\LoggerInterface $logger
) => new Supervisor\Supervisor(
new fXmlRpc\Client(
'path_to_url
new fXmlRpc\Transport\PsrTransport(
new GuzzleHttp\Psr7\HttpFactory(),
new GuzzleHttp\Client([
'curl' => [
\CURLOPT_UNIX_SOCKET_PATH => '/var/run/supervisor.sock',
],
])
)
),
$logger
),
// NowPlaying Adapter factory
NowPlaying\AdapterFactory::class => static function (
GuzzleHttp\Client $httpClient,
Psr\Log\LoggerInterface $logger
) {
$httpFactory = new GuzzleHttp\Psr7\HttpFactory();
return new NowPlaying\AdapterFactory(
$httpFactory,
$httpFactory,
$httpClient,
$logger
);
},
];
``` | /content/code_sandbox/backend/config/services.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 3,849 |
```php
<?php
declare(strict_types=1);
use App\Console\Command;
return function (App\Event\BuildConsoleCommands $event) {
$event->addAliases([
'azuracast:acme:get-certificate' => Command\Acme\GetCertificateCommand::class,
'azuracast:backup' => Command\Backup\BackupCommand::class,
'azuracast:restore' => Command\Backup\RestoreCommand::class,
'azuracast:debug:optimize-tables' => Command\Debug\OptimizeTablesCommand::class,
'azuracast:internal:on-ssl-renewal' => Command\Internal\OnSslRenewal::class,
'azuracast:internal:ip' => Command\Internal\GetIpCommand::class,
'azuracast:internal:uptime-wait' => Command\Internal\UptimeWaitCommand::class,
'azuracast:media:reprocess' => Command\Media\ReprocessCommand::class,
'azuracast:media:clear-extra' => Command\Media\ClearExtraMetadataCommand::class,
'azuracast:queue:process' => Command\MessageQueue\ProcessCommand::class,
'azuracast:queue:clear' => Command\MessageQueue\ClearCommand::class,
'azuracast:settings:list' => Command\Settings\ListCommand::class,
'azuracast:settings:set' => Command\Settings\SetCommand::class,
'azuracast:station-queues:clear' => Command\ClearQueuesCommand::class,
'azuracast:account:list' => Command\Users\ListCommand::class,
'azuracast:account:login-token' => Command\Users\LoginTokenCommand::class,
'azuracast:account:reset-password' => Command\Users\ResetPasswordCommand::class,
'azuracast:account:set-administrator' => Command\Users\SetAdministratorCommand::class,
'azuracast:cache:clear' => Command\ClearCacheCommand::class,
'azuracast:setup:migrate' => Command\MigrateDbCommand::class,
'azuracast:setup:fixtures' => Command\SetupFixturesCommand::class,
'azuracast:setup:rollback' => Command\RollbackDbCommand::class,
'azuracast:setup' => Command\SetupCommand::class,
'azuracast:radio:restart' => Command\RestartRadioCommand::class,
'azuracast:sync:nowplaying' => Command\Sync\NowPlayingCommand::class,
'azuracast:sync:nowplaying:station' => Command\Sync\NowPlayingPerStationCommand::class,
'azuracast:sync:run' => Command\Sync\RunnerCommand::class,
'azuracast:sync:task' => Command\Sync\SingleTaskCommand::class,
'queue:process' => Command\MessageQueue\ProcessCommand::class,
'queue:clear' => Command\MessageQueue\ClearCommand::class,
'cache:clear' => Command\ClearCacheCommand::class,
'acme:cert' => Command\Acme\GetCertificateCommand::class,
]);
if (!$event->getEnvironment()->isProduction()) {
$event->addAliases([
'azuracast:api:docs' => Command\GenerateApiDocsCommand::class,
'azuracast:locale:generate' => Command\Locale\GenerateCommand::class,
'azuracast:locale:import' => Command\Locale\ImportCommand::class,
'azuracast:new-version' => Command\NewVersionCommand::class,
'locale:generate' => Command\Locale\GenerateCommand::class,
'locale:import' => Command\Locale\ImportCommand::class,
]);
}
};
``` | /content/code_sandbox/backend/config/cli.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 857 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $group) {
$group->group(
'/frontend',
function (RouteCollectorProxy $group) {
$group->group(
'/account',
function (RouteCollectorProxy $group) {
$group->get('/me', Controller\Api\Frontend\Account\GetMeAction::class)
->setName('api:frontend:account:me');
$group->put('/me', Controller\Api\Frontend\Account\PutMeAction::class);
$group->put('/password', Controller\Api\Frontend\Account\PutPasswordAction::class)
->setName('api:frontend:account:password');
$group->get('/two-factor', Controller\Api\Frontend\Account\GetTwoFactorAction::class)
->setName('api:frontend:account:two-factor');
$group->put('/two-factor', Controller\Api\Frontend\Account\PutTwoFactorAction::class);
$group->delete('/two-factor', Controller\Api\Frontend\Account\DeleteTwoFactorAction::class);
$group->get(
'/api-keys',
Controller\Api\Frontend\Account\ApiKeysController::class . ':listAction'
)->setName('api:frontend:api-keys');
$group->post(
'/api-keys',
Controller\Api\Frontend\Account\ApiKeysController::class . ':createAction'
);
$group->get(
'/api-key/{id}',
Controller\Api\Frontend\Account\ApiKeysController::class . ':getAction'
)->setName('api:frontend:api-key');
$group->delete(
'/api-key/{id}',
Controller\Api\Frontend\Account\ApiKeysController::class . ':deleteAction'
);
$group->get(
'/webauthn/register',
Controller\Api\Frontend\Account\WebAuthn\GetRegistrationAction::class
)->setName('api:frontend:webauthn:register');
$group->put(
'/webauthn/register',
Controller\Api\Frontend\Account\WebAuthn\PutRegistrationAction::class
);
$group->get(
'/passkeys',
Controller\Api\Frontend\Account\PasskeysController::class . ':listAction'
)->setName('api:frontend:passkeys');
$group->get(
'/passkey/{id}',
Controller\Api\Frontend\Account\PasskeysController::class . ':getAction'
)->setName('api:frontend:passkey');
$group->delete(
'/passkey/{id}',
Controller\Api\Frontend\Account\PasskeysController::class . ':deleteAction'
);
}
);
$group->group(
'/dashboard',
function (RouteCollectorProxy $group) {
$group->get('/charts', Controller\Api\Frontend\Dashboard\ChartsAction::class)
->setName('api:frontend:dashboard:charts');
$group->get('/notifications', Controller\Api\Frontend\Dashboard\NotificationsAction::class)
->setName('api:frontend:dashboard:notifications');
$group->get('/stations', Controller\Api\Frontend\Dashboard\StationsAction::class)
->setName('api:frontend:dashboard:stations');
}
);
}
)->add(Middleware\RequireLogin::class);
};
``` | /content/code_sandbox/backend/config/routes/api_frontend.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 734 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Enums\StationFeatures;
use App\Enums\StationPermissions;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $app) {
$app->group('/vue', function (RouteCollectorProxy $group) {
$group->get('/files', Controller\Api\Stations\Vue\FilesAction::class)
->setName('api:vue:stations:files:index')
->add(new Middleware\StationSupportsFeature(StationFeatures::Media))
->add(new Middleware\Permissions(StationPermissions::Media, true));
$group->get('/mounts', Controller\Api\Stations\Vue\MountsAction::class)
->setName('api:vue:stations:mounts:index')
->add(new Middleware\Permissions(StationPermissions::MountPoints, true));
$group->get('/playlists', Controller\Api\Stations\Vue\PlaylistsAction::class)
->setName('api:vue:stations:playlists:index')
->add(new Middleware\StationSupportsFeature(StationFeatures::Media))
->add(new Middleware\Permissions(StationPermissions::Media, true));
$group->get('/podcasts', Controller\Api\Stations\Vue\PodcastsAction::class)
->setName('api:vue:stations:podcasts:index')
->add(new Middleware\StationSupportsFeature(StationFeatures::Podcasts))
->add(new Middleware\Permissions(StationPermissions::Podcasts, true));
$group->get('/profile', Controller\Api\Stations\Vue\ProfileAction::class)
->setName('api:vue:stations:profile:index');
$group->get('/profile/edit', Controller\Api\Stations\Vue\ProfileEditAction::class)
->setName('api:vue:stations:profile:edit')
->add(new Middleware\Permissions(StationPermissions::Profile, true));
$group->group(
'/reports',
function (RouteCollectorProxy $group) {
$group->get('/overview', Controller\Api\Stations\Vue\Reports\OverviewAction::class)
->setName('api:vue:stations:reports:overview');
$group->get('/listeners', Controller\Api\Stations\Vue\Reports\ListenersAction::class)
->setName('api:vue:stations:reports:listeners');
}
)->add(new Middleware\Permissions(StationPermissions::Reports, true));
$group->get('/restart', Controller\Api\Stations\Vue\RestartAction::class)
->setName('api:vue:stations:restart:index')
->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
$group->get('/sftp_users', Controller\Api\Stations\Vue\SftpUsersAction::class)
->setName('api:vue:stations:sftp_users:index')
->add(new Middleware\StationSupportsFeature(StationFeatures::Sftp))
->add(new Middleware\Permissions(StationPermissions::Media, true));
$group->get('/streamers', Controller\Api\Stations\Vue\StreamersAction::class)
->setName('api:vue:stations:streamers:index')
->add(new Middleware\StationSupportsFeature(StationFeatures::Streamers))
->add(new Middleware\Permissions(StationPermissions::Streamers, true));
})->add(new Middleware\Permissions(StationPermissions::View, true));
};
``` | /content/code_sandbox/backend/config/routes/api_station_vue.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 729 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Enums\StationFeatures;
use App\Enums\StationPermissions;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $group) {
$group->group(
'/station/{station_id}',
function (RouteCollectorProxy $group) {
/*
* Anonymous Functions
*/
$group->get('', Controller\Api\Stations\IndexController::class . ':indexAction')
->setName('api:stations:index')
->add(new Middleware\RateLimit('api', 5, 2));
$group->get('/nowplaying', Controller\Api\NowPlayingAction::class);
$group->get('/schedule', Controller\Api\Stations\ScheduleAction::class)
->setName('api:stations:schedule');
// Song Requests
$group->get('/requests', Controller\Api\Stations\Requests\ListAction::class)
->add(new Middleware\StationSupportsFeature(StationFeatures::Requests))
->setName('api:requests:list');
$group->map(
['GET', 'POST'],
'/request/{media_id}',
Controller\Api\Stations\Requests\SubmitAction::class
)
->setName('api:requests:submit')
->add(new Middleware\StationSupportsFeature(StationFeatures::Requests))
->add(new Middleware\RateLimit('api', 5, 2));
// On-Demand Streaming
$group->get('/ondemand', Controller\Api\Stations\OnDemand\ListAction::class)
->setName('api:stations:ondemand:list')
->add(new Middleware\StationSupportsFeature(StationFeatures::OnDemand));
$group->get('/ondemand/download/{media_id}', Controller\Api\Stations\OnDemand\DownloadAction::class)
->setName('api:stations:ondemand:download')
->add(new Middleware\StationSupportsFeature(StationFeatures::OnDemand))
->add(Middleware\RateLimit::forDownloads());
// NOTE: See ./api_public.php for podcast public pages.
/*
* Authenticated Functions
*/
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->map(
['GET', 'POST'],
'/nowplaying/update',
Controller\Api\Stations\UpdateMetadataAction::class
)->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
$group->get('/profile', Controller\Api\Stations\ProfileAction::class)
->setName('api:stations:profile')
->add(new Middleware\Permissions(StationPermissions::View, true));
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get(
'/profile/edit',
Controller\Api\Stations\ProfileEditController::class . ':getProfileAction'
)->setName('api:stations:profile:edit');
$group->put(
'/profile/edit',
Controller\Api\Stations\ProfileEditController::class . ':putProfileAction'
);
$group->get(
'/custom_assets/{type}',
Controller\Api\Stations\CustomAssets\GetCustomAssetAction::class
)->setName('api:stations:custom_assets');
$group->post(
'/custom_assets/{type}',
Controller\Api\Stations\CustomAssets\PostCustomAssetAction::class
);
$group->delete(
'/custom_assets/{type}',
Controller\Api\Stations\CustomAssets\DeleteCustomAssetAction::class
);
}
)->add(new Middleware\Permissions(StationPermissions::Profile, true));
// Upcoming Song Queue
$group->group(
'/queue',
function (RouteCollectorProxy $group) {
$group->get('', Controller\Api\Stations\QueueController::class . ':listAction')
->setName('api:stations:queue');
$group->post('/clear', Controller\Api\Stations\QueueController::class . ':clearAction')
->setName('api:stations:queue:clear');
$group->delete('/{id}', Controller\Api\Stations\QueueController::class . ':deleteAction')
->setName('api:stations:queue:record');
}
)->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
// Podcast Private Pages
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get('/podcasts', Controller\Api\Stations\PodcastsController::class . ':listAction')
->setName('api:stations:podcasts');
$group->post(
'/podcasts',
Controller\Api\Stations\PodcastsController::class . ':createAction'
);
$group->post('/podcasts/art', Controller\Api\Stations\Podcasts\Art\PostArtAction::class)
->setName('api:stations:podcasts:new-art');
$group->get('/podcasts/playlists', Controller\Api\Stations\Podcasts\PlaylistsAction::class)
->setName('api:stations:podcasts:playlists');
$group->group(
'/podcast/{podcast_id}',
function (RouteCollectorProxy $group) {
$group->get('', Controller\Api\Stations\PodcastsController::class . ':getAction')
->setName('api:stations:podcast');
$group->put('', Controller\Api\Stations\PodcastsController::class . ':editAction');
$group->delete(
'',
Controller\Api\Stations\PodcastsController::class . ':deleteAction'
);
$group->get(
'/art[-{timestamp}.jpg]',
Controller\Api\Stations\Podcasts\Art\GetArtAction::class
)->setName('api:stations:podcast:art');
$group->post(
'/art',
Controller\Api\Stations\Podcasts\Art\PostArtAction::class
);
$group->delete(
'/art',
Controller\Api\Stations\Podcasts\Art\DeleteArtAction::class
);
$group->get(
'/episodes',
Controller\Api\Stations\PodcastEpisodesController::class . ':listAction'
)->setName('api:stations:podcast:episodes');
$group->post(
'/episodes',
Controller\Api\Stations\PodcastEpisodesController::class . ':createAction'
);
$group->map(
['PUT', 'POST'],
'/batch',
Controller\Api\Stations\Podcasts\BatchAction::class
)->setName('api:stations:podcast:batch');
$group->post(
'/episodes/art',
Controller\Api\Stations\Podcasts\Episodes\Art\PostArtAction::class
)->setName('api:stations:podcast:episodes:new-art');
$group->post(
'/episodes/media',
Controller\Api\Stations\Podcasts\Episodes\Media\PostMediaAction::class
)->setName('api:stations:podcast:episodes:new-media');
$group->group(
'/episode/{episode_id}',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\PodcastEpisodesController::class . ':getAction'
)->setName('api:stations:podcast:episode');
$group->put(
'',
Controller\Api\Stations\PodcastEpisodesController::class . ':editAction'
);
$group->delete(
'',
Controller\Api\Stations\PodcastEpisodesController::class
. ':deleteAction'
);
$group->get(
'/art[-{timestamp}.jpg]',
Controller\Api\Stations\Podcasts\Episodes\Art\GetArtAction::class
)->setName('api:stations:podcast:episode:art');
$group->post(
'/art',
Controller\Api\Stations\Podcasts\Episodes\Art\PostArtAction::class
);
$group->delete(
'/art',
Controller\Api\Stations\Podcasts\Episodes\Art\DeleteArtAction::class
);
$group->get(
'/media',
Controller\Api\Stations\Podcasts\Episodes\Media\GetMediaAction::class
)->setName('api:stations:podcast:episode:media');
$group->post(
'/media',
Controller\Api\Stations\Podcasts\Episodes\Media\PostMediaAction::class
);
$group->delete(
'/media',
Controller\Api\Stations\Podcasts\Episodes\Media\DeleteMediaAction::class
);
}
);
}
)->add(Middleware\GetAndRequirePodcast::class);
}
)->add(new Middleware\Permissions(StationPermissions::Podcasts, true));
// Files/Media
$group->get('/quota[/{type}]', Controller\Api\Stations\GetQuotaAction::class)
->setName('api:stations:quota')
->add(new Middleware\Permissions(StationPermissions::View, true));
$group->get(
'/waveform/{media_id:[a-zA-Z0-9\-]+}[-{timestamp}.json]',
Controller\Api\Stations\Waveform\GetWaveformAction::class
)->setName('api:stations:media:waveform')
->add(new Middleware\Cache\SetStaticFileCache());
$group->post(
'/waveform/{media_id:[a-zA-Z0-9\-]+}',
Controller\Api\Stations\Waveform\PostCacheWaveformAction::class
)->setName('api:stations:media:waveform-cache');
$group->post('/art/{media_id:[a-zA-Z0-9]+}', Controller\Api\Stations\Art\PostArtAction::class)
->add(new Middleware\Permissions(StationPermissions::Media, true));
$group->delete('/art/{media_id:[a-zA-Z0-9]+}', Controller\Api\Stations\Art\DeleteArtAction::class)
->add(new Middleware\Permissions(StationPermissions::Media, true));
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->group(
'/files',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\FilesController::class . ':listAction'
)->setName('api:stations:files');
$group->post(
'',
Controller\Api\Stations\FilesController::class . ':createAction'
);
$group->get('/list', Controller\Api\Stations\Files\ListAction::class)
->setName('api:stations:files:list');
$group->get(
'/directories',
Controller\Api\Stations\Files\ListDirectoriesAction::class
)
->setName('api:stations:files:directories');
$group->put('/rename', Controller\Api\Stations\Files\RenameAction::class)
->setName('api:stations:files:rename');
$group->put('/batch', Controller\Api\Stations\Files\BatchAction::class)
->setName('api:stations:files:batch');
$group->post('/mkdir', Controller\Api\Stations\Files\MakeDirectoryAction::class)
->setName('api:stations:files:mkdir');
$group->get('/bulk', Controller\Api\Stations\BulkMedia\DownloadAction::class)
->setName('api:stations:files:bulk');
$group->post('/bulk', Controller\Api\Stations\BulkMedia\UploadAction::class);
$group->get('/download', Controller\Api\Stations\Files\DownloadAction::class)
->setName('api:stations:files:download');
$group->map(
['GET', 'POST'],
'/upload',
Controller\Api\Stations\Files\FlowUploadAction::class
)->setName('api:stations:files:upload');
}
);
$group->group(
'/file/{id}',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\FilesController::class . ':getAction'
)->setName('api:stations:file');
$group->put(
'',
Controller\Api\Stations\FilesController::class . ':editAction'
);
$group->delete(
'',
Controller\Api\Stations\FilesController::class . ':deleteAction'
);
$group->get('/play', Controller\Api\Stations\Files\PlayAction::class)
->setName('api:stations:files:play');
}
);
}
)->add(new Middleware\StationSupportsFeature(StationFeatures::Media))
->add(new Middleware\Permissions(StationPermissions::Media, true));
// SFTP Users
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get(
'/sftp-users',
Controller\Api\Stations\SftpUsersController::class . ':listAction'
)->setName('api:stations:sftp-users');
$group->post(
'/sftp-users',
Controller\Api\Stations\SftpUsersController::class . ':createAction'
);
$group->get(
'/sftp-user/{id}',
Controller\Api\Stations\SftpUsersController::class . ':getAction'
)->setName('api:stations:sftp-user');
$group->put(
'/sftp-user/{id}',
Controller\Api\Stations\SftpUsersController::class . ':editAction'
);
$group->delete(
'/sftp-user/{id}',
Controller\Api\Stations\SftpUsersController::class . ':deleteAction'
);
}
)->add(new Middleware\StationSupportsFeature(StationFeatures::Sftp))
->add(new Middleware\Permissions(StationPermissions::Media, true));
// Mount Points
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->group(
'/mounts',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\MountsController::class . ':listAction'
)->setName('api:stations:mounts');
$group->post(
'',
Controller\Api\Stations\MountsController::class . ':createAction'
);
$group->post(
'/intro',
Controller\Api\Stations\Mounts\Intro\PostIntroAction::class
)->setName('api:stations:mounts:new-intro');
}
);
$group->group(
'/mount/{id}',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\MountsController::class . ':getAction'
)->setName('api:stations:mount');
$group->put(
'',
Controller\Api\Stations\MountsController::class . ':editAction'
);
$group->delete(
'',
Controller\Api\Stations\MountsController::class . ':deleteAction'
);
$group->get(
'/intro',
Controller\Api\Stations\Mounts\Intro\GetIntroAction::class
)->setName('api:stations:mounts:intro');
$group->post(
'/intro',
Controller\Api\Stations\Mounts\Intro\PostIntroAction::class
);
$group->delete(
'/intro',
Controller\Api\Stations\Mounts\Intro\DeleteIntroAction::class
);
}
);
}
)->add(new Middleware\StationSupportsFeature(StationFeatures::MountPoints))
->add(new Middleware\Permissions(StationPermissions::MountPoints, true));
// Remote Relays
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get(
'/remotes',
Controller\Api\Stations\RemotesController::class . ':listAction'
)->setName('api:stations:remotes');
$group->post(
'/remotes',
Controller\Api\Stations\RemotesController::class . ':createAction'
);
$group->get(
'/remote/{id}',
Controller\Api\Stations\RemotesController::class . ':getAction'
)->setName('api:stations:remote');
$group->put(
'/remote/{id}',
Controller\Api\Stations\RemotesController::class . ':editAction'
);
$group->delete(
'/remote/{id}',
Controller\Api\Stations\RemotesController::class . ':deleteAction'
);
}
)->add(new Middleware\StationSupportsFeature(StationFeatures::RemoteRelays))
->add(new Middleware\Permissions(StationPermissions::RemoteRelays, true));
// HLS Streams
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get(
'/hls_streams',
Controller\Api\Stations\HlsStreamsController::class . ':listAction'
)->setName('api:stations:hls_streams');
$group->post(
'/hls_streams',
Controller\Api\Stations\HlsStreamsController::class . ':createAction'
);
$group->get(
'/hls_stream/{id}',
Controller\Api\Stations\HlsStreamsController::class . ':getAction'
)->setName('api:stations:hls_stream');
$group->put(
'/hls_stream/{id}',
Controller\Api\Stations\HlsStreamsController::class . ':editAction'
);
$group->delete(
'/hls_stream/{id}',
Controller\Api\Stations\HlsStreamsController::class . ':deleteAction'
);
}
)->add(new Middleware\StationSupportsFeature(StationFeatures::HlsStreams))
->add(new Middleware\Permissions(StationPermissions::MountPoints, true));
// Playlist
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get(
'/playlists',
Controller\Api\Stations\PlaylistsController::class . ':listAction'
)->setName('api:stations:playlists');
$group->post(
'/playlists',
Controller\Api\Stations\PlaylistsController::class . ':createAction'
);
$group->get(
'/playlists/schedule',
Controller\Api\Stations\PlaylistsController::class . ':scheduleAction'
)->setName('api:stations:playlists:schedule');
$group->group(
'/playlist/{id}',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\PlaylistsController::class . ':getAction'
)->setName('api:stations:playlist');
$group->put(
'',
Controller\Api\Stations\PlaylistsController::class . ':editAction'
);
$group->delete(
'',
Controller\Api\Stations\PlaylistsController::class . ':deleteAction'
);
$group->put(
'/toggle',
Controller\Api\Stations\Playlists\ToggleAction::class
)->setName('api:stations:playlist:toggle');
$group->put(
'/reshuffle',
Controller\Api\Stations\Playlists\ReshuffleAction::class
)->setName('api:stations:playlist:reshuffle');
$group->get(
'/order',
Controller\Api\Stations\Playlists\GetOrderAction::class
)->setName('api:stations:playlist:order');
$group->put(
'/order',
Controller\Api\Stations\Playlists\PutOrderAction::class
);
$group->get(
'/queue',
Controller\Api\Stations\Playlists\GetQueueAction::class
)->setName('api:stations:playlist:queue');
$group->delete(
'/queue',
Controller\Api\Stations\Playlists\DeleteQueueAction::class
);
$group->post(
'/clone',
Controller\Api\Stations\Playlists\CloneAction::class
)->setName('api:stations:playlist:clone');
$group->post(
'/import',
Controller\Api\Stations\Playlists\ImportAction::class
)->setName('api:stations:playlist:import');
$group->get(
'/export[/{format}]',
Controller\Api\Stations\Playlists\ExportAction::class
)->setName('api:stations:playlist:export');
$group->get(
'/apply-to',
Controller\Api\Stations\Playlists\GetApplyToAction::class
)->setName('api:stations:playlist:applyto');
$group->put(
'/apply-to',
Controller\Api\Stations\Playlists\PutApplyToAction::class
);
$group->delete(
'/empty',
Controller\Api\Stations\Playlists\EmptyAction::class
)->setName('api:stations:playlist:empty');
}
);
}
)->add(new Middleware\StationSupportsFeature(StationFeatures::Media))
->add(new Middleware\Permissions(StationPermissions::Media, true));
// Reports
$group->get('/history', Controller\Api\Stations\HistoryAction::class)
->setName('api:stations:history')
->add(new Middleware\Permissions(StationPermissions::Reports, true));
$group->get('/listeners', Controller\Api\Stations\ListenersAction::class)
->setName('api:listeners:index')
->add(new Middleware\Permissions(StationPermissions::Reports, true));
$group->group(
'/reports',
function (RouteCollectorProxy $group) {
$group->group(
'/requests',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\Reports\RequestsController::class . ':listAction'
)->setName('api:stations:reports:requests');
$group->post(
'/clear',
Controller\Api\Stations\Reports\RequestsController::class . ':clearAction'
)->setName('api:stations:reports:requests:clear');
$group->delete(
'/{request_id}',
Controller\Api\Stations\Reports\RequestsController::class . ':deleteAction'
)->setName('api:stations:reports:requests:delete');
}
)->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
$group->get(
'/overview/charts',
Controller\Api\Stations\Reports\Overview\ChartsAction::class
)->setName('api:stations:reports:overview-charts');
$group->get(
'/overview/best-and-worst',
Controller\Api\Stations\Reports\Overview\BestAndWorstAction::class
)->setName('api:stations:reports:best-and-worst');
$group->get(
'/overview/by-browser',
Controller\Api\Stations\Reports\Overview\ByBrowser::class
)->setName('api:stations:reports:by-browser');
$group->get(
'/overview/by-country',
Controller\Api\Stations\Reports\Overview\ByCountry::class
)->setName('api:stations:reports:by-country');
$group->get(
'/overview/by-stream',
Controller\Api\Stations\Reports\Overview\ByStream::class
)->setName('api:stations:reports:by-stream');
$group->get(
'/overview/by-client',
Controller\Api\Stations\Reports\Overview\ByClient::class
)->setName('api:stations:reports:by-client');
$group->get(
'/overview/by-listening-time',
Controller\Api\Stations\Reports\Overview\ByListeningTime::class
)->setName('api:stations:reports:by-listening-time');
$group->get(
'/soundexchange',
Controller\Api\Stations\Reports\SoundExchangeAction::class
)->setName('api:stations:reports:soundexchange');
}
)->add(new Middleware\Permissions(StationPermissions::Reports, true));
// Streamers
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->group(
'/streamers',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\StreamersController::class . ':listAction'
)->setName('api:stations:streamers');
$group->post(
'',
Controller\Api\Stations\StreamersController::class . ':createAction'
);
$group->get(
'/schedule',
Controller\Api\Stations\StreamersController::class . ':scheduleAction'
)->setName('api:stations:streamers:schedule');
$group->get(
'/broadcasts',
Controller\Api\Stations\Streamers\BroadcastsController::class . ':listAction'
)->setName('api:stations:streamers:broadcasts');
$group->post(
'/art',
Controller\Api\Stations\Streamers\Art\PostArtAction::class
)->setName('api:stations:streamers:new-art');
}
);
$group->group(
'/streamer/{id}',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\StreamersController::class . ':getAction'
)->setName('api:stations:streamer');
$group->put(
'',
Controller\Api\Stations\StreamersController::class . ':editAction'
);
$group->delete(
'',
Controller\Api\Stations\StreamersController::class . ':deleteAction'
);
$group->get(
'/broadcasts',
Controller\Api\Stations\Streamers\BroadcastsController::class . ':listAction'
)->setName('api:stations:streamer:broadcasts');
$group->map(
['PUT', 'POST'],
'/broadcasts/batch',
Controller\Api\Stations\Streamers\Broadcasts\BatchAction::class
)->setName('api:stations:streamer:broadcasts:batch');
$group->get(
'/broadcast/{broadcast_id}/download',
Controller\Api\Stations\Streamers\BroadcastsController::class
. ':downloadAction'
)->setName('api:stations:streamer:broadcast:download');
$group->delete(
'/broadcast/{broadcast_id}',
Controller\Api\Stations\Streamers\BroadcastsController::class . ':deleteAction'
)->setName('api:stations:streamer:broadcast:delete');
$group->post(
'/art',
Controller\Api\Stations\Streamers\Art\PostArtAction::class
)->setName('api:stations:streamer:art-internal');
$group->delete(
'/art',
Controller\Api\Stations\Streamers\Art\DeleteArtAction::class
);
}
);
}
)->add(new Middleware\StationSupportsFeature(StationFeatures::Streamers))
->add(new Middleware\Permissions(StationPermissions::Streamers, true));
$group->get('/restart-status', Controller\Api\Stations\GetRestartStatusAction::class)
->setName('api:stations:restart-status')
->add(new Middleware\Permissions(StationPermissions::View, true));
$group->get('/status', Controller\Api\Stations\ServicesController::class . ':statusAction')
->setName('api:stations:status')
->add(new Middleware\Permissions(StationPermissions::View, true));
$group->post('/backend/{do}', Controller\Api\Stations\ServicesController::class . ':backendAction')
->setName('api:stations:backend')
->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
$group->post(
'/frontend/{do}',
Controller\Api\Stations\ServicesController::class . ':frontendAction'
)->setName('api:stations:frontend')
->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
$group->post('/reload', Controller\Api\Stations\ServicesController::class . ':reloadAction')
->setName('api:stations:reload')
->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
$group->post('/restart', Controller\Api\Stations\ServicesController::class . ':restartAction')
->setName('api:stations:restart')
->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
// Custom Fallback File
$group->group(
'/fallback',
function (RouteCollectorProxy $group) {
$group->get(
'[/{do}]',
Controller\Api\Stations\Fallback\GetFallbackAction::class
)->setName('api:stations:fallback');
$group->post(
'',
Controller\Api\Stations\Fallback\PostFallbackAction::class
);
$group->delete(
'',
Controller\Api\Stations\Fallback\DeleteFallbackAction::class
);
}
)->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
// Webhook Extras
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get(
'/webhooks',
Controller\Api\Stations\WebhooksController::class . ':listAction'
)->setName('api:stations:webhooks');
$group->post(
'/webhooks',
Controller\Api\Stations\WebhooksController::class . ':createAction'
);
$group->group(
'/webhook/{id}',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\WebhooksController::class . ':getAction'
)->setName('api:stations:webhook');
$group->put(
'',
Controller\Api\Stations\WebhooksController::class . ':editAction'
);
$group->delete(
'',
Controller\Api\Stations\WebhooksController::class . ':deleteAction'
);
$group->put(
'/toggle',
Controller\Api\Stations\Webhooks\ToggleAction::class
)->setName('api:stations:webhook:toggle');
$group->put(
'/test',
Controller\Api\Stations\Webhooks\TestAction::class
)->setName('api:stations:webhook:test');
$group->get(
'/test-log/{path}',
Controller\Api\Stations\Webhooks\TestLogAction::class
)->setName('api:stations:webhook:test-log');
}
);
}
)->add(new Middleware\StationSupportsFeature(StationFeatures::Webhooks))
->add(new Middleware\Permissions(StationPermissions::WebHooks, true));
// Custom Liquidsoap Configuration
$group->group(
'/liquidsoap-config',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\LiquidsoapConfig\GetAction::class
)->setName('api:stations:liquidsoap-config');
$group->put(
'',
Controller\Api\Stations\LiquidsoapConfig\PutAction::class
);
}
)->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
// StereoTool Configuration
$group->group(
'/stereo_tool_config',
function (RouteCollectorProxy $group) {
$group->get(
'[/{do}]',
Controller\Api\Stations\StereoTool\GetStereoToolConfigurationAction::class
)->setName('api:stations:stereo_tool_config');
$group->post(
'',
Controller\Api\Stations\StereoTool\PostStereoToolConfigurationAction::class
);
$group->delete(
'',
Controller\Api\Stations\StereoTool\DeleteStereoToolConfigurationAction::class
);
}
)->add(new Middleware\Permissions(StationPermissions::Broadcasting, true));
// Logs
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get('/logs', Controller\Api\Stations\LogsAction::class)
->setName('api:stations:logs');
$group->get('/log/{log}', Controller\Api\Stations\LogsAction::class)
->setName('api:stations:log');
}
)->add(new Middleware\Permissions(StationPermissions::Logs, true));
// Vue Properties
call_user_func(include(__DIR__ . '/api_station_vue.php'), $group);
}
)->add(Middleware\RequireLogin::class);
}
)->add(Middleware\RequireStation::class)
->add(Middleware\GetStation::class);
};
``` | /content/code_sandbox/backend/config/routes/api_station.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 7,080 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Enums\GlobalPermissions;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $group) {
$group->get(
'/prometheus',
Controller\Api\PrometheusAction::class
)->setName('api:prometheus')
->add(new Middleware\Permissions(GlobalPermissions::View));
$group->group(
'/admin',
function (RouteCollectorProxy $group) {
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get(
'/api-keys',
Controller\Api\Admin\ApiKeysController::class . ':listAction'
)->setName('api:admin:api-keys');
$group->get(
'/api-key/{id}',
Controller\Api\Admin\ApiKeysController::class . ':getAction'
)->setName('api:admin:api-key');
$group->delete(
'/api-key/{id}',
Controller\Api\Admin\ApiKeysController::class . ':deleteAction'
);
}
)->add(new Middleware\Permissions(GlobalPermissions::ApiKeys));
$group->get('/auditlog', Controller\Api\Admin\AuditLogAction::class)
->setName('api:admin:auditlog')
->add(new Middleware\Permissions(GlobalPermissions::Logs));
$group->group(
'/backups',
function (RouteCollectorProxy $group) {
$group->get('', Controller\Api\Admin\Backups\GetAction::class)
->setName('api:admin:backups');
$group->post('/run', Controller\Api\Admin\Backups\RunAction::class)
->setName('api:admin:backups:run');
$group->get('/log/{path}', Controller\Api\Admin\Backups\GetLogAction::class)
->setName('api:admin:backups:log');
$group->get('/download/{path}', Controller\Api\Admin\Backups\DownloadAction::class)
->setName('api:admin:backups:download');
$group->delete('/delete/{path}', Controller\Api\Admin\Backups\DeleteAction::class)
->setName('api:admin:backups:delete');
}
)->add(new Middleware\Permissions(GlobalPermissions::Backups));
$group->group(
'/debug',
function (RouteCollectorProxy $group) {
$group->put('/clear-cache', Controller\Api\Admin\Debug\ClearCacheAction::class)
->setName('api:admin:debug:clear-cache');
$group->get(
'/queues',
Controller\Api\Admin\Debug\ListQueuesAction::class
)->setName('api:admin:debug:queues');
$group->put(
'/clear-queue[/{queue}]',
Controller\Api\Admin\Debug\ClearQueueAction::class
)->setName('api:admin:debug:clear-queue');
$group->get(
'/sync-tasks',
Controller\Api\Admin\Debug\ListSyncTasksAction::class
)->setName('api:admin:debug:sync-tasks');
$group->put('/sync/{task}', Controller\Api\Admin\Debug\SyncAction::class)
->setName('api:admin:debug:sync');
$group->get(
'/stations',
Controller\Api\Admin\Debug\ListStationsAction::class
)->setName('api:admin:debug:stations');
$group->group(
'/station/{station_id}',
function (RouteCollectorProxy $group) {
$group->put(
'/nowplaying',
Controller\Api\Admin\Debug\NowPlayingAction::class
)->setName('api:admin:debug:nowplaying');
$group->put(
'/nextsong',
Controller\Api\Admin\Debug\NextSongAction::class
)->setName('api:admin:debug:nextsong');
$group->put(
'/clearqueue',
Controller\Api\Admin\Debug\ClearStationQueueAction::class
)->setName('api:admin:debug:clear-station-queue');
$group->put('/telnet', Controller\Api\Admin\Debug\TelnetAction::class)
->setName('api:admin:debug:telnet');
}
)->add(Middleware\GetStation::class);
}
)->add(new Middleware\Permissions(GlobalPermissions::All));
$group->get('/server/stats', Controller\Api\Admin\ServerStatsAction::class)
->setName('api:admin:server:stats')
->add(new Middleware\Permissions(GlobalPermissions::View));
$group->get(
'/services',
Controller\Api\Admin\ServiceControlController::class . ':getAction'
)->setName('api:admin:services')
->add(new Middleware\Permissions(GlobalPermissions::View));
$group->post(
'/services/restart/{service}',
Controller\Api\Admin\ServiceControlController::class . ':restartAction'
)->setName('api:admin:services:restart')
->add(new Middleware\Permissions(GlobalPermissions::All));
$group->get('/permissions', Controller\Api\Admin\PermissionsAction::class)
->add(new Middleware\Permissions(GlobalPermissions::All));
$group->get('/relays/list', Controller\Api\Admin\RelaysAction::class)
->setName('api:admin:relays')
->add(new Middleware\Permissions(GlobalPermissions::Stations));
$group->map(
['GET', 'POST'],
'/relays',
function (ServerRequest $request, Response $response) {
return $response->withRedirect(
$request->getRouter()->fromHere('api:internal:relays')
);
}
);
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get(
'/settings[/{group}]',
Controller\Api\Admin\SettingsController::class . ':listAction'
)->setName('api:admin:settings');
$group->put(
'/settings[/{group}]',
Controller\Api\Admin\SettingsController::class . ':updateAction'
);
$group->post(
'/send-test-message',
Controller\Api\Admin\SendTestMessageAction::class
)->setName('api:admin:send-test-message');
$group->put(
'/acme',
Controller\Api\Admin\Acme\GenerateCertificateAction::class
)->setName('api:admin:acme');
$group->get(
'/acme-log/{path}',
Controller\Api\Admin\Acme\CertificateLogAction::class
)->setName('api:admin:acme-log');
$group->get(
'/custom_assets/{type}',
Controller\Api\Admin\CustomAssets\GetCustomAssetAction::class
)->setName('api:admin:custom_assets');
$group->post(
'/custom_assets/{type}',
Controller\Api\Admin\CustomAssets\PostCustomAssetAction::class
);
$group->delete(
'/custom_assets/{type}',
Controller\Api\Admin\CustomAssets\DeleteCustomAssetAction::class
);
$group->get(
'/geolite',
Controller\Api\Admin\GeoLite\GetAction::class
)->setName('api:admin:geolite');
$group->post(
'/geolite',
Controller\Api\Admin\GeoLite\PostAction::class
);
$group->get(
'/shoutcast',
Controller\Api\Admin\Shoutcast\GetAction::class
)->setName('api:admin:shoutcast');
$group->post(
'/shoutcast',
Controller\Api\Admin\Shoutcast\PostAction::class
);
$group->get(
'/stereo_tool',
Controller\Api\Admin\StereoTool\GetAction::class
)->setName('api:admin:stereo_tool');
$group->post(
'/stereo_tool',
Controller\Api\Admin\StereoTool\PostAction::class
);
$group->delete(
'/stereo_tool',
Controller\Api\Admin\StereoTool\DeleteAction::class
);
}
)->add(new Middleware\Permissions(GlobalPermissions::Settings));
$adminApiEndpoints = [
[
'custom_field',
'custom_fields',
Controller\Api\Admin\CustomFieldsController::class,
GlobalPermissions::CustomFields,
],
['role', 'roles', Controller\Api\Admin\RolesController::class, GlobalPermissions::All],
['station', 'stations', Controller\Api\Admin\StationsController::class, GlobalPermissions::Stations],
['user', 'users', Controller\Api\Admin\UsersController::class, GlobalPermissions::All],
[
'storage_location',
'storage_locations',
Controller\Api\Admin\StorageLocationsController::class,
GlobalPermissions::StorageLocations,
],
];
foreach ($adminApiEndpoints as [$singular, $plural, $class, $permission]) {
$group->group(
'',
function (RouteCollectorProxy $group) use ($singular, $plural, $class) {
$group->get('/' . $plural, $class . ':listAction')
->setName('api:admin:' . $plural);
$group->post('/' . $plural, $class . ':createAction');
$group->get('/' . $singular . '/{id}', $class . ':getAction')
->setName('api:admin:' . $singular);
$group->put('/' . $singular . '/{id}', $class . ':editAction');
$group->delete('/' . $singular . '/{id}', $class . ':deleteAction');
}
)->add(new Middleware\Permissions($permission));
}
$group->post('/station/{id}/clone', Controller\Api\Admin\Stations\CloneAction::class)
->setName('api:admin:station:clone')
->add(new Middleware\Permissions(GlobalPermissions::Stations));
$group->get(
'/stations/storage-locations',
Controller\Api\Admin\Stations\StorageLocationsAction::class
)->setName('api:admin:stations:storage-locations')
->add(new Middleware\Permissions(GlobalPermissions::Stations));
$group->group(
'',
function (RouteCollectorProxy $group) {
$group->get('/logs', Controller\Api\Admin\LogsAction::class)
->setName('api:admin:logs');
$group->get('/log/{log}', Controller\Api\Admin\LogsAction::class)
->setName('api:admin:log');
}
)->add(new Middleware\Permissions(GlobalPermissions::Logs));
$group->group(
'/updates',
function (RouteCollectorProxy $group) {
$group->get('', Controller\Api\Admin\Updates\GetUpdatesAction::class)
->setName('api:admin:updates');
$group->put('', Controller\Api\Admin\Updates\PutUpdatesAction::class);
}
)->add(new Middleware\Permissions(GlobalPermissions::All));
call_user_func(include(__DIR__ . '/api_admin_vue.php'), $group);
}
);
};
``` | /content/code_sandbox/backend/config/routes/api_admin.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 2,366 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Enums\GlobalPermissions;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $app) {
$app->get('/', Controller\Frontend\IndexAction::class)
->setName('home');
$app->get('/logout', Controller\Frontend\Account\LogoutAction::class)
->setName('account:logout')
->add(Middleware\RequireLogin::class);
$app->get('/login-as/{id}/{csrf}', Controller\Frontend\Account\MasqueradeAction::class)
->setName('account:masquerade')
->add(new Middleware\Permissions(GlobalPermissions::All))
->add(Middleware\RequireLogin::class);
$app->get('/endsession', Controller\Frontend\Account\EndMasqueradeAction::class)
->setName('account:endmasquerade')
->add(Middleware\RequireLogin::class);
$app->group(
'',
function (RouteCollectorProxy $group) {
$group->get('/dashboard', Controller\Frontend\DashboardAction::class)
->setName('dashboard');
$group->get('/profile', Controller\Frontend\Profile\IndexAction::class)
->setName('profile:index');
}
)->add(Middleware\Module\PanelLayout::class)
->add(Middleware\EnableView::class)
->add(Middleware\RequireLogin::class);
$app->map(['GET', 'POST'], '/login', Controller\Frontend\Account\LoginAction::class)
->setName('account:login')
->add(Middleware\EnableView::class);
$app->map(['GET', 'POST'], '/login/2fa', Controller\Frontend\Account\TwoFactorAction::class)
->setName('account:login:2fa')
->add(Middleware\EnableView::class);
$app->map(['GET', 'POST'], '/forgot', Controller\Frontend\Account\ForgotPasswordAction::class)
->setName('account:forgot')
->add(Middleware\EnableView::class);
$app->map(['GET', 'POST'], '/recover/{token}', Controller\Frontend\Account\RecoverAction::class)
->setName('account:recover')
->add(Middleware\EnableView::class);
$app->get('/login/webauthn', Controller\Frontend\Account\WebAuthn\GetValidationAction::class)
->setName('account:webauthn');
$app->post('/login/webauthn', Controller\Frontend\Account\WebAuthn\PostValidationAction::class);
$app->group(
'/setup',
function (RouteCollectorProxy $group) {
$group->map(['GET', 'POST'], '', Controller\Frontend\SetupController::class . ':indexAction')
->setName('setup:index');
$group->map(['GET', 'POST'], '/complete', Controller\Frontend\SetupController::class . ':completeAction')
->setName('setup:complete');
$group->map(['GET', 'POST'], '/register', Controller\Frontend\SetupController::class . ':registerAction')
->setName('setup:register');
$group->map(['GET', 'POST'], '/station', Controller\Frontend\SetupController::class . ':stationAction')
->setName('setup:station')
->add(Middleware\Module\PanelLayout::class);
$group->map(['GET', 'POST'], '/settings', Controller\Frontend\SetupController::class . ':settingsAction')
->setName('setup:settings')
->add(Middleware\Module\PanelLayout::class);
}
)->add(Middleware\EnableView::class);
call_user_func(include(__DIR__ . '/admin.php'), $app);
call_user_func(include(__DIR__ . '/stations.php'), $app);
};
``` | /content/code_sandbox/backend/config/routes/base.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 836 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Slim\Routing\RouteCollectorProxy;
// Public-facing API endpoints (unauthenticated).
return static function (RouteCollectorProxy $group) {
$group->options(
'/{routes:.+}',
function (ServerRequest $request, Response $response, ...$params) {
return $response
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->withHeader(
'Access-Control-Allow-Headers',
'x-api-key, x-requested-with, Content-Type, Accept, Origin, Authorization'
)
->withHeader('Access-Control-Allow-Origin', '*');
}
);
$group->get(
'',
function (ServerRequest $request, Response $response, ...$params): ResponseInterface {
return $response->withRedirect('/docs/api/');
}
)->setName('api:index:index');
$group->get('/openapi.yml', Controller\Api\OpenApiAction::class)
->setName('api:openapi')
->add(new Middleware\Cache\SetCache(60));
$group->get('/status', Controller\Api\IndexController::class . ':statusAction')
->setName('api:index:status');
$group->get('/time', Controller\Api\IndexController::class . ':timeAction')
->setName('api:index:time')
->add(new Middleware\Cache\SetCache(1));
$group->get(
'/nowplaying[/{station_id}]',
Controller\Api\NowPlayingAction::class
)->setName('api:nowplaying:index')
->add(new Middleware\Cache\SetCache(15))
->add(Middleware\GetStation::class);
$group->get(
'/nowplaying/{station_id}/art[/{timestamp}.jpg]',
Controller\Api\NowPlayingArtAction::class
)->setName('api:nowplaying:art')
->add(new Middleware\Cache\SetCache(15))
->add(Middleware\RequireStation::class)
->add(Middleware\GetStation::class);
$group->get('/stations', Controller\Api\Stations\IndexController::class . ':listAction')
->setName('api:stations:list')
->add(new Middleware\RateLimit('api'));
$group->group(
'/station/{station_id}',
function (RouteCollectorProxy $group) {
// Media Art
$group->get(
'/art/{media_id:[a-zA-Z0-9\-]+}[-{timestamp}.jpg]',
Controller\Api\Stations\Art\GetArtAction::class
)->setName('api:stations:media:art')
->add(new Middleware\Cache\SetStaticFileCache());
// Streamer Art
$group->get(
'/streamer/{id}/art[-{timestamp}.jpg]',
Controller\Api\Stations\Streamers\Art\GetArtAction::class
)->setName('api:stations:streamer:art')
->add(new Middleware\Cache\SetStaticFileCache());
$group->group(
'/public',
function (RouteCollectorProxy $group) {
// Podcast Public Pages
$group->get('/podcasts', Controller\Api\Stations\Podcasts\ListPodcastsAction::class)
->setName('api:stations:public:podcasts');
$group->group(
'/podcast/{podcast_id}',
function (RouteCollectorProxy $group) {
$group->get('', Controller\Api\Stations\Podcasts\GetPodcastAction::class)
->setName('api:stations:public:podcast');
$group->get(
'/art[-{timestamp}.jpg]',
Controller\Api\Stations\Podcasts\Art\GetArtAction::class
)->setName('api:stations:public:podcast:art')
->add(new Middleware\Cache\SetStaticFileCache());
$group->get(
'/episodes',
Controller\Api\Stations\Podcasts\Episodes\ListEpisodesAction::class
)->setName('api:stations:public:podcast:episodes');
$group->group(
'/episode/{episode_id}',
function (RouteCollectorProxy $group) {
$group->get(
'',
Controller\Api\Stations\Podcasts\Episodes\GetEpisodeAction::class
)->setName('api:stations:public:podcast:episode')
->add(new Middleware\Cache\SetStaticFileCache());
$group->get(
'/art[-{timestamp}.jpg]',
Controller\Api\Stations\Podcasts\Episodes\Art\GetArtAction::class
)->setName('api:stations:public:podcast:episode:art')
->add(new Middleware\Cache\SetStaticFileCache());
$group->get(
'/download[.{extension}]',
Controller\Api\Stations\Podcasts\Episodes\Media\GetMediaAction::class
)->setName('api:stations:public:podcast:episode:download')
->add(Middleware\RateLimit::forDownloads());
}
);
}
)->add(Middleware\RequirePublishedPodcastEpisodeMiddleware::class)
->add(Middleware\GetAndRequirePodcast::class);
}
);
}
)->add(Middleware\RequireStation::class)
->add(Middleware\GetStation::class);
};
``` | /content/code_sandbox/backend/config/routes/api_public.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,172 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
// Internal API endpoints (called by other programs hosted on the same machine).
return static function (RouteCollectorProxy $group) {
$group->group(
'/internal',
function (RouteCollectorProxy $group) {
$group->group(
'/{station_id}',
function (RouteCollectorProxy $group) {
$group->map(
['GET', 'POST'],
'/liquidsoap/{action}',
Controller\Api\Internal\LiquidsoapAction::class
)->setName('api:internal:liquidsoap');
// Icecast internal auth functions
$group->map(
['GET', 'POST'],
'/listener-auth',
Controller\Api\Internal\ListenerAuthAction::class
)->setName('api:internal:listener-auth');
}
)->add(Middleware\GetStation::class);
$group->post('/sftp-auth', Controller\Api\Internal\SftpAuthAction::class)
->setName('api:internal:sftp-auth');
$group->post('/sftp-event', Controller\Api\Internal\SftpEventAction::class)
->setName('api:internal:sftp-event');
$group->get('/relays', Controller\Api\Internal\RelaysController::class)
->setName('api:internal:relays')
->add(Middleware\RequireLogin::class);
$group->post('/relays', Controller\Api\Internal\RelaysController::class . ':updateAction')
->add(Middleware\RequireLogin::class);
}
);
};
``` | /content/code_sandbox/backend/config/routes/api_internal.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 344 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Enums\GlobalPermissions;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $app) {
$app->group(
'/vue',
function (RouteCollectorProxy $group) {
$group->get('/backups', Controller\Api\Admin\Vue\BackupsAction::class)
->setName('api:vue:admin:backups')
->add(new Middleware\Permissions(GlobalPermissions::Backups));
$group->get('/custom_fields', Controller\Api\Admin\Vue\CustomFieldsAction::class)
->setName('api:vue:admin:custom_fields')
->add(new Middleware\Permissions(GlobalPermissions::CustomFields));
$group->get('/logs', Controller\Api\Admin\Vue\LogsAction::class)
->setName('api:vue:admin:logs')
->add(new Middleware\Permissions(GlobalPermissions::Logs));
$group->get('/permissions', Controller\Api\Admin\Vue\PermissionsAction::class)
->setName('api:vue:admin:permissions')
->add(new Middleware\Permissions(GlobalPermissions::All));
$group->get('/settings', Controller\Api\Admin\Vue\SettingsAction::class)
->setName('api:vue:admin:settings')
->add(new Middleware\Permissions(GlobalPermissions::Settings));
$group->get('/stations', Controller\Api\Admin\Vue\StationsAction::class)
->setName('api:vue:admin:stations')
->add(new Middleware\Permissions(GlobalPermissions::Stations));
$group->get('/updates', Controller\Api\Admin\Vue\UpdatesAction::class)
->setName('api:vue:admin:updates')
->add(new Middleware\Permissions(GlobalPermissions::All));
$group->get('/users', Controller\Api\Admin\Vue\UsersAction::class)
->setName('api:vue:admin:users')
->add(new Middleware\Permissions(GlobalPermissions::All));
}
)->add(new Middleware\Permissions(GlobalPermissions::View))
->add(Middleware\RequireLogin::class);
};
``` | /content/code_sandbox/backend/config/routes/api_admin_vue.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 444 |
```php
<?php
declare(strict_types=1);
use App\Controller\AdminAction;
use App\Enums\GlobalPermissions;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $app) {
$app->group(
'/admin',
function (RouteCollectorProxy $group) {
$routes = [
'admin:index:index' => '',
'admin:debug:index' => '/debug',
'admin:install_shoutcast:index' => '/install/shoutcast',
'admin:install_stereo_tool:index' => '/install/stereo_tool',
'admin:install_geolite:index' => '/install/geolite',
'admin:auditlog:index' => '/auditlog',
'admin:api:index' => '/api-keys',
'admin:backups:index' => '/backups',
'admin:branding:index' => '/branding',
'admin:custom_fields:index' => '/custom_fields',
'admin:logs:index' => '/logs',
'admin:permissions:index' => '/permissions',
'admin:relays:index' => '/relays',
'admin:settings:index' => '/settings',
'admin:stations:index' => '/stations',
'admin:storage_locations:index' => '/storage_locations',
'admin:updates:index' => '/updates',
'admin:users:index' => '/users',
];
foreach ($routes as $routeName => $routePath) {
$group->get($routePath, AdminAction::class)
->setName($routeName);
}
$group->get('/{routes:.+}', AdminAction::class);
}
)->add(Middleware\Module\PanelLayout::class)
->add(Middleware\EnableView::class)
->add(new Middleware\Permissions(GlobalPermissions::View))
->add(Middleware\RequireLogin::class);
};
``` | /content/code_sandbox/backend/config/routes/admin.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 401 |
```php
<?php
declare(strict_types=1);
use App\Controller;
use App\Http\Response;
use App\Http\ServerRequest;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $app) {
$app->get(
'/public/sw.js',
function (ServerRequest $request, Response $response, ...$params) {
return $response
->withHeader('Content-Type', 'text/javascript')
->write(
<<<'JS'
self.addEventListener('install', event => {
// Kick out the old service worker
self.skipWaiting();
});
JS
);
}
)->setName('public:sw');
$app->group(
'/public/{station_id}',
function (RouteCollectorProxy $group) {
$group->get('[/{embed:embed|social}]', Controller\Frontend\PublicPages\PlayerAction::class)
->setName('public:index');
$group->get('/oembed/{format:json|xml}', Controller\Frontend\PublicPages\OEmbedAction::class)
->setName('public:oembed');
$group->get('/app.webmanifest', Controller\Frontend\PWA\AppManifestAction::class)
->setName('public:manifest');
$group->get('/embed-requests', Controller\Frontend\PublicPages\RequestsAction::class)
->setName('public:embedrequests')
->add(new Middleware\StationSupportsFeature(App\Enums\StationFeatures::Requests));
$group->get('/playlist[.{format}]', Controller\Frontend\PublicPages\PlaylistAction::class)
->setName('public:playlist');
$group->get('/history', Controller\Frontend\PublicPages\HistoryAction::class)
->setName('public:history');
$group->get('/dj', Controller\Frontend\PublicPages\WebDjAction::class)
->setName('public:dj');
$group->get('/ondemand[/{embed:embed}]', Controller\Frontend\PublicPages\OnDemandAction::class)
->setName('public:ondemand')
->add(new Middleware\StationSupportsFeature(App\Enums\StationFeatures::OnDemand));
$group->get('/schedule[/{embed:embed}]', Controller\Frontend\PublicPages\ScheduleAction::class)
->setName('public:schedule');
$routes = [
'public:podcasts' => '/podcasts',
'public:podcast' => '/podcast/{podcast_id}',
'public:podcast:episode' => '/podcast/{podcast_id}/episode/{episode_id}',
];
foreach ($routes as $routeName => $routePath) {
$group->get($routePath, Controller\Frontend\PublicPages\PodcastsAction::class)
->setName($routeName);
}
$group->get('/podcast/{podcast_id}/feed', Controller\Frontend\PublicPages\PodcastFeedAction::class)
->setName('public:podcast:feed')
->add(Middleware\GetAndRequirePodcast::class);
}
)
->add(Middleware\EnableView::class)
->add(Middleware\GetStation::class);
};
``` | /content/code_sandbox/backend/config/routes/public.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 688 |
```php
<?php
declare(strict_types=1);
use App\Controller\StationsAction;
use App\Enums\StationPermissions;
use App\Middleware;
use Slim\Routing\RouteCollectorProxy;
return static function (RouteCollectorProxy $app) {
$app->group(
'/station/{station_id}',
function (RouteCollectorProxy $group) {
$routes = [
'stations:index:index' => '',
'stations:branding' => '/branding',
'stations:bulk-media' => '/bulk-media',
'stations:fallback' => '/fallback',
'stations:files:index' => '/files[/{fspath}]',
'stations:hls_streams:index' => '/hls_streams',
'stations:util:ls_config' => '/ls_config',
'stations:stereo_tool_config' => '/stereo_tool_config',
'stations:logs' => '/logs',
'stations:playlists:index' => '/playlists',
'stations:podcasts:index' => '/podcasts',
'stations:podcast:episodes' => '/podcast/{podcast_id}',
'stations:mounts:index' => '/mounts',
'stations:profile:index' => '/profile',
'stations:profile:edit' => '/profile/edit',
'stations:queue:index' => '/queue',
'stations:remotes:index' => '/remotes',
'stations:reports:overview' => '/reports/overview',
'stations:reports:timeline' => '/reports/timeline',
'stations:reports:listeners' => '/reports/listeners',
'stations:reports:soundexchange' => '/reports/soundexchange',
'stations:reports:requests' => '/reports/requests',
'stations:restart:index' => '/restart',
'stations:sftp_users:index' => '/sftp_users',
'stations:streamers:index' => '/streamers',
'stations:webhooks:index' => '/webhooks',
];
foreach ($routes as $routeName => $routePath) {
$group->get($routePath, StationsAction::class)
->setName($routeName);
}
$group->get('/{routes:.+}', StationsAction::class);
}
)->add(Middleware\Module\PanelLayout::class)
->add(new Middleware\Permissions(StationPermissions::View, true))
->add(Middleware\EnableView::class)
->add(Middleware\RequireStation::class)
->add(Middleware\GetStation::class)
->add(Middleware\RequireLogin::class);
};
``` | /content/code_sandbox/backend/config/routes/stations.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 546 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Enums\ReleaseChannel;
use DateTime;
use DateTimeZone;
use Dotenv\Dotenv;
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Process\Process;
use Throwable;
/**
* App Core Framework Version
*
* @phpstan-type VersionDetails array{
* commit: string|null,
* commit_short: string,
* commit_timestamp: int,
* commit_date: string,
* branch: string|null,
* }
*/
final class Version
{
/** @var string The current latest stable version. */
public const STABLE_VERSION = '0.20.2';
private string $repoDir;
public function __construct(
private readonly CacheInterface $cache,
private readonly Environment $environment,
) {
$this->repoDir = $environment->getBaseDirectory();
}
public function getReleaseChannelEnum(): ReleaseChannel
{
if ($this->environment->isDocker()) {
return $this->environment->getReleaseChannelEnum();
}
$details = $this->getDetails();
return ('stable' === $details['branch'])
? ReleaseChannel::Stable
: ReleaseChannel::RollingRelease;
}
/**
* Load cache or generate new repository details from the underlying Git repository.
*
* @return VersionDetails
*/
public function getDetails(): array
{
static $details;
if (!$details) {
$details = $this->cache->get('app_version_details');
if (empty($details)) {
$rawDetails = $this->getRawDetails();
$details = [
'commit' => $rawDetails['commit'],
'commit_short' => substr($rawDetails['commit'] ?? '', 0, 7),
'branch' => $rawDetails['branch'],
];
if (!empty($rawDetails['commit_date_raw'])) {
$commitDate = new DateTime($rawDetails['commit_date_raw']);
$commitDate->setTimezone(new DateTimeZone('UTC'));
$details['commit_timestamp'] = $commitDate->getTimestamp();
$details['commit_date'] = $commitDate->format('Y-m-d G:i');
} else {
$details['commit_timestamp'] = 0;
$details['commit_date'] = 'N/A';
}
$ttl = $this->environment->isProduction() ? 86400 : 600;
$this->cache->set('app_version_details', $details, $ttl);
}
}
return $details;
}
/**
* Generate new repository details from the underlying Git repository.
*
* @return array{
* commit: string|null,
* commit_date_raw: string|null,
* branch: string|null
* }
*/
private function getRawDetails(): array
{
if (is_file($this->repoDir . '/.gitinfo')) {
$fileContents = file_get_contents($this->repoDir . '/.gitinfo');
if (!empty($fileContents)) {
try {
$gitInfo = Dotenv::parse($fileContents);
return [
'commit' => $gitInfo['COMMIT_LONG'] ?? null,
'commit_date_raw' => $gitInfo['COMMIT_DATE'] ?? null,
'branch' => $gitInfo['BRANCH'] ?? null,
];
} catch (Throwable) {
// Noop
}
}
}
if (is_dir($this->repoDir . '/.git')) {
return [
'commit' => $this->runProcess(['git', 'log', '--pretty=%H', '-n1', 'HEAD']),
'commit_date_raw' => $this->runProcess(['git', 'log', '-n1', '--pretty=%ci', 'HEAD']),
'branch' => $this->runProcess(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], 'main'),
];
}
return [
'commit' => null,
'commit_date_raw' => null,
'branch' => null,
];
}
/**
* Run the specified process and return its output.
*/
private function runProcess(array $proc, string $default = ''): string
{
$process = new Process($proc);
$process->setWorkingDirectory($this->repoDir);
$process->run();
if (!$process->isSuccessful()) {
return $default;
}
return trim($process->getOutput());
}
/**
* @return string A textual representation of the current installed version.
*/
public function getVersionText(): string
{
$details = $this->getDetails();
$releaseChannel = $this->getReleaseChannelEnum();
if (ReleaseChannel::RollingRelease === $releaseChannel) {
$commitLink = 'path_to_url . $details['commit'];
$commitText = sprintf(
'#<a href="%s" target="_blank">%s</a> (%s)',
$commitLink,
$details['commit_short'],
$details['commit_date']
);
return 'Rolling Release ' . $commitText;
}
return 'v' . self::STABLE_VERSION . ' Stable';
}
/**
* @return string|null The long-form Git hash that represents the current commit of this installation.
*/
public function getCommitHash(): ?string
{
$details = $this->getDetails();
return $details['commit'];
}
/**
* @return string The shortened Git hash corresponding to the current commit.
*/
public function getCommitShort(): string
{
$details = $this->getDetails();
return $details['commit_short'];
}
public function getVersion(): string
{
return self::STABLE_VERSION;
}
}
``` | /content/code_sandbox/backend/src/Version.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,263 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Console\Application;
use App\Enums\SupportedLocales;
use App\Http\HttpFactory;
use App\Utilities\Logger as AppLogger;
use DI;
use Monolog\ErrorHandler;
use Monolog\Logger;
use Monolog\Registry;
use Psr\EventDispatcher\EventDispatcherInterface;
use Slim\App;
use Slim\Factory\ServerRequestCreatorFactory;
use Slim\Handlers\Strategies\RequestResponse;
/**
* @phpstan-type AppWithContainer App<DI\Container>
*/
final class AppFactory
{
/**
* @return AppWithContainer
*/
public static function createApp(
array $appEnvironment = []
): App {
$environment = self::buildEnvironment($appEnvironment);
$diBuilder = self::createContainerBuilder($environment);
$di = self::buildContainer($diBuilder);
return self::buildAppFromContainer($di);
}
public static function createCli(
array $appEnvironment = []
): Application {
$environment = self::buildEnvironment($appEnvironment);
$diBuilder = self::createContainerBuilder($environment);
$di = self::buildContainer($diBuilder);
// Some CLI commands require the App to be injected for routing.
self::buildAppFromContainer($di);
SupportedLocales::createForCli($environment);
return $di->get(Application::class);
}
/**
* @return AppWithContainer
*/
public static function buildAppFromContainer(
DI\Container $container,
?HttpFactory $httpFactory = null
): App {
$httpFactory ??= new HttpFactory();
ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(false);
ServerRequestCreatorFactory::setServerRequestCreator($httpFactory);
$app = new App(
responseFactory: $httpFactory,
container: $container,
);
$container->set(App::class, $app);
$routeCollector = $app->getRouteCollector();
$routeCollector->setDefaultInvocationStrategy(new RequestResponse());
$environment = $container->get(Environment::class);
if ($environment->isProduction()) {
$routeCollector->setCacheFile($environment->getTempDirectory() . '/app_routes.cache.php');
}
$eventDispatcher = $container->get(EventDispatcherInterface::class);
$eventDispatcher->dispatch(new Event\BuildRoutes($app, $container));
return $app;
}
/**
* @return DI\ContainerBuilder<DI\Container>
*/
public static function createContainerBuilder(
Environment $environment
): DI\ContainerBuilder {
$diDefinitions = [
Environment::class => $environment,
];
Environment::setInstance($environment);
// Override DI definitions for settings.
$plugins = new Plugins($environment->getBaseDirectory() . '/plugins');
$diDefinitions[Plugins::class] = $plugins;
$diDefinitions = $plugins->registerServices($diDefinitions);
$containerBuilder = new DI\ContainerBuilder();
$containerBuilder->useAutowiring(true);
$containerBuilder->useAttributes(true);
if ($environment->isProduction()) {
$containerBuilder->enableCompilation($environment->getTempDirectory());
}
$containerBuilder->addDefinitions($diDefinitions);
$containerBuilder->addDefinitions(dirname(__DIR__) . '/config/services.php');
return $containerBuilder;
}
/**
* @param DI\ContainerBuilder<DI\Container> $containerBuilder
* @return DI\Container
*/
public static function buildContainer(
DI\ContainerBuilder $containerBuilder
): DI\Container {
$di = $containerBuilder->build();
// Monolog setup
$logger = $di->get(Logger::class);
$errorHandler = new ErrorHandler($logger);
$errorHandler->registerFatalHandler();
Registry::addLogger($logger, AppLogger::INSTANCE_NAME, true);
return $di;
}
/**
* @param array<string, mixed> $rawEnvironment
*/
public static function buildEnvironment(array $rawEnvironment = []): Environment
{
$_ENV = getenv();
$rawEnvironment = array_merge(array_filter($_ENV), $rawEnvironment);
$environment = new Environment($rawEnvironment);
self::applyPhpSettings($environment);
return $environment;
}
private static function applyPhpSettings(Environment $environment): void
{
error_reporting(
$environment->isProduction()
? E_ALL & ~E_NOTICE & ~E_WARNING & ~E_STRICT & ~E_DEPRECATED
: E_ALL & ~E_NOTICE
);
$displayStartupErrors = (!$environment->isProduction() || $environment->isCli())
? '1'
: '0';
ini_set('display_startup_errors', $displayStartupErrors);
ini_set('display_errors', $displayStartupErrors);
ini_set('log_errors', '1');
ini_set(
'error_log',
$environment->isDocker()
? '/dev/stderr'
: $environment->getTempDirectory() . '/php_errors.log'
);
mb_internal_encoding('UTF-8');
ini_set('default_charset', 'utf-8');
if (!headers_sent()) {
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_lifetime', '86400');
ini_set('session.use_strict_mode', '1');
session_cache_limiter('');
}
date_default_timezone_set('UTC');
}
}
``` | /content/code_sandbox/backend/src/AppFactory.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,182 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Exception\Http\InvalidRequestAttribute;
use App\Http\Response;
use App\Http\RouterInterface;
use App\Http\ServerRequest;
use Countable;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Generator;
use IteratorAggregate;
use Pagerfanta\Adapter\AdapterInterface;
use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Doctrine\Collections\CollectionAdapter;
use Pagerfanta\Doctrine\ORM\QueryAdapter;
use Pagerfanta\Pagerfanta;
use Psr\Http\Message\ResponseInterface;
/**
* @template TKey of array-key
* @template T of mixed
* @implements IteratorAggregate<TKey, T>
*/
final class Paginator implements IteratorAggregate, Countable
{
private RouterInterface $router;
/** @var int<1,max> The maximum number of records that can be viewed per page for unauthenticated users. */
private int $maxPerPage = 25;
/** @var bool Whether the user is currently authenticated on this request. */
private bool $isAuthenticated;
/** @var bool Whether to show pagination controls. */
private bool $isDisabled = true;
/** @var callable|null A callable postprocessor that can be run on each result. */
private $postprocessor;
/**
* @param Pagerfanta<T> $paginator
*/
public function __construct(
private readonly Pagerfanta $paginator,
ServerRequest $request
) {
$this->router = $request->getRouter();
try {
$user = $request->getUser();
} catch (InvalidRequestAttribute) {
$user = null;
}
$this->isAuthenticated = ($user !== null);
$params = $request->getQueryParams();
$perPage = $params['rowCount'] ?? $params['per_page'] ?? null;
$currentPage = $params['current'] ?? $params['page'] ?? null;
if (null !== $perPage) {
$this->setPerPage((int)$perPage);
}
if (null !== $currentPage) {
$this->setCurrentPage((int)$currentPage);
}
}
public function getCurrentPage(): int
{
return $this->paginator->getCurrentPage();
}
public function setCurrentPage(int $currentPage): void
{
$this->paginator->setCurrentPage(
($currentPage >= 1) ? $currentPage : 1
);
}
public function setMaxPerPage(int $maxPerPage): void
{
$this->maxPerPage = ($maxPerPage > 0) ? $maxPerPage : 1;
$this->isDisabled = false;
}
public function getPerPage(): int
{
return $this->paginator->getMaxPerPage();
}
public function setPerPage(int $perPage): void
{
if ($perPage <= 0) {
$perPage = PHP_INT_MAX;
}
/** @var int<1,max> $maxPerPage */
$maxPerPage = $this->isAuthenticated
? $perPage
: min($perPage, $this->maxPerPage);
$this->paginator->setMaxPerPage($maxPerPage);
$this->isDisabled = false;
}
public function setPostprocessor(callable $postprocessor): void
{
$this->postprocessor = $postprocessor;
}
public function isDisabled(): bool
{
return $this->isDisabled;
}
public function setIsDisabled(bool $isDisabled): void
{
$this->isDisabled = $isDisabled;
}
public function getIterator(): Generator
{
$iterator = $this->paginator->getIterator();
if ($this->postprocessor) {
foreach ($iterator as $row) {
yield ($this->postprocessor)($row, $this);
}
} else {
yield from $iterator;
}
}
public function count(): int
{
return $this->paginator->getNbResults();
}
public function write(Response $response): ResponseInterface
{
if ($this->isDisabled) {
/** @var int<1,max> $maxPerPage */
$maxPerPage = PHP_INT_MAX;
$this->paginator->setCurrentPage(1);
$this->paginator->setMaxPerPage($maxPerPage);
}
$total = $this->count();
$totalPages = $this->paginator->getNbPages();
$results = iterator_to_array($this->getIterator(), false);
if ($this->isDisabled) {
return $response->withJson($results);
}
$pageLinks = [];
$pageLinks['first'] = $this->router->fromHereWithQuery(null, [], ['page' => 1]);
$prevPage = $this->paginator->hasPreviousPage()
? $this->paginator->getPreviousPage()
: 1;
$pageLinks['previous'] = $this->router->fromHereWithQuery(null, [], ['page' => $prevPage]);
$nextPage = $this->paginator->hasNextPage()
? $this->paginator->getNextPage()
: $this->paginator->getNbPages();
$pageLinks['next'] = $this->router->fromHereWithQuery(null, [], ['page' => $nextPage]);
$pageLinks['last'] = $this->router->fromHereWithQuery(null, [], ['page' => $totalPages]);
return $response->withJson(
[
'page' => $this->getCurrentPage(),
'per_page' => $this->getPerPage(),
'total' => $total,
'total_pages' => $totalPages,
'links' => $pageLinks,
'rows' => $results,
]
);
}
/**
* @template X of mixed
*
* @param AdapterInterface<X> $adapter
* @return static<array-key, X>
*/
public static function fromAdapter(
AdapterInterface $adapter,
ServerRequest $request
): self {
return new self(
new Pagerfanta($adapter),
$request
);
}
/**
* @template XKey of array-key
* @template X of mixed
*
* @param array<XKey, X> $input
* @return static<XKey, X>
*/
public static function fromArray(array $input, ServerRequest $request): self
{
return self::fromAdapter(new ArrayAdapter($input), $request);
}
/**
* @template XKey of array-key
* @template X of mixed
*
* @param Collection<XKey, X> $collection
* @return static<XKey, X>
*/
public static function fromCollection(Collection $collection, ServerRequest $request): self
{
return self::fromAdapter(new CollectionAdapter($collection), $request);
}
/**
* @return static<int, mixed>
*/
public static function fromQueryBuilder(QueryBuilder $qb, ServerRequest $request): self
{
return self::fromAdapter(new QueryAdapter($qb), $request);
}
/**
* @return static<int, mixed>
*/
public static function fromQuery(Query $query, ServerRequest $request): self
{
return self::fromAdapter(new QueryAdapter($query), $request);
}
}
``` | /content/code_sandbox/backend/src/Paginator.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,583 |
```php
<?php
declare(strict_types=1);
namespace App;
use Exception as PhpException;
use Monolog\Level;
use Throwable;
class Exception extends PhpException
{
/** @var array Any additional data that can be displayed in debugging. */
protected array $extraData = [];
/** @var array Additional data supplied to the logger class when handling the exception. */
protected array $loggingContext = [];
protected ?string $formattedMessage;
public function __construct(
string $message = '',
int $code = 0,
Throwable $previous = null,
protected Level $loggerLevel = Level::Error
) {
parent::__construct($message, $code, $previous);
}
public function setMessage(string $message): void
{
$this->message = $message;
}
/**
* @return string A display-formatted message, if one exists, or
* the regular message if one doesn't.
*/
public function getFormattedMessage(): string
{
return $this->formattedMessage ?? $this->message;
}
/**
* Set a display-formatted message (if one exists).
*/
public function setFormattedMessage(?string $message): void
{
$this->formattedMessage = $message;
}
public function getLoggerLevel(): Level
{
return $this->loggerLevel;
}
public function setLoggerLevel(Level $loggerLevel): void
{
$this->loggerLevel = $loggerLevel;
}
public function addExtraData(int|string $legend, mixed $data): void
{
if (is_array($data)) {
$this->extraData[$legend] = $data;
}
}
/**
* @return mixed[]
*/
public function getExtraData(): array
{
return $this->extraData;
}
public function addLoggingContext(int|string $key, mixed $data): void
{
$this->loggingContext[$key] = $data;
}
public function getLoggingContext(): array
{
return $this->loggingContext;
}
}
``` | /content/code_sandbox/backend/src/Exception.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 452 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Assets\AssetTypes;
use App\Assets\BrowserIconCustomAsset;
use App\Container\EnvironmentAwareTrait;
use App\Entity\Repository\SettingsRepository;
use App\Entity\Settings;
use App\Entity\Station;
use App\Enums\SupportedLocales;
use App\Enums\SupportedThemes;
use App\Http\ServerRequest;
use App\Traits\RequestAwareTrait;
final class Customization
{
use RequestAwareTrait;
use EnvironmentAwareTrait;
private Settings $settings;
private SupportedLocales $locale;
private ?SupportedThemes $publicTheme;
private string $instanceName;
public function __construct(
SettingsRepository $settingsRepo
) {
$this->settings = $settingsRepo->readSettings();
$this->instanceName = $this->settings->getInstanceName() ?? '';
$this->publicTheme = $this->settings->getPublicTheme();
$this->locale = SupportedLocales::default();
}
public function setRequest(?ServerRequest $request): void
{
$this->request = $request;
if (null !== $request) {
// Register current theme
$queryParams = $request->getQueryParams();
if (!empty($queryParams['theme'])) {
$theme = SupportedThemes::tryFrom($queryParams['theme']);
if (null !== $theme && $theme !== SupportedThemes::Browser) {
$this->publicTheme = $theme;
}
}
// Register locale
$this->locale = SupportedLocales::createFromRequest($this->environment, $request);
}
}
public function getLocale(): SupportedLocales
{
return $this->locale;
}
/**
* Get the instance name for this AzuraCast instance.
*/
public function getInstanceName(): string
{
return $this->instanceName;
}
/**
* Get the theme name to be used in public (non-logged-in) pages.
*/
public function getPublicTheme(): ?SupportedThemes
{
return (SupportedThemes::Browser !== $this->publicTheme)
? $this->publicTheme
: null;
}
/**
* Return the administrator-supplied custom CSS for public (minimal layout) pages, if specified.
*/
public function getCustomPublicCss(): string
{
$publicCss = $this->settings->getPublicCustomCss() ?? '';
$background = AssetTypes::Background->createObject($this->environment);
if ($background->isUploaded()) {
$backgroundUrl = $background->getUrl();
$publicCss .= <<<CSS
[data-bs-theme] body.page-minimal {
background-image: url('{$backgroundUrl}');
}
CSS;
}
return $publicCss;
}
public function getStationCustomPublicCss(Station $station): string
{
$publicCss = $station->getBrandingConfig()->getPublicCustomCss() ?? '';
$background = AssetTypes::Background->createObject($this->environment, $station);
if ($background->isUploaded()) {
$backgroundUrl = $background->getUrl();
$publicCss .= <<<CSS
[data-bs-theme] body.page-minimal {
background-image: url('{$backgroundUrl}');
}
CSS;
}
return $publicCss;
}
/**
* Return the administrator-supplied custom JS for public (minimal layout) pages, if specified.
*/
public function getCustomPublicJs(): string
{
return $this->settings->getPublicCustomJs() ?? '';
}
public function getStationCustomPublicJs(Station $station): string
{
return $station->getBrandingConfig()->getPublicCustomJs() ?? '';
}
/**
* Return the administrator-supplied custom CSS for internal (full layout) pages, if specified.
*/
public function getCustomInternalCss(): string
{
return $this->settings->getInternalCustomCss() ?? '';
}
public function getBrowserIconUrl(int $size = 256): string
{
/** @var BrowserIconCustomAsset $browserIcon */
$browserIcon = AssetTypes::BrowserIcon->createObject($this->environment);
return $browserIcon->getUrlForSize($size);
}
/**
* Return whether to show or hide album art on public pages.
*/
public function hideAlbumArt(): bool
{
return $this->settings->getHideAlbumArt();
}
/**
* Return the calculated page title given branding settings and the application environment.
*
* @param string|null $title
*/
public function getPageTitle(?string $title = null): string
{
if (!$this->hideProductName()) {
if ($title) {
$title .= ' - ' . $this->environment->getAppName();
} else {
$title = $this->environment->getAppName();
}
}
if (!$this->environment->isProduction()) {
$title = '(' . $this->environment->getAppEnvironmentEnum()->getName() . ') ' . $title;
}
return $title ?? '';
}
/**
* Return whether to show or hide the AzuraCast name from public-facing pages.
*/
public function hideProductName(): bool
{
return $this->settings->getHideProductName();
}
public function enableAdvancedFeatures(): bool
{
return $this->settings->getEnableAdvancedFeatures();
}
public function useStaticNowPlaying(): bool
{
return $this->settings->getEnableStaticNowPlaying();
}
}
``` | /content/code_sandbox/backend/src/Customization.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,206 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Container\EnvironmentAwareTrait;
use App\Entity\Repository\UserRepository;
use App\Entity\User;
use App\Utilities\Types;
use Mezzio\Session\SessionInterface;
final class Auth
{
use EnvironmentAwareTrait;
public const string SESSION_IS_LOGIN_COMPLETE_KEY = 'is_login_complete';
public const string SESSION_USER_ID_KEY = 'user_id';
public const string SESSION_MASQUERADE_USER_ID_KEY = 'masquerade_user_id';
/** @var int The window of valid one-time passwords outside the current timestamp. */
public const int TOTP_WINDOW = 5;
private bool|User|null $user = null;
private bool|User|null $masqueraded_user = null;
public function __construct(
private readonly UserRepository $userRepo,
private readonly SessionInterface $session
) {
}
/**
* Authenticate a given username and password combination against the User repository.
*
* @param string $username
* @param string $password
*/
public function authenticate(string $username, string $password): ?User
{
$userAuth = $this->userRepo->authenticate($username, $password);
if ($userAuth instanceof User) {
$this->setUser($userAuth);
return $userAuth;
}
return null;
}
/**
* Get the currently logged in user.
*
* @param bool $realUserOnly
*
* @throws Exception
*/
public function getLoggedInUser(bool $realUserOnly = false): ?User
{
if (!$realUserOnly && $this->isMasqueraded()) {
return $this->getMasquerade();
}
if (!$this->isLoginComplete()) {
return null;
}
return $this->getUser();
}
/**
* Check if the current user is masquerading as another account.
*/
public function isMasqueraded(): bool
{
if (!$this->isLoggedIn()) {
$this->masqueraded_user = false;
return false;
}
if (null === $this->masqueraded_user) {
if (!$this->session->has(self::SESSION_MASQUERADE_USER_ID_KEY)) {
$this->masqueraded_user = false;
} else {
$maskUserId = Types::int($this->session->get(self::SESSION_MASQUERADE_USER_ID_KEY));
if (0 !== $maskUserId) {
$user = $this->userRepo->getRepository()->find($maskUserId);
} else {
$user = null;
}
if ($user instanceof User) {
$this->masqueraded_user = $user;
} else {
$this->session->clear();
$this->masqueraded_user = false;
}
}
}
return ($this->masqueraded_user instanceof User);
}
/**
* Check if a user account is currently authenticated.
*/
public function isLoggedIn(): bool
{
if ($this->environment->isCli() && !$this->environment->isTesting()) {
return false;
}
if (!$this->isLoginComplete()) {
return false;
}
$user = $this->getUser();
return ($user instanceof User);
}
/**
* Indicate whether login is "complete", i.e. whether any necessary
* second-factor authentication steps have been completed.
*/
public function isLoginComplete(): bool
{
return Types::bool($this->session->get(self::SESSION_IS_LOGIN_COMPLETE_KEY, false));
}
/**
* Get the authenticated user entity.
*
* @throws Exception
*/
public function getUser(): ?User
{
if (null === $this->user) {
$userId = Types::int($this->session->get(self::SESSION_USER_ID_KEY));
if (0 === $userId) {
$this->user = false;
return null;
}
$user = $this->userRepo->getRepository()->find($userId);
if ($user instanceof User) {
$this->user = $user;
} else {
$this->user = false;
$this->logout();
throw new Exception('Invalid user!');
}
}
if (!$this->user instanceof User) {
return null;
}
/** @var User|null $user */
$user = $this->userRepo->getRepository()->find($this->user->getId());
return $user;
}
/**
* Masquerading
*/
/**
* Set the currently authenticated user.
*
* @param User $user
*/
public function setUser(User $user, ?bool $isLoginComplete = null): void
{
$this->session->set(
self::SESSION_IS_LOGIN_COMPLETE_KEY,
(null !== $isLoginComplete)
? $isLoginComplete
: null === $user->getTwoFactorSecret()
);
$this->session->set(self::SESSION_USER_ID_KEY, $user->getId());
$this->session->regenerate();
$this->user = $user;
}
/**
* End the user's currently logged in session.
*/
public function logout(): void
{
if (isset($this->session) && $this->session instanceof SessionInterface) {
$this->session->clear();
}
$this->session->regenerate();
$this->user = null;
}
/**
* Return the currently masqueraded user, if one is set.
*/
public function getMasquerade(): ?User
{
if ($this->masqueraded_user instanceof User) {
return $this->masqueraded_user;
}
return null;
}
/**
* Become a different user across the application.
*/
public function masqueradeAsUser(User $user): void
{
$this->session->set(self::SESSION_MASQUERADE_USER_ID_KEY, $user->getId());
$this->masqueraded_user = $user;
}
/**
* Return to the regular authenticated account.
*/
public function endMasquerade(): void
{
$this->session->unset(self::SESSION_MASQUERADE_USER_ID_KEY);
$this->masqueraded_user = null;
}
/**
* Verify a supplied one-time password.
*
* @param string $otp
*/
public function verifyTwoFactor(string $otp): bool
{
$user = $this->getUser();
if (!($user instanceof User)) {
return false;
}
if ($user->verifyTwoFactor($otp)) {
$this->session->set(self::SESSION_IS_LOGIN_COMPLETE_KEY, true);
return true;
}
return false;
}
}
``` | /content/code_sandbox/backend/src/Auth.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,482 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Doctrine\ReloadableEntityManagerInterface;
use App\Entity\Role;
use App\Entity\Station;
use App\Entity\User;
use App\Enums\GlobalPermissions;
use App\Enums\PermissionInterface;
use App\Enums\StationPermissions;
use App\Exception\Http\InvalidRequestAttribute;
use App\Http\ServerRequest;
use App\Traits\RequestAwareTrait;
use Psr\EventDispatcher\EventDispatcherInterface;
use function in_array;
use function is_array;
/**
* @phpstan-type PermissionsArray array{
* global: array<string, string>,
* station: array<string, string>
* }
*/
final class Acl
{
use RequestAwareTrait;
/**
* @var PermissionsArray
*/
private array $permissions;
/**
* @var null|array<
* int,
* array{
* stations?: array<int, array<string>>,
* global?: array<string>
* }
* >
*/
private ?array $actions;
public function __construct(
private readonly ReloadableEntityManagerInterface $em,
private readonly EventDispatcherInterface $dispatcher
) {
$this->reload();
}
/**
* Force a reload of the internal ACL cache (used in the event of a user status change).
*/
public function reload(): void
{
$sql = $this->em->createQuery(
<<<'DQL'
SELECT rp.station_id, rp.role_id, rp.action_name FROM App\Entity\RolePermission rp
DQL
);
$this->actions = [];
foreach ($sql->toIterable() as $row) {
if ($row['station_id']) {
$this->actions[$row['role_id']]['stations'][$row['station_id']][] = $row['action_name'];
} else {
$this->actions[$row['role_id']]['global'][] = $row['action_name'];
}
}
}
/**
* @param string $permissionName
* @param bool $isGlobal
*/
public function isValidPermission(string $permissionName, bool $isGlobal): bool
{
$permissions = $this->listPermissions();
return $isGlobal
? isset($permissions['global'][$permissionName])
: isset($permissions['station'][$permissionName]);
}
/**
* @return array
*/
public function listPermissions(): array
{
if (!isset($this->permissions)) {
$permissions = [
'global' => [],
'station' => [],
];
foreach (GlobalPermissions::cases() as $globalPermission) {
$permissions['global'][$globalPermission->value] = $globalPermission->getName();
}
foreach (StationPermissions::cases() as $stationPermission) {
$permissions['station'][$stationPermission->value] = $stationPermission->getName();
}
$buildPermissionsEvent = new Event\BuildPermissions($permissions);
$this->dispatcher->dispatch($buildPermissionsEvent);
$this->permissions = $buildPermissionsEvent->getPermissions();
}
return $this->permissions;
}
/**
* Check if the current user associated with the request has the specified permission.
*
* @param array<string|PermissionInterface>|string|PermissionInterface $action
* @param int|Station|null $stationId
*/
public function isAllowed(
array|string|PermissionInterface $action,
Station|int $stationId = null
): bool {
if ($this->request instanceof ServerRequest) {
try {
$user = $this->request->getUser();
return $this->userAllowed($user, $action, $stationId);
} catch (InvalidRequestAttribute) {
}
}
return false;
}
/**
* Check if a specified User entity is allowed to perform an action (or array of actions).
*
* @param User|null $user
* @param array<string|PermissionInterface>|string|PermissionInterface $action
* @param int|Station|null $stationId
*/
public function userAllowed(
?User $user = null,
array|string|PermissionInterface $action = null,
Station|int $stationId = null
): bool {
if (null === $user || null === $action) {
return false;
}
if ($stationId instanceof Station) {
$stationId = $stationId->getId();
}
$numRoles = $user->getRoles()->count();
if ($numRoles > 0) {
if ($numRoles === 1) {
/** @var Role $role */
$role = $user->getRoles()->first();
return $this->roleAllowed($role->getIdRequired(), $action, $stationId);
}
$roles = [];
foreach ($user->getRoles() as $role) {
$roles[] = $role->getId();
}
return $this->roleAllowed($roles, $action, $stationId);
}
return false;
}
/**
* Check if a role (or array of roles) is allowed to perform an action (or array of actions).
*
* @param array|int $roleId
* @param array<(string | PermissionInterface)>|string|PermissionInterface $action
* @param int|Station|null $stationId
*/
public function roleAllowed(
array|int $roleId,
array|string|PermissionInterface $action,
Station|int $stationId = null
): bool {
if ($stationId instanceof Station) {
$stationId = $stationId->getId();
}
if ($action instanceof PermissionInterface) {
$action = $action->getValue();
}
// Iterate through an array of roles and return with the first "true" response, or "false" otherwise.
if (is_array($roleId)) {
foreach ($roleId as $r) {
if ($this->roleAllowed($r, $action, $stationId)) {
return true;
}
}
return false;
}
// If multiple actions are supplied, treat the list as "x OR y OR z", returning if any action is allowed.
if (is_array($action)) {
foreach ($action as $a) {
if ($this->roleAllowed($roleId, $a, $stationId)) {
return true;
}
}
return false;
}
if (!empty($this->actions[$roleId])) {
$roleActions = (array)$this->actions[$roleId];
if (
in_array(
GlobalPermissions::All->value,
(array)($roleActions['global'] ?? []),
true
)
) {
return true;
}
if ($stationId !== null) {
if (
in_array(
GlobalPermissions::Stations->value,
(array)($roleActions['global'] ?? []),
true
)
) {
return true;
}
if (!empty($roleActions['stations'][$stationId])) {
if (
in_array(
StationPermissions::All->value,
$roleActions['stations'][$stationId],
true
)
) {
return true;
}
return in_array($action, (array)$roleActions['stations'][$stationId], true);
}
} else {
return in_array(
$action,
(array)($roleActions['global'] ?? []),
true
);
}
}
return false;
}
}
``` | /content/code_sandbox/backend/src/Acl.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,610 |
```php
<?php
declare(strict_types=1);
namespace App;
use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\InflectorFactory;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
final class Plugins
{
/** @var array An array of all plugins and their capabilities. */
private array $plugins = [];
private Inflector $inflector;
public function __construct(string $baseDir)
{
$this->inflector = InflectorFactory::create()
->build();
$this->loadDirectory($baseDir);
}
public function loadDirectory(string $dir): void
{
$plugins = (new Finder())
->ignoreUnreadableDirs()
->directories()
->depth('== 0')
->in($dir);
foreach ($plugins as $pluginDir) {
/** @var SplFileInfo $pluginDir */
$pluginPrefix = $pluginDir->getRelativePathname();
$pluginNamespace = 'Plugin\\' . $this->inflector->classify($pluginPrefix) . '\\';
$this->plugins[$pluginPrefix] = [
'namespace' => $pluginNamespace,
'path' => $pluginDir->getPathname(),
];
}
}
/**
* Register or override any services contained in the global Dependency Injection container.
*
* @param array $diDefinitions
*
* @return mixed[]
*/
public function registerServices(array $diDefinitions = []): array
{
foreach ($this->plugins as $plugin) {
$pluginPath = $plugin['path'];
if (is_file($pluginPath . '/services.php')) {
$services = include $pluginPath . '/services.php';
$diDefinitions = array_merge($diDefinitions, $services);
}
}
return $diDefinitions;
}
/**
* Register custom events that the plugin overrides with the Event Dispatcher.
*
* @param CallableEventDispatcherInterface $dispatcher
*/
public function registerEvents(CallableEventDispatcherInterface $dispatcher): void
{
foreach ($this->plugins as $plugin) {
$pluginPath = $plugin['path'];
if (file_exists($pluginPath . '/events.php')) {
call_user_func(include($pluginPath . '/events.php'), $dispatcher);
}
}
}
/**
* @param mixed[] $receivers
*
* @return mixed[]
*/
public function registerMessageQueueReceivers(array $receivers): array
{
foreach ($this->plugins as $plugin) {
$pluginPath = $plugin['path'];
if (is_file($pluginPath . '/messagequeue.php')) {
$pluginReceivers = include $pluginPath . '/messagequeue.php';
$receivers = array_merge($receivers, $pluginReceivers);
}
}
return $receivers;
}
}
``` | /content/code_sandbox/backend/src/Plugins.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 624 |
```php
<?php
declare(strict_types=1);
namespace App;
use OpenApi\Attributes as OA;
#[
OA\OpenApi(
openapi: '3.0.0',
info: new OA\Info(
version: AZURACAST_VERSION,
description: "AzuraCast is a standalone, turnkey web radio management tool. Radio stations hosted by"
. " AzuraCast expose a public API for viewing now playing data, making requests and more.",
title: 'AzuraCast',
name: 'Apache 2.0',
url: "path_to_url"
),
),
servers: [
new OA\Server(
url: AZURACAST_API_URL,
description: AZURACAST_API_NAME
),
],
tags: [
new OA\Tag(
name: "Now Playing",
description: "Endpoints that provide full summaries of the current state of stations.",
),
new OA\Tag(name: "Stations: General"),
new OA\Tag(name: "Stations: Broadcasting"),
new OA\Tag(name: "Stations: Song Requests"),
new OA\Tag(name: "Stations: Service Control"),
new OA\Tag(name: "Stations: Automation"),
new OA\Tag(name: "Stations: History"),
new OA\Tag(name: "Stations: HLS Streams"),
new OA\Tag(name: "Stations: Listeners"),
new OA\Tag(name: "Stations: Schedules"),
new OA\Tag(name: "Stations: Media"),
new OA\Tag(name: "Stations: Mount Points"),
new OA\Tag(name: "Stations: Playlists"),
new OA\Tag(name: "Stations: Podcasts"),
new OA\Tag(name: "Stations: Queue"),
new OA\Tag(name: "Stations: Remote Relays"),
new OA\Tag(name: "Stations: SFTP Users"),
new OA\Tag(name: "Stations: Streamers/DJs"),
new OA\Tag(name: "Stations: Web Hooks"),
new OA\Tag(name: "Administration: Custom Fields"),
new OA\Tag(name: "Administration: Users"),
new OA\Tag(name: "Administration: Relays"),
new OA\Tag(name: "Administration: Roles"),
new OA\Tag(name: "Administration: Settings"),
new OA\Tag(name: "Administration: Stations"),
new OA\Tag(name: "Administration: Storage Locations"),
new OA\Tag(name: "Miscellaneous"),
],
externalDocs: new OA\ExternalDocumentation(
description: "AzuraCast on GitHub",
url: "path_to_url"
)
),
OA\Parameter(
parameter: "StationIdRequired",
name: "station_id",
in: "path",
required: true,
schema: new OA\Schema(
anyOf: [
new OA\Schema(type: "integer", format: "int64"),
new OA\Schema(type: "string", format: "string"),
]
),
),
OA\Response(
response: 'Success',
description: 'Success',
content: new OA\JsonContent(ref: '#/components/schemas/Api_Status')
),
OA\Response(
response: 'AccessDenied',
description: 'Access denied.',
content: new OA\JsonContent(ref: '#/components/schemas/Api_Error')
),
OA\Response(
response: 'RecordNotFound',
description: 'Record not found.',
content: new OA\JsonContent(ref: '#/components/schemas/Api_Error')
),
OA\Response(
response: 'GenericError',
description: 'A generic exception has occurred.',
content: new OA\JsonContent(ref: '#/components/schemas/Api_Error')
),
OA\SecurityScheme(
securityScheme: "ApiKey",
type: "apiKey",
name: "X-API-Key",
in: "header"
)
]
final class OpenApi
{
public const int SAMPLE_TIMESTAMP = 1609480800;
public const array API_KEY_SECURITY = [['ApiKey' => []]];
public const string REF_STATION_ID_REQUIRED = '#/components/parameters/StationIdRequired';
public const string REF_RESPONSE_SUCCESS = '#/components/responses/Success';
public const string REF_RESPONSE_ACCESS_DENIED = '#/components/responses/AccessDenied';
public const string REF_RESPONSE_NOT_FOUND = '#/components/responses/RecordNotFound';
public const string REF_RESPONSE_GENERIC_ERROR = '#/components/responses/GenericError';
}
``` | /content/code_sandbox/backend/src/OpenApi.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 973 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Container\ContainerAwareTrait;
use Closure;
use Symfony\Component\EventDispatcher\EventDispatcher;
use function is_array;
use function is_string;
final class CallableEventDispatcher extends EventDispatcher implements CallableEventDispatcherInterface
{
use ContainerAwareTrait;
/**
* @param array|class-string $className
*/
public function addServiceSubscriber(array|string $className): void
{
if (is_array($className)) {
foreach ($className as $service) {
$this->addServiceSubscriber($service);
}
return;
}
foreach ($className::getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
$this->addCallableListener(
$eventName,
$className,
$params
);
} elseif (is_string($params[0])) {
$this->addCallableListener(
$eventName,
$className,
$params[0],
$params[1] ?? 0
);
} else {
foreach ($params as $listener) {
$this->addCallableListener(
$eventName,
$className,
$listener[0],
$listener[1] ?? 0
);
}
}
}
}
/**
* @param array|class-string $className
*/
public function removeServiceSubscriber(array|string $className): void
{
if (is_array($className)) {
foreach ($className as $service) {
$this->removeServiceSubscriber($service);
}
return;
}
foreach ($className::getSubscribedEvents() as $eventName => $params) {
if (is_array($params) && is_array($params[0])) {
foreach ($params as $listener) {
$this->removeCallableListener(
$eventName,
$className,
$listener[0]
);
}
} else {
$this->removeCallableListener(
$eventName,
$className,
is_string($params) ? $params : $params[0]
);
}
}
}
/**
* @param class-string $className
*/
public function addCallableListener(
string $eventName,
string $className,
?string $method = '__invoke',
int $priority = 0
): void {
$this->addListener(
$eventName,
$this->getCallable($className, $method),
$priority
);
}
/**
* @param class-string $className
*/
public function removeCallableListener(
string $eventName,
string $className,
?string $method = '__invoke'
): void {
$this->removeListener(
$eventName,
$this->getCallable($className, $method)
);
}
/**
* @param class-string $className
*/
private function getCallable(
string $className,
?string $method = '__invoke'
): Closure {
return fn(...$args) => $this->di->get($className)->$method(...$args);
}
}
``` | /content/code_sandbox/backend/src/CallableEventDispatcher.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 669 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Entity\Station;
use App\Entity\User;
use App\Enums\SupportedLocales;
use App\Http\RouterInterface;
use App\Http\ServerRequest;
use App\Traits\RequestAwareTrait;
use App\Utilities\Json;
use App\View\GlobalSections;
use Doctrine\Common\Collections\ArrayCollection;
use League\Plates\Engine;
use League\Plates\Template\Data;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Message\ResponseInterface;
use stdClass;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
final class View extends Engine
{
use RequestAwareTrait;
private GlobalSections $sections;
/** @var ArrayCollection<string, array|object|string|int|bool> */
private ArrayCollection $globalProps;
public function __construct(
Customization $customization,
Environment $environment,
EventDispatcherInterface $dispatcher,
Version $version,
RouterInterface $router
) {
parent::__construct(
$environment->getBackendDirectory() . '/templates',
'phtml'
);
$this->sections = new GlobalSections();
$this->globalProps = new ArrayCollection();
// Add non-request-dependent content.
$this->addData(
[
'sections' => $this->sections,
'globalProps' => $this->globalProps,
'customization' => $customization,
'environment' => $environment,
'version' => $version,
'router' => $router,
]
);
$this->registerFunction(
'escapeJs',
function ($string) {
return json_encode($string, JSON_THROW_ON_ERROR);
}
);
$this->registerFunction(
'dump',
function ($value) {
if (class_exists(VarCloner::class)) {
$varCloner = new VarCloner();
$dumpedValue = (new CliDumper())->dump($varCloner->cloneVar($value), true);
} else {
$dumpedValue = json_encode($value, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
}
return '<pre>' . htmlspecialchars($dumpedValue ?? '', ENT_QUOTES | ENT_HTML5) . '</pre>';
}
);
$vueComponents = (!$environment->isDevelopment())
? Json::loadFromFile($environment->getBaseDirectory() . '/web/static/vite_dist/.vite/manifest.json')
: [];
$this->registerFunction(
'getVueComponentInfo',
function (string $componentPath) use ($vueComponents, $environment) {
$assetRoot = '/static/vite_dist';
if ($environment->isDevelopment() || $environment->isTesting()) {
return [
'js' => $assetRoot . '/' . $componentPath,
'css' => [],
'prefetch' => [],
];
}
if (!isset($vueComponents[$componentPath])) {
return null;
}
$includes = [
'js' => $assetRoot . '/' . $vueComponents[$componentPath]['file'],
'css' => [],
'prefetch' => [],
];
$visitedNodes = [];
$fetchCss = function ($component) use (
$vueComponents,
$assetRoot,
&$includes,
&$fetchCss,
&$visitedNodes
): void {
if (!isset($vueComponents[$component]) || isset($visitedNodes[$component])) {
return;
}
$visitedNodes[$component] = true;
$componentInfo = $vueComponents[$component];
if (isset($componentInfo['css'])) {
foreach ($componentInfo['css'] as $css) {
$includes['css'][] = $assetRoot . '/' . $css;
}
}
if (isset($componentInfo['file'])) {
$fileUrl = $assetRoot . '/' . $componentInfo['file'];
if ($fileUrl !== $includes['js']) {
$includes['prefetch'][] = $fileUrl;
}
}
if (isset($componentInfo['imports'])) {
foreach ($componentInfo['imports'] as $import) {
$fetchCss($import);
}
}
};
$fetchCss($componentPath);
return $includes;
}
);
$dispatcher->dispatch(new Event\BuildView($this));
}
public function setRequest(?ServerRequest $request): void
{
$this->request = $request;
if (null !== $request) {
$requestData = [
'request' => $request,
'auth' => $request->getAttribute(ServerRequest::ATTR_AUTH),
'acl' => $request->getAttribute(ServerRequest::ATTR_ACL),
'flash' => $request->getAttribute(ServerRequest::ATTR_SESSION_FLASH),
];
$router = $request->getAttribute(ServerRequest::ATTR_ROUTER);
if (null !== $router) {
$requestData['router'] = $router;
}
$customization = $request->getAttribute(ServerRequest::ATTR_CUSTOMIZATION);
if ($customization instanceof Customization) {
$requestData['customization'] = $customization;
$this->globalProps->set(
'enableAdvancedFeatures',
$customization->enableAdvancedFeatures()
);
}
$localeObj = $request->getAttribute(ServerRequest::ATTR_LOCALE);
if (!($localeObj instanceof SupportedLocales)) {
$localeObj = SupportedLocales::default();
}
$locale = $localeObj->getLocaleWithoutEncoding();
$localeShort = substr($locale, 0, 2);
$localeWithDashes = str_replace('_', '-', $locale);
$this->globalProps->set('locale', $locale);
$this->globalProps->set('localeShort', $localeShort);
$this->globalProps->set('localeWithDashes', $localeWithDashes);
// User profile-specific 24-hour display setting.
$userObj = $request->getAttribute(ServerRequest::ATTR_USER);
$requestData['user'] = $userObj;
$timeConfig = new stdClass();
if ($userObj instanceof User) {
// See: path_to_url#hourcycle
$timeConfig->hourCycle = $userObj->getShow24HourTime() ? 'h23' : 'h12';
$globalPermissions = [];
$stationPermissions = [];
foreach ($userObj->getRoles() as $role) {
foreach ($role->getPermissions() as $permission) {
$station = $permission->getStation();
if (null !== $station) {
$stationPermissions[$station->getIdRequired()][] = $permission->getActionName();
} else {
$globalPermissions[] = $permission->getActionName();
}
}
}
$this->globalProps->set('user', [
'id' => $userObj->getIdRequired(),
'displayName' => $userObj->getDisplayName(),
'globalPermissions' => $globalPermissions,
'stationPermissions' => $stationPermissions,
]);
}
$this->globalProps->set('timeConfig', $timeConfig);
// Station-specific properties
$station = $request->getAttribute(ServerRequest::ATTR_STATION);
if ($station instanceof Station) {
$this->globalProps->set('station', [
'id' => $station->getIdRequired(),
'name' => $station->getName(),
'isEnabled' => $station->getIsEnabled(),
'shortName' => $station->getShortName(),
'timezone' => $station->getTimezone(),
'offlineText' => $station->getBrandingConfig()->getOfflineText(),
]);
}
$this->addData($requestData);
}
}
public function getSections(): GlobalSections
{
return $this->sections;
}
/** @return ArrayCollection<string, array|object|string|int|bool> */
public function getGlobalProps(): ArrayCollection
{
return $this->globalProps;
}
public function reset(): void
{
$this->sections = new GlobalSections();
$this->globalProps = new ArrayCollection();
$this->data = new Data();
}
/**
* @param string $name
* @param array $data
*/
public function fetch(string $name, array $data = []): string
{
return $this->render($name, $data);
}
/**
* Trigger rendering of template and write it directly to the PSR-7 compatible Response object.
*
* @param ResponseInterface $response
* @param string $templateName
* @param array $templateArgs
*/
public function renderToResponse(
ResponseInterface $response,
string $templateName,
array $templateArgs = []
): ResponseInterface {
$response->getBody()->write(
$this->render($templateName, $templateArgs)
);
return $response->withHeader('Content-type', 'text/html; charset=utf-8');
}
public function renderVuePage(
ResponseInterface $response,
string $component,
?string $id = null,
string $layout = 'panel',
?string $title = null,
array $layoutParams = [],
array $props = [],
): ResponseInterface {
$id ??= $component;
return $this->renderToResponse(
$response,
'system/vue_page',
[
'component' => $component,
'id' => $id,
'layout' => $layout,
'title' => $title,
'layoutParams' => $layoutParams,
'props' => $props,
]
);
}
}
``` | /content/code_sandbox/backend/src/View.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 2,100 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Enums\ApplicationEnvironment;
use App\Enums\ReleaseChannel;
use App\Installer\EnvFiles\AzuraCastEnvFile;
use App\Radio\Configuration;
use App\Utilities\File;
use App\Utilities\Types;
use Exception;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\UriInterface;
use Psr\Log\LogLevel;
final class Environment
{
private static Environment $instance;
// Cached immutable values that are frequently used.
private readonly string $baseDir;
private readonly string $backendDir;
private readonly string $parentDir;
private readonly bool $isDocker;
private readonly ApplicationEnvironment $appEnv;
/** @var array<string, string|int|bool|float> */
private readonly array $data;
// Core settings values
public const string APP_NAME = 'APP_NAME';
public const string APP_ENV = 'APPLICATION_ENV';
public const string TEMP_DIR = 'TEMP_DIR';
public const string UPLOADS_DIR = 'UPLOADS_DIR';
public const string IS_DOCKER = 'IS_DOCKER';
public const string IS_CLI = 'IS_CLI';
public const string ASSET_URL = 'ASSETS_URL';
public const string LANG = 'LANG';
public const string RELEASE_CHANNEL = 'AZURACAST_VERSION';
public const string SFTP_PORT = 'AZURACAST_SFTP_PORT';
public const string AUTO_ASSIGN_PORT_MIN = 'AUTO_ASSIGN_PORT_MIN';
public const string AUTO_ASSIGN_PORT_MAX = 'AUTO_ASSIGN_PORT_MAX';
public const string SYNC_SHORT_EXECUTION_TIME = 'SYNC_SHORT_EXECUTION_TIME';
public const string SYNC_LONG_EXECUTION_TIME = 'SYNC_LONG_EXECUTION_TIME';
public const string NOW_PLAYING_DELAY_TIME = 'NOW_PLAYING_DELAY_TIME';
public const string NOW_PLAYING_MAX_CONCURRENT_PROCESSES = 'NOW_PLAYING_MAX_CONCURRENT_PROCESSES';
public const string LOG_LEVEL = 'LOG_LEVEL';
public const string SHOW_DETAILED_ERRORS = 'SHOW_DETAILED_ERRORS';
public const string PROFILING_EXTENSION_ENABLED = 'PROFILING_EXTENSION_ENABLED';
public const string PROFILING_EXTENSION_ALWAYS_ON = 'PROFILING_EXTENSION_ALWAYS_ON';
public const string PROFILING_EXTENSION_HTTP_KEY = 'PROFILING_EXTENSION_HTTP_KEY';
public const string ENABLE_WEB_UPDATER = 'ENABLE_WEB_UPDATER';
// Database and Cache Configuration Variables
public const string DB_HOST = 'MYSQL_HOST';
public const string DB_PORT = 'MYSQL_PORT';
public const string DB_NAME = 'MYSQL_DATABASE';
public const string DB_USER = 'MYSQL_USER';
public const string DB_PASSWORD = 'MYSQL_PASSWORD';
public const string ENABLE_REDIS = 'ENABLE_REDIS';
public const string REDIS_HOST = 'REDIS_HOST';
public const string REDIS_PORT = 'REDIS_PORT';
public function __construct(array $elements = [])
{
$this->baseDir = dirname(__DIR__, 2);
$this->backendDir = dirname(__DIR__);
$this->parentDir = dirname($this->baseDir);
$this->isDocker = file_exists($this->parentDir . '/.docker');
if (! $this->isDocker) {
try {
$azuracastEnvPath = AzuraCastEnvFile::buildPathFromBase($this->baseDir);
$azuracastEnv = AzuraCastEnvFile::fromEnvFile($azuracastEnvPath);
$this->data = array_merge($elements, $azuracastEnv->toArray());
} catch (Exception $e) {
$this->data = $elements;
}
} else {
$this->data = $elements;
}
$this->appEnv = ApplicationEnvironment::tryFrom(
Types::string($this->data[self::APP_ENV] ?? null, '', true)
) ?? ApplicationEnvironment::default();
}
public function toArray(): array
{
return $this->data;
}
public function getAppEnvironmentEnum(): ApplicationEnvironment
{
return $this->appEnv;
}
/**
* @return string The base directory of the application, i.e. `/var/app/www` for Docker installations.
*/
public function getBaseDirectory(): string
{
return $this->baseDir;
}
/**
* @return string The base directory for PHP application files, i.e. `/var/app/www/backend`.
*/
public function getBackendDirectory(): string
{
return $this->backendDir;
}
/**
* @return string The parent directory the application is within, i.e. `/var/azuracast`.
*/
public function getParentDirectory(): string
{
return $this->parentDir;
}
public function isDocker(): bool
{
return $this->isDocker;
}
public function isProduction(): bool
{
return ApplicationEnvironment::Production === $this->getAppEnvironmentEnum();
}
public function isTesting(): bool
{
return ApplicationEnvironment::Testing === $this->getAppEnvironmentEnum();
}
public function isDevelopment(): bool
{
return ApplicationEnvironment::Development === $this->getAppEnvironmentEnum();
}
public function showDetailedErrors(): bool
{
return Types::bool(
$this->data[self::SHOW_DETAILED_ERRORS] ?? null,
!$this->isProduction(),
true
);
}
public function isCli(): bool
{
return Types::bool(
$this->data[self::IS_CLI] ?? null,
('cli' === PHP_SAPI)
);
}
public function getAppName(): string
{
return Types::string(
$this->data[self::APP_NAME] ?? null,
'AzuraCast',
true
);
}
public function getAssetUrl(): ?string
{
return Types::string(
$this->data[self::ASSET_URL] ?? null,
'/static',
true
);
}
/**
* @return string The directory where temporary files are stored by the application, i.e. `/var/app/www_tmp`
*/
public function getTempDirectory(): string
{
return Types::string(
$this->data[self::TEMP_DIR] ?? null,
$this->getParentDirectory() . '/www_tmp',
true
);
}
/**
* @return string The directory where user system-level uploads are stored.
*/
public function getUploadsDirectory(): string
{
return Types::string(
$this->data[self::UPLOADS_DIR] ?? null,
File::getFirstExistingDirectory([
$this->getParentDirectory() . '/storage/uploads',
$this->getParentDirectory() . '/uploads',
]),
true
);
}
/**
* @return string The default directory where station data is stored.
*/
public function getStationDirectory(): string
{
return $this->getParentDirectory() . '/stations';
}
public function getInternalUri(): UriInterface
{
return new Uri('path_to_url
}
public function getLocalUri(): UriInterface
{
return new Uri('path_to_url
}
public function getLang(): ?string
{
return Types::stringOrNull($this->data[self::LANG]);
}
public function getReleaseChannelEnum(): ReleaseChannel
{
return ReleaseChannel::tryFrom(Types::string($this->data[self::RELEASE_CHANNEL] ?? null))
?? ReleaseChannel::default();
}
public function getSftpPort(): int
{
return Types::int(
$this->data[self::SFTP_PORT] ?? null,
2022
);
}
public function getAutoAssignPortMin(): int
{
return Types::int(
$this->data[self::AUTO_ASSIGN_PORT_MIN] ?? null,
Configuration::DEFAULT_PORT_MIN
);
}
public function getAutoAssignPortMax(): int
{
return Types::int(
$this->data[self::AUTO_ASSIGN_PORT_MAX] ?? null,
Configuration::DEFAULT_PORT_MAX
);
}
public function getSyncShortExecutionTime(): int
{
return Types::int(
$this->data[self::SYNC_SHORT_EXECUTION_TIME] ?? null,
600
);
}
public function getSyncLongExecutionTime(): int
{
return Types::int(
$this->data[self::SYNC_LONG_EXECUTION_TIME] ?? null,
1800
);
}
public function getNowPlayingDelayTime(): ?int
{
return Types::intOrNull($this->data[self::NOW_PLAYING_DELAY_TIME] ?? null);
}
public function getNowPlayingMaxConcurrentProcesses(): ?int
{
return Types::intOrNull($this->data[self::NOW_PLAYING_MAX_CONCURRENT_PROCESSES] ?? null);
}
/**
* @phpstan-return LogLevel::*
*/
public function getLogLevel(): string
{
$logLevelRaw = Types::stringOrNull($this->data[self::LOG_LEVEL] ?? null, true);
if (null !== $logLevelRaw) {
$loggingLevel = strtolower($logLevelRaw);
$allowedLogLevels = [
LogLevel::DEBUG,
LogLevel::INFO,
LogLevel::NOTICE,
LogLevel::WARNING,
LogLevel::ERROR,
LogLevel::CRITICAL,
LogLevel::ALERT,
LogLevel::EMERGENCY,
];
if (in_array($loggingLevel, $allowedLogLevels, true)) {
return $loggingLevel;
}
}
return $this->isProduction()
? LogLevel::NOTICE
: LogLevel::INFO;
}
/**
* @return array{
* host: string,
* port: int,
* dbname: string,
* user: string,
* password: string,
* unix_socket?: string
* }
*/
public function getDatabaseSettings(): array
{
$dbSettings = [
'host' => Types::string(
$this->data[self::DB_HOST] ?? null,
'localhost',
true
),
'port' => Types::int(
$this->data[self::DB_PORT] ?? null,
3306
),
'dbname' => Types::string(
$this->data[self::DB_NAME] ?? null,
'azuracast',
true
),
'user' => Types::string(
$this->data[self::DB_USER] ?? null,
'azuracast',
true
),
'password' => Types::string(
$this->data[self::DB_PASSWORD] ?? null,
'azur4c457',
true
),
];
if ('localhost' === $dbSettings['host'] && $this->isDocker()) {
$dbSettings['unix_socket'] = '/run/mysqld/mysqld.sock';
}
return $dbSettings;
}
public function useLocalDatabase(): bool
{
return 'localhost' === $this->getDatabaseSettings()['host'];
}
public function enableRedis(): bool
{
return Types::bool(
$this->data[self::ENABLE_REDIS],
true,
true
);
}
/**
* @return array{
* host: string,
* port: int,
* socket?: string
* }
*/
public function getRedisSettings(): array
{
$redisSettings = [
'host' => Types::string(
$this->data[self::REDIS_HOST] ?? null,
'localhost',
true
),
'port' => Types::int(
$this->data[self::REDIS_PORT] ?? null,
6379
),
];
if ('localhost' === $redisSettings['host'] && $this->isDocker()) {
$redisSettings['socket'] = '/run/redis/redis.sock';
}
return $redisSettings;
}
public function useLocalRedis(): bool
{
return $this->enableRedis() && 'localhost' === $this->getRedisSettings()['host'];
}
public function isProfilingExtensionEnabled(): bool
{
return Types::bool(
$this->data[self::PROFILING_EXTENSION_ENABLED] ?? null,
false,
true
);
}
public function isProfilingExtensionAlwaysOn(): bool
{
return Types::bool(
$this->data[self::PROFILING_EXTENSION_ALWAYS_ON] ?? null,
false,
true
);
}
public function getProfilingExtensionHttpKey(): string
{
return Types::string(
$this->data[self::PROFILING_EXTENSION_HTTP_KEY] ?? null,
'dev',
true
);
}
public function enableWebUpdater(): bool
{
if (!$this->isDocker()) {
return false;
}
return Types::bool(
$this->data[self::ENABLE_WEB_UPDATER] ?? null,
false,
true
);
}
public static function getDefaultsForEnvironment(Environment $existingEnv): self
{
return new self([
self::IS_CLI => $existingEnv->isCli(),
self::IS_DOCKER => $existingEnv->isDocker(),
]);
}
public static function getInstance(): Environment
{
return self::$instance;
}
public static function setInstance(Environment $instance): void
{
self::$instance = $instance;
}
}
``` | /content/code_sandbox/backend/src/Environment.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 2,947 |
```php
<?php
declare(strict_types=1);
namespace App;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
interface CallableEventDispatcherInterface extends EventDispatcherInterface
{
/**
* @param array|class-string $className
*/
public function addServiceSubscriber(array|string $className): void;
/**
* @param array|class-string $className
*/
public function removeServiceSubscriber(array|string $className): void;
public function addCallableListener(
string $eventName,
string $className,
?string $method = '__invoke',
int $priority = 0
): void;
public function removeCallableListener(
string $eventName,
string $className,
?string $method = '__invoke'
): void;
}
``` | /content/code_sandbox/backend/src/CallableEventDispatcherInterface.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 158 |
```php
<?php
declare(strict_types=1);
namespace App;
use App\Container\EnvironmentAwareTrait;
use App\Entity\Repository\SettingsRepository;
use App\Exception\Http\RateLimitExceededException;
use App\Http\ServerRequest;
use App\Lock\LockFactory;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\ProxyAdapter;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\RateLimiter\Storage\CacheStorage;
final class RateLimit
{
use EnvironmentAwareTrait;
private CacheItemPoolInterface $psr6Cache;
public function __construct(
private readonly LockFactory $lockFactory,
private readonly SettingsRepository $settingsRepo,
CacheItemPoolInterface $cacheItemPool
) {
$this->psr6Cache = new ProxyAdapter($cacheItemPool, 'ratelimit.');
}
/**
* @param ServerRequest $request
* @param string $groupName
* @param int $interval
* @param int $limit
*
* @throws RateLimitExceededException
*/
public function checkRequestRateLimit(
ServerRequest $request,
string $groupName,
int $interval = 5,
int $limit = 2
): void {
if ($this->environment->isTesting() || $this->environment->isCli()) {
return;
}
$ip = $this->settingsRepo->readSettings()->getIp($request);
$ipKey = str_replace([':', '.'], '_', $ip);
if (!$this->checkRateLimit($groupName, $ipKey, $interval, $limit)) {
throw new RateLimitExceededException($request);
}
}
public function checkRateLimit(
string $groupName,
string $key,
int $interval = 5,
int $limit = 2
): bool {
$cacheStore = new CacheStorage($this->psr6Cache);
$config = [
'id' => 'ratelimit.' . $groupName,
'policy' => 'sliding_window',
'interval' => $interval . ' seconds',
'limit' => $limit,
];
$rateLimiterFactory = new RateLimiterFactory($config, $cacheStore, $this->lockFactory);
$rateLimiter = $rateLimiterFactory->create($key);
return $rateLimiter->consume()->isAccepted();
}
}
``` | /content/code_sandbox/backend/src/RateLimit.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 524 |
```php
<?php
declare(strict_types=1);
namespace App\Container;
use App\Entity\Repository\SettingsRepository;
use App\Entity\Settings;
use DI\Attribute\Inject;
trait SettingsAwareTrait
{
protected SettingsRepository $settingsRepo;
#[Inject]
public function setSettingsRepo(SettingsRepository $settingsRepo): void
{
$this->settingsRepo = $settingsRepo;
}
public function readSettings(): Settings
{
return $this->settingsRepo->readSettings();
}
public function writeSettings(Settings|array $settings): void
{
$this->settingsRepo->writeSettings($settings);
}
}
``` | /content/code_sandbox/backend/src/Container/SettingsAwareTrait.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 134 |
```php
<?php
declare(strict_types=1);
namespace App\Container;
use App\Doctrine\ReloadableEntityManagerInterface;
use DI\Attribute\Inject;
trait EntityManagerAwareTrait
{
protected ReloadableEntityManagerInterface $em;
#[Inject]
public function setEntityManager(ReloadableEntityManagerInterface $em): void
{
$this->em = $em;
}
public function getEntityManager(): ReloadableEntityManagerInterface
{
return $this->em;
}
}
``` | /content/code_sandbox/backend/src/Container/EntityManagerAwareTrait.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 100 |
```php
<?php
declare(strict_types=1);
namespace App\Container;
use DI\Attribute\Inject;
use Monolog\Logger;
trait LoggerAwareTrait
{
protected Logger $logger;
#[Inject]
public function setLogger(Logger $logger): void
{
$this->logger = $logger;
}
public function getLogger(): Logger
{
return $this->logger;
}
}
``` | /content/code_sandbox/backend/src/Container/LoggerAwareTrait.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 86 |
```php
<?php
declare(strict_types=1);
namespace App\Container;
use DI\Attribute\Inject;
use DI\Container;
trait ContainerAwareTrait
{
protected Container $di;
#[Inject]
public function setContainer(Container $container): void
{
$this->di = $container;
}
public function getContainer(): Container
{
return $this->di;
}
}
``` | /content/code_sandbox/backend/src/Container/ContainerAwareTrait.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 85 |
```php
<?php
declare(strict_types=1);
namespace App\Container;
use App\Environment;
use DI\Attribute\Inject;
trait EnvironmentAwareTrait
{
protected Environment $environment;
#[Inject]
public function setEnvironment(Environment $environment): void
{
$this->environment = $environment;
}
public function getEnvironment(): Environment
{
return $this->environment;
}
}
``` | /content/code_sandbox/backend/src/Container/EnvironmentAwareTrait.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 86 |
```php
<?php
declare(strict_types=1);
namespace App\Message;
use App\MessageQueue\QueueNames;
final class ReprocessMediaMessage extends AbstractUniqueMessage
{
/** @var int The numeric identifier for the StorageLocation entity. */
public int $storage_location_id;
/** @var int The numeric identifier for the StationMedia record being processed. */
public int $media_id;
/** @var bool Whether to force reprocessing even if checks indicate it is not necessary. */
public bool $force = false;
public function getIdentifier(): string
{
return 'ReprocessMediaMessage_' . $this->media_id;
}
public function getQueue(): QueueNames
{
return QueueNames::Media;
}
}
``` | /content/code_sandbox/backend/src/Message/ReprocessMediaMessage.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 156 |
```php
<?php
declare(strict_types=1);
namespace App\Message;
use App\MessageQueue\QueueNames;
final class WritePlaylistFileMessage extends AbstractUniqueMessage
{
/** @var int The numeric identifier for the StationPlaylist record being processed. */
public int $playlist_id;
public function getIdentifier(): string
{
return 'WritePlaylistFileMessage_' . $this->playlist_id;
}
public function getQueue(): QueueNames
{
return QueueNames::LowPriority;
}
}
``` | /content/code_sandbox/backend/src/Message/WritePlaylistFileMessage.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 106 |
```php
<?php
declare(strict_types=1);
namespace App\Message;
use App\MessageQueue\QueueNames;
abstract class AbstractMessage
{
public function getQueue(): QueueNames
{
return QueueNames::NormalPriority;
}
}
``` | /content/code_sandbox/backend/src/Message/AbstractMessage.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 49 |
```php
<?php
declare(strict_types=1);
namespace App\Message;
use App\MessageQueue\QueueNames;
final class ProcessCoverArtMessage extends AbstractUniqueMessage
{
/** @var int The numeric identifier for the StorageLocation entity. */
public int $storage_location_id;
/** @var string The relative path for the cover file to be processed. */
public string $path;
/** @var string The hash of the folder (used for storing and indexing the cover art). */
public string $folder_hash;
public function getQueue(): QueueNames
{
return QueueNames::Media;
}
}
``` | /content/code_sandbox/backend/src/Message/ProcessCoverArtMessage.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 128 |
```php
<?php
declare(strict_types=1);
namespace App\Message;
final class GenerateAcmeCertificate extends AbstractMessage
{
/** @var string|null The path to log output of the command to. */
public ?string $outputPath = null;
public bool $force = false;
}
``` | /content/code_sandbox/backend/src/Message/GenerateAcmeCertificate.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 61 |
```php
<?php
declare(strict_types=1);
namespace App\Message;
use App\MessageQueue\QueueNames;
final class BackupMessage extends AbstractUniqueMessage
{
/** @var int|null The storage location to back up to. */
public ?int $storageLocationId = null;
/** @var string|null The absolute or relative path of the backup file. */
public ?string $path = null;
/** @var string|null The path to log output of the Backup command to. */
public ?string $outputPath = null;
/** @var bool Whether to exclude media, producing a much more compact backup. */
public bool $excludeMedia = false;
public function getIdentifier(): string
{
// The system should only ever be running one backup task at a given time.
return 'BackupMessage';
}
public function getTtl(): ?float
{
return 86400;
}
public function getQueue(): QueueNames
{
return QueueNames::LowPriority;
}
}
``` | /content/code_sandbox/backend/src/Message/BackupMessage.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 215 |
```php
<?php
declare(strict_types=1);
namespace App\Message;
use App\MessageQueue\QueueNames;
final class AddNewMediaMessage extends AbstractUniqueMessage
{
/** @var int The numeric identifier for the StorageLocation entity. */
public int $storage_location_id;
/** @var string The relative path for the media file to be processed. */
public string $path;
public function getQueue(): QueueNames
{
return QueueNames::Media;
}
}
``` | /content/code_sandbox/backend/src/Message/AddNewMediaMessage.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 100 |
```php
<?php
declare(strict_types=1);
namespace App\Message;
use App\Environment;
use Monolog\Level;
final class TestWebhookMessage extends AbstractUniqueMessage
{
public int $webhookId;
/** @var string|null The path to log output of the Backup command to. */
public ?string $outputPath = null;
/** @var value-of<Level::VALUES> */
public int $logLevel = Level::Info->value;
public function getIdentifier(): string
{
return 'TestWebHook_' . $this->webhookId;
}
public function getTtl(): ?float
{
return Environment::getInstance()->getSyncLongExecutionTime();
}
}
``` | /content/code_sandbox/backend/src/Message/TestWebhookMessage.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\Message;
use App\Entity\Api\NowPlaying\NowPlaying;
use App\MessageQueue\QueueNames;
final class DispatchWebhookMessage extends AbstractUniqueMessage
{
public int $station_id;
public NowPlaying $np;
/** @var array<string> */
public array $triggers = [];
public function getIdentifier(): string
{
return 'DispatchWebhookMessage_' . $this->station_id;
}
public function getQueue(): QueueNames
{
return QueueNames::HighPriority;
}
}
``` | /content/code_sandbox/backend/src/Message/DispatchWebhookMessage.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\Message;
use App\MessageQueue\UniqueMessageInterface;
abstract class AbstractUniqueMessage extends AbstractMessage implements UniqueMessageInterface
{
public function getIdentifier(): string
{
$staticClassParts = explode("\\", static::class);
$staticClass = array_pop($staticClassParts);
return $staticClass . '_' . md5(serialize($this));
}
public function getTtl(): ?float
{
return 60;
}
}
``` | /content/code_sandbox/backend/src/Message/AbstractUniqueMessage.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 109 |
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use App\Entity\Enums\StationBackendPerformanceModes;
use App\Radio\Enums\AudioProcessingMethods;
use App\Radio\Enums\CrossfadeModes;
use App\Radio\Enums\MasterMePresets;
use App\Radio\Enums\StreamFormats;
use App\Utilities\Types;
use LogicException;
class StationBackendConfiguration extends AbstractStationConfiguration
{
public const string CHARSET = 'charset';
public function getCharset(): string
{
return Types::stringOrNull($this->get(self::CHARSET), true) ?? 'UTF-8';
}
public function setCharset(?string $charset): void
{
$this->set(self::CHARSET, $charset);
}
public const string DJ_PORT = 'dj_port';
public function getDjPort(): ?int
{
return Types::intOrNull($this->get(self::DJ_PORT));
}
public function setDjPort(int|string $port = null): void
{
$this->set(self::DJ_PORT, $port);
}
public const string TELNET_PORT = 'telnet_port';
public function getTelnetPort(): ?int
{
return Types::intOrNull($this->get(self::TELNET_PORT));
}
public function setTelnetPort(int|string $port = null): void
{
$this->set(self::TELNET_PORT, $port);
}
public const string RECORD_STREAMS = 'record_streams';
public function recordStreams(): bool
{
return Types::boolOrNull($this->get(self::RECORD_STREAMS)) ?? false;
}
public function setRecordStreams(string|bool $recordStreams): void
{
$this->set(self::RECORD_STREAMS, $recordStreams);
}
public const string RECORD_STREAMS_FORMAT = 'record_streams_format';
public function getRecordStreamsFormat(): string
{
return $this->getRecordStreamsFormatEnum()->value;
}
public function getRecordStreamsFormatEnum(): StreamFormats
{
return StreamFormats::tryFrom(
Types::stringOrNull($this->get(self::RECORD_STREAMS_FORMAT)) ?? ''
)
?? StreamFormats::Mp3;
}
public function setRecordStreamsFormat(?string $format): void
{
if (null !== $format) {
$format = strtolower($format);
if (null === StreamFormats::tryFrom($format)) {
$format = null;
}
}
$this->set(self::RECORD_STREAMS_FORMAT, $format);
}
public const string RECORD_STREAMS_BITRATE = 'record_streams_bitrate';
public function getRecordStreamsBitrate(): int
{
return Types::intOrNull($this->get(self::RECORD_STREAMS_BITRATE)) ?? 128;
}
public function setRecordStreamsBitrate(int|string $bitrate = null): void
{
$this->set(self::RECORD_STREAMS_BITRATE, $bitrate);
}
public const string USE_MANUAL_AUTODJ = 'use_manual_autodj';
public function useManualAutoDj(): bool
{
return Types::boolOrNull($this->get(self::USE_MANUAL_AUTODJ)) ?? false;
}
public function setUseManualAutoDj(?bool $useManualAutoDj): void
{
$this->set(self::USE_MANUAL_AUTODJ, $useManualAutoDj);
}
public const string AUTODJ_QUEUE_LENGTH = 'autodj_queue_length';
protected const int DEFAULT_QUEUE_LENGTH = 3;
public function getAutoDjQueueLength(): int
{
return Types::intOrNull($this->get(self::AUTODJ_QUEUE_LENGTH)) ?? self::DEFAULT_QUEUE_LENGTH;
}
public function setAutoDjQueueLength(int|string $queueLength = null): void
{
$this->set(self::AUTODJ_QUEUE_LENGTH, $queueLength);
}
public const string DJ_MOUNT_POINT = 'dj_mount_point';
public function getDjMountPoint(): string
{
return Types::stringOrNull($this->get(self::DJ_MOUNT_POINT)) ?? '/';
}
public function setDjMountPoint(?string $mountPoint): void
{
$this->set(self::DJ_MOUNT_POINT, $mountPoint);
}
public const string DJ_BUFFER = 'dj_buffer';
protected const int DEFAULT_DJ_BUFFER = 5;
public function getDjBuffer(): int
{
return Types::intOrNull($this->get(self::DJ_BUFFER)) ?? self::DEFAULT_DJ_BUFFER;
}
public function setDjBuffer(int|string $buffer = null): void
{
$this->set(self::DJ_BUFFER, $buffer);
}
public const string AUDIO_PROCESSING_METHOD = 'audio_processing_method';
public function getAudioProcessingMethod(): ?string
{
return $this->getAudioProcessingMethodEnum()->value;
}
public function getAudioProcessingMethodEnum(): AudioProcessingMethods
{
return AudioProcessingMethods::tryFrom(
Types::stringOrNull($this->get(self::AUDIO_PROCESSING_METHOD)) ?? ''
) ?? AudioProcessingMethods::default();
}
public function isAudioProcessingEnabled(): bool
{
return AudioProcessingMethods::None !== $this->getAudioProcessingMethodEnum();
}
public function setAudioProcessingMethod(?string $method): void
{
if (null !== $method) {
$method = strtolower($method);
if (null === AudioProcessingMethods::tryFrom($method)) {
$method = null;
}
}
$this->set(self::AUDIO_PROCESSING_METHOD, $method);
}
public const string POST_PROCESSING_INCLUDE_LIVE = 'post_processing_include_live';
public function getPostProcessingIncludeLive(): bool
{
return Types::boolOrNull($this->get(self::POST_PROCESSING_INCLUDE_LIVE)) ?? false;
}
public function setPostProcessingIncludeLive(bool|string $postProcessingIncludeLive = null): void
{
$this->set(self::POST_PROCESSING_INCLUDE_LIVE, $postProcessingIncludeLive);
}
public const string STEREO_TOOL_LICENSE_KEY = 'stereo_tool_license_key';
{
return Types::stringOrNull($this->get(self::STEREO_TOOL_LICENSE_KEY), true);
}
{
$this->set(self::STEREO_TOOL_LICENSE_KEY, $licenseKey);
}
public const string STEREO_TOOL_CONFIGURATION_PATH = 'stereo_tool_configuration_path';
public function getStereoToolConfigurationPath(): ?string
{
return Types::stringOrNull($this->get(self::STEREO_TOOL_CONFIGURATION_PATH), true);
}
public function setStereoToolConfigurationPath(?string $stereoToolConfigurationPath): void
{
$this->set(self::STEREO_TOOL_CONFIGURATION_PATH, $stereoToolConfigurationPath);
}
public const string MASTER_ME_PRESET = 'master_me_preset';
public function getMasterMePreset(): ?string
{
return Types::stringOrNull($this->get(self::MASTER_ME_PRESET), true);
}
public function getMasterMePresetEnum(): MasterMePresets
{
return MasterMePresets::tryFrom($this->getMasterMePreset() ?? '')
?? MasterMePresets::default();
}
public function setMasterMePreset(?string $masterMePreset): void
{
if (null !== $masterMePreset) {
$masterMePreset = strtolower($masterMePreset);
if (null === MasterMePresets::tryFrom($masterMePreset)) {
$masterMePreset = null;
}
}
$this->set(self::MASTER_ME_PRESET, $masterMePreset);
}
public const string MASTER_ME_LOUDNESS_TARGET = 'master_me_loudness_target';
protected const int MASTER_ME_DEFAULT_LOUDNESS_TARGET = -16;
public function getMasterMeLoudnessTarget(): int
{
return Types::intOrNull($this->get(self::MASTER_ME_LOUDNESS_TARGET))
?? self::MASTER_ME_DEFAULT_LOUDNESS_TARGET;
}
public function setMasterMeLoudnessTarget(int|string $masterMeLoudnessTarget = null): void
{
$this->set(self::MASTER_ME_LOUDNESS_TARGET, $masterMeLoudnessTarget);
}
public const string USE_REPLAYGAIN = 'enable_replaygain_metadata';
public function useReplayGain(): bool
{
// AutoCue overrides this functionality.
if ($this->getEnableAutoCue()) {
return false;
}
return Types::boolOrNull($this->get(self::USE_REPLAYGAIN)) ?? false;
}
public function setUseReplayGain(bool|string $useReplayGain): void
{
$this->set(self::USE_REPLAYGAIN, $useReplayGain);
}
public const string CROSSFADE_TYPE = 'crossfade_type';
public function getCrossfadeTypeEnum(): CrossfadeModes
{
// AutoCue overrides this functionality.
if ($this->getEnableAutoCue()) {
return CrossfadeModes::Disabled;
}
return CrossfadeModes::tryFrom(
Types::stringOrNull($this->get(self::CROSSFADE_TYPE)) ?? ''
) ?? CrossfadeModes::default();
}
public function getCrossfadeType(): string
{
return $this->getCrossfadeTypeEnum()->value;
}
public function setCrossfadeType(string $crossfadeType): void
{
$this->set(self::CROSSFADE_TYPE, $crossfadeType);
}
public const string CROSSFADE = 'crossfade';
protected const int DEFAULT_CROSSFADE_DURATION = 2;
public function getCrossfade(): float
{
return round(
Types::floatOrNull($this->get(self::CROSSFADE)) ?? self::DEFAULT_CROSSFADE_DURATION,
1
);
}
public function setCrossfade(float|string $crossfade = null): void
{
$this->set(self::CROSSFADE, $crossfade);
}
public function getCrossfadeDuration(): float
{
$crossfade = $this->getCrossfade();
$crossfadeType = $this->getCrossfadeTypeEnum();
if (CrossfadeModes::Disabled !== $crossfadeType && $crossfade > 0) {
return round($crossfade * 1.5, 2);
}
return 0;
}
public function isCrossfadeEnabled(): bool
{
return $this->getCrossfadeDuration() > 0;
}
public const string DUPLICATE_PREVENTION_TIME_RANGE = 'duplicate_prevention_time_range';
protected const int DEFAULT_DUPLICATE_PREVENTION_TIME_RANGE = 120;
public function getDuplicatePreventionTimeRange(): int
{
return Types::intOrNull($this->get(self::DUPLICATE_PREVENTION_TIME_RANGE))
?? self::DEFAULT_DUPLICATE_PREVENTION_TIME_RANGE;
}
public function setDuplicatePreventionTimeRange(int|string $duplicatePreventionTimeRange = null): void
{
$this->set(self::DUPLICATE_PREVENTION_TIME_RANGE, $duplicatePreventionTimeRange);
}
public const string PERFORMANCE_MODE = 'performance_mode';
public function getPerformanceMode(): string
{
return $this->getPerformanceModeEnum()->value;
}
public function getPerformanceModeEnum(): StationBackendPerformanceModes
{
return StationBackendPerformanceModes::tryFrom(
Types::stringOrNull($this->get(self::PERFORMANCE_MODE)) ?? ''
) ?? StationBackendPerformanceModes::default();
}
public function setPerformanceMode(?string $performanceMode): void
{
$perfModeEnum = StationBackendPerformanceModes::tryFrom($performanceMode ?? '');
if (null === $perfModeEnum) {
$this->set(self::PERFORMANCE_MODE, null);
} else {
$this->set(self::PERFORMANCE_MODE, $perfModeEnum->value);
}
}
public const string HLS_SEGMENT_LENGTH = 'hls_segment_length';
public function getHlsSegmentLength(): int
{
return Types::intOrNull($this->get(self::HLS_SEGMENT_LENGTH)) ?? 4;
}
public function setHlsSegmentLength(int|string $length = null): void
{
$this->set(self::HLS_SEGMENT_LENGTH, $length);
}
public const string HLS_SEGMENTS_IN_PLAYLIST = 'hls_segments_in_playlist';
public function getHlsSegmentsInPlaylist(): int
{
return Types::intOrNull($this->get(self::HLS_SEGMENTS_IN_PLAYLIST)) ?? 5;
}
public function setHlsSegmentsInPlaylist(int|string $value = null): void
{
$this->set(self::HLS_SEGMENTS_IN_PLAYLIST, $value);
}
public const string HLS_SEGMENTS_OVERHEAD = 'hls_segments_overhead';
public function getHlsSegmentsOverhead(): int
{
return Types::intOrNull($this->get(self::HLS_SEGMENTS_OVERHEAD)) ?? 2;
}
public function setHlsSegmentsOverhead(int|string $value = null): void
{
$this->set(self::HLS_SEGMENTS_OVERHEAD, $value);
}
public const string HLS_ENABLE_ON_PUBLIC_PLAYER = 'hls_enable_on_public_player';
public function getHlsEnableOnPublicPlayer(): bool
{
return Types::boolOrNull($this->get(self::HLS_ENABLE_ON_PUBLIC_PLAYER)) ?? false;
}
public function setHlsEnableOnPublicPlayer(bool|string $enable): void
{
$this->set(self::HLS_ENABLE_ON_PUBLIC_PLAYER, $enable);
}
public const string HLS_IS_DEFAULT = 'hls_is_default';
public function getHlsIsDefault(): bool
{
return Types::boolOrNull($this->get(self::HLS_IS_DEFAULT)) ?? false;
}
public function setHlsIsDefault(bool|string $value): void
{
$this->set(self::HLS_IS_DEFAULT, $value);
}
public const string LIVE_BROADCAST_TEXT = 'live_broadcast_text';
public function getLiveBroadcastText(): string
{
return Types::stringOrNull($this->get(self::LIVE_BROADCAST_TEXT), true)
?? 'Live Broadcast';
}
public function setLiveBroadcastText(?string $text): void
{
$this->set(self::LIVE_BROADCAST_TEXT, $text);
}
public const string ENABLE_AUTO_CUE = 'enable_auto_cue';
public function getEnableAutoCue(): bool
{
return Types::bool($this->get(self::ENABLE_AUTO_CUE));
}
public function setEnableAutoCue(bool $value): void
{
$this->set(self::ENABLE_AUTO_CUE, $value);
}
public const string WRITE_PLAYLISTS_TO_LIQUIDSOAP = 'write_playlists_to_liquidsoap';
public function getWritePlaylistsToLiquidsoap(): bool
{
return Types::bool($this->get(self::WRITE_PLAYLISTS_TO_LIQUIDSOAP), true);
}
public function setWritePlaylistsToLiquidsoap(bool $value): void
{
$this->set(self::WRITE_PLAYLISTS_TO_LIQUIDSOAP, $value);
}
public const string CUSTOM_TOP = 'custom_config_top';
public const string CUSTOM_PRE_PLAYLISTS = 'custom_config_pre_playlists';
public const string CUSTOM_PRE_LIVE = 'custom_config_pre_live';
public const string CUSTOM_PRE_FADE = 'custom_config_pre_fade';
public const string CUSTOM_PRE_BROADCAST = 'custom_config';
public const string CUSTOM_BOTTOM = 'custom_config_bottom';
/** @return array<int, string> */
public static function getCustomConfigurationSections(): array
{
return [
self::CUSTOM_TOP,
self::CUSTOM_PRE_PLAYLISTS,
self::CUSTOM_PRE_FADE,
self::CUSTOM_PRE_LIVE,
self::CUSTOM_PRE_BROADCAST,
self::CUSTOM_BOTTOM,
];
}
public function getCustomConfigurationSection(string $section): ?string
{
$allSections = self::getCustomConfigurationSections();
if (!in_array($section, $allSections, true)) {
throw new LogicException('Invalid custom configuration section.');
}
return Types::stringOrNull($this->get($section), true);
}
public function setCustomConfigurationSection(string $section, ?string $value = null): void
{
$allSections = self::getCustomConfigurationSections();
if (!in_array($section, $allSections, true)) {
throw new LogicException('Invalid custom configuration section.');
}
$this->set($section, $value);
}
}
``` | /content/code_sandbox/backend/src/Entity/StationBackendConfiguration.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 3,679 |
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use App\Entity\Interfaces\IdentifiableEntityInterface;
use App\Utilities\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
#[
ORM\Entity,
ORM\Table(name: 'podcast_media'),
Attributes\Auditable
]
class PodcastMedia implements IdentifiableEntityInterface
{
use Traits\HasUniqueId;
use Traits\TruncateStrings;
#[ORM\ManyToOne]
#[ORM\JoinColumn(name: 'storage_location_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
protected StorageLocation $storage_location;
#[ORM\OneToOne(inversedBy: 'media')]
#[ORM\JoinColumn(name: 'episode_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
protected ?PodcastEpisode $episode;
#[ORM\Column(length: 200)]
#[Assert\NotBlank]
protected string $original_name;
#[ORM\Column(type: 'decimal', precision: 7, scale: 2)]
protected string $length = '0.0';
/** @var string The formatted podcast media's duration (in mm:ss format) */
#[ORM\Column(length: 10)]
protected string $length_text = '0:00';
#[ORM\Column(length: 500)]
#[Assert\NotBlank]
protected string $path;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
protected string $mime_type = 'application/octet-stream';
#[ORM\Column]
protected int $modified_time = 0;
#[ORM\Column]
#[Attributes\AuditIgnore]
protected int $art_updated_at = 0;
public function __construct(StorageLocation $storageLocation)
{
$this->storage_location = $storageLocation;
}
public function getStorageLocation(): StorageLocation
{
return $this->storage_location;
}
public function getEpisode(): ?PodcastEpisode
{
return $this->episode;
}
public function setEpisode(?PodcastEpisode $episode): self
{
$this->episode = $episode;
return $this;
}
public function getOriginalName(): string
{
return $this->original_name;
}
public function setOriginalName(string $originalName): self
{
$this->original_name = $this->truncateString($originalName);
return $this;
}
public function getLength(): float
{
return Types::float($this->length);
}
public function setLength(float $length): self
{
$lengthMin = floor($length / 60);
$lengthSec = (int)$length % 60;
$this->length = (string)$length;
$this->length_text = $lengthMin . ':' . str_pad((string)$lengthSec, 2, '0', STR_PAD_LEFT);
return $this;
}
public function getLengthText(): string
{
return $this->length_text;
}
public function setLengthText(string $lengthText): self
{
$this->length_text = $lengthText;
return $this;
}
public function getPath(): string
{
return $this->path;
}
public function setPath(string $path): self
{
$this->path = $path;
return $this;
}
public function getMimeType(): string
{
return $this->mime_type;
}
public function setMimeType(string $mimeType): self
{
$this->mime_type = $mimeType;
return $this;
}
public function getModifiedTime(): int
{
return $this->modified_time;
}
public function setModifiedTime(int $modifiedTime): self
{
$this->modified_time = $modifiedTime;
return $this;
}
public function getArtUpdatedAt(): int
{
return $this->art_updated_at;
}
public function setArtUpdatedAt(int $artUpdatedAt): self
{
$this->art_updated_at = $artUpdatedAt;
return $this;
}
}
``` | /content/code_sandbox/backend/src/Entity/PodcastMedia.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 895 |
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use JsonSerializable;
#[ORM\Embeddable]
class ListenerDevice implements JsonSerializable
{
#[ORM\Column(length: 255)]
protected ?string $client = null;
#[ORM\Column]
protected bool $is_browser = false;
#[ORM\Column]
protected bool $is_mobile = false;
#[ORM\Column]
protected bool $is_bot = false;
#[ORM\Column(length: 150, nullable: true)]
protected ?string $browser_family = null;
#[ORM\Column(length: 150, nullable: true)]
protected ?string $os_family = null;
public function getClient(): ?string
{
return $this->client;
}
public function isBrowser(): bool
{
return $this->is_browser;
}
public function isMobile(): bool
{
return $this->is_mobile;
}
public function isBot(): bool
{
return $this->is_bot;
}
public function getBrowserFamily(): ?string
{
return $this->browser_family;
}
public function getOsFamily(): ?string
{
return $this->os_family;
}
public function jsonSerialize(): array
{
return [
'client' => $this->client,
'is_browser' => $this->is_browser,
'is_mobile' => $this->is_mobile,
'is_bot' => $this->is_bot,
'browser_family' => $this->browser_family,
'os_family' => $this->os_family,
];
}
}
``` | /content/code_sandbox/backend/src/Entity/ListenerDevice.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 357 |
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use App\Entity\Interfaces\IdentifiableEntityInterface;
use Carbon\CarbonImmutable;
use Doctrine\ORM\Mapping as ORM;
use OpenApi\Attributes as OA;
use Stringable;
#[
OA\Schema(
description: 'Each individual broadcast associated with a streamer.',
type: "object"
),
ORM\Entity,
ORM\Table(name: 'station_streamer_broadcasts')
]
class StationStreamerBroadcast implements IdentifiableEntityInterface, Stringable
{
use Traits\HasAutoIncrementId;
use Traits\TruncateStrings;
public const string PATH_PREFIX = 'stream';
#[
ORM\ManyToOne(inversedBy: 'streamer_broadcasts'),
ORM\JoinColumn(name: 'station_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')
]
protected Station $station;
#[
ORM\ManyToOne(inversedBy: 'broadcasts'),
ORM\JoinColumn(name: 'streamer_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')
]
protected StationStreamer $streamer;
#[ORM\Column(name: 'timestamp_start')]
protected int $timestampStart = 0;
#[ORM\Column(name: 'timestamp_end')]
protected int $timestampEnd = 0;
#[ORM\Column(name: 'recording_path', length: 255, nullable: true)]
protected ?string $recordingPath = null;
public function __construct(StationStreamer $streamer)
{
$this->streamer = $streamer;
$this->station = $streamer->getStation();
$this->timestampStart = time();
}
public function getStation(): Station
{
return $this->station;
}
public function getStreamer(): StationStreamer
{
return $this->streamer;
}
public function getTimestampStart(): int
{
return $this->timestampStart;
}
public function setTimestampStart(int $timestampStart): void
{
$this->timestampStart = $timestampStart;
}
public function getTimestampEnd(): int
{
return $this->timestampEnd;
}
public function setTimestampEnd(int $timestampEnd): void
{
$this->timestampEnd = $timestampEnd;
}
public function getRecordingPath(): ?string
{
return $this->recordingPath;
}
public function setRecordingPath(?string $recordingPath): void
{
$this->recordingPath = $recordingPath;
}
public function __toString(): string
{
return (CarbonImmutable::createFromTimestamp($this->timestampStart, 'UTC'))->toAtomString()
. '-'
. (0 !== $this->timestampEnd
? (CarbonImmutable::createFromTimestamp($this->timestampEnd, 'UTC'))->toAtomString()
: 'Now'
);
}
}
``` | /content/code_sandbox/backend/src/Entity/StationStreamerBroadcast.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 622 |
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use App\Utilities\Types;
use App\Webhook\Enums\WebhookTriggers;
use App\Webhook\Enums\WebhookTypes;
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_webhooks', options: ['charset' => 'utf8mb4', 'collate' => 'utf8mb4_unicode_ci']),
Attributes\Auditable
]
class StationWebhook implements
Stringable,
Interfaces\StationCloneAwareInterface,
Interfaces\IdentifiableEntityInterface
{
use Traits\HasAutoIncrementId;
use Traits\TruncateStrings;
public const string LAST_SENT_TIMESTAMP_KEY = 'last_message_sent';
#[
ORM\ManyToOne(inversedBy: 'webhooks'),
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(
description: "The nickname of the webhook connector.",
example: "Twitter Post"
),
ORM\Column(length: 100, nullable: true)
]
protected ?string $name = null;
#[
OA\Property(
description: "The type of webhook connector to use.",
example: "twitter"
),
ORM\Column(type: "string", length: 100, enumType: WebhookTypes::class),
Assert\NotBlank
]
protected WebhookTypes $type;
#[
OA\Property(example: true),
ORM\Column
]
protected bool $is_enabled = true;
#[
OA\Property(
description: "List of events that should trigger the webhook notification.",
type: "array",
items: new OA\Items()
),
ORM\Column(type: 'json', nullable: true)
]
protected ?array $triggers = null;
#[
OA\Property(
description: "Detailed webhook configuration (if applicable)",
type: "array",
items: new OA\Items()
),
ORM\Column(type: 'json', nullable: true)
]
protected ?array $config = null;
#[
OA\Property(
description: "Internal details used by the webhook to preserve state.",
type: "array",
items: new OA\Items()
),
ORM\Column(type: 'json', nullable: true),
Attributes\AuditIgnore
]
protected ?array $metadata = null;
public function __construct(Station $station, WebhookTypes $type)
{
$this->station = $station;
$this->type = $type;
}
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->truncateNullableString($name, 100);
}
public function getType(): WebhookTypes
{
return $this->type;
}
public function getIsEnabled(): bool
{
return $this->is_enabled;
}
public function setIsEnabled(bool $isEnabled): void
{
$this->is_enabled = $isEnabled;
}
/**
* @return string[]
*/
public function getTriggers(): array
{
return (array)$this->triggers;
}
public function setTriggers(?array $triggers = null): void
{
$this->triggers = $triggers;
}
public function hasTriggers(): bool
{
return 0 !== count($this->getTriggers());
}
public function hasTrigger(WebhookTriggers|string $trigger): bool
{
if ($trigger instanceof WebhookTriggers) {
$trigger = $trigger->value;
}
return in_array($trigger, $this->getTriggers(), true);
}
/**
* @return mixed[]
*/
public function getConfig(): array
{
return (array)$this->config;
}
public function setConfig(?array $config = null): void
{
$this->config = $config;
}
/**
* Set the value of a given metadata key.
*
* @param string $key
* @param mixed|null $value
*/
public function setMetadataKey(string $key, mixed $value = null): void
{
if (null === $value) {
unset($this->metadata[$key]);
} else {
$this->metadata[$key] = $value;
}
}
/**
* Return the value of a given metadata key, or a default if it is null or doesn't exist.
*
* @param string $key
* @param mixed|null $default
*
*/
public function getMetadataKey(string $key, mixed $default = null): mixed
{
return $this->metadata[$key] ?? $default;
}
/**
* Clear all metadata associated with this webhook.
*/
public function clearMetadata(): void
{
$this->metadata = [];
}
/**
* Check whether this webhook was dispatched in the last $seconds seconds.
*
* @param int $seconds
*
*/
public function checkRateLimit(int $seconds): bool
{
$lastMessageSent = Types::int($this->getMetadataKey(self::LAST_SENT_TIMESTAMP_KEY));
return $lastMessageSent <= (time() - $seconds);
}
public function updateLastSentTimestamp(): void
{
$this->setMetadataKey(self::LAST_SENT_TIMESTAMP_KEY, time());
}
public function __toString(): string
{
return $this->getStation() . ' Web Hook: ' . $this->getName();
}
public function __clone()
{
$this->metadata = null;
}
}
``` | /content/code_sandbox/backend/src/Entity/StationWebhook.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,360 |
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use App\Entity\Enums\StorageLocationAdapters;
use App\Entity\Enums\StorageLocationTypes;
use App\Entity\Interfaces\IdentifiableEntityInterface;
use App\Exception\StorageLocationFullException;
use App\Radio\Quota;
use App\Validator\Constraints as AppAssert;
use Brick\Math\BigInteger;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Stringable;
use Symfony\Component\Filesystem\Path;
#[
ORM\Entity,
ORM\Table(name: 'storage_location'),
Attributes\Auditable,
AppAssert\StorageLocation
]
class StorageLocation implements Stringable, IdentifiableEntityInterface
{
use Traits\HasAutoIncrementId;
use Traits\TruncateStrings;
public const string DEFAULT_BACKUPS_PATH = '/var/azuracast/backups';
#[ORM\Column(type: 'string', length: 50, enumType: StorageLocationTypes::class)]
protected StorageLocationTypes $type;
#[ORM\Column(type: 'string', length: 50, enumType: StorageLocationAdapters::class)]
protected StorageLocationAdapters $adapter;
#[ORM\Column(length: 255, nullable: false)]
protected string $path = '';
#[ORM\Column(name: 's3_credential_key', length: 255, nullable: true)]
protected ?string $s3CredentialKey = null;
#[ORM\Column(name: 's3_credential_secret', length: 255, nullable: true)]
protected ?string $s3CredentialSecret = null;
#[ORM\Column(name: 's3_region', length: 150, nullable: true)]
protected ?string $s3Region = null;
#[ORM\Column(name: 's3_version', length: 150, nullable: true)]
protected ?string $s3Version = 'latest';
#[ORM\Column(name: 's3_bucket', length: 255, nullable: true)]
protected ?string $s3Bucket = null;
#[ORM\Column(name: 's3_endpoint', length: 255, nullable: true)]
protected ?string $s3Endpoint = null;
#[ORM\Column(name: 's3_use_path_style', nullable: true)]
protected ?bool $s3UsePathStyle = false;
#[ORM\Column(name: 'dropbox_app_key', length: 50, nullable: true)]
protected ?string $dropboxAppKey = null;
#[ORM\Column(name: 'dropbox_app_secret', length: 150, nullable: true)]
protected ?string $dropboxAppSecret = null;
#[ORM\Column(name: 'dropbox_auth_token', length: 255, nullable: true)]
protected ?string $dropboxAuthToken = null;
#[ORM\Column(name: 'dropbox_refresh_token', length: 255, nullable: true)]
protected ?string $dropboxRefreshToken = null;
#[ORM\Column(name: 'sftp_host', length: 255, nullable: true)]
protected ?string $sftpHost = null;
#[ORM\Column(name: 'sftp_username', length: 255, nullable: true)]
protected ?string $sftpUsername = null;
#[ORM\Column(name: 'sftp_password', length: 255, nullable: true)]
protected ?string $sftpPassword = null;
#[ORM\Column(name: 'sftp_port', nullable: true)]
protected ?int $sftpPort = null;
#[ORM\Column(name: 'sftp_private_key', type: 'text', nullable: true)]
protected ?string $sftpPrivateKey = null;
#[ORM\Column(name: 'sftp_private_key_pass_phrase', length: 255, nullable: true)]
protected ?string $sftpPrivateKeyPassPhrase = null;
#[ORM\Column(name: 'storage_quota', type: 'bigint', nullable: true)]
protected string|int|null $storageQuota = null;
#[ORM\Column(name: 'storage_used', type: 'bigint', nullable: true)]
#[Attributes\AuditIgnore]
protected string|int|null $storageUsed = null;
/** @var Collection<int, StationMedia> */
#[ORM\OneToMany(targetEntity: StationMedia::class, mappedBy: 'storage_location')]
protected Collection $media;
/** @var Collection<int, UnprocessableMedia> */
#[ORM\OneToMany(targetEntity: UnprocessableMedia::class, mappedBy: 'storage_location')]
protected Collection $unprocessable_media;
public function __construct(
StorageLocationTypes $type,
StorageLocationAdapters $adapter
) {
$this->type = $type;
$this->adapter = $adapter;
$this->media = new ArrayCollection();
$this->unprocessable_media = new ArrayCollection();
}
public function getType(): StorageLocationTypes
{
return $this->type;
}
public function getAdapter(): StorageLocationAdapters
{
return $this->adapter;
}
public function getPath(): string
{
return $this->path;
}
public function setPath(string $path): void
{
$this->path = $this->truncateString(
Path::canonicalize($path)
);
}
public function getS3CredentialKey(): ?string
{
return $this->s3CredentialKey;
}
public function setS3CredentialKey(?string $s3CredentialKey): void
{
$this->s3CredentialKey = $this->truncateNullableString($s3CredentialKey);
}
public function getS3CredentialSecret(): ?string
{
return $this->s3CredentialSecret;
}
public function setS3CredentialSecret(?string $s3CredentialSecret): void
{
$this->s3CredentialSecret = $this->truncateNullableString($s3CredentialSecret);
}
public function getS3Region(): ?string
{
return $this->s3Region;
}
public function setS3Region(?string $s3Region): void
{
$this->s3Region = $s3Region;
}
public function getS3Version(): ?string
{
return $this->s3Version;
}
public function setS3Version(?string $s3Version): void
{
$this->s3Version = $s3Version;
}
public function getS3Bucket(): ?string
{
return $this->s3Bucket;
}
public function setS3Bucket(?string $s3Bucket): void
{
$this->s3Bucket = $s3Bucket;
}
public function getS3Endpoint(): ?string
{
return $this->s3Endpoint;
}
public function setS3Endpoint(?string $s3Endpoint): void
{
$this->s3Endpoint = $this->truncateNullableString($s3Endpoint);
}
public function getS3UsePathStyle(): bool
{
return $this->s3UsePathStyle ?? false;
}
public function setS3UsePathStyle(?bool $s3UsePathStyle): void
{
$this->s3UsePathStyle = $s3UsePathStyle;
}
public function getDropboxAppKey(): ?string
{
return $this->dropboxAppKey;
}
public function setDropboxAppKey(?string $dropboxAppKey): void
{
$this->dropboxAppKey = $dropboxAppKey;
}
public function getDropboxAppSecret(): ?string
{
return $this->dropboxAppSecret;
}
public function setDropboxAppSecret(?string $dropboxAppSecret): void
{
$this->dropboxAppSecret = $dropboxAppSecret;
}
public function getDropboxAuthToken(): ?string
{
return $this->dropboxAuthToken;
}
public function setDropboxAuthToken(?string $dropboxAuthToken): void
{
$this->dropboxAuthToken = $dropboxAuthToken;
}
public function getDropboxRefreshToken(): ?string
{
return $this->dropboxRefreshToken;
}
public function setDropboxRefreshToken(?string $dropboxRefreshToken): void
{
$this->dropboxRefreshToken = $dropboxRefreshToken;
}
public function getSftpHost(): ?string
{
return $this->sftpHost;
}
public function setSftpHost(?string $sftpHost): void
{
$this->sftpHost = $sftpHost;
}
public function getSftpUsername(): ?string
{
return $this->sftpUsername;
}
public function setSftpUsername(?string $sftpUsername): void
{
$this->sftpUsername = $sftpUsername;
}
public function getSftpPassword(): ?string
{
return $this->sftpPassword;
}
public function setSftpPassword(?string $sftpPassword): void
{
$this->sftpPassword = $sftpPassword;
}
public function getSftpPort(): ?int
{
return $this->sftpPort;
}
public function setSftpPort(?int $sftpPort): void
{
$this->sftpPort = $sftpPort;
}
public function getSftpPrivateKey(): ?string
{
return $this->sftpPrivateKey;
}
public function setSftpPrivateKey(?string $sftpPrivateKey): void
{
$this->sftpPrivateKey = $sftpPrivateKey;
}
public function getSftpPrivateKeyPassPhrase(): ?string
{
return $this->sftpPrivateKeyPassPhrase;
}
public function setSftpPrivateKeyPassPhrase(?string $sftpPrivateKeyPassPhrase): void
{
$this->sftpPrivateKeyPassPhrase = $sftpPrivateKeyPassPhrase;
}
public function isLocal(): bool
{
return $this->getAdapter()->isLocal();
}
public function getStorageQuota(): ?string
{
$rawQuota = $this->getStorageQuotaBytes();
return ($rawQuota instanceof BigInteger)
? Quota::getReadableSize($rawQuota)
: '';
}
/**
* @param string|BigInteger|null $storageQuota
*/
public function setStorageQuota(BigInteger|string|null $storageQuota): void
{
$storageQuota = (string)Quota::convertFromReadableSize($storageQuota);
$this->storageQuota = !empty($storageQuota) ? $storageQuota : null;
}
public function getStorageQuotaBytes(): ?BigInteger
{
$size = $this->storageQuota;
return (null !== $size && '' !== $size)
? BigInteger::of($size)
: null;
}
public function getStorageUsed(): ?string
{
$rawSize = $this->getStorageUsedBytes();
return Quota::getReadableSize($rawSize);
}
/**
* @param string|BigInteger|null $storageUsed
*/
public function setStorageUsed(BigInteger|string|null $storageUsed): void
{
$storageUsed = (string)Quota::convertFromReadableSize($storageUsed);
$this->storageUsed = !empty($storageUsed) ? $storageUsed : null;
}
public function getStorageUsedBytes(): BigInteger
{
$size = $this->storageUsed;
return (null !== $size && '' !== $size)
? BigInteger::of($size)
: BigInteger::zero();
}
/**
* Increment the current used storage total.
*
* @param int|string|BigInteger $newStorageAmount
*/
public function addStorageUsed(BigInteger|int|string $newStorageAmount): void
{
if (empty($newStorageAmount)) {
return;
}
$currentStorageUsed = $this->getStorageUsedBytes();
$this->storageUsed = (string)$currentStorageUsed->plus($newStorageAmount);
}
/**
* Decrement the current used storage total.
*
* @param int|string|BigInteger $amountToRemove
*/
public function removeStorageUsed(BigInteger|int|string $amountToRemove): void
{
if (empty($amountToRemove)) {
return;
}
$storageUsed = $this->getStorageUsedBytes()->minus($amountToRemove);
if ($storageUsed->isLessThan(0)) {
$storageUsed = BigInteger::zero();
}
$this->storageUsed = (string)$storageUsed;
}
public function getStorageAvailable(): string
{
$rawSize = $this->getStorageAvailableBytes();
return ($rawSize instanceof BigInteger)
? Quota::getReadableSize($rawSize)
: '';
}
public function getStorageAvailableBytes(): ?BigInteger
{
$quota = $this->getStorageQuotaBytes();
if ($this->isLocal()) {
$localPath = $this->getPath();
$totalSpaceFloat = disk_total_space($localPath);
if (is_float($totalSpaceFloat)) {
$totalSpace = BigInteger::of($totalSpaceFloat);
if (null === $quota || $quota->isGreaterThan($totalSpace)) {
return $totalSpace;
}
}
}
return $quota ?? null;
}
public function isStorageFull(): bool
{
$quota = $this->getStorageQuotaBytes();
if ($quota === null) {
return false;
}
$used = $this->getStorageUsedBytes();
return ($used->compareTo($quota) !== -1);
}
public function canHoldFile(BigInteger|int|string $size): bool
{
if (empty($size)) {
return true;
}
$quota = $this->getStorageQuotaBytes();
if ($quota === null) {
return true;
}
$newStorageUsed = $this->getStorageUsedBytes()->plus($size);
return ($newStorageUsed->compareTo($quota) === -1);
}
public function errorIfFull(): void
{
if ($this->isStorageFull()) {
throw new StorageLocationFullException();
}
}
public function getStorageUsePercentage(): int
{
$storageUsed = $this->getStorageUsedBytes();
$storageAvailable = $this->getStorageAvailableBytes();
if (null === $storageAvailable) {
return 0;
}
return Quota::getPercentage($storageUsed, $storageAvailable);
}
/**
* @return Collection<int, StationMedia>
*/
public function getMedia(): Collection
{
return $this->media;
}
public function getUri(?string $suffix = null): string
{
$adapterClass = $this->getAdapter()->getAdapterClass();
return $adapterClass::getUri($this, $suffix);
}
public function getFilteredPath(): string
{
$adapterClass = $this->getAdapter()->getAdapterClass();
return $adapterClass::filterPath($this->path);
}
public function __toString(): string
{
return $this->getAdapter()->getName() . ': ' . $this->getUri();
}
}
``` | /content/code_sandbox/backend/src/Entity/StorageLocation.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 3,314 |
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use NowPlaying\Result\Client;
#[
ORM\Entity,
ORM\Table(name: 'listener'),
ORM\Index(name: 'idx_timestamps', columns: ['timestamp_end', 'timestamp_start']),
ORM\Index(name: 'idx_statistics_country', columns: ['location_country']),
ORM\Index(name: 'idx_statistics_os', columns: ['device_os_family']),
ORM\Index(name: 'idx_statistics_browser', columns: ['device_browser_family'])
]
class Listener implements
Interfaces\IdentifiableEntityInterface,
Interfaces\StationAwareInterface
{
use Traits\HasAutoIncrementId;
use Traits\TruncateStrings;
#[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(targetEntity: StationMount::class)]
#[ORM\JoinColumn(name: 'mount_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
protected ?StationMount $mount = null;
#[ORM\Column(nullable: true, insertable: false, updatable: false)]
protected ?int $mount_id = null;
#[ORM\ManyToOne(targetEntity: StationRemote::class)]
#[ORM\JoinColumn(name: 'remote_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
protected ?StationRemote $remote = null;
#[ORM\Column(nullable: true, insertable: false, updatable: false)]
protected ?int $remote_id = null;
#[ORM\ManyToOne(targetEntity: StationHlsStream::class)]
#[ORM\JoinColumn(name: 'hls_stream_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
protected ?StationHlsStream $hls_stream = null;
#[ORM\Column(nullable: true, insertable: false, updatable: false)]
protected ?int $hls_stream_id = null;
#[ORM\Column]
protected int $listener_uid;
#[ORM\Column(length: 45)]
protected string $listener_ip;
#[ORM\Column(length: 255)]
protected string $listener_user_agent;
#[ORM\Column(length: 32)]
protected string $listener_hash;
#[ORM\Column]
protected int $timestamp_start;
#[ORM\Column]
protected int $timestamp_end;
#[ORM\Embedded(class: ListenerLocation::class, columnPrefix: 'location_')]
protected ListenerLocation $location;
#[ORM\Embedded(class: ListenerDevice::class, columnPrefix: 'device_')]
protected ListenerDevice $device;
public function __construct(Station $station, Client $client)
{
$this->station = $station;
$this->timestamp_start = time();
$this->timestamp_end = 0;
$this->listener_uid = (int)$client->uid;
$this->listener_user_agent = $this->truncateString($client->userAgent);
$this->listener_ip = $client->ip;
$this->listener_hash = self::calculateListenerHash($client);
$this->location = new ListenerLocation();
$this->device = new ListenerDevice();
}
public function getStation(): Station
{
return $this->station;
}
public function getMount(): ?StationMount
{
return $this->mount;
}
public function getMountId(): ?int
{
return $this->mount_id;
}
public function setMount(?StationMount $mount): void
{
$this->mount = $mount;
}
public function getRemote(): ?StationRemote
{
return $this->remote;
}
public function getRemoteId(): ?int
{
return $this->remote_id;
}
public function setRemote(?StationRemote $remote): void
{
$this->remote = $remote;
}
public function getHlsStream(): ?StationHlsStream
{
return $this->hls_stream;
}
public function getHlsStreamId(): ?int
{
return $this->hls_stream_id;
}
public function setHlsStream(?StationHlsStream $hlsStream): void
{
$this->hls_stream = $hlsStream;
}
public function getListenerUid(): int
{
return $this->listener_uid;
}
public function getListenerIp(): string
{
return $this->listener_ip;
}
public function getListenerUserAgent(): string
{
return $this->listener_user_agent;
}
public function getListenerHash(): string
{
return $this->listener_hash;
}
public function getTimestampStart(): int
{
return $this->timestamp_start;
}
public function getTimestamp(): int
{
return $this->timestamp_start;
}
public function getTimestampEnd(): int
{
return $this->timestamp_end;
}
public function setTimestampEnd(int $timestampEnd): void
{
$this->timestamp_end = $timestampEnd;
}
public function getConnectedSeconds(): int
{
return $this->timestamp_end - $this->timestamp_start;
}
public function getLocation(): ListenerLocation
{
return $this->location;
}
public function getDevice(): ListenerDevice
{
return $this->device;
}
/**
* Filter clients to exclude any listeners that shouldn't be included (i.e. relays).
*
* @param array $clients
*
* @return mixed[]
*/
public static function filterClients(array $clients): array
{
return array_filter(
$clients,
static function ($client) {
// Ignore clients with the "Icecast" UA as those are relays and not listeners.
return !(false !== stripos($client['user_agent'], 'Icecast'));
}
);
}
public static function getListenerSeconds(array $intervals): int
{
// Sort by start time.
usort(
$intervals,
static function ($a, $b) {
return $a['start'] <=> $b['start'];
}
);
$seconds = 0;
while (count($intervals) > 0) {
$currentInterval = array_shift($intervals);
$start = $currentInterval['start'];
$end = $currentInterval['end'];
foreach ($intervals as $intervalKey => $interval) {
// Starts after this interval ends; no more entries to process
if ($interval['start'] > $end) {
break;
}
// Extend the current interval's end
if ($interval['end'] > $end) {
$end = $interval['end'];
}
unset($intervals[$intervalKey]);
}
$seconds += $end - $start;
}
return $seconds;
}
public static function calculateListenerHash(Client $client): string
{
$hashParts = $client->ip . $client->userAgent;
if (!empty($client->mount)) {
$hashParts .= $client->mount;
}
return md5($hashParts);
}
}
``` | /content/code_sandbox/backend/src/Entity/Listener.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 1,606 |
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use App\Entity\Enums\StorageLocationAdapters;
use App\Entity\Enums\StorageLocationTypes;
use App\Entity\Interfaces\EntityGroupsInterface;
use App\Entity\Interfaces\IdentifiableEntityInterface;
use App\Environment;
use App\Radio\Enums\BackendAdapters;
use App\Radio\Enums\FrontendAdapters;
use App\Utilities\File;
use App\Validator\Constraints as AppAssert;
use Azura\Normalizer\Attributes\DeepNormalize;
use DateTimeZone;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use InvalidArgumentException;
use League\Flysystem\UnixVisibility\PortableVisibilityConverter;
use League\Flysystem\Visibility;
use OpenApi\Attributes as OA;
use RuntimeException;
use Stringable;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @phpstan-import-type ConfigData from AbstractStationConfiguration
*/
#[
OA\Schema(schema: "Station", type: "object"),
ORM\Entity,
ORM\Table(name: 'station'),
ORM\Index(name: 'idx_short_name', columns: ['short_name']),
ORM\HasLifecycleCallbacks,
Attributes\Auditable,
AppAssert\StationPortChecker,
AppAssert\UniqueEntity(fields: ['short_name'])
]
class Station implements Stringable, IdentifiableEntityInterface
{
use Traits\HasAutoIncrementId;
use Traits\TruncateStrings;
#[
OA\Property(description: "The full display name of the station.", example: "AzuraTest Radio"),
ORM\Column(length: 100, nullable: false),
Assert\NotBlank,
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected string $name = '';
#[
OA\Property(
description: "The URL-friendly name for the station, typically auto-generated from the full station name.",
example: "azuratest_radio"
),
ORM\Column(length: 100, nullable: false),
Assert\NotBlank,
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected string $short_name = '';
#[
OA\Property(
description: "If set to 'false', prevents the station from broadcasting but leaves it in the database.",
example: true
),
ORM\Column,
Serializer\Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL])
]
protected bool $is_enabled = true;
#[
OA\Property(
description: "The frontend adapter (icecast,shoutcast,remote,etc)",
example: "icecast"
),
ORM\Column(type: 'string', length: 100, enumType: FrontendAdapters::class),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected FrontendAdapters $frontend_type;
/**
* @var ConfigData|null
*/
#[
OA\Property(
description: "An array containing station-specific frontend configuration",
type: "object"
),
ORM\Column(type: 'json', nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?array $frontend_config = null;
#[
OA\Property(
description: "The backend adapter (liquidsoap,etc)",
example: "liquidsoap"
),
ORM\Column(type: 'string', length: 100, enumType: BackendAdapters::class),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected BackendAdapters $backend_type;
/**
* @var ConfigData|null
*/
#[
OA\Property(
description: "An array containing station-specific backend configuration",
type: "object"
),
ORM\Column(type: 'json', nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?array $backend_config = null;
#[
ORM\Column(length: 150, nullable: true),
Attributes\AuditIgnore
]
protected ?string $adapter_api_key = null;
#[
OA\Property(example: "A sample radio station."),
ORM\Column(type: 'text', nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?string $description = null;
#[
OA\Property(example: "path_to_url"),
ORM\Column(length: 255, nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?string $url = null;
#[
OA\Property(example: "Various"),
ORM\Column(length: 255, nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?string $genre = null;
#[
OA\Property(example: "/var/azuracast/stations/azuratest_radio"),
ORM\Column(length: 255, nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL])
]
protected ?string $radio_base_dir = null;
#[
OA\Property(
description: "Whether listeners can request songs to play on this station.",
example: true
),
ORM\Column,
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected bool $enable_requests = false;
#[
OA\Property(example: 5),
ORM\Column(nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?int $request_delay = 5;
#[
OA\Property(example: 15),
ORM\Column(nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?int $request_threshold = 15;
#[
OA\Property(example: 0),
ORM\Column(nullable: true, options: ['default' => 0]),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?int $disconnect_deactivate_streamer = 0;
#[
OA\Property(
description: "Whether streamers are allowed to broadcast to this station at all.",
example: false
),
ORM\Column,
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected bool $enable_streamers = false;
#[
OA\Property(
description: "Whether a streamer is currently active on the station.",
example: false
),
ORM\Column,
Attributes\AuditIgnore
]
protected bool $is_streamer_live = false;
#[
OA\Property(
description: "Whether this station is visible as a public page and in a now-playing API response.",
example: true
),
ORM\Column,
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected bool $enable_public_page = true;
#[
OA\Property(
description: "Whether this station has a public 'on-demand' streaming and download page.",
example: true
),
ORM\Column,
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected bool $enable_on_demand = false;
#[
OA\Property(
description: "Whether the 'on-demand' page offers download capability.",
example: true
),
ORM\Column,
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected bool $enable_on_demand_download = true;
#[
OA\Property(
description: "Whether HLS streaming is enabled.",
example: true
),
ORM\Column,
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected bool $enable_hls = false;
#[
ORM\Column,
Attributes\AuditIgnore
]
protected bool $needs_restart = false;
#[
ORM\Column,
Attributes\AuditIgnore
]
protected bool $has_started = false;
#[
OA\Property(
description: "The number of 'last played' history items to show for a station in API responses.",
example: 5
),
ORM\Column(type: 'smallint'),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected int $api_history_items = 5;
#[
OA\Property(
description: "The time zone that station operations should take place in.",
example: "UTC"
),
ORM\Column(length: 100, nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?string $timezone = 'UTC';
/**
* @var ConfigData|null
*/
#[
OA\Property(
description: "An array containing station-specific branding configuration",
type: "object"
),
ORM\Column(type: 'json', nullable: true),
Serializer\Groups([EntityGroupsInterface::GROUP_GENERAL, EntityGroupsInterface::GROUP_ALL])
]
protected ?array $branding_config = null;
/** @var Collection<int, SongHistory> */
#[
ORM\OneToMany(targetEntity: SongHistory::class, mappedBy: 'station'),
ORM\OrderBy(['timestamp_start' => 'desc'])
]
protected Collection $history;
#[
ORM\ManyToOne,
ORM\JoinColumn(
name: 'media_storage_location_id',
referencedColumnName: 'id',
nullable: true,
onDelete: 'SET NULL'
),
DeepNormalize(true),
Serializer\MaxDepth(1),
Serializer\Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL])
]
protected ?StorageLocation $media_storage_location = null;
#[
ORM\ManyToOne,
ORM\JoinColumn(
name: 'recordings_storage_location_id',
referencedColumnName: 'id',
nullable: true,
onDelete: 'SET NULL'
),
DeepNormalize(true),
Serializer\MaxDepth(1),
Serializer\Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL])
]
protected ?StorageLocation $recordings_storage_location = null;
#[
ORM\ManyToOne,
ORM\JoinColumn(
name: 'podcasts_storage_location_id',
referencedColumnName: 'id',
nullable: true,
onDelete: 'SET NULL'
),
DeepNormalize(true),
Serializer\MaxDepth(1),
Serializer\Groups([EntityGroupsInterface::GROUP_ADMIN, EntityGroupsInterface::GROUP_ALL])
]
protected ?StorageLocation $podcasts_storage_location = null;
/** @var Collection<int, StationStreamer> */
#[ORM\OneToMany(targetEntity: StationStreamer::class, mappedBy: 'station')]
protected Collection $streamers;
#[
ORM\ManyToOne,
ORM\JoinColumn(name: 'current_streamer_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL'),
Attributes\AuditIgnore
]
protected ?StationStreamer $current_streamer = null;
#[
ORM\Column(nullable: true, insertable: false, updatable: false),
Attributes\AuditIgnore
]
private ?int $current_streamer_id = null;
#[ORM\Column(length: 255, nullable: true)]
protected ?string $fallback_path = null;
/** @var Collection<int, RolePermission> */
#[ORM\OneToMany(targetEntity: RolePermission::class, mappedBy: 'station')]
protected Collection $permissions;
/** @var Collection<int, StationPlaylist> */
#[
ORM\OneToMany(targetEntity: StationPlaylist::class, mappedBy: 'station'),
ORM\OrderBy(['type' => 'ASC', 'weight' => 'DESC'])
]
protected Collection $playlists;
/** @var Collection<int, StationMount> */
#[ORM\OneToMany(targetEntity: StationMount::class, mappedBy: 'station')]
protected Collection $mounts;
/** @var Collection<int, StationRemote> */
#[ORM\OneToMany(targetEntity: StationRemote::class, mappedBy: 'station')]
protected Collection $remotes;
/** @var Collection<int, StationHlsStream> */
#[ORM\OneToMany(targetEntity: StationHlsStream::class, mappedBy: 'station')]
protected Collection $hls_streams;
/** @var Collection<int, StationWebhook> */
#[ORM\OneToMany(
targetEntity: StationWebhook::class,
mappedBy: 'station',
cascade: ['persist'],
fetch: 'EXTRA_LAZY'
)]
protected Collection $webhooks;
/** @var Collection<int, StationStreamerBroadcast> */
#[ORM\OneToMany(targetEntity: StationStreamerBroadcast::class, mappedBy: 'station')]
protected Collection $streamer_broadcasts;
/** @var Collection<int, SftpUser> */
#[ORM\OneToMany(targetEntity: SftpUser::class, mappedBy: 'station')]
protected Collection $sftp_users;
/** @var Collection<int, StationRequest> */
#[ORM\OneToMany(targetEntity: StationRequest::class, mappedBy: 'station')]
protected Collection $requests;
#[
ORM\ManyToOne,
ORM\JoinColumn(name: 'current_song_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL'),
Attributes\AuditIgnore
]
protected ?SongHistory $current_song = null;
public function __construct()
{
$this->frontend_type = FrontendAdapters::default();
$this->backend_type = BackendAdapters::default();
$this->history = new ArrayCollection();
$this->permissions = new ArrayCollection();
$this->playlists = new ArrayCollection();
$this->mounts = new ArrayCollection();
$this->remotes = new ArrayCollection();
$this->hls_streams = new ArrayCollection();
$this->webhooks = new ArrayCollection();
$this->streamers = new ArrayCollection();
$this->streamer_broadcasts = new ArrayCollection();
$this->sftp_users = new ArrayCollection();
$this->requests = new ArrayCollection();
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = $this->truncateString($name, 100);
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)) {
$shortName = $this->name;
}
$shortName = self::generateShortName($shortName);
$shortName = $this->truncateString($shortName, 100);
if ($this->short_name !== $shortName) {
$this->setNeedsRestart(true);
}
$this->short_name = $shortName;
}
public function setIsEnabled(bool $isEnabled): void
{
$this->is_enabled = $isEnabled;
}
public function getFrontendType(): FrontendAdapters
{
return $this->frontend_type;
}
public function setFrontendType(FrontendAdapters $frontendType): void
{
$this->frontend_type = $frontendType;
}
public function getFrontendConfig(): StationFrontendConfiguration
{
return new StationFrontendConfiguration((array)$this->frontend_config);
}
/**
* @param StationFrontendConfiguration|ConfigData $frontendConfig
*/
public function setFrontendConfig(
StationFrontendConfiguration|array $frontendConfig
): void {
$config = $this->getFrontendConfig()
->fromArray($frontendConfig)
->toArray();
if ($this->frontend_config !== $config) {
$this->setNeedsRestart(true);
}
$this->frontend_config = $config;
}
public function getBackendType(): BackendAdapters
{
return $this->backend_type;
}
public function setBackendType(BackendAdapters $backendType): void
{
$this->backend_type = $backendType;
}
/**
* Whether the station uses AzuraCast to directly manage the AutoDJ or lets the backend handle it.
*/
public function useManualAutoDJ(): bool
{
return $this->getBackendConfig()->useManualAutoDj();
}
public function supportsAutoDjQueue(): bool
{
return $this->getIsEnabled()
&& !$this->useManualAutoDJ()
&& BackendAdapters::None !== $this->getBackendType();
}
public function getBackendConfig(): StationBackendConfiguration
{
return new StationBackendConfiguration((array)$this->backend_config);
}
public function hasLocalServices(): bool
{
return $this->getIsEnabled() &&
($this->getBackendType()->isEnabled() || $this->getFrontendType()->isEnabled());
}
/**
* @param StationBackendConfiguration|ConfigData $backendConfig
*/
public function setBackendConfig(StationBackendConfiguration|array $backendConfig): void
{
$config = $this->getBackendConfig()
->fromArray($backendConfig)
->toArray();
if ($this->backend_config !== $config) {
$this->setNeedsRestart(true);
}
$this->backend_config = $config;
}
public function getAdapterApiKey(): ?string
{
return $this->adapter_api_key;
}
/**
* Generate a random new adapter API key.
*/
public function generateAdapterApiKey(): void
{
$this->adapter_api_key = bin2hex(random_bytes(50));
}
/**
* Authenticate the supplied adapter API key.
*
* @param string $apiKey
*/
public function validateAdapterApiKey(string $apiKey): bool
{
return hash_equals($apiKey, $this->adapter_api_key ?? '');
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description = null): void
{
$this->description = $description;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(string $url = null): void
{
$url = $this->truncateNullableString($url);
if ($url !== $this->url) {
$this->setNeedsRestart(true);
}
$this->url = $url;
}
public function getGenre(): ?string
{
return $this->genre;
}
public function setGenre(?string $genre): void
{
$this->genre = $this->truncateNullableString($genre);
}
public function getRadioBaseDir(): string
{
if (null === $this->radio_base_dir) {
$this->setRadioBaseDir();
}
return (string)$this->radio_base_dir;
}
public function setRadioBaseDir(?string $newDir = null): void
{
$newDir = $this->truncateNullableString(trim($newDir ?? ''));
if (empty($newDir)) {
$newDir = $this->getShortName();
}
if (Path::isRelative($newDir)) {
$newDir = Path::makeAbsolute(
$newDir,
Environment::getInstance()->getStationDirectory()
);
}
$this->radio_base_dir = $newDir;
}
public function ensureDirectoriesExist(): void
{
// Flysystem adapters will automatically create the main directory.
$this->ensureDirectoryExists($this->getRadioBaseDir());
$this->ensureDirectoryExists($this->getRadioPlaylistsDir());
$this->ensureDirectoryExists($this->getRadioConfigDir());
$this->ensureDirectoryExists($this->getRadioTempDir());
$this->ensureDirectoryExists($this->getRadioHlsDir());
if (null === $this->media_storage_location) {
$storageLocation = new StorageLocation(
StorageLocationTypes::StationMedia,
StorageLocationAdapters::Local
);
$mediaPath = $this->getRadioBaseDir() . '/media';
$this->ensureDirectoryExists($mediaPath);
$storageLocation->setPath($mediaPath);
$this->media_storage_location = $storageLocation;
}
if (null === $this->recordings_storage_location) {
$storageLocation = new StorageLocation(
StorageLocationTypes::StationRecordings,
StorageLocationAdapters::Local
);
$recordingsPath = $this->getRadioBaseDir() . '/recordings';
$this->ensureDirectoryExists($recordingsPath);
$storageLocation->setPath($recordingsPath);
$this->recordings_storage_location = $storageLocation;
}
if (null === $this->podcasts_storage_location) {
$storageLocation = new StorageLocation(
StorageLocationTypes::StationPodcasts,
StorageLocationAdapters::Local
);
$podcastsPath = $this->getRadioBaseDir() . '/podcasts';
$this->ensureDirectoryExists($podcastsPath);
$storageLocation->setPath($podcastsPath);
$this->podcasts_storage_location = $storageLocation;
}
}
protected function ensureDirectoryExists(string $dirname): void
{
if (is_dir($dirname)) {
return;
}
$visibility = (new PortableVisibilityConverter(
defaultForDirectories: Visibility::PUBLIC
))->defaultForDirectories();
(new Filesystem())->mkdir($dirname, $visibility);
}
public function getRadioPlaylistsDir(): string
{
return $this->radio_base_dir . '/playlists';
}
public function getRadioConfigDir(): string
{
return $this->radio_base_dir . '/config';
}
public function getRadioTempDir(): string
{
return $this->radio_base_dir . '/temp';
}
public function getRadioHlsDir(): string
{
return $this->radio_base_dir . '/hls';
}
public function getEnableRequests(): bool
{
return $this->enable_requests;
}
public function setEnableRequests(bool $enableRequests): void
{
$this->enable_requests = $enableRequests;
}
public function getRequestDelay(): ?int
{
return $this->request_delay;
}
public function setRequestDelay(int $requestDelay = null): void
{
$this->request_delay = $requestDelay;
}
public function getRequestThreshold(): ?int
{
return $this->request_threshold;
}
public function setRequestThreshold(int $requestThreshold = null): void
{
$this->request_threshold = $requestThreshold;
}
public function getDisconnectDeactivateStreamer(): ?int
{
return $this->disconnect_deactivate_streamer;
}
public function setDisconnectDeactivateStreamer(?int $disconnectDeactivateStreamer): void
{
$this->disconnect_deactivate_streamer = $disconnectDeactivateStreamer;
}
public function getEnableStreamers(): bool
{
return $this->enable_streamers;
}
public function setEnableStreamers(bool $enableStreamers): void
{
if ($this->enable_streamers !== $enableStreamers) {
$this->setNeedsRestart(true);
}
$this->enable_streamers = $enableStreamers;
}
public function getIsStreamerLive(): bool
{
return $this->is_streamer_live;
}
public function setIsStreamerLive(bool $isStreamerLive): void
{
$this->is_streamer_live = $isStreamerLive;
}
public function getEnablePublicPage(): bool
{
return $this->enable_public_page && $this->getIsEnabled();
}
public function setEnablePublicPage(bool $enablePublicPage): void
{
$this->enable_public_page = $enablePublicPage;
}
public function getEnableOnDemand(): bool
{
return $this->enable_on_demand;
}
public function setEnableOnDemand(bool $enableOnDemand): void
{
$this->enable_on_demand = $enableOnDemand;
}
public function getEnableOnDemandDownload(): bool
{
return $this->enable_on_demand_download;
}
public function setEnableOnDemandDownload(bool $enableOnDemandDownload): void
{
$this->enable_on_demand_download = $enableOnDemandDownload;
}
public function getEnableHls(): bool
{
return $this->enable_hls;
}
public function setEnableHls(bool $enableHls): void
{
$this->enable_hls = $enableHls;
}
public function getIsEnabled(): bool
{
return $this->is_enabled;
}
public function getNeedsRestart(): bool
{
return $this->needs_restart;
}
public function setNeedsRestart(bool $needsRestart): void
{
$this->needs_restart = $this->hasLocalServices() && $this->has_started
? $needsRestart
: false;
}
public function getHasStarted(): bool
{
return $this->has_started;
}
public function setHasStarted(bool $hasStarted): void
{
$this->has_started = $this->hasLocalServices()
? $hasStarted
: true;
}
public function getApiHistoryItems(): int
{
return $this->api_history_items ?? 5;
}
public function setApiHistoryItems(int $apiHistoryItems): void
{
$this->api_history_items = $apiHistoryItems;
}
public function getTimezone(): string
{
if (!empty($this->timezone)) {
return $this->timezone;
}
return 'UTC';
}
public function getTimezoneObject(): DateTimeZone
{
return new DateTimeZone($this->getTimezone());
}
public function setTimezone(?string $timezone): void
{
$this->timezone = $timezone;
}
public function getBrandingConfig(): StationBrandingConfiguration
{
return new StationBrandingConfiguration((array)$this->branding_config);
}
/**
* @param StationBrandingConfiguration|ConfigData $brandingConfig
*/
public function setBrandingConfig(
StationBrandingConfiguration|array $brandingConfig
): void {
$this->branding_config = $this->getBrandingConfig()
->fromArray($brandingConfig)
->toArray();
}
/**
* @return Collection<int, SongHistory>
*/
public function getHistory(): Collection
{
return $this->history;
}
/**
* @return Collection<int, StationStreamer>
*/
public function getStreamers(): Collection
{
return $this->streamers;
}
public function getCurrentStreamer(): ?StationStreamer
{
return $this->current_streamer;
}
public function setCurrentStreamer(?StationStreamer $currentStreamer): void
{
if (null !== $this->current_streamer || null !== $currentStreamer) {
$this->current_streamer = $currentStreamer;
}
}
public function getMediaStorageLocation(): StorageLocation
{
if (null === $this->media_storage_location) {
throw new RuntimeException('Media storage location not initialized.');
}
return $this->media_storage_location;
}
public function setMediaStorageLocation(?StorageLocation $storageLocation = null): void
{
if (null !== $storageLocation && StorageLocationTypes::StationMedia !== $storageLocation->getType()) {
throw new RuntimeException('Invalid storage location.');
}
$this->media_storage_location = $storageLocation;
}
public function getRecordingsStorageLocation(): StorageLocation
{
if (null === $this->recordings_storage_location) {
throw new RuntimeException('Recordings storage location not initialized.');
}
return $this->recordings_storage_location;
}
public function setRecordingsStorageLocation(?StorageLocation $storageLocation = null): void
{
if (null !== $storageLocation && StorageLocationTypes::StationRecordings !== $storageLocation->getType()) {
throw new RuntimeException('Invalid storage location.');
}
$this->recordings_storage_location = $storageLocation;
}
public function getPodcastsStorageLocation(): StorageLocation
{
if (null === $this->podcasts_storage_location) {
throw new RuntimeException('Podcasts storage location not initialized.');
}
return $this->podcasts_storage_location;
}
public function setPodcastsStorageLocation(?StorageLocation $storageLocation = null): void
{
if (null !== $storageLocation && StorageLocationTypes::StationPodcasts !== $storageLocation->getType()) {
throw new RuntimeException('Invalid storage location.');
}
$this->podcasts_storage_location = $storageLocation;
}
public function getStorageLocation(StorageLocationTypes $type): StorageLocation
{
return match ($type) {
StorageLocationTypes::StationMedia => $this->getMediaStorageLocation(),
StorageLocationTypes::StationRecordings => $this->getRecordingsStorageLocation(),
StorageLocationTypes::StationPodcasts => $this->getPodcastsStorageLocation(),
default => throw new InvalidArgumentException('Invalid storage location.')
};
}
/** @return StorageLocation[] */
public function getAllStorageLocations(): array
{
return [
$this->getMediaStorageLocation(),
$this->getRecordingsStorageLocation(),
$this->getPodcastsStorageLocation(),
];
}
/**
* @return array<string, StorageLocationTypes>
*/
public static function getStorageLocationTypes(): array
{
return [
'media_storage_location' => StorageLocationTypes::StationMedia,
'recordings_storage_location' => StorageLocationTypes::StationRecordings,
'podcasts_storage_location' => StorageLocationTypes::StationPodcasts,
];
}
public function getFallbackPath(): ?string
{
return $this->fallback_path;
}
public function setFallbackPath(?string $fallbackPath): void
{
if ($this->fallback_path !== $fallbackPath) {
$this->setNeedsRestart(true);
}
$this->fallback_path = $fallbackPath;
}
/**
* @return Collection<int, RolePermission>
*/
public function getPermissions(): Collection
{
return $this->permissions;
}
/**
* @return Collection<int, StationMedia>
*/
public function getMedia(): Collection
{
return $this->getMediaStorageLocation()->getMedia();
}
/**
* @return Collection<int, StationPlaylist>
*/
public function getPlaylists(): Collection
{
return $this->playlists;
}
/**
* @return Collection<int, StationMount>
*/
public function getMounts(): Collection
{
return $this->mounts;
}
/**
* @return Collection<int, StationRemote>
*/
public function getRemotes(): Collection
{
return $this->remotes;
}
/**
* @return Collection<int, StationHlsStream>
*/
public function getHlsStreams(): Collection
{
return $this->hls_streams;
}
/**
* @return Collection<int, StationWebhook>
*/
public function getWebhooks(): Collection
{
return $this->webhooks;
}
/**
* @return Collection<int, SftpUser>
*/
public function getSftpUsers(): Collection
{
return $this->sftp_users;
}
public function getCurrentSong(): ?SongHistory
{
return $this->current_song;
}
public function setCurrentSong(?SongHistory $currentSong): void
{
$this->current_song = $currentSong;
}
public function __toString(): string
{
$name = $this->getName();
if (null !== $name) {
return $name;
}
$id = $this->getId();
return (null !== $id) ? 'Station #' . $id : 'New Station';
}
public function __clone()
{
$this->id = null;
$this->short_name = '';
$this->radio_base_dir = null;
$this->adapter_api_key = null;
$this->current_streamer = null;
$this->current_streamer_id = null;
$this->is_streamer_live = false;
$this->needs_restart = false;
$this->has_started = false;
$this->current_song = null;
$this->media_storage_location = null;
$this->recordings_storage_location = null;
$this->podcasts_storage_location = null;
// Clear ports
$feConfig = $this->getFrontendConfig();
$feConfig->setPort(null);
$this->setFrontendConfig($feConfig);
$beConfig = $this->getBackendConfig();
$beConfig->setDjPort(null);
$beConfig->setTelnetPort(null);
$this->setBackendConfig($beConfig);
}
public static function generateShortName(string $str): string
{
$str = File::sanitizeFileName($str);
return (is_numeric($str))
? 'station_' . $str
: $str;
}
}
``` | /content/code_sandbox/backend/src/Entity/Station.php | php | 2016-04-30T21:41:23 | 2024-08-16T18:27:26 | AzuraCast | AzuraCast/AzuraCast | 2,978 | 7,393 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.