Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: decouple sorter from manager (#98)

NTFSvolumeab5fb8217a5f
diff --git a/cyberdrop_dl/director.py b/cyberdrop_dl/director.py
index 3f82e4d38..30f20075b 100644
--- a/cyberdrop_dl/director.py
+++ b/cyberdrop_dl/director.py
@@ -110,7 +110,7 @@ async def _post_runtime(manager: Manager) -> None:
await manager.hash_manager.hash_client.cleanup_dupes_after_download()
if manager.config_manager.settings_data.sorting.sort_downloads and not manager.parsed_args.cli_only_args.retry_any:
- sorter = Sorter(manager)
+ sorter = Sorter.from_manager(manager)
await sorter.run()
check_partials_and_empty_folders(manager)
diff --git a/cyberdrop_dl/ui/program_ui.py b/cyberdrop_dl/ui/program_ui.py
index 59783cce7..4d78b0a44 100644
--- a/cyberdrop_dl/ui/program_ui.py
+++ b/cyberdrop_dl/ui/program_ui.py
@@ -86,7 +86,7 @@ class ProgramUI:
def _sort_files(self) -> None:
"""Sort files in download folder"""
- sorter = Sorter(self.manager)
+ sorter = Sorter.from_manager(self.manager)
asyncio.run(sorter.run())
def _view_changelog(self) -> None:
diff --git a/cyberdrop_dl/ui/progress/sort_progress.py b/cyberdrop_dl/ui/progress/sort_progress.py
index e57684285..809d0464d 100644
--- a/cyberdrop_dl/ui/progress/sort_progress.py
+++ b/cyberdrop_dl/ui/progress/sort_progress.py
@@ -47,9 +47,6 @@ class SortProgress(DequeProgress):
padding=(1, 1),
)
- def set_queue_length(self, length: int) -> None:
- self.queue_length = length
-
def add_task(self, folder: str, expected_size: int | None) -> TaskID:
"""Adds a new task to the progress bar."""
# description = f'Sorting {folder}'
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index 2c0cae833..0ce31b103 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -1,141 +1,124 @@
from __future__ import annotations
import asyncio
-import itertools
+import dataclasses
+import datetime
import logging
-from datetime import datetime
+import shutil
from pathlib import Path
from subprocess import CalledProcessError
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Self
import imagesize
-from cyberdrop_dl import constants
-from cyberdrop_dl.constants import FileExt
-from cyberdrop_dl.ffmpeg import probe
+from cyberdrop_dl import ffmpeg
+from cyberdrop_dl.constants import FileExt, TempExt
from cyberdrop_dl.utils import strings
-from cyberdrop_dl.utils.logger import log_with_color
-from cyberdrop_dl.utils.utilities import purge_dir_tree
+from cyberdrop_dl.utils.utilities import purge_dir_tree as delete_empty_files_and_folders
if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from cyberdrop_dl.managers.live_manager import LiveManager
from cyberdrop_dl.managers.manager import Manager
+ from cyberdrop_dl.managers.progress_manager import ProgressManager
logger = logging.getLogger(__name__)
-async def get_modified_date(file: Path) -> datetime:
+async def _get_modified_date(file: Path) -> datetime.datetime:
stat = await asyncio.to_thread(file.stat)
- return datetime.fromtimestamp(stat.st_mtime).replace(microsecond=0)
+ return datetime.datetime.fromtimestamp(stat.st_mtime).replace(microsecond=0)
[email protected](slots=True, frozen=True)
class Sorter:
- def __init__(self, manager: Manager) -> None:
- self.manager = manager
- self.download_folder = manager.config.sorting.scan_folder or manager.config.files.download_folder
- self.sorted_folder = manager.config.sorting.sort_folder
- self.incrementer_format: str = manager.config_manager.settings_data.sorting.sort_incrementer_format
- self.db_manager = manager.db_manager
-
- settings = manager.config_manager.settings_data.sorting
- self.audio_format: str | None = settings.sorted_audio
- self.image_format: str | None = settings.sorted_image
- self.video_format: str | None = settings.sorted_video
- self.other_format: str | None = settings.sorted_other
-
- def _move_file(self, old_path: Path, new_path: Path) -> bool:
- """Moves a file to a destination folder."""
- if new_path.is_symlink():
- new_path = new_path.resolve()
- if old_path == new_path:
- return True
-
- new_path.parent.mkdir(parents=True, exist_ok=True)
-
- try:
- old_path.rename(new_path)
- except FileExistsError:
- if old_path.stat().st_size == new_path.stat().st_size:
- old_path.unlink()
- return True
- for auto_index in itertools.count(1):
- new_filename = f"{new_path.stem}{self.incrementer_format.format(i=auto_index)}{new_path.suffix}"
- possible_new_path = new_path.parent / new_filename
- try:
- old_path.rename(possible_new_path)
- break
- except FileExistsError:
- continue
- except OSError:
- return False
-
- return True
+ live_manager: LiveManager
+ tui: ProgressManager
+ input_dir: Path
+ output_dir: Path
+
+ incrementer_format: str
+ audio_format: str | None
+ image_format: str | None
+ video_format: str | None
+ other_format: str | None
+
+ @classmethod
+ def from_manager(cls, manager: Manager) -> Self:
+ settings = manager.config.sorting
+ return cls(
+ manager.live_manager,
+ tui=manager.progress_manager,
+ input_dir=settings.scan_folder or manager.config.files.download_folder,
+ output_dir=settings.sort_folder,
+ incrementer_format=settings.sort_incrementer_format,
+ audio_format=settings.sorted_audio,
+ image_format=settings.sorted_image,
+ video_format=settings.sorted_video,
+ other_format=settings.sorted_other,
+ )
async def run(self) -> None:
- """Sorts the files in the download directory into their respective folders."""
- if not await asyncio.to_thread(self.download_folder.is_dir):
- log_with_color(f"Download directory ({self.download_folder}) does not exist", "red", 40)
+ if not await asyncio.to_thread(self.input_dir.is_dir):
+ logger.error(f"Sort directory ('{self.input_dir}' does not exist", extra={"color": "red"})
return
- log_with_color("\nSorting downloads, please wait", "cyan", 20)
- await asyncio.to_thread(self.sorted_folder.mkdir, parents=True, exist_ok=True)
-
- files_to_sort: dict[str, list[Path]] = {}
-
- with self.manager.live_manager.get_sort_live(stop=True):
- for subfolder in await asyncio.to_thread(_subfolders, self.download_folder):
- files_to_sort[subfolder.name] = await asyncio.to_thread(_get_files, subfolder)
-
- await self._sort_files(files_to_sort)
- log_with_color("DONE!", "green", 20)
-
- _ = purge_dir_tree(self.download_folder)
-
- async def _sort_files(self, files_to_sort: dict[str, list[Path]]) -> None:
- queue_length = len(files_to_sort)
- self.manager.progress_manager.sort_progress.set_queue_length(queue_length)
-
- for folder_name, files in files_to_sort.items():
- task_id = self.manager.progress_manager.sort_progress.add_task(folder_name, len(files))
-
- for file in files:
- ext = file.suffix.lower()
-
- if ext in constants.TempExt:
- continue
-
- if ext in FileExt.AUDIO:
- await self.sort_audio(file, folder_name)
- elif ext in FileExt.IMAGE:
- await self.sort_image(file, folder_name)
- elif ext in FileExt.VIDEO:
- await self.sort_video(file, folder_name)
- else:
- await self.sort_other(file, folder_name)
+ logger.info("Sorting downloads...", extra={"color": "cyan"})
+ await asyncio.to_thread(self.output_dir.mkdir, parents=True, exist_ok=True)
+
+ with self.live_manager.get_sort_live(stop=True):
+ subfolders = await asyncio.to_thread(_subfolders, self.input_dir)
+ await self._sort_files(subfolders)
+ logger.info("DONE!", extra={"color": "green"})
+ _ = delete_empty_files_and_folders(self.input_dir)
+
+ async def _sort_files(self, folders: Iterable[Path]) -> None:
+ for fut in asyncio.as_completed(asyncio.to_thread(_get_files, f) for f in folders):
+ folder, files = await fut
+ folder_name = folder.name
+ self.tui.sort_progress.queue_length += len(files)
+ task_id = self.tui.sort_progress.add_task(folder_name, len(files))
+ try:
+
+ async def sort(file: Path, name: str = folder_name, task_id=task_id) -> None:
+ try:
+ await self.__sort(name, file)
+ finally:
+ self.tui.sort_progress.advance_folder(task_id)
+ self.tui.sort_progress.queue_length -= 1
+
+ _ = await asyncio.gather(*map(sort, files))
+ finally:
+ self.tui.sort_progress.remove_task(task_id)
+
+ async def __sort(self, folder_name: str, file: Path) -> None:
+ ext = file.suffix.lower()
+ if ext in TempExt:
+ return
- self.manager.progress_manager.sort_progress.advance_folder(task_id)
+ if ext in FileExt.AUDIO:
+ return await self.sort_audio(file, folder_name)
+ if ext in FileExt.IMAGE:
+ return await self.sort_image(file, folder_name)
+ if ext in FileExt.VIDEO:
+ return await self.sort_video(file, folder_name)
- self.manager.progress_manager.sort_progress.remove_task(task_id)
- queue_length -= 1
- self.manager.progress_manager.sort_progress.set_queue_length(queue_length)
+ await self.sort_other(file, folder_name)
async def sort_audio(self, file: Path, base_name: str) -> None:
- """Sorts an audio file into the sorted audio folder."""
if not self.audio_format:
return
bitrate = duration = sample_rate = None
- try:
- probe_output = await probe(file)
- if audio := probe_output.audio:
- duration = audio.duration or probe_output.format.duration
- bitrate = audio.bitrate
- sample_rate = audio.sample_rate
-
- except (RuntimeError, CalledProcessError, OSError):
- logger.exception(f"Unable to get audio properties of '{file}'")
+ probe_output = await _try_probe("audio", file)
+ if probe_output and (audio := probe_output.audio):
+ duration = audio.duration or probe_output.format.duration
+ bitrate = audio.bitrate
+ sample_rate = audio.sample_rate
- if await self._process_file_move(
+ if await self._move_file(
file,
base_name,
self.audio_format,
@@ -144,25 +127,22 @@ class Sorter:
length=duration,
sample_rate=sample_rate,
):
- self.manager.progress_manager.sort_progress.increment_audio()
+ self.tui.sort_progress.increment_audio()
async def sort_image(self, file: Path, base_name: str) -> None:
- """Sorts an image file into the sorted image folder."""
if not self.image_format:
return
+
height = resolution = width = None
try:
width, height = await asyncio.to_thread(imagesize.get, file)
if width > 0 and height > 0:
resolution = f"{width}x{height}"
- else:
- # imagesize returns (-1, -1) for unsupported/corrupted images
- width = height = resolution = None
except (OSError, ValueError):
logger.exception(f"Unable to get some image properties of '{file}'")
- if await self._process_file_move(
+ if await self._move_file(
file,
base_name,
self.image_format,
@@ -170,59 +150,49 @@ class Sorter:
resolution=resolution,
width=width,
):
- self.manager.progress_manager.sort_progress.increment_image()
+ self.tui.sort_progress.increment_image()
async def sort_video(self, file: Path, base_name: str) -> None:
- """Sorts a video file into the sorted video folder."""
if not self.video_format:
return
codec = duration = framerate = height = resolution = width = None
-
- try:
- probe_output = await probe(file)
- if video := probe_output.video:
- width = video.width
- height = video.height
- resolution = video.resolution
- codec = video.codec
- duration = video.duration or probe_output.format.duration
- framerate = video.fps
-
- except (RuntimeError, CalledProcessError, OSError):
- logger.exception(f"Unable to get some video properties of '{file}'")
-
- if await self._process_file_move(
+ probe_output = await _try_probe("video", file)
+ if probe_output and (video := probe_output.video):
+ width = video.width
+ height = video.height
+ resolution = video.resolution
+ codec = video.codec
+ duration = video.duration or probe_output.format.duration
+ framerate = video.fps
+
+ if await self._move_file(
file,
base_name,
self.video_format,
codec=codec,
duration=duration,
+ length=duration,
fps=framerate,
height=height,
resolution=resolution,
width=width,
):
- self.manager.progress_manager.sort_progress.increment_video()
+ self.tui.sort_progress.increment_video()
async def sort_other(self, file: Path, base_name: str) -> None:
- """Sorts an other file into the sorted other folder."""
if not self.other_format:
return
- if await self._process_file_move(file, base_name, self.other_format):
- self.manager.progress_manager.sort_progress.increment_other()
+ if await self._move_file(file, base_name, self.other_format):
+ self.tui.sort_progress.increment_other()
- async def _process_file_move(self, file: Path, base_name: str, format_str: str, **kwargs: Any) -> bool:
- file_date = await get_modified_date(file)
+ async def _move_file(self, file: Path, base_name: str, format_str: str, /, **kwargs: object) -> bool:
+ file_date = await _get_modified_date(file)
file_date_us = file_date.strftime("%Y-%d-%m")
file_date_iso = file_date.strftime("%Y-%m-%d")
- duration = kwargs.get("duration") or kwargs.get("length")
- if duration is not None:
- kwargs["duration"] = kwargs["length"] = duration
-
- file_path, _ = strings.safe_format(
+ dest, _ = strings.safe_format(
format_str,
base_dir=base_name,
ext=file.suffix,
@@ -231,29 +201,81 @@ class Sorter:
file_date_us=file_date_us,
filename=file.stem,
parent_dir=file.parent.name,
- sort_dir=self.sorted_folder,
+ sort_dir=self.output_dir,
**kwargs,
)
- new_file = Path(file_path)
- return self._move_file(file, new_file)
-
-
-def _subfolders(directory: Path) -> list[Path]:
- def walk():
- for subfolder in directory.resolve().iterdir():
- if subfolder.is_dir():
- yield subfolder
-
- return list(walk())
+ dest = Path(dest)
+ dest = await asyncio.to_thread(_move_file, file, dest, self.incrementer_format)
+ if dest:
+ logger.debug("Moved '{}' to '{}'", file, dest)
+ return bool(dest)
+
+
+def _subfolders(directory: Path) -> tuple[Path, ...]:
+ return tuple(path for path in directory.resolve().iterdir() if path.is_dir())
+
+
+def _get_files(directory: Path) -> tuple[Path, tuple[Path, ...]]:
+ return directory, tuple(path for path in directory.resolve().rglob("*") if path.is_file())
+
+
+def _move_file(
+ source: Path,
+ dest: Path,
+ incrementer_format: str = "{i}",
+ *,
+ max_retries: int = 10,
+) -> Path | None:
+
+ dest = dest.resolve()
+ if source == dest:
+ return dest
+
+ dest_parent = dest.parent
+ dest_parent.mkdir(parents=True, exist_ok=True)
+
+ try:
+ _ = shutil.move(source, dest)
+ except FileExistsError:
+ dest_stem = dest.stem
+ source_size = source.stat().st_size
+ for auto_index in range(1, max_retries + 1):
+ if source_size == dest.stat().st_size:
+ source.unlink()
+ return dest
+
+ new_filename = f"{dest_stem}{incrementer_format.format(i=auto_index)}{dest.suffix}"
+ logger.warning(
+ "Found name collision when moving '{}' to '{}'. Retring with '{}'",
+ source,
+ dest,
+ dest := dest_parent / new_filename,
+ )
+
+ try:
+ _ = shutil.move(source, dest)
+ except FileExistsError:
+ continue
+ except OSError:
+ logger.exception("Unable to move '{}'", source)
+ return
+ else:
+ return dest
+ else:
+ logger.error("Unable to move '{}'. Giving up after {} attempts", source, max_retries)
+ return
+ except OSError:
+ logger.exception("Unable to move '{}'", source)
+ return
-def _get_files(directory: Path) -> list[Path]:
- """Finds all files in a directory and returns them in a list."""
+ else:
+ return dest
- def walk():
- for file in directory.resolve().rglob("*"):
- if file.is_file():
- yield file
- return list(walk())
+async def _try_probe(kind: str, file: Path) -> ffmpeg.FFprobeResult | None:
+ try:
+ return await ffmpeg.probe(file)
+ except (RuntimeError, CalledProcessError, OSError):
+ logger.exception(f"Unable to get {kind} properties of '{file}'")