Обход ограничения http/https при загрузке логотипов каналов + их ленивое кэширование

This commit is contained in:
2024-09-25 01:13:39 +08:00
parent d097366605
commit 2f0186e49f
11 changed files with 230 additions and 6 deletions

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Controllers;
use App\Core\ChannelLogo;
use App\Exceptions\PlaylistNotFoundException;
use Exception;
use Flight;
@@ -41,7 +42,6 @@ class PlaylistController extends Controller
public function details(string $id): void
{
$result = $this->getPlaylistResponse($id);
view('details', $result);
}
@@ -57,4 +57,34 @@ class PlaylistController extends Controller
$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) {
Flight::notFound();
die;
}
$logo->store();
$body = $logo->asBase64();
$size = $logo->size();
$mime = $logo->mimeType();
Flight::response()
->write($body)
->header('Content-Type', $mime)
->header('Content-Length', (string)$size);
}
}

View File

@@ -29,7 +29,7 @@ final class Bootstrapper
Flight::set('config', $config);
}
public static function bootIni(): void
public static function bootCore(): void
{
$loader = new IniFile();
$loader->load();

View File

@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace App\Core;
class ChannelLogo implements \Stringable
{
/**
* @var string Валидированная ссылка на изображение
*/
public readonly string $url;
/**
* @var string|null Хэш от ссылки на изображение
*/
public readonly ?string $hash;
/**
* @var string|null Путь к файлу изображению на диске
*/
public readonly ?string $path;
/**
* @var string|null MIME-тип изображения
*/
protected ?string $mimeType = null;
/**
* @var false|string|null Сырое изображение:
* null -- не загружалось;
* false -- ошибка загрузки;
* string -- бинарные данные.
*/
protected false|string|null $rawData = null;
/**
* Конструктор
*
* @param string $url Внешняя ссылка на изображение
*/
public function __construct(string $url)
{
$url = $this->prepareUrl($url);
if (is_string($url)) {
$this->url = $url;
$this->hash = md5($url);
$this->path = cache_path("tv-logos/$this->hash");
}
}
/**
* Валидирует и очищает ссылку на изображение
*
* @param string $url
* @return false|string
*/
protected function prepareUrl(string $url): false|string
{
$url = filter_var(trim($url), FILTER_VALIDATE_URL);
if ($url === false) {
return false;
}
$parts = parse_url($url);
if (!is_array($parts)) {
return false;
}
return $parts['scheme'] . '://' . $parts['host'] . $parts['path'];
}
/**
* Загружает сырое изображение по ссылке и определяет его MIME-тип
*
* @return bool
*/
public function fetch(): bool
{
$this->rawData = @file_get_contents($this->url);
$isFetched = is_string($this->rawData);
if (!$isFetched) {
return false;
}
$this->mimeType = $this->mimeType();
return true;
}
/**
* Сохраняет сырое изображение в кэш
*
* @return bool
*/
public function store(): bool
{
return is_string($this->rawData)
&& $this->prepareCacheDir()
&& @file_put_contents($this->path, $this->rawData);
}
/**
* Считывает изображение из кэша
*
* @return bool
*/
public function readFile(): bool
{
if (!file_exists($this->path)) {
return false;
}
$this->rawData = @file_get_contents($this->path);
return is_string($this->rawData);
}
/**
* Возвращает base64-кодированное изображение
*
* @return string|null
*/
public function asBase64(): ?string
{
if (!is_string($this->rawData)) {
return null;
}
$mime = $this->mimeType();
return "data:$mime;base64," . base64_encode($this->rawData);
}
/**
* Проверяет готовность директории кэша изображений, создавая её при необходимости
*
* @return bool
*/
public function prepareCacheDir(): bool
{
$cacheFileDir = cache_path('tv-logos');
return is_dir($cacheFileDir)
|| @mkdir($cacheFileDir, 0775, true);
}
/**
* Возвращает MIME-тип сырого изображения
*
* @return string|null
*/
public function mimeType(): ?string
{
if (!is_string($this->rawData)) {
return null;
}
$finfo = new \finfo(FILEINFO_MIME_TYPE);
return $finfo->buffer($this->rawData) ?: null;
}
/**
* Возвращает размер сырого изображения в байтах
*
* @return int
*/
public function size(): int
{
return strlen((string)$this->rawData);
}
/**
* @inheritDoc
*/
public function __toString(): string
{
return $this->asBase64();
}
}

View File

@@ -204,6 +204,16 @@ class Playlist
if ($isChannel) {
$channel['url'] = str_starts_with($line, 'http') ? $line : null;
$logoUrl = $channel['attributes']['tvg-logo'] ?? null;
if (is_string($logoUrl)) {
$logo = new ChannelLogo($logoUrl);
$logo->readFile();
$channel['logo'] = [
'base64' => $logo->asBase64(),
'size' => $logo->size(),
'mime-type' => $logo->mimeType(),
];
}
$result['channels'][] = $channel;
$isChannel = false;
unset($channel);