1 Commits
master ... wip2

Author SHA1 Message Date
29e6479741 WIP 2025-02-24 22:47:01 +08:00
75 changed files with 1591 additions and 5039 deletions

3
.dockerignore Normal file
View File

@@ -0,0 +1,3 @@
*.md
*.example

View File

@@ -1,2 +1 @@
IPTV_ENV=dev
REDIS_PORT=6379

14
.gitignore vendored
View File

@@ -1,17 +1,13 @@
/.idea
/.vscode
.idea/
.vscode/
downloaded/
/src/commit
/src/cache/*
/src/vendor
/src/config/playlists.ini
/src/views/custom.twig
/tmp
commit
*.log
.env
*.m3u
*.m3u.*
*.m3u8
*.m3u8.*
*.rdb
!/**/.gitkeep

View File

@@ -4,24 +4,8 @@ networks:
services:
keydb:
container_name: iptv-keydb
image: eqalpha/keydb:latest
restart: unless-stopped
volumes:
- /etc/localtime:/etc/localtime:ro
- ./docker/keydb/keydb.conf:/etc/keydb/keydb.conf
- ./docker/keydb/data/:/data:rw
- ./log/keydb:/var/log/keydb/:rw
env_file:
- .env
ports:
- "${REDIS_PORT:-6379}:6379"
networks:
- iptv
php:
container_name: iptv-php
svc-main:
container_name: iptv-svc-main
env_file:
- .env
environment:
@@ -29,8 +13,6 @@ services:
build:
dockerfile: docker/php/${IPTV_ENV}.dockerfile
restart: unless-stopped
extra_hosts:
- host.docker.internal:host-gateway
networks:
- iptv
volumes:
@@ -38,27 +20,24 @@ services:
- ./docker/php/www.conf:/usr/local/etc/php-fpm.d/www.conf:ro
- ./docker/php/${IPTV_ENV}.php.ini:/usr/local/etc/php/conf.d/php.ini:ro
- ./log/php:/var/log/php:rw
- ./src:/var/www:rw
- ./playlists.ini:/var/www/config/playlists.ini:ro
depends_on:
- keydb
- ./src/svc-main:/var/www:rw
- ./commit:/var/www/commit:ro
- ./playlists.ini:/var/www/playlists.ini:ro
nginx:
container_name: iptv-nginx
image: nginx:latest
restart: unless-stopped
extra_hosts:
- host.docker.internal:host-gateway
networks:
- iptv
volumes:
- /etc/localtime:/etc/localtime:ro
- ./docker/nginx/vhost.conf:/etc/nginx/conf.d/default.conf:ro
- ./docker/nginx/vhost.conf:/etc/nginx/conf.d/default.conf
- ./log/nginx:/var/log/nginx:rw
- ./src:/var/www:ro
- ./src/svc-main:/var/www:ro
ports:
- '8080:80'
links:
- php
- svc-main
depends_on:
- php
- svc-main

File diff suppressed because it is too large Load Diff

View File

@@ -20,7 +20,7 @@ server {
}
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_pass php:9000;
fastcgi_pass svc-main:9000;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

View File

@@ -1,17 +1,16 @@
FROM php:8.3-fpm
FROM php:8.4-fpm
RUN apt update && \
apt upgrade -y && \
apt install -y git unzip 7zip
apt install -y --no-install-recommends git unzip 7zip && \
apt-get clean autoclean && \
apt-get autoremove --yes && \
rm -rf /var/lib/{apt,dpkg,cache,log}/
# https://pecl.php.net/package/xdebug
# https://pecl.php.net/package/redis
RUN pecl channel-update pecl.php.net && \
pecl install xdebug-3.4.1 redis && \
docker-php-ext-enable redis && \
mkdir -p /var/run/php && \
mkdir -p /var/log/php && \
chmod -R 777 /var/log/php
pecl install xdebug-3.4.0 unzip && \
mkdir -p /var/log/php
COPY --from=composer /usr/bin/composer /usr/local/bin/composer

View File

@@ -2,7 +2,10 @@
error_reporting = E_ALL
expose_php = Off
file_uploads = Off
memory_limit=-1
max_execution_time=-1
; upload_max_filesize=10M
; post_max_size=10M
[opcache]
opcache.enable = 1
@@ -19,7 +22,7 @@ zend_extension = xdebug.so
xdebug.mode = debug
xdebug.start_with_request = yes
xdebug.trigger_value = go
xdebug.client_host = host.docker.internal
xdebug.client_host = 172.17.0.1
xdebug.REQUEST = *
xdebug.SESSION = *
xdebug.SERVER = *

View File

@@ -1,19 +1,14 @@
FROM php:8.3-fpm
FROM php:8.4-fpm
RUN apt update && \
apt upgrade -y && \
apt install -y git
# https://pecl.php.net/package/redis
RUN pecl channel-update pecl.php.net && \
pecl install redis && \
docker-php-ext-enable redis && \
mkdir -p /var/log/php && \
chmod -R 777 /var/log/php
apt install -y --no-install-recommends git && \
apt-get clean autoclean && \
apt-get autoremove --yes && \
rm -rf /var/lib/{apt,dpkg,cache,log}/
COPY --from=composer /usr/bin/composer /usr/local/bin/composer
USER www-data
EXPOSE 9000
WORKDIR /var/www
CMD composer install

View File

@@ -16,6 +16,6 @@ access.log = /var/log/php/$pool.access.log
; chroot = /var/www
; chdir = /var/www
php_flag[display_errors] = on
php_admin_value[error_log] = /var/log/php/$pool.error.log
php_admin_value[error_log] = /var/log/php/www.error.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 512M
php_admin_value[memory_limit] = 32M

4
hooks/post-commit Executable file
View File

@@ -0,0 +1,4 @@
#!/bin/bash
# хук пробрасывает хэш свежего коммита в контейнер
# для его отображения в подвале страницы
git rev-parse HEAD > commit

7
hooks/post-merge Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
# хук пробрасывает хэш свежего коммита в контейнер
# для его отображения в подвале страницы и очищает
# кеш шаблонов twig после слияния веток
# главным образом необходимо при git pull
git rev-parse HEAD > commit
docker exec -ti svc-main rm -rf cache/views

6
iptv
View File

