-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgamdl_gui.py
More file actions
459 lines (378 loc) · 20.6 KB
/
gamdl_gui.py
File metadata and controls
459 lines (378 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import customtkinter as ctk
from tkinter import filedialog, messagebox
import subprocess
import threading
import sys
import os
import shutil
import json
import locale
import re
ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")
class GamdlGUI(ctk.CTk):
def __init__(self):
super().__init__()
self.config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
self.langs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "langs")
self.current_lang = self.load_config_lang()
self.lang_texts = {}
self.load_language(self.current_lang)
self.title(self.tr("app_title"))
self.geometry("850x650")
# main layout
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
# Sidebar
self.sidebar_frame = ctk.CTkFrame(self, width=220, corner_radius=0)
self.sidebar_frame.grid(row=0, column=0, rowspan=4, sticky="nsew")
self.sidebar_frame.grid_rowconfigure(10, weight=1)
self.logo_label = ctk.CTkLabel(self.sidebar_frame, text=self.tr("logo_text"), font=ctk.CTkFont(size=24, weight="bold"))
self.logo_label.grid(row=0, column=0, padx=20, pady=(20, 10))
# Cookie selection
self.cookie_label = ctk.CTkLabel(self.sidebar_frame, text=self.tr("cookie_label"))
self.cookie_label.grid(row=1, column=0, padx=20, pady=(10, 0), sticky="w")
self.cookie_btn = ctk.CTkButton(self.sidebar_frame, text=self.tr("cookie_btn"))
self.cookie_btn.grid(row=2, column=0, padx=20, pady=5)
self.cookie_btn.bind("<Button-1>", self.select_cookie)
default_cookie = os.path.join(os.path.expanduser("~"), ".gamdl", "cookies.txt")
if os.path.exists(default_cookie):
self.cookie_path = default_cookie
else:
self.cookie_path = ""
# Log level
self.log_level_label = ctk.CTkLabel(self.sidebar_frame, text=self.tr("log_level_label"))
self.log_level_label.grid(row=3, column=0, padx=20, pady=(10, 0), sticky="w")
self.log_level_var = ctk.StringVar(value="INFO")
self.log_level_menu = ctk.CTkOptionMenu(self.sidebar_frame, values=["DEBUG", "INFO", "WARNING", "ERROR"], variable=self.log_level_var)
self.log_level_menu.grid(row=4, column=0, padx=20, pady=5)
# Download Mode
self.dl_mode_label = ctk.CTkLabel(self.sidebar_frame, text=self.tr("dl_mode_label"))
self.dl_mode_label.grid(row=5, column=0, padx=20, pady=(10, 0), sticky="w")
self.dl_mode_var = ctk.StringVar(value="ytdlp")
self.dl_mode_menu = ctk.CTkOptionMenu(self.sidebar_frame, values=["ytdlp", "nm3u8dlre"], variable=self.dl_mode_var)
self.dl_mode_menu.grid(row=6, column=0, padx=20, pady=5)
# Language Selection
self.language_label = ctk.CTkLabel(self.sidebar_frame, text=self.tr("language_label"))
self.language_label.grid(row=7, column=0, padx=20, pady=(10, 0), sticky="w")
self.lang_map = {"English": "en", "中文": "zh"}
self.inv_lang_map = {"en": "English", "zh": "中文"}
self.language_var = ctk.StringVar(value=self.inv_lang_map.get(self.current_lang, "English"))
self.language_menu = ctk.CTkOptionMenu(self.sidebar_frame, values=["English", "中文"], variable=self.language_var, command=self.on_language_change)
self.language_menu.grid(row=8, column=0, padx=20, pady=5)
self.version_label = ctk.CTkLabel(self.sidebar_frame, text=self.tr("version_label"), text_color="gray", font=ctk.CTkFont(size=10))
self.version_label.grid(row=10, column=0, padx=20, pady=(0, 0), sticky="s")
# Action button
self.download_btn = ctk.CTkButton(self.sidebar_frame, text=self.tr("start_download_btn"), height=40)
self.download_btn.grid(row=11, column=0, padx=20, pady=(10, 20), sticky="s")
self.download_btn.bind("<Button-1>", self.start_download)
# Download status label
self.download_name_label = ctk.CTkLabel(self.sidebar_frame, text="", text_color="gray", font=ctk.CTkFont(size=11))
self.download_name_label.grid(row=12, column=0, padx=20, pady=(5, 0), sticky="ew")
self.download_name_label.grid_remove() # Hide initially
# Progress bar
self.progress_bar = ctk.CTkProgressBar(self.sidebar_frame, mode="indeterminate")
self.progress_bar.grid(row=13, column=0, padx=20, pady=(5, 20), sticky="ew")
self.progress_bar.set(0)
self.progress_bar.grid_remove() # Hide initially
# Stop Button
self.stop_btn = ctk.CTkButton(self.sidebar_frame, text=self.tr("stop_dl_btn"), fg_color="#FF5555", hover_color="#CC0000")
self.stop_btn.grid(row=14, column=0, padx=20, pady=(0, 20), sticky="ew")
self.stop_btn.bind("<Button-1>", self.stop_download)
self.stop_btn.grid_remove()
self.current_process = None
# Main content
self.main_frame = ctk.CTkFrame(self)
self.main_frame.grid(row=0, column=1, sticky="nsew", padx=10, pady=10)
self.main_frame.grid_columnconfigure(0, weight=1)
self.main_frame.grid_rowconfigure(8, weight=1)
# URL
self.url_label = ctk.CTkLabel(self.main_frame, text=self.tr("url_label"), font=ctk.CTkFont(weight="bold"))
self.url_label.grid(row=0, column=0, padx=20, pady=(10, 0), sticky="w")
self.url_textbox = ctk.CTkTextbox(self.main_frame, height=100)
self.url_textbox.grid(row=1, column=0, padx=20, pady=5, sticky="ew")
# Output directory
self.out_dir_frame = ctk.CTkFrame(self.main_frame, fg_color="transparent")
self.out_dir_frame.grid(row=2, column=0, padx=20, pady=5, sticky="ew")
self.out_dir_frame.grid_columnconfigure(1, weight=1)
self.out_dir_label = ctk.CTkLabel(self.out_dir_frame, text=self.tr("out_dir_label"))
self.out_dir_label.grid(row=0, column=0, padx=(0, 10), sticky="w")
self.out_dir_entry = ctk.CTkEntry(self.out_dir_frame, width=300)
# Default downloads folder
default_dl = os.path.join(os.path.expanduser("~"), "Downloads", "Apple Music")
self.out_dir_entry.insert(0, default_dl)
self.out_dir_entry.grid(row=0, column=1, sticky="ew")
self.out_dir_btn = ctk.CTkButton(self.out_dir_frame, text=self.tr("browse_btn"), width=80)
self.out_dir_btn.grid(row=0, column=2, padx=(10, 0))
self.out_dir_btn.bind("<Button-1>", self.select_out_dir)
# Settings frame
self.settings_frame = ctk.CTkFrame(self.main_frame)
self.settings_frame.grid(row=3, column=0, padx=20, pady=10, sticky="ew")
self.settings_frame.grid_columnconfigure((0, 1), weight=1)
# Options frame
self.opts_frame = ctk.CTkFrame(self.settings_frame, fg_color="transparent")
self.opts_frame.grid(row=0, column=0, columnspan=2, sticky="w", padx=10, pady=(10, 10))
# Save Cover checkbox
self.save_cover_var = ctk.BooleanVar(value=True)
self.save_cover_cb = ctk.CTkCheckBox(self.opts_frame, text=self.tr("save_cover_cb"), variable=self.save_cover_var)
self.save_cover_cb.grid(row=0, column=0, pady=5, sticky="w")
# Synced lyrics checkbox
self.synced_lyrics_var = ctk.BooleanVar(value=False)
self.synced_lyrics_cb = ctk.CTkCheckBox(self.opts_frame, text=self.tr("synced_lyrics_cb"), variable=self.synced_lyrics_var)
self.synced_lyrics_cb.grid(row=0, column=1, padx=20, pady=5, sticky="w")
# Console Output
self.console_header_frame = ctk.CTkFrame(self.main_frame, fg_color="transparent")
self.console_header_frame.grid(row=7, column=0, padx=20, pady=(10, 0), sticky="ew")
self.console_header_frame.grid_columnconfigure(0, weight=1)
self.console_label = ctk.CTkLabel(self.console_header_frame, text=self.tr("console_label"), font=ctk.CTkFont(weight="bold"))
self.console_label.grid(row=0, column=0, sticky="w")
self.clear_console_btn = ctk.CTkButton(self.console_header_frame, text=self.tr("clear_console_btn"), width=80)
self.clear_console_btn.grid(row=0, column=1, sticky="e")
self.clear_console_btn.bind("<Button-1>", self.clear_console)
self.console_textbox = ctk.CTkTextbox(self.main_frame, font=ctk.CTkFont(family="Courier", size=12))
self.console_textbox.grid(row=8, column=0, padx=20, pady=10, sticky="nsew")
self.console_textbox.configure(state="disabled")
# Configure ANSI colors for console
for i, color in zip(["30", "31", "32", "33", "34", "35", "36", "37"],
["gray", "#FF5555", "#50FA7B", "#F1FA8C", "#BD93F9", "#FF79C6", "#8BE9FD", "#F8F8F2"]):
self.console_textbox.tag_config(f"ansi_{i}", foreground=color)
for i, color in zip(["90", "91", "92", "93", "94", "95", "96", "97"],
["#6272A4", "#FF6E6E", "#69FF94", "#FFFFA5", "#D6ACFF", "#FF92DF", "#A4FFFF", "#FFFFFF"]):
self.console_textbox.tag_config(f"ansi_{i}", foreground=color)
self.current_ansi_tags = ()
def load_config_lang(self):
if os.path.exists(self.config_path):
try:
with open(self.config_path, "r", encoding="utf-8") as f:
config = json.load(f)
return config.get("language", "en")
except:
pass
# fallback to system language
try:
sys_lang, _ = locale.getdefaultlocale()
if sys_lang and sys_lang.startswith("zh"):
return "zh"
except:
pass
return "en"
def save_config_lang(self, lang_code):
try:
config = {}
if os.path.exists(self.config_path):
with open(self.config_path, "r", encoding="utf-8") as f:
config = json.load(f)
config["language"] = lang_code
with open(self.config_path, "w", encoding="utf-8") as f:
json.dump(config, f)
except Exception as e:
print(f"Failed to save language config: {e}")
def load_language(self, lang_code):
lang_file = os.path.join(self.langs_dir, f"{lang_code}.json")
if not os.path.exists(lang_file):
lang_file = os.path.join(self.langs_dir, "en.json")
if os.path.exists(lang_file):
try:
with open(lang_file, "r", encoding="utf-8") as f:
self.lang_texts = json.load(f)
except Exception as e:
print(f"Failed to load language file {lang_file}: {e}")
self.lang_texts = {}
else:
self.lang_texts = {}
def tr(self, key):
return self.lang_texts.get(key, key)
def on_language_change(self, choice):
lang_code = self.lang_map.get(choice, "en")
self.current_lang = lang_code
self.save_config_lang(lang_code)
self.load_language(lang_code)
self.update_ui_texts()
def update_ui_texts(self):
self.title(self.tr("app_title"))
self.logo_label.configure(text=self.tr("logo_text"))
self.cookie_label.configure(text=self.tr("cookie_label"))
# Only update if the button doesn't say "cookie.txt Saved" currently
if self.cookie_path:
self.cookie_btn.configure(text=self.tr("cookie_saved_btn_text"))
else:
self.cookie_btn.configure(text=self.tr("cookie_btn"))
self.log_level_label.configure(text=self.tr("log_level_label"))
self.dl_mode_label.configure(text=self.tr("dl_mode_label"))
self.language_label.configure(text=self.tr("language_label"))
self.version_label.configure(text=self.tr("version_label"))
self.download_btn.configure(text=self.tr("start_download_btn"))
self.url_label.configure(text=self.tr("url_label"))
self.out_dir_label.configure(text=self.tr("out_dir_label"))
self.out_dir_btn.configure(text=self.tr("browse_btn"))
self.save_cover_cb.configure(text=self.tr("save_cover_cb"))
self.synced_lyrics_cb.configure(text=self.tr("synced_lyrics_cb"))
self.console_label.configure(text=self.tr("console_label"))
self.clear_console_btn.configure(text=self.tr("clear_console_btn"))
self.stop_btn.configure(text=self.tr("stop_dl_btn"))
def select_cookie(self, event=None):
file_path = filedialog.askopenfilename(title=self.tr("select_cookie_title"), filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if file_path:
try:
gamdl_dir = os.path.join(os.path.expanduser("~"), ".gamdl")
os.makedirs(gamdl_dir, exist_ok=True)
dest_path = os.path.join(gamdl_dir, "cookies.txt")
if os.path.exists(dest_path):
os.remove(dest_path)
shutil.copy(file_path, dest_path)
self.cookie_path = dest_path
self.cookie_btn.configure(text=self.tr("cookie_saved_btn_text"))
self.log_console(self.tr("cookie_saved_log").format(dest_path))
except Exception as e:
messagebox.showerror(self.tr("error_title"), self.tr("cookie_error_msg").format(e))
def clear_console(self, event=None):
self.console_textbox.configure(state="normal")
self.console_textbox.delete("1.0", ctk.END)
self.console_textbox.configure(state="disabled")
def select_out_dir(self, event=None):
dir_path = filedialog.askdirectory(title=self.tr("select_out_dir_title"))
if dir_path:
self.out_dir_entry.delete(0, ctk.END)
self.out_dir_entry.insert(0, dir_path)
def log_console(self, text):
self.console_textbox.configure(state="normal")
ansi_regex = re.compile(r'(\x1b\[[0-9;]*[mK])')
parts = ansi_regex.split(text + "\n")
for part in parts:
if part.startswith('\x1b['):
# parse ansi sequence
code_str = part[2:-1].replace('K', 'm').strip('m')
codes = code_str.split(';')
for code in codes:
if code == '0' or code == '' or code == '39':
self.current_ansi_tags = ()
elif code in [str(i) for i in range(30, 38)] + [str(i) for i in range(90, 98)]:
self.current_ansi_tags = tuple(t for t in self.current_ansi_tags if not t.startswith('ansi_')) + (f"ansi_{code}",)
else:
if part:
if self.current_ansi_tags:
self.console_textbox.insert(ctk.END, part, tags=self.current_ansi_tags)
else:
self.console_textbox.insert(ctk.END, part)
self.console_textbox.see(ctk.END)
self.console_textbox.configure(state="disabled")
def start_download(self, event=None):
if self.download_btn.cget("state") == "disabled":
return
urls = self.url_textbox.get("1.0", ctk.END).strip().split('\n')
urls = [url.strip() for url in urls if url.strip()]
for url in urls:
if not url.startswith("https"):
messagebox.showerror(self.tr("error_title"), self.tr("invalid_url_error_msg"))
return
if not urls:
messagebox.showerror(self.tr("error_title"), self.tr("empty_url_error_msg"))
return
if not self.cookie_path and not os.path.exists(os.path.join(os.path.expanduser("~"), ".gamdl", "cookies.txt")):
messagebox.showerror(self.tr("error_title"), self.tr("missing_cookie_error_msg"))
return
cmd = ["gamdl"]
if self.cookie_path:
cmd.extend(["-c", self.cookie_path])
out_dir = self.out_dir_entry.get()
if out_dir:
cmd.extend(["-o", out_dir])
has_song = False
has_video = False
for url in urls:
if '/music-video/' in url or '/post/' in url:
has_video = True
elif '/song/' in url or '/album/' in url or '/playlist/' in url or '/station/' in url:
has_song = True
# If neither is matched clearly, apply both just in case
if not has_song and not has_video:
has_song = True
has_video = True
cmd.extend(["--log-level", self.log_level_var.get()])
cmd.extend(["--download-mode", self.dl_mode_var.get()])
if has_song:
if self.save_cover_var.get():
cmd.append("--save-cover")
if self.synced_lyrics_var.get():
cmd.append("--no-synced-lyrics")
cmd.extend(urls)
self.log_console(self.tr("executing_log").format(' '.join(cmd)))
self.download_btn.configure(state="disabled")
self.progress_bar.grid()
self.progress_bar.configure(mode="indeterminate")
self.progress_bar.start()
self.download_name_label.configure(text="...")
self.download_name_label.grid()
self.stop_btn.grid()
threading.Thread(target=self.run_process, args=(cmd,), daemon=True).start()
def stop_download(self, event=None):
if self.current_process and self.current_process.poll() is None:
if messagebox.askyesno(self.tr("stop_dl_confirm_title"), self.tr("stop_dl_confirm_msg")):
try:
self.current_process.kill()
self.log_console(self.tr("dl_aborted_log"))
except Exception as e:
pass
def extract_download_name(self, line):
patterns = [
r'Downloading\s+[\'"]([^\'"]+)[\'"]',
r'Destination:\s*(.+)',
r'Task Start:\s*(.+)',
r'Saving to:\s*(.+)'
]
for p in patterns:
match = re.search(p, line, re.IGNORECASE)
if match:
name = match.group(1).strip()
return os.path.basename(name)
return None
def update_progress(self, line):
match = re.search(r'(\d+(?:\.\d+)?)\s*%', line)
if match:
try:
percent = float(match.group(1))
if self.progress_bar.cget("mode") == "indeterminate":
self.progress_bar.stop()
self.progress_bar.configure(mode="determinate")
self.progress_bar.set(percent / 100.0)
except ValueError:
pass
name = self.extract_download_name(line)
if name:
if len(name) > 25:
# Add a bit of safety for very long filenames
name = name[:22] + "..."
self.download_name_label.configure(text=name)
def run_process(self, cmd):
try:
# Run command unbuffered and force color
env = os.environ.copy()
env["FORCE_COLOR"] = "1"
env["CLICOLOR_FORCE"] = "1"
self.current_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, universal_newlines=True, env=env) # pyright: ignore
for line in iter(self.current_process.stdout.readline, ''): # pyright: ignore
line_str = line.strip()
self.after(0, self.log_console, line_str)
self.after(0, self.update_progress, line_str)
self.current_process.stdout.close() # pyright: ignore
return_code = self.current_process.wait()
if return_code == 0:
self.after(0, self.log_console, self.tr("success_log"))
elif return_code < 0 or return_code == 137 or return_code == 9:
pass
else:
self.after(0, self.log_console, self.tr("process_exit_log").format(return_code))
except FileNotFoundError:
self.after(0, self.log_console, self.tr("cmd_not_found_log"))
except Exception as e:
self.after(0, self.log_console, self.tr("launch_error_log").format(str(e)))
finally:
self.current_process = None
self.after(0, lambda: self.download_btn.configure(state="normal"))
self.after(0, lambda: self.progress_bar.stop())
self.after(0, lambda: self.progress_bar.grid_remove())
self.after(0, lambda: self.download_name_label.grid_remove())
self.after(0, lambda: self.stop_btn.grid_remove())
if __name__ == "__main__":
app = GamdlGUI()
app.mainloop()