fix: move DownloadService to session Context to prevent worker registration crash

DownloadService was instantiated every time the download_episodes menu
was entered, unconditionally registering a worker on the global
ThreadManager singleton. The second download in the same session would
crash with "Worker with name 'download_worker' already registered".

Move DownloadService to a lazy property on Context (as the existing
TODO suggested), matching the pattern used by all other services.
This commit is contained in:
Castrozan
2026-03-07 14:00:16 -03:00
parent 91aa6b599e
commit a7e75ae543
2 changed files with 14 additions and 8 deletions

View File

@@ -8,7 +8,6 @@ def download_episodes(ctx: Context, state: State) -> State | InternalDirective:
"""Menu to select and download episodes synchronously."""
from viu_media.cli.utils.search import find_best_match_title
from .....core.utils.normalizer import normalize_title
from ....service.download.service import DownloadService
feedback = ctx.feedback
selector = ctx.selector
@@ -71,16 +70,11 @@ def download_episodes(ctx: Context, state: State) -> State | InternalDirective:
feedback.info("No episodes selected for download.")
return InternalDirective.BACK
# Step 3: Download episodes synchronously
# TODO: move to main ctx
download_service = DownloadService(
config, ctx.media_registry, ctx.media_api, ctx.provider
)
# Step 3: Download episodes synchronously using the session-scoped service
feedback.info(
f"Starting download of {len(selected_episodes)} episodes. This may take a while..."
)
download_service.download_episodes_sync(media_item, selected_episodes)
ctx.download.download_episodes_sync(media_item, selected_episodes)
feedback.success(f"Finished downloading {len(selected_episodes)} episodes.")

View File

@@ -16,6 +16,7 @@ if TYPE_CHECKING:
from ...libs.provider.anime.base import BaseAnimeProvider
from ...libs.selectors.base import BaseSelector
from ..service.auth import AuthService
from ..service.download.service import DownloadService
from ..service.feedback import FeedbackService
from ..service.player import PlayerService
from ..service.registry import MediaRegistryService
@@ -86,6 +87,7 @@ class Context:
_selector: Optional["BaseSelector"] = None
_media_api: Optional["BaseApiClient"] = None
_download: Optional["DownloadService"] = None
_feedback: Optional["FeedbackService"] = None
_media_registry: Optional["MediaRegistryService"] = None
_watch_history: Optional["WatchHistoryService"] = None
@@ -137,6 +139,16 @@ class Context:
return self._media_api
@property
def download(self) -> "DownloadService":
if not self._download:
from ..service.download.service import DownloadService
self._download = DownloadService(
self.config, self.media_registry, self.media_api, self.provider
)
return self._download
@property
def player(self) -> "PlayerService":
if not self._player: