Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
fix: use explicit utf8 on FS calls
NTFSvolume7c41602a88d1
diff --git a/.zed/debug.json b/.zed/debug.jsonindex ffb102b1a..019175ba4 100644--- a/.zed/debug.json+++ b/.zed/debug.json@@ -26,6 +26,7 @@],"env": {"PYTHONASYNCIODEBUG": "1",+ "PYTHONWARNDEFAULTENCODING": "1","CDL_ENABLE_TWITTER": "true",},},@@ -52,6 +53,7 @@],"env": {"PYTHONASYNCIODEBUG": "1",+ "PYTHONWARNDEFAULTENCODING": "1","CDL_ENABLE_TWITTER": "true",},},diff --git a/cyberdrop_dl/cache.py b/cyberdrop_dl/cache.pyindex 7587a0909..933261e4b 100644--- a/cyberdrop_dl/cache.py+++ b/cyberdrop_dl/cache.py@@ -48,14 +48,14 @@ def _load_cache(content: str) -> dict[str, Any]:def _dump_cache(cache_file: Path, cache: dict[str, Any]):cache["version"] = __version__- cache_file.write_text(json.dumps(cache, indent=2, ensure_ascii=False, sort_keys=True))+ cache_file.write_text(json.dumps(cache, indent=2, ensure_ascii=False, sort_keys=True), encoding="utf8")@contextlib.contextmanagerdef cache_context(cache_file: Path, cache: dict[str, Any]) -> Generator[None]:# TODO: Add a background task to dump cache to disk every 5 minutestry:- content = cache_file.read_text()+ content = cache_file.read_text(encoding="utf8")except FileNotFoundError:cache_file.parent.mkdir(exist_ok=True, parents=True)cache_file.touch()diff --git a/cyberdrop_dl/config/__init__.py b/cyberdrop_dl/config/__init__.pyindex b8d297f9c..494461dcf 100644--- a/cyberdrop_dl/config/__init__.py+++ b/cyberdrop_dl/config/__init__.py@@ -43,7 +43,7 @@ class Files:def update() -> None:import json- Files.SCHEMA.write_text(json.dumps(Config.model_json_schema(), indent=2, ensure_ascii=False))+ Files.SCHEMA.write_text(json.dumps(Config.model_json_schema(), indent=2, ensure_ascii=False), encoding="utf8")Config().save_to(Files.DEFAULT)@@ -211,7 +211,7 @@ def _load_yaml(file: Path) -> dict[str, Any]:import yamltry:- return yaml.safe_load(file.read_text()) or {}+ return yaml.safe_load(file.read_text(encoding="utf8")) or {}except yaml.YAMLError as e:raise CDLConfigRuntimeErrorsGroup("Invalid YAML file", (InvalidYamlError(file, e),)) from Nonediff --git a/cyberdrop_dl/downloader/hls.py b/cyberdrop_dl/downloader/hls.pyindex ca21aa4ba..0d7430d0c 100644--- a/cyberdrop_dl/downloader/hls.py+++ b/cyberdrop_dl/downloader/hls.py@@ -141,7 +141,7 @@ async def _discard_stale_segments(folder: Path, playlist_id: str) -> None:were part of this one"""marker = folder / _PLAYLIST_FILEtry:- previous_id = await aio.read_text(marker)+ previous_id = await aio.read_text(marker, encoding="utf8")except FileNotFoundError:previous_id = None@@ -153,7 +153,7 @@ async def _discard_stale_segments(folder: Path, playlist_id: str) -> None:await asyncio.to_thread(rm_partial_files, folder)await aio.mkdir(folder, parents=True, exist_ok=True)- await aio.write_text(marker, playlist_id)+ await aio.write_text(marker, playlist_id, encoding="utf8")def _check_segments(m3u8: M3U8) -> None:diff --git a/cyberdrop_dl/utils/next_js.py b/cyberdrop_dl/utils/next_js.pyindex db602d8be..0f4ddda2a 100644--- a/cyberdrop_dl/utils/next_js.py+++ b/cyberdrop_dl/utils/next_js.py@@ -281,8 +281,8 @@ if __name__ == "__main__":from pathlib import Pathfile = Path(sys.argv[1])- soup = css.soup(file.read_text())+ soup = css.soup(file.read_text(encoding="utf8"))flight_data = extract_flight_data(soup)- Path("flight_data.txt").write_text(flight_data)+ Path("flight_data.txt").write_text(flight_data, encoding="utf8")decoded = parse(flight_data)- Path("flight_data_decoded.json").write_text(json.dumps(decoded, indent=2, ensure_ascii=False))+ Path("flight_data_decoded.json").write_text(json.dumps(decoded, indent=2, ensure_ascii=False), encoding="utf8")diff --git a/scripts/tools/make_test_cases.py b/scripts/tools/make_test_cases.pyindex 74784ce0d..39a9bfcfc 100644--- a/scripts/tools/make_test_cases.py+++ b/scripts/tools/make_test_cases.py@@ -94,7 +94,7 @@ def create_test_files(file: Path) -> None:for url, results in cases.items()]test_file = TEST_FOLDER / f"test_case_{domain.replace('.', '_')}.py"- _ = test_file.write_text(f"DOMAIN = {domain!r}\nTEST_CASES = {test_cases}")+ _ = test_file.write_text(f"DOMAIN = {domain!r}\nTEST_CASES = {test_cases}", encoding="utf8")test_files.append(test_file)if test_files:diff --git a/scripts/tools/update_docs.py b/scripts/tools/update_docs.pyindex 61d8a8adc..5ca1d49f4 100644--- a/scripts/tools/update_docs.py+++ b/scripts/tools/update_docs.py@@ -58,7 +58,7 @@ def _get_help_message() -> str:def _update_file(file: Path, new_content: str, *, marker: str) -> None:new_content = _replace_content(- old_content := file.read_text(),+ old_content := file.read_text(encoding="utf8"),marker=marker,new_content=new_content,)diff --git a/tests/next_js/test_next_js.py b/tests/next_js/test_next_js.pyindex 31bd6f794..08e4b93ef 100644--- a/tests/next_js/test_next_js.py+++ b/tests/next_js/test_next_js.py@@ -6,7 +6,7 @@ import pytestfrom cyberdrop_dl.utils import css, next_js-TEST_HTML = (Path(__file__).parent / "nextjsv13.html").read_text()+TEST_HTML = (Path(__file__).parent / "nextjsv13.html").read_text(encoding="utf8")TEST_SOUP = css.soup(TEST_HTML)diff --git a/tests/test_cache.py b/tests/test_cache.pyindex 7bc2ea3bd..b3e019dce 100644--- a/tests/test_cache.py+++ b/tests/test_cache.py@@ -38,7 +38,7 @@ def test_cache_file_is_saved_in_ctx(tmp_path: Path) -> None:assert cache_file.is_file()assert cache_file.is_file()- assert json.loads(cache_file.read_text()) == {"test": 1, "version": __version__}+ assert json.loads(cache_file.read_text(encoding="utf8")) == {"test": 1, "version": __version__}def test_ttl_cache_creation() -> None:diff --git a/tests/test_config.py b/tests/test_config.pyindex cd731ad94..e4504a03e 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -286,7 +286,7 @@ def test_config_from_file(tmp_cwd: Path) -> None:@pytest.mark.skipif(os.name == "nt", reason="pydantic can't generate schema w pathlib.WindowsPath defaults")def test_schema_has_not_changed() -> None:schema = Config.model_json_schema()- expected_schema = json.loads(Files.SCHEMA.read_text())+ expected_schema = json.loads(Files.SCHEMA.read_text(encoding="utf8"))assert schema == expected_schema, "Validation schema changed"@@ -301,7 +301,7 @@ def test_round_trip_parsed_the_same_config() -> None:@pytest.mark.skipif(os.name == "nt", reason="OS separators make paths different on Windows")def test_config_default_has_not_changed() -> None:config = Config().model_dump(mode="json")- expected = yaml.safe_load(Files.DEFAULT.read_text())+ expected = yaml.safe_load(Files.DEFAULT.read_text(encoding="utf8"))assert config == expected, "Config serialization changed"diff --git a/tests/test_csv_logs.py b/tests/test_csv_logs.pyindex 5178e94de..3cdcabb30 100644--- a/tests/test_csv_logs.py+++ b/tests/test_csv_logs.py@@ -39,7 +39,7 @@ async def test_delete_old_logs_removes_a_stale_dedupe_log(tmp_cwd: Path) -> Noneconfig.logs.resolve_filenames(tmp_cwd)stale_log = config.logs.files.dedupestale_log.parent.mkdir(parents=True, exist_ok=True)- _ = stale_log.write_text("from a previous run")+ _ = stale_log.write_text("from a previous run", encoding="utf8")async with asyncio.TaskGroup() as task_group:CSVLogsManager(CSVFiles.from_config(config), task_group).delete_old_logs()@@ -66,10 +66,10 @@ class TestWriteToCsv:file = tmp_path / "subfolder" / "errors.csv"file.parent.mkdir()header = "<<TEST_HEADER>>"- file.write_text(header + "\n")+ file.write_text(header + "\n", encoding="utf8")_write_to_csv(file, row, write_headers=False)- lines = file.read_text().splitlines()+ lines = file.read_text(encoding="utf8").splitlines()assert len(lines) == 2assert lines[0] == headerassert lines[1] == '"https://example.com","URLs.txt"'@@ -77,12 +77,12 @@ class TestWriteToCsv:def test_write_headers_true(self, tmp_path: Path, row: dict[str, object]) -> None:file = tmp_path / "subfolder" / "errors.csv"_write_to_csv(file, row, write_headers=True)- assert file.read_text().splitlines()[0] == '"url","origin"'+ assert file.read_text(encoding="utf8").splitlines()[0] == '"url","origin"'def test_write_headers_false(self, tmp_path: Path, row: dict[str, object]) -> None:file = tmp_path / "errors.csv"_write_to_csv(file, row, write_headers=False)- assert file.read_text().splitlines()[0] == '"https://example.com","URLs.txt"'+ assert file.read_text(encoding="utf8").splitlines()[0] == '"https://example.com","URLs.txt"'def test_row_w_various_data_types(self, tmp_path: Path) -> None:file = tmp_path / "subfolder" / "errors.csv"diff --git a/tests/test_dedupe.py b/tests/test_dedupe.pyindex 12ff71bb7..b926b81ef 100644--- a/tests/test_dedupe.py+++ b/tests/test_dedupe.py@@ -19,7 +19,7 @@ _HASH = "a5aec63d0fef8660b00570f23be727e9"@pytest.fixturedef txt_file(tmp_path: Path) -> Path:file = tmp_path / "text_file.txt"- file.write_text("12345")+ file.write_text("12345", encoding="utf8")return file@@ -131,7 +131,7 @@ async def _seed_duplicates(manager: Manager, base_dir: Path, *names: str) -> tupfor name in names:file = base_dir / namefile.parent.mkdir(parents=True, exist_ok=True)- _ = file.write_text("same content")+ _ = file.write_text("same content", encoding="utf8")await manager.database.hash.insert_or_update_hash_db(_HASH, "xxh128", file, None, None)files.append(file)@@ -176,7 +176,7 @@ class TestDedupeRun:async def test_writes_the_csv_log(self, case: _DedupeCase) -> None:await case.run()- assert case.csv_file.read_text("utf8").splitlines() == [+ assert case.csv_file.read_text(encoding="utf8").splitlines() == ['"duplicate","original","hash"',f'"{case.duplicate}","{case.original}","xxh128:{_HASH}"',]@@ -190,7 +190,7 @@ class TestDedupeRun:await deduper.run(file_hashes)original, *duplicates = files- header, *rows = deduper.csv_files.dedupe.read_text("utf8").splitlines()+ header, *rows = deduper.csv_files.dedupe.read_text(encoding="utf8").splitlines()assert header == '"duplicate","original","hash"'assert sorted(rows) == sorted(f'"{dupe}","{original}","xxh128:{_HASH}"' for dupe in duplicates)diff --git a/tests/test_hashing.py b/tests/test_hashing.pyindex b6752d3ed..aa0bdf257 100644--- a/tests/test_hashing.py+++ b/tests/test_hashing.py@@ -96,6 +96,6 @@ async def test_hash_directory_does_not_crash_with_subfolders(tmp_cwd: Path, manadef test_compute_hash(tmp_cwd: Path, algo: Literal["xxh128", "md5", "sha256"], expected: str) -> None:license_file = Path(__file__).parent.parent / "LICENSE"file = tmp_cwd / "license"- file.write_bytes(license_file.read_text("utf8").encode()) # Remove windows EOL+ file.write_bytes(license_file.read_text(encoding="utf8").encode()) # Remove windows EOLresult = _compute_hash(file, algo)assert result == expecteddiff --git a/tests/test_hls.py b/tests/test_hls.pyindex affa14a61..dfe31115b 100644--- a/tests/test_hls.py+++ b/tests/test_hls.py@@ -162,7 +162,7 @@ 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")+ (folder / "notes.txt").write_text("not ours", encoding="utf8")await hls._discard_stale_segments(folder, "playlist-a")assert not (folder / "00001.cdl_hls").exists()- assert (folder / "notes.txt").read_text() == "not ours"+ assert (folder / "notes.txt").read_text(encoding="utf8") == "not ours"diff --git a/tests/test_prune.py b/tests/test_prune.pyindex 6cc4ee674..82dd138d3 100644--- a/tests/test_prune.py+++ b/tests/test_prune.py@@ -40,7 +40,7 @@ def _stat_raises(target: Path, error: OSError) -> Generator[None]:async def _add_file(database: Database, file: Path) -> None:file.parent.mkdir(parents=True, exist_ok=True)- file.write_text(file.name)+ file.write_text(file.name, encoding="utf8")await database.hash.insert_or_update_hash_db(_HASH, "md5", file, file.name, _REFERER)@@ -66,7 +66,7 @@ async def database(running_manager: Manager) -> Database:@pytest.fixturedef txt_file(tmp_cwd: Path) -> Path:file = tmp_cwd / "text_file.txt"- file.write_text("12345")+ file.write_text("12345", encoding="utf8")return filediff --git a/tests/test_sorter.py b/tests/test_sorter.pyindex 9d794a7ab..99d793023 100644--- a/tests/test_sorter.py+++ b/tests/test_sorter.py@@ -79,31 +79,31 @@ class TestHaveSameContent:class TestMoveFile:def test_same_file_returns_immediately(self, tmp_path: Path) -> None:foo = tmp_path / "foo.txt"- foo.write_text("x")+ foo.write_text("x", encoding="utf8")assert _move_file(foo, foo) == fooassert foo.exists()def test_simple_move(self, tmp_path: Path) -> None:src = tmp_path / "foo.txt"- src.write_text("data")+ src.write_text("data", encoding="utf8")dst = tmp_path / "sub" / "bar.txt"out = _move_file(src, dst)assert out == dstassert not src.exists()- assert dst.read_text() == "data"+ assert dst.read_text(encoding="utf8") == "data"def test_name_collision_same_size_diferent_content(self, tmp_path: Path) -> None:src = tmp_path / "foo.txt"- src.write_text("abc")+ src.write_text("abc", encoding="utf8")dst = tmp_path / "bar.txt"- dst.write_text("123")+ dst.write_text("123", encoding="utf8")out = _move_file(src, dst)assert outassert out != dstassert not src.exists()- assert dst.read_text() == "123"- assert out.read_text() == "abc"+ assert dst.read_text(encoding="utf8") == "123"+ assert out.read_text(encoding="utf8") == "abc"def test_name_collision_different_size(self, tmp_path: Path) -> None:src = tmp_path / "foo.jpg"@@ -118,17 +118,17 @@ class TestMoveFile:def test_custom_incrementer_format(self, tmp_path: Path) -> None:src = tmp_path / "foo.log"- src.write_text("a")+ src.write_text("a", encoding="utf8")dest = tmp_path / "bar.log"- dest.write_text("x")+ dest.write_text("x", encoding="utf8")for i in range(1, 4):- (tmp_path / f"bar_{i}.log").write_text("x")+ (tmp_path / f"bar_{i}.log").write_text("x", encoding="utf8")out = _move_file(src, dest, incrementer_format="_{i}")assert out == tmp_path / "bar_4.log"def test_max_retries_exceeded(self, tmp_path: Path) -> None:src = tmp_path / "foo.txt"- src.write_text("x")+ src.write_text("x", encoding="utf8")dest = tmp_path / "bar.txt"dest.touch()for i in range(1, 12):@@ -139,7 +139,7 @@ class TestMoveFile:def test_os_error_during_move_cancels_it(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:src = tmp_path / "foo.txt"- src.write_text("x")+ src.write_text("x", encoding="utf8")dst = tmp_path / "bar.txt"def boom(*_: object, **_k: object) -> Never:@@ -184,7 +184,7 @@ async def test_sorter(tmp_path: Path) -> None:for idx, file in enumerate(Files.ALL):path = input_dir / filepath.parent.mkdir(parents=True, exist_ok=True)- path.write_text(str(idx))+ path.write_text(str(idx), encoding="utf8")await sorter.run(disable_tui=True)stats = sorter.statsdiff --git a/tests/test_unicode_emoji_sanitization.py b/tests/test_unicode_emoji_sanitization.pyindex ecdc89e99..bbbd4d5e4 100644--- a/tests/test_unicode_emoji_sanitization.py+++ b/tests/test_unicode_emoji_sanitization.py@@ -27,10 +27,10 @@ def test_sanitization_must_keep_other_languages_chars(name: str) -> None:@pytest.mark.xfaildef test_unicode9_filename_raise_os_error(tmp_path: Path) -> None:with pytest.raises(OSError):- tmp_path.joinpath(INVALID_UNICODE9_STRING).with_suffix(".txt").write_text("OK")+ tmp_path.joinpath(INVALID_UNICODE9_STRING).with_suffix(".txt").write_text("OK", encoding="utf8")@pytest.mark.parametrize("name", [INVALID_UNICODE9_STRING, *FOREIGN_LENGUAGE_STRINGS])def test_sanitized_filename_do_not_raise_os_errors(name: str, tmp_path: Path) -> None:filename = sanitize_filename(name)- tmp_path.joinpath(filename).with_suffix(".txt").write_text("OK")+ tmp_path.joinpath(filename).with_suffix(".txt").write_text("OK", encoding="utf8")diff --git a/tests/test_utils.py b/tests/test_utils.pyindex 94e24ed5a..cfdf335b9 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -160,7 +160,7 @@ class TestTextEditor:assert cmd == text_editor._editor_cmd()assert cmd == ("C:\\Windows\\system32\\notepad.exe",)np = tmp_cwd / "notepad++.exe"- np.write_text("test")+ np.write_text("test", encoding="utf8")cmd = text_editor._find_win_editor()assert cmdassert cmd[1:] == (