FR
apps/winzik / src / Media / Tools.php · commit 6576d6f
<?phpnamespace App\Media;/** * yt-dlp and ffmpeg for the YouTube search, the MP3 / MP4 downloads and the video player of the installed WinZik. * Those of the computer when it has them (PATH), else downloaded once in the background into WinZik's data folder * (var/bin): yt-dlp from its own releases, ffmpeg from yt-dlp's builds (the ones it recommends). yt-dlp is always * WinZik's own copy, the newest: downloaded at the first start (the computer's one only meanwhile: a system's yt-dlp is * often old, and YouTube changes often), then `yt-dlp -U` at each start and every day. Linux and Windows (x86_64); * elsewhere only what the PATH has. * * The phone app (Tools::forPhone()): no yt-dlp (it needs Python: YouTube then goes through YouTubeInnerTube), no Whisper, * nothing downloaded; ffmpeg is the app's own, given by JUMPHP_FFMPEG (absent: the downloads and films say so). * JUMPHP_FFMPEG is taken on a computer too, before the PATH. * * States of each tool: missing | downloading | extracting | ready | error | unsupported */class Tools{    public const YTDLP = ['Linux' => 'https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux',        'Windows' => 'https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe'];    public const FFMPEG = ['Linux' => 'https://github.com/yt-dlp/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz',        'Windows' => 'https://github.com/yt-dlp/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip'];    private const DAY = 24 * 3600;    /** the computer's yt-dlp is used while WinZik's own is downloaded */    private bool $ownYtdlp = false;    private float $lastUpdate = -1.0;    /** @var array<string, string> tool => state */    public array $state = ['yt-dlp' => 'missing', 'ffmpeg' => 'missing'];    /** @var array<string, string> tool => path of the program when ready */    public array $path = [];    public string $error = '';    private ?FileDownload $download = null;    private string $downloading = '';    private ?Process $job = null;    private string $jobKind = '';    private float $clock = 0.0;    private bool $looked = false;    /** the phone app: no yt-dlp, no Whisper, nothing downloaded, ffmpeg from JUMPHP_FFMPEG */    public bool $phone = false;    public function __construct(public readonly string $binDir, public readonly string $tmpDir)    {    }    /** The tools of the phone app: ffmpeg is $ffmpeg (default: JUMPHP_FFMPEG), yt-dlp never. */    public static function forPhone(string $binDir, string $tmpDir, ?string $ffmpeg = null): self    {        $tools = new self($binDir, $tmpDir);        $tools->phone = true;        $tools->looked = true;        $tools->state = ['yt-dlp' => 'unsupported', 'ffmpeg' => 'unsupported'];        $ffmpeg ??= self::envFfmpeg();        if ($ffmpeg !== null && function_exists('proc_open')) {            $tools->state['ffmpeg'] = 'ready';            $tools->path['ffmpeg'] = $ffmpeg;        }        return $tools;    }    /** JUMPHP_FFMPEG: the ffmpeg the app brings (the phone app), when it is a file. */    public static function envFfmpeg(): ?string    {        $env = getenv('JUMPHP_FFMPEG');        return is_string($env) && $env !== '' && is_file($env) ? $env : null;    }    /** Whisper (Python or whisper.cpp) may be used: not on the phone. */    public function whisper(): bool    {        return !$this->phone;    }    /** Why ffmpeg is not there (French, for the notices), '' when it is. */    public function ffmpegMissing(): string    {        return match (true) {            $this->ready('ffmpeg') => '',            $this->phone => 'ffmpeg manque à cette version de l\'application : téléchargements et vidéos impossibles',            in_array($this->state['ffmpeg'] ?? '', ['unsupported', 'error'], true) => 'ffmpeg absent : installez-le sur cet ordinateur',            default => 'ffmpeg arrive (téléchargement en cours) : réessayez dans un instant',        };    }    public static function exe(string $name): string    {        return PHP_OS_FAMILY === 'Windows' ? $name . '.exe' : $name;    }    public function ready(string $tool): bool    {        return ($this->state[$tool] ?? '') === 'ready';    }    public function program(string $tool): ?string    {        return $this->ready($tool) ? $this->path[$tool] : null;    }    /** The folder of ffmpeg (yt-dlp's --ffmpeg-location), null when it is the computer's own. */    public function ffmpegDir(): ?string    {        $ffmpeg = $this->program('ffmpeg');        if ($ffmpeg !== null && $ffmpeg === self::envFfmpeg()) {            return $ffmpeg;     // JUMPHP_FFMPEG: yt-dlp takes the program itself too        }        return $ffmpeg !== null && str_starts_with($ffmpeg, $this->binDir) ? dirname($ffmpeg) : null;    }    /** One line for the dialog: where the tools are. */    public function describe(): string    {        $say = fn (string $tool): string => match ($this->state[$tool]) {            'ready' => "$tool prêt",            'downloading' => sprintf('%s : téléchargement %d %%', $tool, (int)round(($this->download !== null ? $this->download->progress : 0) * 100)),            'extracting' => "$tool : installation...",            'error' => "$tool : erreur ($this->error)",            'unsupported' => $this->phone ? ($tool === 'yt-dlp' ? 'YouTube direct (sans yt-dlp)' : "$tool : absent de l'application")                : "$tool : absent (installez-le sur cet ordinateur)",            default => "$tool : en attente",        };        return $say('yt-dlp') . '  -  ' . $say('ffmpeg');    }    /** Looks on the computer and in var/bin (at once: no download). */    public function look(): void    {        $this->looked = true;        if ($this->phone) {            return;        }        if ($this->state['ffmpeg'] !== 'ready' && ($env = self::envFfmpeg()) !== null) {            $this->state['ffmpeg'] = 'ready';            $this->path['ffmpeg'] = $env;        }        foreach (['yt-dlp', 'ffmpeg'] as $tool) {            if ($this->state[$tool] === 'ready' || $this->state[$tool] === 'downloading' || $this->state[$tool] === 'extracting') {                continue;            }            $own = $this->binDir . '/' . self::exe($tool);            $found = is_file($own) ? $own : self::onPath($tool);            if ($tool === 'yt-dlp') {                $this->ownYtdlp = is_file($own);            }            if ($found !== null) {                $this->state[$tool] = 'ready';                $this->path[$tool] = $found;            } elseif (!isset(self::YTDLP[PHP_OS_FAMILY]) || php_uname('m') !== 'x86_64' && php_uname('m') !== 'AMD64') {                $this->state[$tool] = 'unsupported';            }        }    }    public static function onPath(string $tool): ?string    {        $sep = PHP_OS_FAMILY === 'Windows' ? ';' : ':';        foreach (explode($sep, (string)getenv('PATH')) as $dir) {            $file = rtrim($dir, '/\\') . '/' . self::exe($tool);            if ($dir !== '' && is_file($file) && (PHP_OS_FAMILY === 'Windows' || is_executable($file))) {                return $file;            }        }        return null;    }    /** Each frame: $auto = the tools may be downloaded (Options). */    public function tick(float $dt, bool $auto): void    {        $this->clock += $dt;        if (!$this->looked) {            $this->look();        }        if ($this->phone) {            return;     // nothing to download on a phone        }        if ($this->download !== null) {            if ($this->download->poll()) {                $this->downloaded();            }            return;        }        if ($this->job !== null) {            $this->job->poll();            if ($this->job->done()) {                $this->jobDone();            }            return;        }        if (!$auto || $this->clock < 5.0) {            return;     // a few seconds after the start: the splash and the music first        }        foreach (['yt-dlp', 'ffmpeg'] as $tool) {            if ($this->state[$tool] === 'missing') {                $this->fetch($tool);                return;            }        }        if (!$this->ownYtdlp && isset(self::YTDLP[PHP_OS_FAMILY])) {            // the computer's yt-dlp works meanwhile; WinZik's own (the newest) replaces it            $this->fetch('yt-dlp', true);            return;        }        $this->dailyUpdate();    }    /** Quitting: tar / yt-dlp -U ended now (the archive is opened again next time), the download dropped; again: nothing. */    public function stop(): void    {        if ($this->job !== null) {            $this->job->stop();            $this->job->cleanup();            $this->job = null;        }        $this->download = null;        foreach ($this->state as $tool => $state) {            if ($state === 'extracting' || $state === 'downloading') {                $this->state[$tool] = 'missing';            }        }    }    private function fetch(string $tool, bool $keepUsing = false): void    {        $url = ($tool === 'yt-dlp' ? self::YTDLP : self::FFMPEG)[PHP_OS_FAMILY] ?? null;        if ($url === null) {            $this->state[$tool] = 'unsupported';            return;        }        if ($keepUsing) {            $this->ownYtdlp = true;     // once (an error leaves the computer's one)        } else {            $this->state[$tool] = 'downloading';        }        $this->downloading = $tool;        $target = $tool === 'yt-dlp' ? $this->binDir . '/' . self::exe('yt-dlp') : $this->tmpDir . '/' . basename($url);        $this->download = new FileDownload($url, $target);    }    private function downloaded(): void    {        $d = $this->download;        $tool = $this->downloading;        $this->download = null;        if ($d === null || !$d->ok()) {            if ($this->state[$tool] === 'ready') {                return;     // the computer's one goes on            }            $this->fail($tool, 'téléchargement : ' . ($d !== null ? $d->error : '?'));            return;        }        if ($tool === 'yt-dlp') {            @chmod($d->target, 0755);            @touch($d->target);            $this->state['yt-dlp'] = 'ready';            $this->path['yt-dlp'] = $d->target;            $this->lastUpdate = $this->clock;     // just downloaded: the newest            return;        }        // ffmpeg: an archive (tar.xz on Linux, zip on Windows: Windows 10 has tar.exe, which opens zips too)        $this->state['ffmpeg'] = 'extracting';        $dir = $this->tmpDir . '/ffmpeg-x';        self::remove($dir);        @mkdir($dir, 0777, true);        $this->jobKind = 'extract';        $this->job = Process::start(['tar', '-xf', $d->target, '-C', $dir], $this->tmpDir . '/logs');    }    private function jobDone(): void    {        $job = $this->job;        $kind = $this->jobKind;        $this->job = null;        if ($kind === 'update') {            @touch((string)($this->path['yt-dlp'] ?? ''));            $job?->cleanup();            return;        }        $archive = $this->tmpDir . '/' . basename(self::FFMPEG[PHP_OS_FAMILY] ?? 'x');        $dir = $this->tmpDir . '/ffmpeg-x';        if ($job !== null && !$job->ok() && class_exists(\ZipArchive::class) && str_ends_with($archive, '.zip')) {            // no tar: ZipArchive (a few seconds)            $zip = new \ZipArchive();            if ($zip->open($archive) === true) {                $zip->extractTo($dir);                $zip->close();            }        }        $job?->cleanup();        @mkdir($this->binDir, 0777, true);        $found = false;        foreach (['ffmpeg', 'ffprobe'] as $name) {            foreach ((array)glob($dir . '/*/bin/' . self::exe($name)) as $file) {                $target = $this->binDir . '/' . self::exe($name);                @unlink($target);                if (@rename((string)$file, $target) || @copy((string)$file, $target)) {                    @chmod($target, 0755);                    $found = $found || $name === 'ffmpeg';                }            }        }        self::remove($dir);        @unlink($archive);        if (!$found) {            $this->fail('ffmpeg', "l'archive ne contient pas ffmpeg");            return;        }        $this->state['ffmpeg'] = 'ready';        $this->path['ffmpeg'] = $this->binDir . '/' . self::exe('ffmpeg');    }    /** WinZik's yt-dlp: -U at each start and every day (YouTube changes, old versions stop working). */    private function dailyUpdate(): void    {        $ytdlp = $this->program('yt-dlp');        if ($ytdlp === null || !str_starts_with($ytdlp, $this->binDir) || ($this->lastUpdate >= 0 && $this->clock - $this->lastUpdate < self::DAY)) {            return;        }        $this->lastUpdate = $this->clock;        @touch($ytdlp);        $this->jobKind = 'update';        $this->job = Process::start([$ytdlp, '-U'], $this->tmpDir . '/logs');    }    private function fail(string $tool, string $message): void    {        $this->state[$tool] = 'error';        $this->error = $message;        defined('STDERR') ? fwrite(STDERR, "[tools] $tool: $message\n") : error_log("[tools] $tool: $message");     // no STDERR in the Android app    }    /** Try again (after an error). */    public function retry(): void    {        foreach ($this->state as $tool => $state) {            if ($state === 'error') {                $this->state[$tool] = 'missing';            }        }        $this->clock = max($this->clock, 5.0);    }    public static function remove(string $dir): void    {        if (!is_dir($dir)) {            return;        }        $items = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);        foreach ($items as $item) {            $item->isDir() && !$item->isLink() ? @rmdir($item->getPathname()) : @unlink($item->getPathname());        }        @rmdir($dir);    }}