Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: keep finished HLS segments when a resume request returns 416 (#2166)

Michael Menanno010108e16323
diff --git a/cyberdrop_dl/clients/downloads.py b/cyberdrop_dl/clients/downloads.py
index fa29c00db..241339864 100644
--- a/cyberdrop_dl/clients/downloads.py
+++ b/cyberdrop_dl/clients/downloads.py
@@ -114,7 +114,10 @@ class DownloadClient:
resume_point: int,
resp: AbstractResponse[Any],
) -> bool:
- await _check_response(media_item, resp, resume_point)
+ if await _check_response(media_item, resp, resume_point):
+ media_item.size = resume_point
+ return True
+
media_item.size = _get_content_length(resp.headers)
if resp.status == HTTPStatus.PARTIAL_CONTENT:
# Content-Length of a ranged response only counts the bytes after resume_point.
@@ -459,8 +462,12 @@ def _set_upload_date(media_item: MediaItem, headers: Mapping[str, str]) -> None:
media_item.uploaded_at = last_modified
-async def _check_response(media_item: MediaItem, resp: AbstractResponse[Any], resume_point: int) -> None:
+async def _check_response(media_item: MediaItem, resp: AbstractResponse[Any], resume_point: int) -> bool:
+ """Returns `True` if the partial file is already complete"""
if resp.status == HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE:
+ if media_item.is_segment and resume_point and resp.headers.get(hdrs.CONTENT_RANGE) == f"bytes */{resume_point}":
+ return True
+
logger.warning(
"Deleting partial file '%s'. Download is corrupted. Partial file is bigger that expected size",
media_item.partial_file,
@@ -482,6 +489,8 @@ async def _check_response(media_item: MediaItem, resp: AbstractResponse[Any], re
)
await aio.unlink(media_item.partial_file)
+ return False
+
def resolve_download_dir(download_folder: Path, config: Config) -> Path:
if config.subfolders.create or USE_RETRY_PATH.get():
diff --git a/cyberdrop_dl/downloader/hls.py b/cyberdrop_dl/downloader/hls.py
index 59ead8b0b..9194681ac 100644
--- a/cyberdrop_dl/downloader/hls.py
+++ b/cyberdrop_dl/downloader/hls.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import dataclasses
+import hashlib
import itertools
import logging
from contextvars import ContextVar
@@ -11,6 +12,7 @@ from typing import TYPE_CHECKING, NamedTuple, Protocol
from cyberdrop_dl import aio, constants, ffmpeg
from cyberdrop_dl.exceptions import DownloadError
from cyberdrop_dl.utils import parse_url
+from cyberdrop_dl.utils.cleanup import rm_partial_files
from cyberdrop_dl.utils.crypto import aes_cbc_decrypt, aes_unpad
from cyberdrop_dl.utils.m3u8 import HLSKey
@@ -30,6 +32,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
CONCURRENT_SEGMENTS: ContextVar[int] = ContextVar("CONCURRENT_SEGMENTS")
+_PLAYLIST_FILE = f"playlist{constants.TempExt.HLS}"
_DECRYPTER: ContextVar[AESHLSDecrypter] = ContextVar("_DECRYPTER")
@@ -105,6 +108,37 @@ def _create_media_segments(m3u8: M3U8, temp_dir: Path, item: MediaItem) -> Gener
yield _create_media_segment(item, segment, out_folder)
+def _playlist_id(m3u8: M3U8) -> str:
+ """Identifies the files a playlist points to. The query is ignored: it usually holds a short-lived token"""
+ hasher = hashlib.sha256()
+ for segment in itertools.chain(m3u8.segment_map, m3u8.segments):
+ hasher.update(segment.absolute_uri.partition("?")[0].encode() + b"\n")
+ return hasher.hexdigest()
+
+
+async def _discard_stale_segments(folder: Path, playlist_id: str) -> None:
+ """Delete segments downloaded from a different playlist.
+
+ Segments are named by their position, so the ones left over by an interrupted download of another playlist
+ (another CDN, another format, or a CDL version without this check) would be resumed and merged as if they
+ were part of this one"""
+ marker = folder / _PLAYLIST_FILE
+ try:
+ previous_id = await aio.read_text(marker)
+ except FileNotFoundError:
+ previous_id = None
+
+ if previous_id == playlist_id:
+ return
+
+ if await aio.is_dir(folder):
+ logger.info("Deleting segments in '%s' downloaded from a different playlist", folder)
+ await asyncio.to_thread(rm_partial_files, folder)
+
+ await aio.mkdir(folder, parents=True, exist_ok=True)
+ await aio.write_text(marker, playlist_id)
+
+
def _check_segments(m3u8: M3U8) -> None:
if m3u8.total_segments == 0:
msg = f"{m3u8.media_type} m3u8 manifest ({m3u8.source}) has no valid segments"
@@ -132,6 +166,8 @@ async def _download_m3u8(
m3u8.source,
)
+ folder = temp_dir / m3u8.media_type
+ await _discard_stale_segments(folder, _playlist_id(m3u8))
m_segments = await _download_segments(
_create_media_segments(m3u8, temp_dir, item),
m3u8.total_segments,
@@ -140,6 +176,7 @@ async def _download_m3u8(
)
await _decrypt_segments(m_segments, sem)
await _merge_segments(m_segments, output)
+ await aio.unlink(folder / _PLAYLIST_FILE, missing_ok=True)
return output
diff --git a/tests/test_download_resume.py b/tests/test_download_resume.py
index f608e303e..ae8c3f212 100644
--- a/tests/test_download_resume.py
+++ b/tests/test_download_resume.py
@@ -121,3 +121,49 @@ async def test_truncated_resume_is_not_marked_complete(running_manager: Manager,
pytest.raises(DownloadError, match="Corrupted File"),
):
await client._process_response(item, _DOMAIN, resume_point, resp)
+
+
+def _range_not_satisfiable(total: int) -> _FakeResponse:
+ return _FakeResponse(
+ content_type="text/plain",
+ status=416,
+ headers=CIMultiDictProxy(CIMultiDict({"Content-Length": "0", "Content-Range": f"bytes */{total}"})),
+ url=AbsoluteHttpURL("https://cdn.example.com/seg-1.m4s"),
+ location=None,
+ _resp=b"",
+ )
+
+
+async def _segment(manager: Manager, tmp_path: Path, on_disk: bytes) -> MediaItem:
+ parent = await _resumable_item(manager, tmp_path, 0)
+ item = parent.as_segment("00001.cdl_hls", AbsoluteHttpURL("https://cdn.example.com/seg-1.m4s"))
+ item.partial_file = item.path = parent.download_folder / item.filename
+ item.path.write_bytes(on_disk)
+ return item
+
+
+async def test_finished_segment_is_kept_when_resume_is_not_satisfiable(
+ running_manager: Manager, tmp_path: Path
+) -> None:
+ item = await _segment(running_manager, tmp_path, _PAYLOAD)
+ client = DownloadClient(running_manager)
+ resp = _range_not_satisfiable(len(_PAYLOAD))
+ assert await client._process_response(item, _DOMAIN, len(_PAYLOAD), resp)
+ assert item.path.read_bytes() == _PAYLOAD
+
+
+async def test_oversized_segment_is_still_discarded(running_manager: Manager, tmp_path: Path) -> None:
+ item = await _segment(running_manager, tmp_path, _PAYLOAD + b"junk")
+ client = DownloadClient(running_manager)
+ resp = _range_not_satisfiable(len(_PAYLOAD))
+ with pytest.raises(DownloadError):
+ await client._process_response(item, _DOMAIN, len(_PAYLOAD) + 4, resp)
+ assert not item.path.exists()
+
+
+async def test_complete_partial_of_a_regular_file_is_unchanged(running_manager: Manager, tmp_path: Path) -> None:
+ item = await _resumable_item(running_manager, tmp_path, len(_PAYLOAD))
+ client = DownloadClient(running_manager)
+ resp = _range_not_satisfiable(len(_PAYLOAD))
+ with pytest.raises(DownloadError):
+ await client._process_response(item, _DOMAIN, len(_PAYLOAD), resp)
diff --git a/tests/test_hls.py b/tests/test_hls.py
index b9105c307..affa14a61 100644
--- a/tests/test_hls.py
+++ b/tests/test_hls.py
@@ -116,3 +116,53 @@ def test_init_segments_should_be_include() -> None:
assert len(m3u8.segments) == 5
hls._check_segments(m3u8)
assert m3u8.total_segments == 6
+
+
+def _playlist(*urls: str) -> M3U8:
+ return M3U8("#EXTM3U\n" + "".join(f"#EXTINF:10,\n{url}\n" for url in urls) + "#EXT-X-ENDLIST\n")
+
+
+def test_playlist_id_ignores_query() -> None:
+ first = _playlist("https://cdn.example.com/seg-1.ts?hash=abc", "https://cdn.example.com/seg-2.ts?hash=abc")
+ second = _playlist("https://cdn.example.com/seg-1.ts?hash=xyz", "https://cdn.example.com/seg-2.ts?hash=xyz")
+ assert hls._playlist_id(first) == hls._playlist_id(second)
+
+
+def test_playlist_id_changes_with_segments() -> None:
+ ts = _playlist("https://cdn.example.com/seg-1.ts", "https://cdn.example.com/seg-2.ts")
+ fmp4 = _playlist("https://cdn.example.com/init.mp4", "https://cdn.example.com/seg-1.m4s")
+ assert hls._playlist_id(ts) != hls._playlist_id(fmp4)
+
+
+async def test_segments_of_the_same_playlist_are_kept(tmp_path: Path) -> None:
+ folder = tmp_path / "video"
+ await hls._discard_stale_segments(folder, "playlist-a")
+ (folder / "00001.cdl_hls").write_bytes(b"segment")
+ await hls._discard_stale_segments(folder, "playlist-a")
+ assert (folder / "00001.cdl_hls").read_bytes() == b"segment"
+
+
+async def test_segments_of_another_playlist_are_discarded(tmp_path: Path) -> None:
+ folder = tmp_path / "video"
+ await hls._discard_stale_segments(folder, "playlist-a")
+ (folder / "00001.cdl_hls").write_bytes(b"segment")
+ await hls._discard_stale_segments(folder, "playlist-b")
+ assert not (folder / "00001.cdl_hls").exists()
+
+
+async def test_segments_of_an_unknown_playlist_are_discarded(tmp_path: Path) -> None:
+ folder = tmp_path / "video"
+ folder.mkdir()
+ (folder / "00001.cdl_hls").write_bytes(b"segment")
+ await hls._discard_stale_segments(folder, "playlist-a")
+ assert not (folder / "00001.cdl_hls").exists()
+
+
+async def test_only_partial_files_are_discarded(tmp_path: Path) -> None:
+ folder = tmp_path / "video"
+ folder.mkdir()
+ (folder / "00001.cdl_hls").write_bytes(b"segment")
+ (folder / "notes.txt").write_text("not ours")
+ await hls._discard_stale_segments(folder, "playlist-a")
+ assert not (folder / "00001.cdl_hls").exists()
+ assert (folder / "notes.txt").read_text() == "not ours"