Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
fix: sanitizing title to avoid illegal byte sequence error (#1023)
Barbarella6666666feb0694ad0b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 04cbf7629..05b285a65 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -63,6 +63,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Try to use original server (kemono, coomer, nekohouse)- Improve cloudflare captcha detection- General performance improvements+- CDL will remove simbols and emojis from filenames in Windows and macOS### Removeddiff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.pyindex 5e36fc229..916bb8938 100644--- a/cyberdrop_dl/utils/utilities.py+++ b/cyberdrop_dl/utils/utilities.py@@ -8,6 +8,7 @@ import platformimport reimport shutilimport subprocess+import unicodedatafrom dataclasses import dataclass, fieldsfrom functools import lru_cache, partial, wrapsfrom pathlib import Path@@ -50,6 +51,7 @@ R = TypeVar("R")TEXT_EDITORS = "micro", "nano", "vim" # Ordered by preferenceFILENAME_REGEX = re.compile(r"filename\*=UTF-8''(.+)|.*filename=\"(.*?)\"", re.IGNORECASE)+ALLOWED_FILEPATH_PUNCTUATION = " .-_!#$%'()+,;=@[]^{}~"subprocess_get_text = partial(subprocess.run, capture_output=True, text=True, check=False)@@ -125,17 +127,28 @@ def error_handling_wrapper("""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""-def sanitize_filename(name: str) -> str:+def sanitize_unicode_emojis_and_symbols(title: str) -> str:+ """Allow all Unicode letters/numbers/marks, plus safe filename punctuation, but not symbols or emoji."""+ return "".join(+ c for c in title if (c in ALLOWED_FILEPATH_PUNCTUATION or unicodedata.category(c)[0] in {"L", "N", "M"})+ ).strip()+++def sanitize_filename(name: str, sub: str = "") -> str:"""Simple sanitization to remove illegal characters from filename."""- return re.sub(constants.SANITIZE_FILENAME_PATTERN, "", name).strip()+ clean_name = re.sub(constants.SANITIZE_FILENAME_PATTERN, sub, name)+ if platform.system() in ("Windows", "Darwin"):+ return sanitize_unicode_emojis_and_symbols(clean_name)+ return clean_namedef sanitize_folder(title: str) -> str:"""Simple sanitization to remove illegal characters from titles and trim the length to be less than 60 chars."""+title = title.replace("\n", "").strip()title = title.replace("\t", "").strip()title = re.sub(" +", " ", title)- title = re.sub(r'[\\*?:"<>|/]', "-", title)+ title = sanitize_filename(title, "-")title = re.sub(r"\.{2,}", ".", title)title = title.rstrip(".").strip()diff --git a/tests/test_unicode_emoji_sanitization.py b/tests/test_unicode_emoji_sanitization.pynew file mode 100644index 000000000..6ef005306--- /dev/null+++ b/tests/test_unicode_emoji_sanitization.py@@ -0,0 +1,34 @@+import sys+from pathlib import Path++import pytest++from cyberdrop_dl.utils.utilities import sanitize_filename, sanitize_unicode_emojis_and_symbols++IS_MACOS = sys.platform == "darwin"+++FOREIGN_LENGUAGE_STRINGS = ["これは単なるテストです", "это всего лишь тест", "این فقط یک آزمایش است", "هذا مجرد اختبار"]+INVALID_UNICODE9_STRING = "🫧Bubblz🫧"+++def test_sanitize_macos_problematic_unicode_symbol() -> None:+ assert sanitize_unicode_emojis_and_symbols(INVALID_UNICODE9_STRING) == "Bubblz"++[email protected]("name", FOREIGN_LENGUAGE_STRINGS)+def test_sanitization_must_keep_other_languages_chars(name: str) -> None:+ assert sanitize_unicode_emojis_and_symbols(name) == name++[email protected](not IS_MACOS, reason="Only fails in older macOS with APFS")+def 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")++[email protected]("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")