northtracks 1.0.0__py3-none-any.whl

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.
musicdl/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
musicdl/cli.py ADDED
@@ -0,0 +1,241 @@
1
+ import os
2
+ import sys
3
+ from pathlib import Path
4
+ from rich.console import Console
5
+ from rich.table import Table
6
+ from rich import box
7
+
8
+ from prompt_toolkit import prompt
9
+ from prompt_toolkit.formatted_text import HTML
10
+
11
+ from musicdl.config import (
12
+ load_config,
13
+ get_download_dir,
14
+ set_download_dir
15
+ )
16
+ from musicdl.spotify import is_spotify_url, extract_spotify_entity
17
+ from musicdl.youtube import is_youtube_url, fetch_youtube_audio_stream
18
+ from musicdl.downloader import download_track, download_batch_tracks
19
+ from musicdl.fixer import scan_music_files, repair_single_file
20
+ from musicdl.logger import log_info, log_error
21
+
22
+ console = Console()
23
+
24
+ def clear_screen():
25
+ os.system("cls" if os.name == "nt" else "clear")
26
+
27
+ def get_library_stats(dest: Path):
28
+ if not dest.exists():
29
+ return 0, 0.0
30
+ files = [f for f in dest.rglob("*.*") if f.is_file() and f.suffix.lower() in [".m4a", ".mp3", ".webm", ".flac"]]
31
+ total_bytes = sum(f.stat().st_size for f in files)
32
+ return len(files), total_bytes / (1024 * 1024)
33
+
34
+ def print_header(dest: Path):
35
+ total_tracks, total_mb = get_library_stats(dest)
36
+ console.print()
37
+ console.print(" [bold white]North Tracks[/bold white] [dim]• 320k Studio Downloader[/dim]")
38
+ console.print(f" [dim]{dest} ({total_tracks} tracks • {total_mb:.1f} MB)[/dim]")
39
+ console.print()
40
+
41
+ def handle_input(query: str, dest_dir: Path):
42
+ target = query.strip()
43
+ if not target or target.lower() == "b":
44
+ return
45
+
46
+ # Command handlers
47
+ cmd = target.lower()
48
+ if cmd in [":dest", ":folder", ":d"]:
49
+ screen_change_destination()
50
+ return
51
+ elif cmd in [":stats", ":library", ":s"]:
52
+ screen_library_stats()
53
+ return
54
+ elif cmd in [":repair", ":fix", ":r"]:
55
+ screen_repair()
56
+ return
57
+ elif cmd in [":exit", ":quit", ":q"]:
58
+ console.print("\n [cyan]♪ North Tracks closed.[/cyan]\n")
59
+ sys.exit(0)
60
+
61
+ # 1. Spotify Link
62
+ if is_spotify_url(target):
63
+ console.print("\n [cyan]●[/cyan] Resolving Spotify metadata...")
64
+ entity = extract_spotify_entity(target)
65
+ if not entity:
66
+ console.print(" [red]✕ Failed to resolve Spotify link.[/red]")
67
+ return
68
+
69
+ tracks = entity.get("tracks", [])
70
+ if not tracks:
71
+ console.print(" [red]✕ No playable tracks found in Spotify link.[/red]")
72
+ return
73
+ is_collection = entity.get("type") in ["playlist", "album"]
74
+ pl_name = entity.get("title") if is_collection else ""
75
+
76
+ if len(tracks) > 1:
77
+ batch_result = download_batch_tracks(tracks, dest_dir=dest_dir, playlist_title=pl_name)
78
+ while batch_result.get("failed"):
79
+ failed_tracks = batch_result["failed"]
80
+ console.print(f" [red]✕ {len(failed_tracks)} track(s) failed.[/red] [dim]Press 'r' to retry, or Enter to continue[/dim]")
81
+ retry_choice = input(" Action › ").strip().lower()
82
+ if retry_choice == "r":
83
+ batch_result = download_batch_tracks(failed_tracks, dest_dir=dest_dir, playlist_title=pl_name)
84
+ else:
85
+ break
86
+ elif len(tracks) == 1:
87
+ console.print(" " + "─" * 74)
88
+ download_track(tracks[0], dest_dir=dest_dir, track_idx="01/01")
89
+ console.print(" " + "─" * 74 + "\n")
90
+
91
+ # 2. YouTube Link
92
+ elif is_youtube_url(target):
93
+ console.print("\n [cyan]●[/cyan] Resolving YouTube audio stream via InnerTube...")
94
+ yt_data = fetch_youtube_audio_stream(target)
95
+ if not yt_data:
96
+ console.print(" [red]✕ Could not fetch YouTube audio.[/red]")
97
+ return
98
+ console.print(" " + "─" * 74)
99
+ download_track(yt_data, dest_dir=dest_dir, track_idx="01/01")
100
+ console.print(" " + "─" * 74 + "\n")
101
+
102
+ # 3. Direct Song Title Search
103
+ else:
104
+ console.print(f"\n [cyan]●[/cyan] Searching studio catalog for: [bold white]{target}[/]")
105
+ console.print(" " + "─" * 74)
106
+ download_track({"title": target, "artist": ""}, dest_dir=dest_dir, track_idx="01/01")
107
+ console.print(" " + "─" * 74 + "\n")
108
+
109
+ def screen_change_destination():
110
+ dest = get_download_dir()
111
+ console.print(f"\n [bold white]Current Storage:[/] [dim]{dest}[/dim]")
112
+ console.print(" [dim]Enter new folder path (or press Enter / 'b' to cancel):[/dim]")
113
+ new_path = input(" New Path › ").strip()
114
+ if new_path and new_path.lower() != "b":
115
+ updated = set_download_dir(new_path)
116
+ console.print(f" [green]✓ Storage updated to:[/] {updated}\n")
117
+
118
+ def screen_library_stats():
119
+ dest = get_download_dir()
120
+ subdirs = [d for d in dest.iterdir() if d.is_dir() and not d.name.startswith(".")] if dest.exists() else []
121
+ total_tracks, total_mb = get_library_stats(dest)
122
+
123
+ console.print(f"\n [bold white]Library Categories[/bold white] [dim]({total_tracks} tracks • {total_mb:.1f} MB on disk)[/dim]")
124
+ console.print(" " + "─" * 74)
125
+
126
+ tbl = Table(box=box.SIMPLE, show_header=True, padding=(0, 2))
127
+ tbl.add_column("Category", style="bold white")
128
+ tbl.add_column("Tracks", justify="right", style="cyan")
129
+ tbl.add_column("Size", justify="right", style="dim")
130
+ tbl.add_column("Sample Artists", style="dim")
131
+
132
+ for d in sorted(subdirs):
133
+ tracks = list(d.glob("*.m4a")) + list(d.glob("*.mp3")) + list(d.glob("*.webm"))
134
+ dir_mb = sum(t.stat().st_size for t in tracks) / (1024 * 1024)
135
+ artists = []
136
+ for t in tracks[:3]:
137
+ parts = t.stem.split(" - ")
138
+ if len(parts) > 1:
139
+ artists.append(parts[0])
140
+ sample_str = ", ".join(list(dict.fromkeys(artists)))
141
+ tbl.add_row(d.name, str(len(tracks)), f"{dir_mb:.1f} MB", sample_str)
142
+
143
+ console.print(tbl)
144
+ console.print(" " + "─" * 74 + "\n")
145
+
146
+ def screen_repair():
147
+ dest = get_download_dir()
148
+ console.print(f"\n [bold white]Library Repair & Dual Artwork Verification[/bold white]")
149
+ console.print(f" [dim]Default scan location: {dest}[/dim]")
150
+ console.print(" [dim]Enter folder path to scan (or press Enter for default / 'b' to cancel):[/dim]")
151
+ custom_dir = input(" Scan Path › ").strip()
152
+
153
+ if custom_dir.lower() == "b":
154
+ return
155
+
156
+ scan_dir = Path(custom_dir).resolve() if custom_dir else dest
157
+ if not scan_dir.exists() or not scan_dir.is_dir():
158
+ console.print(f" [red]✕ Directory not found:[/] {scan_dir}\n")
159
+ return
160
+
161
+ scanned = scan_music_files(scan_dir)
162
+ if not scanned:
163
+ console.print(" [yellow]No music files found in directory.[/yellow]\n")
164
+ return
165
+
166
+ console.print(" " + "─" * 74)
167
+ tbl = Table(box=box.SIMPLE, show_header=True, padding=(0, 2))
168
+ tbl.add_column("#", justify="right", style="dim", width=3)
169
+ tbl.add_column("File Name", style="bold white")
170
+ tbl.add_column("Artwork", justify="center")
171
+ tbl.add_column("Folder", style="dim")
172
+ tbl.add_column("Clean Short Name", style="cyan")
173
+
174
+ for idx, t in enumerate(scanned, 1):
175
+ art_status = "[green]✓ HD[/green]" if t["has_art"] else "[red]✕ Broken[/red]"
176
+ tbl.add_row(str(idx), t["filename"][:26], art_status, t["current_folder"][:14], t["suggested_name"][:26])
177
+
178
+ console.print(tbl)
179
+ console.print(" " + "─" * 74)
180
+ console.print(" [dim]Options: [bold white]A[/bold white] (Fix All) • [cyan]1, 3, 5-8[/cyan] (Select) • [bold white]b[/bold white] (Cancel)[/dim]")
181
+ choice = input(" Choice › ").strip().upper()
182
+
183
+ if choice in ["B", "C", "CANCEL", ""]:
184
+ return
185
+
186
+ to_repair = []
187
+ if choice in ["A", "ALL"]:
188
+ to_repair = scanned
189
+ else:
190
+ selected_indices = set()
191
+ for chunk in choice.split(","):
192
+ chunk = chunk.strip()
193
+ if "-" in chunk:
194
+ parts = chunk.split("-")
195
+ try:
196
+ start, end = int(parts[0]), int(parts[1])
197
+ selected_indices.update(range(start, end + 1))
198
+ except ValueError:
199
+ pass
200
+ else:
201
+ try:
202
+ selected_indices.add(int(chunk))
203
+ except ValueError:
204
+ pass
205
+ to_repair = [scanned[i - 1] for i in selected_indices if 1 <= i <= len(scanned)]
206
+
207
+ if not to_repair:
208
+ console.print(" [red]✕ No valid tracks selected.[/red]\n")
209
+ return
210
+
211
+ console.print(f"\n [cyan]● Repairing {len(to_repair)} track(s)...[/cyan]")
212
+ for item in to_repair:
213
+ res = repair_single_file(item, dest)
214
+ if res:
215
+ console.print(f" [green]✓[/green] {res['new_name'][:36]:<36} [dim]• {res['new_category']} • Art: {res['art_source']}[/dim]")
216
+
217
+ console.print(f" [green]Done.[/green] [dim]{len(to_repair)} track(s) repaired and verified.[/dim]\n")
218
+
219
+ def main():
220
+ while True:
221
+ try:
222
+ dest = get_download_dir()
223
+ print_header(dest)
224
+ console.print(" [dim]› Paste Spotify/YouTube link, song name, or command (:repair, :dest, :stats, :exit):[/dim]")
225
+
226
+ raw_input = input(" › ").strip()
227
+
228
+ if not raw_input:
229
+ continue
230
+
231
+ handle_input(raw_input, dest)
232
+
233
+ except KeyboardInterrupt:
234
+ console.print("\n\n [cyan]♪ North Tracks closed.[/cyan]\n")
235
+ sys.exit(0)
236
+ except Exception as e:
237
+ log_error("Unhandled CLI exception", e)
238
+ console.print(f"\n [red]✕ Error:[/] {e} [dim](details in northtracks.log)[/dim]\n")
239
+
240
+ if __name__ == "__main__":
241
+ main()
musicdl/config.py ADDED
@@ -0,0 +1,80 @@
1
+ import os
2
+ import json
3
+ from pathlib import Path
4
+ from datetime import datetime
5
+ from musicdl.logger import log_info, log_error
6
+
7
+ LOCAL_ROOT = Path(__file__).resolve().parent.parent
8
+ if (LOCAL_ROOT / "app.py").exists():
9
+ CONFIG_FILE = LOCAL_ROOT / "config.json"
10
+ DEFAULT_DOWNLOAD_DIR = LOCAL_ROOT / "downloads"
11
+ else:
12
+ USER_DIR = Path.home() / ".northtracks"
13
+ USER_DIR.mkdir(parents=True, exist_ok=True)
14
+ CONFIG_FILE = USER_DIR / "config.json"
15
+ DEFAULT_DOWNLOAD_DIR = Path.home() / "Music" / "NorthTracks"
16
+
17
+ DEFAULT_CONFIG = {
18
+ "download_dir": str(DEFAULT_DOWNLOAD_DIR),
19
+ "preferred_bitrate": "320kbps",
20
+ "naming_style": "short", # "short" (Lead Artist - Title), "title_only", "full"
21
+ "create_m3u": True, # Generates .m3u companion for playlists
22
+ "embed_lyrics": True, # Synchronized / plain lyrics
23
+ "skip_duplicates": True, # Prevents downloading existing songs
24
+ "total_downloads": 0
25
+ }
26
+
27
+ def load_config() -> dict:
28
+ if CONFIG_FILE.exists():
29
+ try:
30
+ with open(CONFIG_FILE, "r", encoding="utf-8") as f:
31
+ data = json.load(f)
32
+ return {**DEFAULT_CONFIG, **data}
33
+ except Exception as e:
34
+ log_error("Failed to read config.json, restoring defaults", e)
35
+ save_config(DEFAULT_CONFIG)
36
+ return DEFAULT_CONFIG.copy()
37
+
38
+ def save_config(cfg: dict):
39
+ try:
40
+ with open(CONFIG_FILE, "w", encoding="utf-8") as f:
41
+ json.dump(cfg, f, indent=4)
42
+ except Exception as e:
43
+ log_error("Failed to save config.json", e)
44
+
45
+ def get_download_dir() -> Path:
46
+ cfg = load_config()
47
+ p = Path(cfg.get("download_dir", DEFAULT_DOWNLOAD_DIR))
48
+ p.mkdir(parents=True, exist_ok=True)
49
+ return p
50
+
51
+ def set_download_dir(new_path: str) -> Path:
52
+ p = Path(new_path).resolve()
53
+ p.mkdir(parents=True, exist_ok=True)
54
+ cfg = load_config()
55
+ cfg["download_dir"] = str(p)
56
+ save_config(cfg)
57
+ log_info(f"Download directory changed to: {p}")
58
+ return p
59
+
60
+ def set_config_value(key: str, val):
61
+ cfg = load_config()
62
+ cfg[key] = val
63
+ save_config(cfg)
64
+ log_info(f"Config updated: {key} = {val}")
65
+
66
+ def increment_download_count():
67
+ cfg = load_config()
68
+ cfg["total_downloads"] = cfg.get("total_downloads", 0) + 1
69
+ save_config(cfg)
70
+
71
+ def get_greeting() -> str:
72
+ hour = datetime.now().hour
73
+ if 5 <= hour < 12:
74
+ return "Good morning"
75
+ elif 12 <= hour < 17:
76
+ return "Good afternoon"
77
+ elif 17 <= hour < 22:
78
+ return "Good evening"
79
+ else:
80
+ return "Good night"
musicdl/downloader.py ADDED
@@ -0,0 +1,333 @@
1
+ from pathlib import Path
2
+ import os
3
+ import sys
4
+ import shutil
5
+ import time
6
+ import requests
7
+ from rich.console import Console
8
+
9
+ from musicdl.normalizer import (
10
+ clean_filename, clean_short_filename, normalize_genre,
11
+ clean_search_query, find_library_duplicate
12
+ )
13
+ from musicdl.saavn import search_track
14
+ from musicdl.youtube import search_youtube_audio
15
+ from musicdl.itunes import search_itunes
16
+ from musicdl.tagger import tag_file, fetch_artwork_bytes
17
+ from musicdl.lyrics import fetch_lyrics
18
+ from musicdl.config import get_download_dir, increment_download_count, load_config
19
+ from musicdl.logger import log_info, log_error, log_warning
20
+
21
+ console = Console()
22
+ HEADERS = {
23
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
24
+ }
25
+
26
+ def resolve_audio_stream(track_info: dict, context: str = "") -> dict:
27
+ title = track_info.get("title", "")
28
+ artist = track_info.get("artist", "")
29
+ search_q = f"{clean_search_query(title)} {clean_search_query(artist)}".strip()
30
+
31
+ # 1. Fetch iTunes metadata
32
+ itunes_meta = search_itunes(clean_search_query(title), clean_search_query(artist))
33
+
34
+ # 2. Try JioSaavn 320k Studio
35
+ resolved = search_track(search_q)
36
+ if not resolved and clean_search_query(title) != search_q:
37
+ resolved = search_track(clean_search_query(title))
38
+
39
+ # 3. Fallback: YouTube Innertube
40
+ if not resolved or not resolved.get("stream_url"):
41
+ yt_res = search_youtube_audio(search_q)
42
+ if yt_res and yt_res.get("stream_url"):
43
+ resolved = yt_res
44
+
45
+ if not resolved:
46
+ log_warning(f"Could not resolve audio stream for: {artist} - {title}")
47
+ return None
48
+
49
+ resolved["title"] = title or resolved.get("title", "Unknown Title")
50
+ resolved["artist"] = artist or resolved.get("artist", "Unknown Artist")
51
+
52
+ if itunes_meta and itunes_meta.get("artwork_url"):
53
+ resolved["artwork_url"] = itunes_meta["artwork_url"]
54
+ resolved["art_source_label"] = "Apple iTunes HD (600k)"
55
+ elif resolved.get("artwork_url"):
56
+ resolved["art_source_label"] = "JioSaavn CDN (500k)"
57
+ elif track_info.get("artwork_url"):
58
+ resolved["artwork_url"] = track_info["artwork_url"]
59
+ resolved["art_source_label"] = "Web Thumbnail"
60
+ else:
61
+ resolved["art_source_label"] = "None"
62
+
63
+ if itunes_meta:
64
+ if itunes_meta.get("album") and not track_info.get("album"):
65
+ resolved["album"] = itunes_meta["album"]
66
+ if itunes_meta.get("release_date"):
67
+ resolved["year"] = itunes_meta["release_date"]
68
+ raw_genre = itunes_meta.get("genre", "")
69
+ else:
70
+ raw_genre = track_info.get("genre") or resolved.get("genre", "")
71
+
72
+ resolved["genre"] = normalize_genre(
73
+ raw_genre=raw_genre,
74
+ artist=resolved["artist"],
75
+ title=resolved["title"],
76
+ context=context or track_info.get("album", "")
77
+ )
78
+
79
+ return resolved
80
+
81
+ def download_track(
82
+ track_info: dict,
83
+ dest_dir: Path = None,
84
+ playlist_name: str = None,
85
+ track_idx: str = "01/01",
86
+ show_header: bool = False
87
+ ) -> dict:
88
+ if not dest_dir:
89
+ dest_dir = get_download_dir()
90
+
91
+ cfg = load_config()
92
+ raw_title = track_info.get("title", "Unknown")
93
+ raw_artist = track_info.get("artist", "")
94
+
95
+ # Duplicate Check
96
+ if cfg.get("skip_duplicates", True):
97
+ existing = find_library_duplicate(raw_artist, raw_title, dest_dir)
98
+ if existing:
99
+ cat_name = existing.parent.name
100
+ display_name = f"{clean_short_filename(raw_artist, raw_title).replace(existing.suffix, '')}"
101
+ console.print(f" [{track_idx}] [dim]⏩ {display_name:<40} Already in {cat_name}[/dim]")
102
+ log_info(f"Duplicate skipped: {raw_title} (Exists at: {existing})")
103
+ return {
104
+ "status": "skipped",
105
+ "file": existing,
106
+ "title": raw_title,
107
+ "artist": raw_artist,
108
+ "genre": cat_name
109
+ }
110
+
111
+ # Resolve Stream
112
+ context = playlist_name or track_info.get("album", "")
113
+ resolved = resolve_audio_stream(track_info, context=context)
114
+
115
+ if not resolved or not resolved.get("stream_url"):
116
+ display_name = f"{raw_artist} — {raw_title}" if raw_artist else raw_title
117
+ console.print(f" [{track_idx}] [red]✕ {display_name:<40} Stream not found[/red]")
118
+ return {
119
+ "status": "failed",
120
+ "title": raw_title,
121
+ "artist": raw_artist,
122
+ "track_info": track_info,
123
+ "error": "Stream not found"
124
+ }
125
+
126
+ title = resolved.get("title") or raw_title
127
+ artist = resolved.get("artist") or raw_artist
128
+ genre = resolved.get("genre", "Pop")
129
+
130
+ ext = ".webm" if resolved.get("is_webm") else ".m4a"
131
+ file_name = clean_short_filename(artist, title, ext=ext)
132
+
133
+ target_folder = dest_dir / genre
134
+ target_folder.mkdir(parents=True, exist_ok=True)
135
+ out_file = target_folder / file_name
136
+ part_file = target_folder / f"{file_name}.part"
137
+
138
+ # Display format: LeadArtist — Title
139
+ display_name = file_name.replace(ext, "").replace(" - ", " — ")
140
+
141
+ # Resume support
142
+ req_headers = dict(HEADERS)
143
+ existing_bytes = 0
144
+ mode = "wb"
145
+
146
+ if part_file.exists() and part_file.stat().st_size > 0:
147
+ existing_bytes = part_file.stat().st_size
148
+ req_headers["Range"] = f"bytes={existing_bytes}-"
149
+ mode = "ab"
150
+ log_info(f"Resuming download for {file_name} from byte {existing_bytes}")
151
+
152
+ try:
153
+ start_time = time.time()
154
+ resp = requests.get(resolved["stream_url"], headers=req_headers, stream=True, timeout=15)
155
+
156
+ if resp.status_code == 416 or (resp.status_code == 200 and mode == "ab"):
157
+ mode = "wb"
158
+ existing_bytes = 0
159
+ resp = requests.get(resolved["stream_url"], headers=HEADERS, stream=True, timeout=15)
160
+
161
+ resp.raise_for_status()
162
+ content_len = int(resp.headers.get("content-length", 0))
163
+ total_size = content_len + existing_bytes if resp.status_code == 206 else content_len
164
+ downloaded = existing_bytes
165
+
166
+ # In-place single-line progress updater (ZERO screen sliding/jitter)
167
+ with open(part_file, mode) as f:
168
+ last_update = time.time()
169
+ for chunk in resp.iter_content(chunk_size=16384):
170
+ if chunk:
171
+ f.write(chunk)
172
+ downloaded += len(chunk)
173
+ now = time.time()
174
+ if now - last_update > 0.08:
175
+ last_update = now
176
+ elapsed = now - start_time
177
+ speed_mb = (downloaded - existing_bytes) / (1024 * 1024) / max(elapsed, 0.001)
178
+ pct = int((downloaded / total_size) * 100) if total_size > 0 else 0
179
+ bar_blocks = "█" * (pct // 10) + "░" * (10 - (pct // 10))
180
+ line_str = f"\r [{track_idx}] ↓ {display_name[:36]:<36} [{bar_blocks}] {pct:2d}% • {speed_mb:.1f} MB/s"
181
+ sys.stdout.write(line_str)
182
+ sys.stdout.flush()
183
+
184
+ # Sanity check
185
+ if not part_file.exists() or part_file.stat().st_size < 300000:
186
+ if part_file.exists():
187
+ part_file.unlink()
188
+ raise ValueError("Downloaded file truncated or below 300KB")
189
+
190
+ # Atomic Rename from .part
191
+ if out_file.exists():
192
+ out_file.unlink()
193
+ shutil.move(str(part_file), str(out_file))
194
+
195
+ # Lyrics (optional)
196
+ if cfg.get("embed_lyrics", True):
197
+ duration_sec = resolved.get("duration", 0)
198
+ lyrics_text = fetch_lyrics(title, artist, duration=duration_sec)
199
+ if lyrics_text:
200
+ resolved["lyrics"] = lyrics_text
201
+
202
+ # Embed Artwork & Metadata Tags
203
+ art_bytes = fetch_artwork_bytes(resolved.get("artwork_url"))
204
+ tag_file(out_file, resolved, art_bytes)
205
+ increment_download_count()
206
+
207
+ final_mb = out_file.stat().st_size / (1024 * 1024)
208
+
209
+ # Clear the live line and print the permanent completed record
210
+ sys.stdout.write("\r" + " " * 95 + "\r")
211
+ sys.stdout.flush()
212
+ console.print(f" [{track_idx}] [green]✓[/green] {display_name[:36]:<36} [bold white]320k[/] • [cyan]{genre}[/] [dim]({final_mb:.1f} MB)[/dim]")
213
+
214
+ log_info(f"Downloaded and verified: {out_file.name}")
215
+ return {
216
+ "status": "success",
217
+ "file": out_file,
218
+ "title": title,
219
+ "artist": artist,
220
+ "genre": genre,
221
+ "filename": file_name,
222
+ "size_mb": final_mb
223
+ }
224
+
225
+ except KeyboardInterrupt:
226
+ if part_file.exists():
227
+ try:
228
+ part_file.unlink()
229
+ except Exception:
230
+ pass
231
+ sys.stdout.write("\r" + " " * 95 + "\r")
232
+ sys.stdout.flush()
233
+ raise
234
+
235
+ except Exception as e:
236
+ log_error(f"Download failed for {raw_title}", e)
237
+ sys.stdout.write("\r" + " " * 95 + "\r")
238
+ sys.stdout.flush()
239
+ display_name = file_name.replace(ext, "").replace(" - ", " — ")
240
+ console.print(f" [{track_idx}] [red]✕ {display_name[:36]:<36} {e}[/red]")
241
+ return {
242
+ "status": "failed",
243
+ "title": raw_title,
244
+ "artist": raw_artist,
245
+ "track_info": track_info,
246
+ "error": str(e)
247
+ }
248
+
249
+ def generate_m3u_playlist(playlist_name: str, saved_files: list, dest_dir: Path):
250
+ try:
251
+ pl_dir = dest_dir / "Playlists"
252
+ pl_dir.mkdir(parents=True, exist_ok=True)
253
+ clean_pl_name = clean_filename(playlist_name)
254
+ m3u_file = pl_dir / f"{clean_pl_name}.m3u"
255
+
256
+ with open(m3u_file, "w", encoding="utf-8") as f:
257
+ f.write("#EXTM3U\n")
258
+ for item in saved_files:
259
+ f_path = item.get("file")
260
+ if f_path and f_path.exists():
261
+ try:
262
+ rel_path = os.path.relpath(f_path, pl_dir)
263
+ except ValueError:
264
+ rel_path = str(f_path)
265
+ f.write(f"#EXTINF:-1,{item.get('artist', '')} - {item.get('title', '')}\n")
266
+ f.write(f"{rel_path}\n")
267
+
268
+ log_info(f"Generated companion playlist: {m3u_file}")
269
+ return m3u_file
270
+ except Exception as e:
271
+ log_error(f"Failed to generate M3U for {playlist_name}", e)
272
+ return None
273
+
274
+ def download_batch_tracks(tracks: list, dest_dir: Path = None, playlist_title: str = None) -> dict:
275
+ if not dest_dir:
276
+ dest_dir = get_download_dir()
277
+
278
+ total = len(tracks)
279
+ console.print(f"\n [cyan]●[/cyan] Resolving: [bold white]{playlist_title or 'Collection'}[/] [dim]({total} tracks detected)[/dim]")
280
+ console.print(" " + "─" * 74)
281
+
282
+ saved = []
283
+ skipped = []
284
+ failed = []
285
+ start_batch_time = time.time()
286
+
287
+ try:
288
+ for idx, track_item in enumerate(tracks, 1):
289
+ idx_str = f"{idx:02d}/{total:02d}"
290
+ res = download_track(
291
+ track_item,
292
+ dest_dir=dest_dir,
293
+ playlist_name=playlist_title,
294
+ track_idx=idx_str
295
+ )
296
+ if res:
297
+ if res.get("status") == "success":
298
+ saved.append(res)
299
+ elif res.get("status") == "skipped":
300
+ skipped.append(res)
301
+ else:
302
+ failed.append(track_item)
303
+ else:
304
+ failed.append(track_item)
305
+
306
+ except KeyboardInterrupt:
307
+ console.print("\n [yellow]⚠ Batch download paused cleanly (Ctrl+C).[/yellow]")
308
+
309
+ console.print(" " + "─" * 74)
310
+
311
+ # M3U Playlist Companion
312
+ if playlist_title and saved:
313
+ generate_m3u_playlist(playlist_title, saved + skipped, dest_dir)
314
+
315
+ total_time = max(time.time() - start_batch_time, 0.001)
316
+ total_saved_mb = sum(s.get("size_mb", 0) for s in saved)
317
+ avg_speed = total_saved_mb / total_time if total_saved_mb > 0 else 0
318
+
319
+ parts = [f"[green]{len(saved)} saved[/green]"]
320
+ if skipped:
321
+ parts.append(f"[dim]{len(skipped)} skipped[/dim]")
322
+ if failed:
323
+ parts.append(f"[red]{len(failed)} failed[/red]")
324
+
325
+ summary_str = " • ".join(parts)
326
+ speed_str = f"Avg {avg_speed:.1f} MB/s" if avg_speed > 0 else "Instant"
327
+ console.print(f" Completed: {summary_str} [dim]• {speed_str} • Category Routing: Done[/dim]\n")
328
+
329
+ return {
330
+ "saved": saved,
331
+ "skipped": skipped,
332
+ "failed": failed
333
+ }