FR
apps/winzik / src / Media / RangedDownload.php · commit 6576d6f
<?phpnamespace App\Media;/** * A YouTube stream (googlevideo.com) downloaded by ranges, one FileDownload after the other: `&range=a-b` in its address, * 10 Mo each (as yt-dlp does: asked in one go, YouTube sends it at the speed of playing). Each range is appended to * the file; a range that fails is asked again (3 times). Its size unknown: one plain FileDownload. */final class RangedDownload{    public const CHUNK = 10 * 1024 * 1024;    private const TRIES = 3;    /** 0..1 */    public float $progress = 0.0;    public string $error = '';    public int $received = 0;    private bool $done = false;    private int $from = 0;    private int $tries = 0;    private ?FileDownload $part = null;    /** @var \Closure(string, string): FileDownload */    private \Closure $factory;    /** @param (\Closure(string, string): FileDownload)|null $factory how a range is downloaded (url, target) */    public function __construct(public readonly string $url, public readonly string $target, public readonly int $size, private int $chunk = self::CHUNK,        ?\Closure $factory = null)    {        $this->factory = $factory ?? fn (string $url, string $target): FileDownload => new FileDownload($url, $target);        @mkdir(dirname($target), 0777, true);        @unlink($target);        if (@file_put_contents($target . '.part', '') === false) {            $this->fail('impossible d\'écrire ' . $target);            return;        }        $this->next();    }    private function next(): void    {        if ($this->size <= 0) {            $this->part = ($this->factory)($this->url, $this->target . '.range');            return;        }        $to = min($this->from + $this->chunk, $this->size) - 1;        $this->part = ($this->factory)($this->url . (str_contains($this->url, '?') ? '&' : '?') . 'range=' . $this->from . '-' . $to, $this->target . '.range');    }    /** Each frame. @return bool true once it ended (ok() or error) */    public function poll(): bool    {        if ($this->done || $this->part === null) {            return $this->done;        }        $part = $this->part;        $ended = $part->poll();        $this->progress = $this->size > 0 ? min(0.999, ($this->from + $part->received) / $this->size) : $part->progress;        $this->received = $this->from + $part->received;        if (!$ended) {            return false;        }        $this->part = null;        if (!$part->ok()) {            if (++$this->tries < self::TRIES) {                $this->next();      // the same range again                return false;            }            $this->fail($part->error);            return true;        }        $this->tries = 0;        $got = (int)@filesize($this->target . '.range');        if (!$this->append($this->target . '.range')) {            return true;        }        $this->from += $got;        if ($this->size > 0 && $this->from < $this->size && $got > 0) {            $this->next();            return false;        }        if ($this->size > 0 && $this->from < $this->size) {            $this->fail(sprintf('téléchargement coupé (%d / %d octets)', $this->from, $this->size));            return true;        }        @unlink($this->target);        if (!@rename($this->target . '.part', $this->target)) {            $this->fail('impossible d\'écrire ' . $this->target);            return true;        }        $this->progress = 1.0;        $this->done = true;        return true;    }    private function append(string $file): bool    {        $in = @fopen($file, 'rb');        $out = @fopen($this->target . '.part', 'ab');        $ok = $in !== false && $out !== false && stream_copy_to_stream($in, $out) !== false;        $in !== false && fclose($in);        $out !== false && fclose($out);        @unlink($file);        if (!$ok) {            $this->fail('impossible d\'écrire ' . $this->target);        }        return $ok;    }    public function ok(): bool    {        return $this->done && $this->error === '';    }    /** Stopped for good: its files removed. */    public function cancel(): void    {        $this->part?->cancel();        $this->part = null;        if (!$this->done) {            $this->fail('arrêté');        }    }    private function fail(string $message): void    {        $this->error = $message;        $this->done = true;        @unlink($this->target . '.part');        @unlink($this->target . '.range');    }}