vega-cli 0.1.4__tar.gz → 0.1.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. {vega_cli-0.1.4 → vega_cli-0.1.6}/PKG-INFO +1 -1
  2. {vega_cli-0.1.4 → vega_cli-0.1.6}/pyproject.toml +2 -1
  3. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/cli.py +96 -3
  4. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/display.py +4 -3
  5. vega_cli-0.1.6/vega_cli/downloader.py +347 -0
  6. vega_cli-0.1.6/vega_cli/gui.py +1011 -0
  7. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/images.py +84 -6
  8. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/interactive.py +26 -4
  9. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli.egg-info/PKG-INFO +1 -1
  10. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli.egg-info/SOURCES.txt +1 -0
  11. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli.egg-info/entry_points.txt +1 -0
  12. vega_cli-0.1.4/vega_cli/downloader.py +0 -153
  13. {vega_cli-0.1.4 → vega_cli-0.1.6}/README.md +0 -0
  14. {vega_cli-0.1.4 → vega_cli-0.1.6}/setup.cfg +0 -0
  15. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/__init__.py +0 -0
  16. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/__main__.py +0 -0
  17. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/config.py +0 -0
  18. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/history.py +0 -0
  19. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/html.py +0 -0
  20. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/player.py +0 -0
  21. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/__init__.py +0 -0
  22. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/ani_dream.py +0 -0
  23. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/anikoto.py +0 -0
  24. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/animesalt.py +0 -0
  25. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/animesub.py +0 -0
  26. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/animeworld.py +0 -0
  27. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/auto_embed.py +0 -0
  28. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/castle.py +0 -0
  29. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/cncverse.py +0 -0
  30. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/__init__.py +0 -0
  31. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/aes.py +0 -0
  32. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/aniskip.py +0 -0
  33. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/base_url.py +0 -0
  34. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/cinemeta.py +0 -0
  35. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/errors.py +0 -0
  36. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/__init__.py +0 -0
  37. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/abbasy.py +0 -0
  38. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/buzzheavier.py +0 -0
  39. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/cinejoy.py +0 -0
  40. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/gdflix.py +0 -0
  41. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/gofile.py +0 -0
  42. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/hubcloud.py +0 -0
  43. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/movy.py +0 -0
  44. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/st111477.py +0 -0
  45. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/transferit.py +0 -0
  46. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/vegadrive.py +0 -0
  47. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/vidstuck.py +0 -0
  48. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/zcloud.py +0 -0
  49. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/extractors/zypter.py +0 -0
  50. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/headers.py +0 -0
  51. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/http.py +0 -0
  52. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/net_mirror.py +0 -0
  53. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/theintrodb.py +0 -0
  54. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/common/unpack.py +0 -0
  55. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/disney_mirror.py +0 -0
  56. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/dramacool.py +0 -0
  57. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/drive.py +0 -0
  58. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/durbin_live.py +0 -0
  59. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/eon_movies.py +0 -0
  60. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/extraflix.py +0 -0
  61. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/four_khdhub.py +0 -0
  62. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/goku_hd.py +0 -0
  63. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/hdhub4u.py +0 -0
  64. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/internet_archive.py +0 -0
  65. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/kartoons.py +0 -0
  66. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/kartoons2.py +0 -0
  67. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/katmovies.py +0 -0
  68. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/kick_ass_anime.py +0 -0
  69. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/kiss_kh.py +0 -0
  70. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/live_tg_tv.py +0 -0
  71. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/lux_movies.py +0 -0
  72. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/mod.py +0 -0
  73. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/movie_box_web.py +0 -0
  74. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/movielinkdb.py +0 -0
  75. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/movies4u.py +0 -0
  76. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/moviezwap.py +0 -0
  77. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/mxplayer.py +0 -0
  78. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/netflix_mirror.py +0 -0
  79. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/one_cinevood.py +0 -0
  80. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/prime_mirror.py +0 -0
  81. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/rareanimes.py +0 -0
  82. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/registry.py +0 -0
  83. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/showbox.py +0 -0
  84. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/topmovies.py +0 -0
  85. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/torrentio.py +0 -0
  86. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/uhd.py +0 -0
  87. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/vega.py +0 -0
  88. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/youtube.py +0 -0
  89. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/providers/zeefliz.py +0 -0
  90. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/search_all.py +0 -0
  91. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/store.py +0 -0
  92. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli/utils.py +0 -0
  93. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli.egg-info/dependency_links.txt +0 -0
  94. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli.egg-info/requires.txt +0 -0
  95. {vega_cli-0.1.4 → vega_cli-0.1.6}/vega_cli.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vega-cli