@@ -1,7 +1,7 @@
#!/bin/bash
# https://gist.github.com/anthonyaxenov/89c99e09ddb195985707e2b24a57257d
CONTAINER="iptv-php" # the name of the container in which to 'exec' something
CONTAINER="iptv-main" # the name of the container in which to 'exec' something
CONFIG="$(dirname $([ -L $0 ] && readlink -f $0 || echo $0))/docker-compose.yml" # path to compose yml file
CMD="docker compose -f $CONFIG" # docker-compose command
APP_URL='http://localhost:8080/'
@@ -15,9 +15,10 @@ open_browser() {
}
case "$1" in
'' | 'help' ) echo -e "Provide one of operations: \t init, start, stop, up, down, restart, rebuild, open";
'' | 'help' ) echo -e "Provide one of operations: \t init, start, stop, up, down, restart, rebuild, open, hooks";
echo "Otherwise all args will passed to 'docker exec -ti $CONTAINER ...'" ;;
'init' ) cp src/.env.example src/.env && \
./iptv hooks && \
./iptv up && \
./iptv composer i && \
echo "Project started successfully! $APP_URL" ;;
@@ -28,5 +29,6 @@ case "$1" in
'restart' ) $CMD stop && $CMD start ;; # restart containers
'rebuild' ) $CMD down --remove-orphans && $CMD up -d --build ;; # rebuild containers
'open' ) open_browser $APP_URL && echo -e "\nYou're welcome!\n\t$APP_URL" ;;
'hooks' ) сp -f hooks/* .git/hooks ;;
* ) docker exec -ti $CONTAINER $* ;; # exec anything else in container
esac

View File

File diff suppressed because it is too large Load Diff

View File

@@ -1,18 +0,0 @@
# config/app.php
APP_DEBUG=false
APP_ENV=prod
APP_URL=http://localhost:8080
APP_TITLE='IPTV Плейлисты'
USER_AGENT='Mozilla/5.0 (Windows NT 10.0; Win64; x99) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'
PAGE_SIZE=10
# config/redis.php
REDIS_HOST='keydb'
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0
REDIS_TTL_DAYS=14
# config/redis.php
TWIG_USE_CACHE=true
TWIG_DEBUG=false

View File

@@ -1,36 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Random\RandomException;
/**
*
*/
class ApiController extends BasicController
{
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
* @throws RandomException
*/
public function json(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$code = $request->getAttributes()['code'];
$playlist = $this->getPlaylist($code, true);
$playlist->fetchContent();
$playlist->parse();
$json = json_encode($playlist->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$response->getBody()->write($json);
return $response
->withHeader('Content-Type', 'application/json')
->withHeader('Content-Length', strlen($json));
}
}

View File

@@ -1,58 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\Playlist;
use App\Errors\PlaylistNotFoundException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Views\Twig;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
/**
*
*/
class BasicController
{
/**
* Отправляет сообщение о том, что метод не найден с кодом страницы 404
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function notFound(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$response->withStatus(404);
$this->view($request, $response, 'notfound.twig');
return $response;
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param string $template
* @param array $data
* @return ResponseInterface
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
protected function view(
ServerRequestInterface $request,
ResponseInterface $response,
string $template,
array $data = [],
): ResponseInterface {
$view = Twig::fromRequest($request);
return $view->render($response, $template, $data);
}
}

View File

@@ -1,128 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\ChannelLogo;
use App\Errors\PlaylistNotFoundException;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
/**
*
*/
class WebController extends BasicController
{
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
* @throws Exception
*/
public function home(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
ini()->load();
$playlists = ini()->playlists(false);
$count = count($playlists);
$page = (int)($request->getAttributes()['page'] ?? $request->getQueryParams()['page'] ?? 1);
$pageSize = config('app.page_size');
$pageCount = ceil($count / $pageSize);
$offset = max(0, ($page - 1) * $pageSize);
$list = array_slice($playlists, $offset, $pageSize, true);
return $this->view($request, $response, 'list.twig', [
'updated_at' => ini()->updatedAt(),
'playlists' => $list,
'count' => $count,
'pageCount' => $pageCount,
'pageCurrent' => $page,
]);
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function faq(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
return $this->view($request, $response, 'faq.twig');
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
*/
public function redirect(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
ini()->load();
$code = $request->getAttributes()['code'];
try {
$playlist = ini()->getPlaylist($code);
return $response->withHeader('Location', $playlist->pls);
} catch (PlaylistNotFoundException) {
return $this->notFound($request, $response);
}
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
* @throws \Random\RandomException
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function details(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
ini()->load();
$code = $request->getAttributes()['code'];
try {
$playlist = ini()->getPlaylist($code);
$response->withHeader('Location', $playlist->pls);
} catch (PlaylistNotFoundException) {
return $this->notFound($request, $response);
}
$playlist->fetchContent();
$playlist->parse();
return $this->view($request, $response, 'details.twig', $playlist->toArray());
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return ResponseInterface
*/
public function logo(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$input = $request->getQueryParams()['url'] ?? null;
$logo = new ChannelLogo($input);
$logo->readFile() || $logo->fetch();
$logo->size() === 0 && $logo->setDefault();
$logo->store();
$body = $logo->raw();
$size = $logo->size();
$mime = $logo->mimeType();
$response->getBody()->write($body);
return $response->withHeader('Content-Type', $mime)
->withHeader('Content-Length', $size);
}
}

View File

@@ -1,230 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Core;
use App\Core\TwigExtention as IptvTwigExtension;
use Dotenv\Dotenv;
use InvalidArgumentException;
use Redis;
use Slim\App;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
use Twig\Error\LoaderError;
/**
* Загрузчик приложения
*/
final class Core
{
/**
* @var Core
*/
private static Core $instance;
/**
* @var App
*/
protected App $app;
/**
* @var array Конфигурация приложения
*/
protected array $config = [];
/**
* @var Redis
*/
protected Redis $redis;
/**
* @var IniFile
*/
protected IniFile $iniFile;
/**
* Закрытый конструктор
*/
private function __construct()
{
}
/**
* Возвращает объект приложения
*
* @return Core
*/
public static function get(): Core
{
return self::$instance ??= new self();
}
/**
* Загружает приложение
*
* @return App
* @throws LoaderError
*/
public function boot(): App
{
$this->app = AppFactory::create();
$this->bootSettings();
$this->bootRoutes();
$this->bootTwig();
$this->bootRedis();
$this->bootIni();
return $this->app;
}
/**
* Возвращает значение из конфига
*
* @param string $key Ключ в формате "config.key"
* @param mixed|null $default Значение по умолчанию
* @return mixed
*/
public function config(string $key, mixed $default = null): mixed
{
$parts = explode('.', $key);
return $this->config[$parts[0]][$parts[1]] ?? $default;
}
/**
* @return Redis
*/
public function redis(): Redis
{
return $this->redis;
}
/**
* @return IniFile
*/
public function ini(): IniFile
{
return $this->iniFile;
}
/**
* @return App
*/
public function app(): App
{
return $this->app;
}
/**
* Загружает файл .env или .env.$env
*
* @param string $env
* @return array
*/
protected function loadDotEnvFile(string $env = ''): array
{
$filename = empty($env) ? '.env' : ".env.$env";
if (!file_exists(root_path($filename))) {
return [];
}
$dotenv = Dotenv::createMutable(root_path(), $filename);
return $dotenv->safeLoad();
}
/**
* Загружает конфигурационные файлы
*
* @return void
*/
protected function bootSettings(): void
{
$env = $this->loadDotEnvFile();
if (!empty($env['APP_ENV'])) {
$this->loadDotEnvFile($env['APP_ENV']);
}
foreach (glob(config_path() . '/*.php') as $file) {
$key = basename($file, '.php');
$this->config += [$key => require_once $file];
}
}
/**
* Загружает маршруты
*
* @return void
* @see https://www.slimframework.com/docs/v4/objects/routing.html
*/
protected function bootRoutes(): void
{
foreach ($this->config['routes'] as $route) {
if (is_array($route['method'])) {
$definition = $this->app->map($route['method'], $route['path'], $route['handler']);
} else {
$isPossible = in_array($route['method'], ['GET', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE']);
$func = match (true) {
$route['method'] === '*' => 'any',
$isPossible => strtolower($route['method']),
default => throw new InvalidArgumentException(sprintf('Неверный HTTP метод %s', $route['method']))
};
$definition = $this->app->$func($route['path'], $route['handler']);
}
if (!empty($route['name'])) {
$definition->setName($route['name']);
}
}
}
/**
* Загружает шаблонизатор и его расширения
*
* @return void
* @throws LoaderError
* @see https://www.slimframework.com/docs/v4/features/twig-view.html
*/
protected function bootTwig(): void
{
$twig = Twig::create(root_path('views'), $this->config['twig']);
$twig->addExtension(new IptvTwigExtension());
$this->app->add(TwigMiddleware::create($this->app, $twig));
}
/**
* Инициализирует подключение к Redis
*
* @return void
* @see https://github.com/phpredis/phpredis/?tab=readme-ov-file
*/
protected function bootRedis(): void
{
$options = [
'host' => $this->config['redis']['host'],
'port' => (int)$this->config['redis']['port'],
];
if (!empty($this->config['redis']['password'])) {
$options['auth'] = $this->config['redis']['password'];
}
$this->redis = new Redis($options);
$this->redis->select((int)$this->config['redis']['db']);
$this->redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_JSON);
}
/**
* Инициализирует объект ini-файла
*
* @return void
*/
protected function bootIni(): void
{
$this->iniFile = new IniFile();
}
}

View File

@@ -1,92 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Errors;
use Psr\Http\Message\{
ResponseInterface,
ServerRequestInterface};
use Psr\Log\LoggerInterface;
use Slim\Handlers\ErrorHandler as SlimErrorHandler;
use Throwable;
/**
* Обработчик ошибок
*/
class ErrorHandler extends SlimErrorHandler
{
/**
* Логирует ошибку и отдаёт JSON-ответ с необходимым содержимым
*
* @param ServerRequestInterface $request
* @param Throwable $exception
* @param bool $displayErrorDetails
* @param bool $logErrors
* @param bool $logErrorDetails
* @param LoggerInterface|null $logger
* @return ResponseInterface
*/
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails,
?LoggerInterface $logger = null
): ResponseInterface {
$payload = $this->payload($exception, $displayErrorDetails);
$response = app()->getResponseFactory()->createResponse();
$response->getBody()->write(json_encode($payload, JSON_UNESCAPED_UNICODE));
return $response;
}
/**
* Возвращает структуру исключения для контекста
*
* @param Throwable $e Исключение
* @param bool $logErrorDetails Признак дополнения деталями
* @return array
*/
protected function context(Throwable $e, bool $logErrorDetails): array
{
$result = ['code' => $e->getCode()];
$logErrorDetails && $result += [
'class' => $e::class,
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace()
];
return $result;
}
/**
* Возвращает структуру исключения для передачи в ответе
*
* @param Throwable $e Исключение
* @param bool $displayErrorDetails Признак дополнения деталями
* @return array
*/
protected function payload(Throwable $e, bool $displayErrorDetails): array
{
$result = [
'error' => [
'code' => $e->getCode(),
'message' => $e->getMessage(),
],
];
$displayErrorDetails && $result['error'] += [
'class' => $e::class,
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
];
return $result;
}
}

View File

@@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Middleware для добавления запросу заголовка X-Request-ID
*/
class RequestId
{
/**
* Добавляет запросу заголовок X-Request-ID
*
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$request = $request->withHeader('X-Request-ID', uniqid());
return $handler->handle($request);
}
}

0
src/cache/.gitkeep vendored
View File

View File

@@ -1,46 +0,0 @@
{
"name": "axenov/iptv",
"type": "project",
"description": "Сервис для сбора IPTV-плейлистов и сокращения ссылок",
"authors": [
{
"name": "Anthony Axenov",
"homepage": "https://axenov.dev/",
"role": "author"
}
],
"license": "MIT",
"require": {
"php": "^8.3",
"ext-json": "*",
"ext-curl": "*",
"ext-redis": "*",
"ext-fileinfo": "*",
"guzzlehttp/guzzle": "^7.8",
"nyholm/psr7": "^1.6",
"vlucas/phpdotenv": "*",
"slim/slim": "^4.11",
"slim/twig-view": "^3.4"
},
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php"
]
},
"scripts": {
"clear-views": "rm -rf cache/views",
"post-install-cmd": [
"@clear-views"
]
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
}

1860
src/composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
return [
'base_url' => env('APP_URL', 'http://localhost:8080'),
'debug' => bool(env('APP_DEBUG', false)),
'env' => env('APP_ENV', env('IPTV_ENV', 'prod')),
'title' => env('APP_TITLE', 'IPTV Плейлисты'),
'user_agent' => env('USER_AGENT'),
'page_size' => (int)env('PAGE_SIZE', 10),
'pls_encodings' => [
'UTF-8',
'CP1251',
// 'CP866',
// 'ISO-8859-5',
],
];

View File

@@ -1,11 +0,0 @@
<?php
declare(strict_types=1);
return [
'host' => env('REDIS_HOST', 'keydb'),
'port' => (int)env('REDIS_PORT', 6379),
'password' => env('REDIS_PASSWORD'),
'db' => (int)env('REDIS_DB', 0),
'ttl_days' => (int)env('REDIS_TTL_DAYS', 14) * 60 * 60 * 24, // 2 недели
];

View File

@@ -1,52 +0,0 @@
<?php
use App\Controllers\ApiController;
use App\Controllers\BasicController;
use App\Controllers\WebController;
return [
[
'method' => 'GET',
'path' => '/[page/{page:[0-9]+}]',
'handler' => [WebController::class, 'home'],
'name' => 'home',
],
[
'method' => 'GET',
'path' => '/faq',
'handler' => [WebController::class, 'faq'],
'name' => 'faq',
],
[
'method' => 'GET',
'path' => '/logo',
'handler' => [WebController::class, 'logo'],
'name' => 'logo',
],
[
'method' => 'GET',
'path' => '/{code:[0-9a-zA-Z]+}',
'handler' => [WebController::class, 'redirect'],
'name' => 'redirect',
],
[
'method' => 'GET',
'path' => '/{code:[0-9a-zA-Z]+}/details',
'handler' => [WebController::class, 'details'],
'name' => 'details',
],
[
'method' => 'GET',
'path' => '/{code:[0-9a-zA-Z]+}/json',
'handler' => [ApiController::class, 'json'],
'name' => 'json',
],
[
'method' => '*',
'path' => '/{path:.*}',
'handler' => [BasicController::class, 'notFound'],
'name' => 'not-found',
],
// ...
];

View File

@@ -1,8 +0,0 @@
<?php
declare(strict_types=1);
return [
'cache' => bool(env('TWIG_USE_CACHE', true)) ? cache_path() . '/views' : false,
'debug' => bool(env('TWIG_DEBUG', false)),
];

View File

@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 24.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Слой_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 235.6 292.2" style="enable-background:new 0 0 235.6 292.2;" xml:space="preserve">
<style type="text/css">
.st0{fill:#FFFFFF;}
</style>
<g id="b_1_">
<path class="st0" d="M44.3,164.5L76.9,51.6H127l-10.1,35c-0.1,0.2-0.2,0.4-0.3,0.6L90,179.6h24.8c-10.4,25.9-18.5,46.2-24.3,60.9
c-45.8-0.5-58.6-33.3-47.4-72.1 M90.7,240.6l60.4-86.9h-25.6l22.3-55.7c38.2,4,56.2,34.1,45.6,70.5
c-11.3,39.1-57.1,72.1-101.7,72.1C91.3,240.6,91,240.6,90.7,240.6z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 735 B

View File

@@ -1,7 +0,0 @@
<?php
declare(strict_types=1);
require '../vendor/autoload.php';
core()->boot()->run();

View File

@@ -18,7 +18,7 @@
TOOLS_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]:-$0}"; )" &> /dev/null && pwd 2> /dev/null; )";
DL_DIR="$TOOLS_DIR/downloaded"
INI_FILE="$(dirname "$TOOLS_DIR")/playlists.ini"
INI_FILE="$(dirname "$TOOLS_DIR")/../../playlists.ini"
rm -rf "$DL_DIR" && \
mkdir -p "$DL_DIR" && \

View File

@@ -0,0 +1,7 @@
APP_TITLE='Плейлисты IPTV'
APP_URL=http://localhost:8080
TWIG_CACHE=1
TWIG_DEBUG=0
FLIGHT_CASE_SENSITIVE=0
FLIGHT_HANDLE_ERRORS=1
FLIGHT_LOG_ERRORS=1

10
src/svc-main/.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
vendor/
cache/
views/custom.twig
playlists.ini
commit
*.log
.env
!/**/.gitkeep

View File

@@ -0,0 +1,31 @@
{
"require": {
"php": "^8.4",
"ext-json": "*",
"ext-curl": "*",
"ext-fileinfo": "*",
"mikecao/flight": "^3.12",
"symfony/dotenv": "^7.1",
"twig/twig": "^3.14"
},
"autoload": {
"psr-4": {
"Core\\": "core/",
"Controllers\\": "controllers/",
"Exceptions\\": "exceptions/"
},
"files": [
"helpers.php"
]
},
"scripts": {
"clear-views": "rm -rf cache/views",
"post-install-cmd": [
"@clear-views"
]
},
"config": {
"optimize-autoloader": true,
"sort-packages": true
}
}

551
src/svc-main/composer.lock generated Normal file
View File

@@ -0,0 +1,551 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "1aaea4609092e8a88074f050dab42323",
"packages": [
{
"name": "mikecao/flight",
"version": "v3.13.0",
"source": {
"type": "git",
"url": "https://github.com/flightphp/core.git",
"reference": "1307e8a39d89fadba69d0c2dad53b6e0da83fd96"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/flightphp/core/zipball/1307e8a39d89fadba69d0c2dad53b6e0da83fd96",
"reference": "1307e8a39d89fadba69d0c2dad53b6e0da83fd96",
"shasum": ""
},
"require": {
"ext-json": "*",
"php": ">=7.4"
},
"require-dev": {
"ext-pdo_sqlite": "*",
"flightphp/runway": "^0.2.3 || ^1.0",
"league/container": "^4.2",
"level-2/dice": "^4.0",
"phpstan/extension-installer": "^1.3",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^9.5",
"rregeer/phpunit-coverage-check": "^0.3.1",
"squizlabs/php_codesniffer": "^3.8"
},
"suggest": {
"latte/latte": "Latte template engine",
"phpstan/phpstan": "PHP Static Analyzer",
"tracy/tracy": "Tracy debugger"
},
"type": "library",
"autoload": {
"files": [
"flight/autoload.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mike Cao",
"email": "mike@mikecao.com",
"homepage": "http://www.mikecao.com/",
"role": "Original Developer"
},
{
"name": "Franyer Sánchez",
"email": "franyeradriansanchez@gmail.com",
"homepage": "https://faslatam.000webhostapp.com",
"role": "Maintainer"
},
{
"name": "n0nag0n",
"email": "n0nag0n@sky-9.com",
"role": "Maintainer"
}
],
"description": "Flight is a fast, simple, extensible framework for PHP. Flight enables you to quickly and easily build RESTful web applications. This is the maintained fork of mikecao/flight",
"homepage": "http://flightphp.com",
"support": {
"issues": "https://github.com/flightphp/core/issues",
"source": "https://github.com/flightphp/core/tree/v3.13.0"
},
"time": "2024-10-30T19:52:23+00:00"
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.5.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6",
"reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6",
"shasum": ""
},
"require": {
"php": ">=8.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "3.5-dev"
},
"thanks": {
"name": "symfony/contracts",
"url": "https://github.com/symfony/contracts"
}
},
"autoload": {
"files": [
"function.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.1"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-25T14:20:29+00:00"
},
{
"name": "symfony/dotenv",
"version": "v7.2.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/dotenv.git",
"reference": "28347a897771d0c28e99b75166dd2689099f3045"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/dotenv/zipball/28347a897771d0c28e99b75166dd2689099f3045",
"reference": "28347a897771d0c28e99b75166dd2689099f3045",
"shasum": ""
},
"require": {
"php": ">=8.2"
},
"conflict": {
"symfony/console": "<6.4",
"symfony/process": "<6.4"
},
"require-dev": {
"symfony/console": "^6.4|^7.0",
"symfony/process": "^6.4|^7.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Symfony\\Component\\Dotenv\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Registers environment variables from a .env file",
"homepage": "https://symfony.com",
"keywords": [
"dotenv",
"env",
"environment"
],
"support": {
"source": "https://github.com/symfony/dotenv/tree/v7.2.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-11-27T11:18:42+00:00"
},
{
"name": "symfony/polyfill-ctype",
"version": "v1.31.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
"reference": "a3cc8b044a6ea513310cbd48ef7333b384945638"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/a3cc8b044a6ea513310cbd48ef7333b384945638",
"reference": "a3cc8b044a6ea513310cbd48ef7333b384945638",
"shasum": ""
},
"require": {
"php": ">=7.2"
},
"provide": {
"ext-ctype": "*"
},
"suggest": {
"ext-ctype": "For best performance"
},
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Ctype\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Gert de Pagter",
"email": "BackEndTea@gmail.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for ctype functions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"ctype",
"polyfill",
"portable"
],
"support": {
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.31.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-09T11:45:10+00:00"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.31.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "85181ba99b2345b0ef10ce42ecac37612d9fd341"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/85181ba99b2345b0ef10ce42ecac37612d9fd341",
"reference": "85181ba99b2345b0ef10ce42ecac37612d9fd341",
"shasum": ""
},
"require": {
"php": ">=7.2"
},
"provide": {
"ext-mbstring": "*"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.31.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-09T11:45:10+00:00"
},
{
"name": "symfony/polyfill-php81",
"version": "v1.31.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php81.git",
"reference": "4a4cfc2d253c21a5ad0e53071df248ed48c6ce5c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/4a4cfc2d253c21a5ad0e53071df248ed48c6ce5c",
"reference": "4a4cfc2d253c21a5ad0e53071df248ed48c6ce5c",
"shasum": ""
},
"require": {
"php": ">=7.2"
},
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Php81\\": ""
},
"classmap": [
"Resources/stubs"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php81/tree/v1.31.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-09T11:45:10+00:00"
},
{
"name": "twig/twig",
"version": "v3.16.0",
"source": {
"type": "git",
"url": "https://github.com/twigphp/Twig.git",
"reference": "475ad2dc97d65d8631393e721e7e44fb544f0561"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/twigphp/Twig/zipball/475ad2dc97d65d8631393e721e7e44fb544f0561",
"reference": "475ad2dc97d65d8631393e721e7e44fb544f0561",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/polyfill-ctype": "^1.8",
"symfony/polyfill-mbstring": "^1.3",
"symfony/polyfill-php81": "^1.29"
},
"require-dev": {
"phpstan/phpstan": "^2.0",
"psr/container": "^1.0|^2.0",
"symfony/phpunit-bridge": "^5.4.9|^6.4|^7.0"
},
"type": "library",
"autoload": {
"files": [
"src/Resources/core.php",
"src/Resources/debug.php",
"src/Resources/escaper.php",
"src/Resources/string_loader.php"
],
"psr-4": {
"Twig\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Twig Team",
"role": "Contributors"
},
{
"name": "Armin Ronacher",
"email": "armin.ronacher@active-4.com",
"role": "Project Founder"
}
],
"description": "Twig, the flexible, fast, and secure template language for PHP",
"homepage": "https://twig.symfony.com",
"keywords": [
"templating"
],
"support": {
"issues": "https://github.com/twigphp/Twig/issues",
"source": "https://github.com/twigphp/Twig/tree/v3.16.0"
},
"funding": [
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/twig/twig",
"type": "tidelift"
}
],
"time": "2024-11-29T08:27:05+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": "^8.2",
"ext-json": "*",
"ext-curl": "*",
"ext-fileinfo": "*"
},
"platform-dev": {},
"plugin-api-version": "2.6.0"
}

22
src/svc-main/config.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
return [
// https://flightphp.com/learn#configuration
'flight.base_url' => env('APP_URL', 'http://localhost:8080'),
'flight.case_sensitive' => bool(env('FLIGHT_CASE_SENSITIVE', false)),
'flight.handle_errors' => bool(env('FLIGHT_HANDLE_ERRORS', true)),
'flight.log_errors' => bool(env('FLIGHT_LOG_ERRORS', true)),
'flight.views.path' => views_path(),
'flight.views.extension' => '.twig',
'twig.cache' => bool(env('TWIG_CACHE', true)) ? cache_path() . '/views' : false,
'twig.debug' => bool(env('TWIG_DEBUG', false)),
'app.title' => env('APP_TITLE', 'IPTV Playlists'),
'app.pls_encodings' => [
'UTF-8',
'CP1251',
// 'CP866',
// 'ISO-8859-5',
],
];

View File

@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace Controllers;
use Core\IniFile;
use Core\Playlist;
use Exception;
use Exceptions\PlaylistNotFoundException;
use Flight;
use Random\RandomException;
/**
* Абстрактный контроллер для расширения
*/
abstract class Controller
{
/**
* @var IniFile Класс для работы с ini-файлом плейлистов
*/
protected IniFile $ini;
/**
* Конструктор
*/
public function __construct()
{
$this->ini = Flight::get('ini');
}
/**
* Возвращает плейлист по его ID для обработки
*
* @param string $id
* @param bool $asJson
* @return Playlist
* @throws Exception
*/
protected function getPlaylist(string $id, bool $asJson = false): Playlist
{
if ($this->ini->getRedirection($id)) {
Flight::redirect(base_url($this->ini->getRedirection($id) . ($asJson ? '/json' : '/details')));
die;
}
try {
return $this->ini->getPlaylist($id);
} catch (PlaylistNotFoundException) {
$this->notFound($id, $asJson);
die;
}
}
/**
* Возвращает обработанный плейлист для ответа
*
* @param string $id ID плейлиста
* @param bool $asJson Обрабатывать как json
* @return array
* @throws RandomException
* @throws Exception
*/
protected function getPlaylistResponse(string $id, bool $asJson = false): array
{
$playlist = $this->getPlaylist($id, $asJson);
$playlist->download();
$playlist->parse();
return $playlist->toArray();
}
/**
* Перебрасывает на страницу 404 при ненайденном плейлисте
*
* @param string $id ID плейлиста
* @param bool $asJson Обрабатывать как json
* @return void
* @throws Exception
*/
public function notFound(string $id, bool $asJson = false): void
{
Flight::response()->status(404)->sendHeaders();
$asJson || view('notfound', ['id' => $id]);
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Controllers;
use Exception;
use Flight;
/**
* Контроллер домашней страницы (списка плейлистов)
*/
class HomeController extends Controller
{
/**
* Отображает главную страницу с учётом пагинации списка плейлистов
*
* @param int $page Текущая страница списка
* @return void
* @throws Exception
*/
public function index(int $page = 1): void
{
// если пришёл любой get-параметр, то считаем его как id плейлиста и перебрасываем на страницу о нём
if (Flight::request()->query->count() > 0) {
$id = Flight::request()->query->keys()[0];
Flight::redirect(base_url($id));
die;
}
// иначе формируем и сортируем список при необходимости, рисуем страницу
$perPage = 20;
$playlists = $this->ini->playlists(false);
$count = count($playlists);
$pageCount = ceil($count / $perPage);
$offset = max(0, ($page - 1) * $perPage);
$list = array_slice($playlists, $offset, $perPage, true);
view('list', [
'updated_at' => $this->ini->updatedAt(),
'count' => $count,
'pages' => [
'count' => $pageCount,
'current' => $page,
],
'playlists' => $list,
]);
}
/**
* Отображает страницу FAQ
*
* @return void
* @throws Exception
*/
public function faq(): void
{
view('faq');
}
}

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace Controllers;
use Core\ChannelLogo;
use Exception;
use Exceptions\PlaylistNotFoundException;
use Flight;
/**
* Контроллер методов получения описания плейлистов
*/
class PlaylistController extends Controller
{
/**
* Отправляет запрос с клиента по прямой ссылке плейлиста
*
* @param string $id ID плейлиста
* @return void
* @throws Exception
*/
public function download(string $id): void
{
try {
$playlist = $this->ini->getPlaylist($id);
Flight::redirect($playlist->pls);
} catch (PlaylistNotFoundException) {
$this->notFound($id);
}
die;
}
/**
* Отображает страницу описания плейлиста
*
* @param string $id ID плейлиста
* @return void
* @throws Exception
*/
public function details(string $id): void
{
$result = $this->getPlaylistResponse($id);
view('details', $result);
}
/**
* Возвращает JSON с описанием плейлиста
*
* @param string $id ID плейлиста
* @return void
* @throws Exception
*/
public function json(string $id): void
{
$result = $this->getPlaylistResponse($id, true);
Flight::json($result);
}
/**
* Возвращает логотип канала, кэшируя при необходимости
*
* @return void
*/
public function logo(): void
{
$input = Flight::request()->query['url'] ?? null;
$logo = new ChannelLogo($input);
if (!$logo->readFile()) {
$logo->fetch();
}
if ($logo->size() === 0) {
$logo->setDefault();
}
$logo->store();
$body = $logo->raw();
$size = $logo->size();
$mime = $logo->mimeType();
Flight::response()
->write($body)
->header('Content-Type', $mime)
->header('Content-Length', (string)$size);
}
}

View File

@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Core;
use Flight;
use Twig\Environment;
use Twig\Extension\DebugExtension;
use Twig\Loader\FilesystemLoader;
/**
* Сборщик приложения
*/
final class Bootstrapper
{
/**
* Загружает конфигурацию приложения в контейнер
*
* @return void
*/
public static function bootSettings(): void
{
$config = require_once root_path('config.php');
foreach ($config as $key => $value) {
Flight::set($key, $value);
}
Flight::set('config', $config);
}
public static function bootCore(): void
{
$loader = new IniFile();
$loader->load();
Flight::set('ini', $loader);
}
/**
* Загружает шаблонизатор и его расширения
*
* @return void
*/
public static function bootTwig(): void
{
$twigCfg = [
'cache' => config('twig.cache'),
'debug' => config('twig.debug'),
];
$closure = static function ($twig) {
/** @var Environment $twig */
Flight::set('twig', $twig);
$twig->addExtension(new TwigFunctions());
$twig->addExtension(new DebugExtension());
};
$loader = new FilesystemLoader(config('flight.views.path'));
Flight::register('view', Environment::class, [$loader, $twigCfg], $closure);
}
/**
* Загружает маршруты
*
* @return void
*/
public static function bootRoutes(): void
{
$routes = require_once root_path('routes.php');
foreach ($routes as $route => $handler) {
Flight::route($route, $handler);
}
}
}

View File

@@ -2,7 +2,7 @@
declare(strict_types=1);
namespace App\Core;
namespace Core;
class ChannelLogo implements \Stringable
{
@@ -41,7 +41,7 @@ class ChannelLogo implements \Stringable
*/
public function __construct(string $url)
{
$url = empty($url) ? base_url('public/no-tvg-logo.png') : $this->prepareUrl($url);
$url = $this->prepareUrl($url);
if (is_string($url)) {
$this->url = $url;
$this->hash = md5($url);
@@ -57,15 +57,17 @@ class ChannelLogo implements \Stringable
*/
protected function prepareUrl(string $url): false|string
{
$parts = parse_url(trim($url));
if (!is_array($parts) || count($parts) < 2) {
$url = filter_var(trim($url), FILTER_VALIDATE_URL);
if ($url === false) {
return false;
}
$result = $parts['scheme'] . '://' . $parts['host'];
$result .= (empty($parts['port']) ? '' : ':' . $parts['port']);
$parts = parse_url($url);
if (!is_array($parts)) {
return false;
}
return $result . $parts['path'];
return $parts['scheme'] . '://' . $parts['host'] . $parts['path'];
}
/**
@@ -120,7 +122,7 @@ class ChannelLogo implements \Stringable
public function setDefault(): bool
{
$this->path = root_path('public/no-tvg-logo.png');
return $this->readFile();
return$this->readFile();
}
/**

View File

@@ -2,10 +2,10 @@
declare(strict_types=1);
namespace App\Core;
namespace Core;
use App\Errors\PlaylistNotFoundException;
use Exception;
use Exceptions\PlaylistNotFoundException;
/**
* Класс для работы с ini-файлом плейлистов
@@ -15,7 +15,7 @@ class IniFile
/**
* @var array Считанное из файла содержимое ini-файла
*/
protected array $ini;
protected array $rawIni;
/**
* @var Playlist[] Коллекция подгруженных плейлистов
@@ -40,30 +40,13 @@ class IniFile
*/
public function load(): void
{
$ini = redis()->hGetAll('_playlists_');
if (empty($ini)) {
$filepath = config_path('playlists.ini');
$ini = parse_ini_file($filepath, true);
$this->updated_at = date('d.m.Y h:i', filemtime($filepath));
$order = array_keys($ini);
}
$filepath = root_path('playlists.ini');
$this->updated_at = date('d.m.Y h:i', filemtime($filepath));
$order ??= redis()->get('_order_');
$this->ini ??= $ini;
$this->updated_at ??= redis()->get('_updated_at_');
$transaction = redis()->multi();
foreach ($order as $id) {
$data = $this->ini[$id];
$this->playlists[(string)$id] = $pls = $this->makePlaylist($id, $data);
$transaction->hSet('_playlists_', $id, $pls);
$this->rawIni = parse_ini_file($filepath, true);
foreach ($this->rawIni as $id => $data) {
$this->playlists[(string)$id] = $this->makePlaylist($id, $data);
}
$expireAfter = config('redis.ttl_days');
$transaction
->expire('_playlists_', $expireAfter)
->set('_order_', $order, ['EX' => $expireAfter])
->set('_updated_at_', $this->updated_at, ['EX' => $expireAfter])
->exec();
}
/**
@@ -74,9 +57,11 @@ class IniFile
*/
public function playlists(bool $all = true): array
{
return $all
? $this->playlists
: array_filter($this->playlists, static fn ($playlist) => is_null($playlist->redirectId));
if ($all) {
return $this->playlists;
}
return array_filter($this->playlists, static fn ($playlist) => is_null($playlist->redirectId));
}
/**
@@ -126,7 +111,7 @@ class IniFile
$id = (string)$id;
if (isset($params['redirect'])) {
$this->redirections[$id] = $redirectId = (string)$params['redirect'];
$params = $this->ini[$redirectId];
$params = $this->rawIni[$redirectId];
return $this->makePlaylist($id, $params, $redirectId);
}

View File

@@ -2,9 +2,8 @@
declare(strict_types=1);
namespace App\Core;
namespace Core;
use CurlHandle;
use Exception;
use Random\RandomException;
@@ -87,19 +86,17 @@ class Playlist
*
* @return void
*/
public function fetchContent(): void
public function download(): void
{
$cached = redis()->get($this->id);
if (is_array($cached)) {
$this->downloadStatus['httpCode'] = $cached['httpCode'];
$this->downloadStatus['errCode'] = $cached['errCode'];
$this->downloadStatus['errText'] = $cached['errText'];
$this->downloadStatus['possibleStatus'] = $cached['possibleStatus'];
$this->rawContent = $cached['content'];
return;
}
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $this->pls,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => false,
CURLOPT_FAILONERROR => true,
]);
$curl = $this->makeCurl();
$content = curl_exec($curl);
$this->rawContent = $content === false ? null : $content;
$this->downloadStatus['httpCode'] = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
@@ -107,16 +104,6 @@ class Playlist
$this->downloadStatus['errText'] = curl_error($curl);
$this->downloadStatus['possibleStatus'] = $this->guessStatus($this->downloadStatus['errCode']);
curl_close($curl);
if ($cached === false) {
redis()->set($this->id, [
'httpCode' => $this->downloadStatus['httpCode'],
'errCode' => $this->downloadStatus['errCode'],
'errText' => $this->downloadStatus['errText'],
'possibleStatus' => $this->downloadStatus['possibleStatus'],
'content' => $this->rawContent,
], ['EX' => config('redis.ttl_days')]);
}
}
/**
@@ -251,53 +238,6 @@ class Playlist
return $this->parsedContent = $result;
}
public function check(): bool
{
$curl = $this->makeCurl([
CURLOPT_RETURNTRANSFER => true,
CURLOPT_NOBODY => true,
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'HEAD',
]);
$content = curl_exec($curl);
$this->rawContent = $content === false ? null : $content;
$this->downloadStatus['httpCode'] = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$this->downloadStatus['errCode'] = curl_errno($curl);
$this->downloadStatus['errText'] = curl_error($curl);
$this->downloadStatus['possibleStatus'] = $this->guessStatus($this->downloadStatus['errCode']);
curl_close($curl);
return $this->downloadStatus['httpCode'] < 400;
}
protected function makeCurl(array $customOptions = []): CurlHandle
{
$options = [
CURLOPT_URL => $this->pls,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => false,
CURLOPT_FAILONERROR => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_USERAGENT => config('app.user_agent'),
];
$curl = curl_init();
foreach ($options as $option => $value) {
curl_setopt($curl, $option, $value);
}
// array_merge($options, $customOptions) loses keys
foreach ($customOptions as $option => $value) {
curl_setopt($curl, $option, $value);
}
return $curl;
}
/**
* Парсит атрибуты строки и возвращает ассоциативный массив
*

View File

@@ -2,12 +2,12 @@
declare(strict_types=1);
namespace App\Core;
namespace Core;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class TwigExtention extends AbstractExtension
class TwigFunctions extends AbstractExtension
{
public function getFunctions(): array
{

View File

@@ -2,7 +2,7 @@
declare(strict_types=1);
namespace App\Errors;
namespace Exceptions;
use Exception;

View File

@@ -2,9 +2,9 @@
declare(strict_types=1);
use App\Core\Core;
use App\Core\IniFile;
use Slim\App;
use flight\Engine;
use flight\net\Response;
use Illuminate\Support\Arr;
/**
* Returns path to root application directory
@@ -17,17 +17,6 @@ function root_path(string $path = ''): string
return rtrim(sprintf('%s/%s', dirname($_SERVER['DOCUMENT_ROOT']), $path), '/');
}
/**
* Return path to application configuration directory
*
* @param string $path
* @return string
*/
function config_path(string $path = ''): string
{
return root_path("config/$path");
}
/**
* Returns path to app cache
*
@@ -58,7 +47,7 @@ function views_path(string $path = ''): string
*/
function base_url(string $route = ''): string
{
return rtrim(sprintf('%s/%s', env('APP_URL'), $route), '/');
return rtrim(sprintf('%s/%s', config('flight.base_url'), $route), '/');
}
/**
@@ -70,7 +59,7 @@ function base_url(string $route = ''): string
*/
function env(string $key, mixed $default = null): mixed
{
return $_ENV[$key] ?? $_SERVER[$key] ?? $default;
return $_ENV[$key] ?? $default;
}
/**
@@ -89,23 +78,23 @@ function view(mixed $template, array $data = []): void
}
/**
* Returns core object
* Returns response object
*
* @return Core
* @return Response
*/
function core(): Core
function response(): Response
{
return Core::get();
return Flight::response();
}
/**
* Returns app object
*
* @return App
* @return Engine
*/
function app(): App
function app(): Engine
{
return Core::get()->app();
return Flight::app();
}
/**
@@ -135,25 +124,5 @@ function bool(mixed $value): bool
*/
function config(string $key, mixed $default = null): mixed
{
return Core::get()->config($key, $default);
}
/**
* Get Redis instance
*
* @return Redis
*/
function redis(): Redis
{
return Core::get()->redis();
}
/**
* Get ini-file instance
*
* @return IniFile
*/
function ini(): IniFile
{
return Core::get()->ini();
return Flight::get('config')[$key] ?? $default;
}

View File

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 22 KiB

View File

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

Before

Width:  |  Height:  |  Size: 7.3 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
use Core\Bootstrapper;
use Symfony\Component\Dotenv\Dotenv;
/*
|--------------------------------------------------------------------------
| Bootstrap all classes, settings, etc.
|--------------------------------------------------------------------------
*/
require '../vendor/autoload.php';
(new Dotenv())->loadEnv(root_path() . '/.env');
Bootstrapper::bootSettings();
Bootstrapper::bootTwig();
Bootstrapper::bootCore();
Bootstrapper::bootRoutes();
Flight::start();

View File

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

17
src/svc-main/routes.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
use Controllers\HomeController;
use Controllers\PlaylistController;
return [
'GET /' => [HomeController::class, 'index'],
'GET /page/@page:[0-9]+' => [HomeController::class, 'index'],
'GET /faq' => [HomeController::class, 'faq'],
'GET /logo' => [PlaylistController::class, 'logo'],
'GET /@id:[a-zA-Z0-9_-]+' => [PlaylistController::class, 'download'],
'GET /?[a-zA-Z0-9_-]+' => [PlaylistController::class, 'download'],
'GET /@id:[a-zA-Z0-9_-]+/details' => [PlaylistController::class, 'details'],
'GET /@id:[a-zA-Z0-9_-]+/json' => [PlaylistController::class, 'json'],
];

View File

@@ -0,0 +1,120 @@
{% extends "template.twig" %}
{% block header %}
<p class="text-muted small">
Обновлено:&nbsp;{{ updated_at }}&nbsp;МСК<br/>
Плейлистов в списке:&nbsp;<strong>{{ count }}</strong>
</p>
<hr/>
{% endblock %}
{% block content %}
<div class="table-responsive">
<table class="table table-responsive table-dark table-hover small">
<thead>
<tr>
<th>ID</th>
<th>Информация о плейлисте</th>
<th>Каналов</th>
<th class="d-none d-sm-table-cell">Ссылка для ТВ</th>
</tr>
</thead>
<tbody>
{% for id, playlist in playlists %}
<tr class="pls" data-playlist-id="{{ id }}">
<td class="text-center font-monospace id">{{ id }}</td>
<td class="info">
<span class="badge small bg-secondary text-dark status">loading</span>
<strong>{{ playlist.name }}</strong>
<div class="small mt-2">
{% if playlist.desc|length > 0 %}
<p class="my-1 d-none d-lg-block">{{ playlist.desc }}</p>
{% endif %}
<a href="{{ base_url(id ~ '/details') }}" class="text-light">Подробнее...</a>
</div>
</td>
<td class="text-center count">
<div class="spinner-border text-success" role="status">
<span class="visually-hidden">загрузка...</span>
</div>
</td>
<td class="col-3 d-none d-sm-table-cell">
<span onclick="prompt('Скопируй адрес плейлиста', '{{ playlist.url }}')"
title="Нажми на ссылку, чтобы скопировать её в буфер обмена"
class="font-monospace cursor-pointer">
{{ playlist.url }}
</span>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if pages.count > 0 %}
<div aria-label="pages">
<ul class="pagination justify-content-center">
{% for page in range(1, pages.count) %}
{% if page == pages.current %}
<li class="page-item active" aria-current="page">
<span class="page-link">{{ page }}</span>
</li>
{% else %}
<li class="page-item">
<a class="page-link bg-dark border-secondary text-light" href="{{ base_url('page/' ~ page) }}">{{ page }}</a>
</li>
{% endif %}
{% endfor %}
</ul>
</div>
{% endif %}
</div>
{% endblock %}
{% block footer %}
<script>
document.querySelectorAll('tr.pls').forEach((tr) => {
const id = tr.attributes['data-playlist-id'].value
const xhr = new XMLHttpRequest()
xhr.responseType = 'json'
xhr.timeout = 60000 // ms = 1 min
let el_status = tr.querySelector('span.status')
let el_count = tr.querySelector('td.count')
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
el_status.classList.remove('bg-secondary')
el_status.innerText = xhr.response?.status.possibleStatus ?? 'error'
el_count.innerText = xhr.response?.content.channelCount ?? 0
switch (el_status.innerText) {
case 'online':
el_status.classList.add('bg-success')
break
case 'timeout':
el_status.classList.add('bg-warning')
break
default:
el_status.classList.add('bg-danger')
break
}
if (xhr.response?.error) {
el_status.title = '[' + xhr.response.error.code + '] ' + xhr.response.error.message
}
}
}
xhr.onerror = () => {
el_status.classList.add('bg-danger')
el_status.innerText = 'error'
el_count.innerText = 0
}
xhr.onabort = () => {
el_status.classList.add('bg-secondary')
el_count.innerText = 0
}
xhr.ontimeout = () => {
el_status.classList.add('bg-secondary')
el_status.innerText = 'timeout'
el_count.innerText = 0
}
xhr.open('GET', '/' + id + '/json')
xhr.send()
})
</script>
{% endblock %}

View File

@@ -16,7 +16,6 @@
<meta name="msapplication-TileColor" content="#00aba9">
<meta name="msapplication-TileImage" content="{{ base_url('/favicon/mstile-144x144.png') }}">
<meta name="theme-color" content="#212529">
<style>.boosty{vertical-align:baseline;float:left;display:inline;width:20px}</style>
{% block head %}{% endblock %}
</head>
<body class="bg-dark text-light">
@@ -50,12 +49,6 @@
<li class="nav-item">
<a class="nav-link" href="https://t.me/iptv_aggregator">Telegram</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://boosty.to/anthonyaxenov">
<img class="boosty" src="{{ base_url('boosty.svg') }}" alt="Boosty">
Boosty
</a>
</li>
</ul>
</div>
</nav>
@@ -74,6 +67,11 @@
href="https://git.axenov.dev/anthony/iptv">Gitea</a>&nbsp;|&nbsp;<a
href="https://axenov.dev">axenov.dev</a>&nbsp;|&nbsp;<a
href="https://t.me/iptv_aggregator">Telegram</a><br>
<span class="small text-muted">
commit&nbsp;<a class="text-muted" target="_blank"
href="https://github.com/anthonyaxenov/iptv/commit/{{ commit() }}"
>{{ commit()[:8] }}</a>
</span>
</footer>
</div>
{% include("custom.twig") ignore missing %}

View File

@@ -1,66 +0,0 @@
{% extends "template.twig" %}
{% block header %}
<p class="text-muted small">
Обновлено:&nbsp;{{ updated_at }}&nbsp;МСК<br/>
Плейлистов в списке:&nbsp;<strong>{{ count }}</strong>
</p>
<hr/>
{% endblock %}
{% block content %}
<div class="table-responsive">
<table class="table table-responsive table-dark table-hover small">
<thead>
<tr>
<th class="text-center">ID</th>
<th>Информация о плейлисте</th>
<th class="d-none d-sm-table-cell">Ссылка для ТВ</th>
</tr>
</thead>
<tbody>
{% for id, playlist in playlists %}
<tr class="pls" data-playlist-id="{{ id }}">
<td class="text-center font-monospace id">{{ id }}</td>
<td class="info">
<a href="{{ base_url(id ~ '/details') }}" class="text-light fw-bold text-decoration-none">{{ playlist.name }}</a>
<div class="small mt-2">
{% if playlist.desc|length > 0 %}
<p class="my-1 d-none d-lg-block">{{ playlist.desc }}</p>
{% endif %}
<a href="{{ base_url(id ~ '/details') }}" class="text-light">Подробнее...</a>
</div>
</td>
<td class="col-3 d-none d-sm-table-cell">
<span onclick="prompt('Скопируй адрес плейлиста', '{{ playlist.url }}')"
title="Нажми на ссылку, чтобы скопировать её в буфер обмена"
class="font-monospace cursor-pointer">
{{ playlist.url }}
</span>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if pageCount > 0 %}
<div aria-label="pages">
<ul class="pagination justify-content-center">
{% for page in range(1, pageCount) %}
{% if page == pageCurrent %}
<li class="page-item active" aria-current="page">
<span class="page-link">{{ page }}</span>
</li>
{% else %}
<li class="page-item">
<a class="page-link bg-dark border-secondary text-light" href="{{ base_url('page/' ~ page) }}">{{ page }}</a>
</li>
{% endif %}
{% endfor %}
</ul>
</div>
{% endif %}
</div>
{% endblock %}
{% block footer %}
{% endblock %}