3
- Version: 0.1.4
3
+ Version: 0.1.6
4
4
  Summary: Pure-Python CLI for Vega streaming and download providers
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "vega-cli"
7
- version = "0.1.4"
7
+ version = "0.1.6"
8
8
  description = "Pure-Python CLI for Vega streaming and download providers"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -18,6 +18,7 @@ dependencies = [
18
18
  [project.scripts]
19
19
  vega = "vega_cli.cli:cli"
20
20
  vega-cli = "vega_cli.cli:cli"
21
+ vega-gui = "vega_cli.gui:main"
21
22
 
22
23
  [tool.setuptools.packages.find]
23
24
  include = ["vega_cli*"]
@@ -20,9 +20,15 @@ from .display import (
20
20
  print_settings,
21
21
  print_streams,
22
22
  )
23
- from .downloader import download_stream
23
+ from .downloader import (
24
+ download_all_episodes,
25
+ download_stream,
26
+ get_default_download_dir,
27
+ set_default_download_dir,
28
+ )
24
29
  from .history import HistoryStore
25
30
  from .html import parse_html
31
+ from .images import open_image_external
26
32
  from .interactive import run_interactive
27
33
  from .player import launch_player, launch_vlc
28
34
  from .providers import (
@@ -185,9 +191,21 @@ def search_all(
185
191
  @cli.command()
186
192
  @_provider_option
187
193
  @click.argument("link")
188
- @click.option("--images/--no-images", "show_image", default=True, help="Render poster in terminal.")
194
+ @click.option(
195
+ "--images/--no-images",
196
+ "show_image",
197
+ default=None,
198
+ help="Render poster in terminal (auto-enabled in iTerm2/Kitty/WezTerm/Ghostty/Warp).",
199
+ )
200
+ @click.option("--open-image", "open_img", is_flag=True, help="Open full-res poster in system viewer.")
189
201
  @click.option("--json", "as_json", is_flag=True, help="Output raw JSON.")
190
- def meta(provider_name: str, link: str, show_image: bool, as_json: bool) -> None:
202
+ def meta(
203
+ provider_name: str,
204
+ link: str,
205
+ show_image: bool | None,
206
+ open_img: bool,
207
+ as_json: bool,
208
+ ) -> None:
191
209
  """Fetch metadata and download/episode links for a post."""
192
210
  client = get_provider(provider_name)
193
211
  info = client.get_meta(link)
@@ -195,6 +213,10 @@ def meta(provider_name: str, link: str, show_image: bool, as_json: bool) -> None
195
213
  click.echo(json.dumps(info, indent=2))
196
214
  return
197
215
  print_meta(info, show_image=show_image)
216
+ if open_img:
217
+ poster_url = info.get("poster") or info.get("image") or ""
218
+ if poster_url:
219
+ open_image_external(poster_url)
198
220
 
199
221
 
200
222
  @cli.command()
@@ -291,6 +313,61 @@ def download(
291
313
  )
292
314
 
293
315
 
316
+ @cli.command("download-all")
317
+ @_provider_option
318
+ @click.argument("url")
319
+ @click.option("--imdb-id", default="", help="Optional IMDb ID.")
320
+ @click.option("--season", default=None, type=int, help="Optional season number.")
321
+ @click.option("-o", "--output", "output_path", default=None, help="Output directory (default: ~/Downloads).")
322
+ @click.option("--title", default="", help="Series title for subfolder and filenames.")
323
+ @click.option("--start", "start_ep", default=1, show_default=True, type=int, help="1-based start episode index.")
324
+ @click.option("--end", "end_ep", default=None, type=int, help="1-based end episode index (inclusive).")
325
+ def download_all_cmd(
326
+ provider_name: str,
327
+ url: str,
328
+ imdb_id: str,
329
+ season: int | None,
330
+ output_path: str | None,
331
+ title: str,
332
+ start_ep: int,
333
+ end_ep: int | None,
334
+ ) -> None:
335
+ """Download all episodes from a season URL."""
336
+ client = get_provider(provider_name)
337
+ eps = client.get_episodes(url, imdb_id=imdb_id, season=season)
338
+ if not eps:
339
+ raise click.ClickException(f"No episodes found for '{url}' on {provider_name}.")
340
+ sliced = eps[max(0, start_ep - 1) : end_ep]
341
+ console.print(f"[cyan]Downloading {len(sliced)} episode(s)...[/cyan]")
342
+ saved, failures = download_all_episodes(
343
+ client,
344
+ sliced,
345
+ output_dir=output_path,
346
+ series_title=title,
347
+ )
348
+ console.print(f"[green]Completed: {len(saved)}/{len(sliced)} downloaded.[/green]")
349
+ if failures:
350
+ for ep_t, err in failures:
351
+ console.print(f"[red]Failed:[/red] {ep_t} ({err})")
352
+
353
+
354
+ @cli.command("download-dir")
355
+ @click.argument("path", required=False)
356
+ @click.option("--reset", is_flag=True, help="Reset to ~/Downloads.")
357
+ def download_dir_cmd(path: str | None, reset: bool) -> None:
358
+ """View or set the default download directory."""
359
+ kv = KVStore()
360
+ if reset:
361
+ kv.delete("vega_download_dir")
362
+ console.print(f"[green]Reset download directory to:[/green] {get_default_download_dir(kv)}")
363
+ return
364
+ if path:
365
+ saved = set_default_download_dir(path, kv)
366
+ console.print(f"[green]Default download directory set to:[/green] {saved}")
367
+ return
368
+ console.print(f"Current download directory: [cyan]{get_default_download_dir(kv)}[/cyan]")
369
+
370
+
294
371
  @cli.command()
295
372
  @click.option("--clear", is_flag=True, help="Clear watch history.")
296
373
  @click.option("--json", "as_json", is_flag=True, help="Output raw JSON.")
@@ -386,6 +463,22 @@ def settings(
386
463
  print_settings(schema, current, kv.path, title=f"{provider_name} Settings ({kv.path})")
387
464
 
388
465
 
466
+ @cli.command()
467
+ @click.option(
468
+ "-p",
469
+ "--provider",
470
+ "provider_name",
471
+ default="drive",
472
+ show_default=True,
473
+ help="Initial provider ID.",
474
+ )
475
+ def gui(provider_name: str) -> None:
476
+ """Launch the Tkinter desktop GUI."""
477
+ from .gui import main as run_gui
478
+
479
+ run_gui(provider_name=provider_name)
480
+
481
+
389
482
  @cli.command()
390
483
  @click.option(
391
484
  "-p",
@@ -9,7 +9,7 @@ from rich.console import Console
9
9
  from rich.panel import Panel
10
10
  from rich.table import Table
11
11
 
12
- from .images import render_image_url
12
+ from .images import render_image_url, supports_native_images
13
13
 
14
14
  console = Console()
15
15
 
@@ -235,9 +235,10 @@ def print_bookmarks(items: list[dict[str, Any]], title: str = "Bookmarks") -> No
235
235
 
236
236
 
237
237
 
238
- def print_meta(info: dict[str, Any], *, show_image: bool = True) -> None:
238
+ def print_meta(info: dict[str, Any], *, show_image: bool | None = None) -> None:
239
239
  """Render post metadata and available links."""
240
- if show_image:
240
+ should_render = supports_native_images() if show_image is None else show_image
241
+ if should_render:
241
242
  poster_url = info.get("poster") or info.get("image") or ""
242
243
  if poster_url:
243
244
  render_image_url(poster_url, width=64, height=32)
@@ -0,0 +1,347 @@
1
+ """Built-in stream downloader with Rich progress bar and HTTP Range resume."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import mimetypes
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any, Callable
9
+ from urllib.parse import unquote, urlparse
10
+
11
+ import requests
12
+ from rich.console import Console
13
+ from rich.progress import (
14
+ BarColumn,
15
+ DownloadColumn,
16
+ Progress,
17
+ TextColumn,
18
+ TimeRemainingColumn,
19
+ TransferSpeedColumn,
20
+ )
21
+
22
+ from .config import DEFAULT_HEADERS
23
+ from .store import KVStore
24
+
25
+ console = Console()
26
+ _DOWNLOAD_DIR_KEY = "vega_download_dir"
27
+
28
+
29
+ def get_default_download_dir(kv: KVStore | None = None) -> Path:
30
+ """Return configured default download directory, or ~/Downloads."""
31
+ store = kv or KVStore()
32
+ raw = str(store.get(_DOWNLOAD_DIR_KEY, "") or "").strip()
33
+ if raw:
34
+ return Path(raw).expanduser()
35
+ return Path.home() / "Downloads"
36
+
37
+
38
+ def set_default_download_dir(path: str | Path, kv: KVStore | None = None) -> Path:
39
+ """Persist a default download directory in KVStore."""
40
+ store = kv or KVStore()
41
+ resolved = Path(path).expanduser().resolve()
42
+ resolved.mkdir(parents=True, exist_ok=True)
43
+ store.set(_DOWNLOAD_DIR_KEY, str(resolved))
44
+ return resolved
45
+
46
+
47
+ def _sanitize_filename(name: str) -> str:
48
+ cleaned = re.sub(r'[\\/:*?"<>|]+', "_", name).strip(" .")
49
+ return cleaned or "vega_download"
50
+
51
+
52
+ def _infer_filename(
53
+ url: str,
54
+ title: str,
55
+ content_type: str = "",
56
+ content_disposition: str = "",
57
+ ) -> str:
58
+ ext = ""
59
+ if content_disposition:
60
+ m = re.search(r'filename\*?=(?:UTF-8\'\')?["\']?([^"\';]+)', content_disposition, re.I)
61
+ if m:
62
+ disp_name = unquote(m.group(1).strip())
63
+ if "." in disp_name:
64
+ ext = Path(disp_name).suffix
65
+ parsed = urlparse(url)
66
+ url_name = unquote(Path(parsed.path).name)
67
+ if not ext and "." in url_name:
68
+ ext = Path(url_name).suffix
69
+ if not ext and content_type:
70
+ ct = content_type.split(";")[0].strip().lower()
71
+ guessed = mimetypes.guess_extension(ct)
72
+ if guessed:
73
+ ext = guessed
74
+ if not ext or ext.lower() not in (".mp4", ".mkv", ".webm", ".avi", ".mov", ".m3u8", ".ts", ".mp3", ".m4a"):
75
+ if not ext:
76
+ ext = ".mp4"
77
+ if title:
78
+ base = _sanitize_filename(title)
79
+ if not base.lower().endswith(ext.lower()):
80
+ return f"{base}{ext}"
81
+ return base
82
+ if url_name:
83
+ return _sanitize_filename(url_name)
84
+ return f"vega_download{ext}"
85
+
86
+
87
+ def download_stream(
88
+ url: str,
89
+ *,
90
+ output: str | Path | None = None,
91
+ title: str = "",
92
+ headers: dict[str, str] | None = None,
93
+ resume: bool = True,
94
+ timeout: int = 30,
95
+ progress_callback: Callable[[int, int | None], None] | None = None,
96
+ ) -> Path:
97
+ """Download a media stream to disk with a progress bar and resume support."""
98
+ req_headers = {**DEFAULT_HEADERS, **(headers or {})}
99
+ dest = Path(output).expanduser() if output else None
100
+
101
+ if dest and dest.exists() and dest.is_dir():
102
+ target_dir = dest
103
+ target_file = None
104
+ elif dest:
105
+ target_dir = dest.parent
106
+ target_file = dest
107
+ else:
108
+ target_dir = get_default_download_dir()
109
+ target_file = None
110
+
111
+ target_dir.mkdir(parents=True, exist_ok=True)
112
+
113
+ # Probe filename and initial size if needed
114
+ existing_bytes = 0
115
+ if target_file and resume and target_file.exists():
116
+ existing_bytes = target_file.stat().st_size
117
+
118
+ if existing_bytes > 0:
119
+ req_headers["Range"] = f"bytes={existing_bytes}-"
120
+
121
+ with requests.get(
122
+ url,
123
+ headers=req_headers,
124
+ stream=True,
125
+ timeout=timeout,
126
+ allow_redirects=True,
127
+ ) as resp:
128
+ # If server doesn't support Range or file is already complete
129
+ if existing_bytes > 0 and resp.status_code == 416:
130
+ console.print(f"[green]Already downloaded:[/green] {target_file}")
131
+ assert target_file is not None
132
+ return target_file
133
+
134
+ resp.raise_for_status()
135
+ is_resumed = resp.status_code == 206 and existing_bytes > 0
136
+
137
+ if target_file is None:
138
+ ct = resp.headers.get("Content-Type", "")
139
+ cd = resp.headers.get("Content-Disposition", "")
140
+ filename = _infer_filename(resp.url or url, title, ct, cd)
141
+ target_file = target_dir / filename
142
+ if resume and target_file.exists() and not is_resumed:
143
+ # Re-open with Range if the inferred file already partially exists
144
+ prev_size = target_file.stat().st_size
145
+ if prev_size > 0:
146
+ resp.close()
147
+ return download_stream(
148
+ url,
149
+ output=target_file,
150
+ title=title,
151
+ headers=headers,
152
+ resume=True,
153
+ timeout=timeout,
154
+ )
155
+
156
+ content_len = resp.headers.get("Content-Length")
157
+ total_bytes = (
158
+ existing_bytes + int(content_len)
159
+ if (is_resumed and content_len and content_len.isdigit())
160
+ else (int(content_len) if (content_len and content_len.isdigit()) else None)
161
+ )
162
+
163
+ mode = "ab" if is_resumed else "wb"
164
+ with Progress(
165
+ TextColumn("[bold blue]{task.fields[filename]}", justify="right"),
166
+ BarColumn(bar_width=None),
167
+ "[progress.percentage]{task.percentage:>3.1f}%",
168
+ "•",
169
+ DownloadColumn(),
170
+ "•",
171
+ TransferSpeedColumn(),
172
+ "•",
173
+ TimeRemainingColumn(),
174
+ console=console,
175
+ ) as progress:
176
+ task_id = progress.add_task(
177
+ "download",
178
+ filename=target_file.name,
179
+ total=total_bytes,
180
+ completed=existing_bytes if is_resumed else 0,
181
+ )
182
+ with open(target_file, mode) as fh:
183
+ downloaded = existing_bytes if is_resumed else 0
184
+ for chunk in resp.iter_content(chunk_size=1024 * 64):
185
+ if chunk:
186
+ fh.write(chunk)
187
+ downloaded += len(chunk)
188
+ progress.update(task_id, advance=len(chunk))
189
+ if progress_callback:
190
+ progress_callback(downloaded, total_bytes)
191
+
192
+ console.print(f"[green]Saved:[/green] {target_file}")
193
+ return target_file
194
+
195
+
196
+ def _is_r2_unavailable(url: str, headers: dict[str, str] | None = None) -> bool:
197
+ if ".r2.cloudflarestorage.com" not in url:
198
+ return False
199
+ try:
200
+ probe = requests.get(
201
+ url,
202
+ headers={**DEFAULT_HEADERS, **(headers or {}), "Range": "bytes=0-1023"},
203
+ timeout=5,
204
+ stream=True,
205
+ allow_redirects=True,
206
+ )
207
+ try:
208
+ sample = next(probe.iter_content(chunk_size=1024), b"")
209
+ finally:
210
+ probe.close()
211
+ txt = sample.decode("utf-8", errors="ignore")
212
+ return "NotEntitled" in txt or "Please enable R2" in txt
213
+ except requests.RequestException:
214
+ return False
215
+
216
+
217
+ def download_all_episodes(
218
+ client: Any,
219
+ episodes: list[dict[str, Any]],
220
+ *,
221
+ output_dir: str | Path | None = None,
222
+ series_title: str = "",
223
+ media_type: str = "series",
224
+ progress_callback: Callable[[int, int, str, int, int | None], None] | None = None,
225
+ ) -> tuple[list[Path], list[tuple[str, str]]]:
226
+ """Download all episodes in a list, returning (saved_paths, failures)."""
227
+ base_dir = Path(output_dir).expanduser() if output_dir else get_default_download_dir()
228
+ if series_title:
229
+ base_dir = base_dir / _sanitize_filename(series_title)
230
+ base_dir.mkdir(parents=True, exist_ok=True)
231
+
232
+ saved: list[Path] = []
233
+ failures: list[tuple[str, str]] = []
234
+ total_eps = len(episodes)
235
+
236
+ for idx, ep in enumerate(episodes, start=1):
237
+ ep_title = ep.get("title") or f"Episode {idx}"
238
+ ep_name = f"{series_title} - {ep_title}" if series_title else ep_title
239
+ try:
240
+ streams = client.get_stream(ep["link"], is_download=True, media_type=media_type) or []
241
+ if not streams:
242
+ failures.append((ep_title, "No streams found"))
243
+ continue
244
+
245
+ chosen = None
246
+ for cand in streams:
247
+ if not _is_r2_unavailable(cand["link"], cand.get("headers")):
248
+ chosen = cand
249
+ break
250
+ if chosen is None:
251
+ failures.append((ep_title, "All streams unavailable"))
252
+ continue
253
+
254
+ def _cb(done: int, total: int | None, _i: int = idx, _t: str = ep_title) -> None:
255
+ if progress_callback:
256
+ progress_callback(_i, total_eps, _t, done, total)
257
+
258
+ path = download_stream(
259
+ chosen["link"],
260
+ output=base_dir,
261
+ title=ep_name,
262
+ headers=chosen.get("headers"),
263
+ resume=True,
264
+ progress_callback=_cb if progress_callback else None,
265
+ )
266
+ saved.append(path)
267
+ except Exception as exc:
268
+ failures.append((ep_title, str(exc)))
269
+
270
+ return saved, failures
271
+
272
+
273
+ def _is_r2_unavailable(url: str, headers: dict[str, str] | None = None) -> bool:
274
+ if ".r2.cloudflarestorage.com" not in url:
275
+ return False
276
+ try:
277
+ probe = requests.get(
278
+ url,
279
+ headers={**DEFAULT_HEADERS, **(headers or {}), "Range": "bytes=0-1023"},
280
+ timeout=5,
281
+ stream=True,
282
+ allow_redirects=True,
283
+ )
284
+ try:
285
+ sample = next(probe.iter_content(chunk_size=1024), b"")
286
+ finally:
287
+ probe.close()
288
+ txt = sample.decode("utf-8", errors="ignore")
289
+ return "NotEntitled" in txt or "Please enable R2" in txt
290
+ except requests.RequestException:
291
+ return False
292
+
293
+
294
+ def download_all_episodes(
295
+ client: Any,
296
+ episodes: list[dict[str, Any]],
297
+ *,
298
+ output_dir: str | Path | None = None,
299
+ series_title: str = "",
300
+ media_type: str = "series",
301
+ progress_callback: Callable[[int, int, str, int, int | None], None] | None = None,
302
+ ) -> tuple[list[Path], list[tuple[str, str]]]:
303
+ """Download all episodes in a list, returning (saved_paths, failures)."""
304
+ base_dir = Path(output_dir).expanduser() if output_dir else get_default_download_dir()
305
+ if series_title:
306
+ base_dir = base_dir / _sanitize_filename(series_title)
307
+ base_dir.mkdir(parents=True, exist_ok=True)
308
+
309
+ saved: list[Path] = []
310
+ failures: list[tuple[str, str]] = []
311
+ total_eps = len(episodes)
312
+
313
+ for idx, ep in enumerate(episodes, start=1):
314
+ ep_title = ep.get("title") or f"Episode {idx}"
315
+ ep_name = f"{series_title} - {ep_title}" if series_title else ep_title
316
+ try:
317
+ streams = client.get_stream(ep["link"], is_download=True, media_type=media_type) or []
318
+ if not streams:
319
+ failures.append((ep_title, "No streams found"))
320
+ continue
321
+
322
+ chosen = None
323
+ for cand in streams:
324
+ if not _is_r2_unavailable(cand["link"], cand.get("headers")):
325
+ chosen = cand
326
+ break
327
+ if chosen is None:
328
+ failures.append((ep_title, "All streams unavailable"))
329
+ continue
330
+
331
+ def _cb(done: int, total: int | None, _i: int = idx, _t: str = ep_title) -> None:
332
+ if progress_callback:
333
+ progress_callback(_i, total_eps, _t, done, total)
334
+
335
+ path = download_stream(
336
+ chosen["link"],
337
+ output=base_dir,
338
+ title=ep_name,
339
+ headers=chosen.get("headers"),
340
+ resume=True,
341
+ progress_callback=_cb if progress_callback else None,
342
+ )
343
+ saved.append(path)
344
+ except Exception as exc:
345
+ failures.append((ep_title, str(exc)))
346
+
347
+ return saved, failures