-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
652 lines (564 loc) · 30.9 KB
/
Copy pathmain.py
File metadata and controls
652 lines (564 loc) · 30.9 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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
import sys
import os
import json
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import time
import importlib
from playwright.sync_api import sync_playwright
# Path fix
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.append(current_dir)
from config.config import config
from common.browser_factory import BrowserFactory
from pages.login_page import LoginPage
# Removed forced IM panel shutdown calls per user request
# Hint for PyInstaller: include dynamically-imported task modules.
# This block is never executed at runtime but ensures PyInstaller
# detects these imports during analysis so the `modules` package
# is bundled into the executable.
if False:
import modules.task1_group
import modules.task10_user
import modules.task11_ACL_user
import modules.task2_context
import modules.task3_perm
import modules.task4_sip_trunk
import modules.task5_custom_outbound
import modules.task5_outbound_routing
import modules.task6_inbound_routing
import modules.task7_caller_id_manipulation
import modules.task8_acl_group
import modules.task9_user_profile
class DeltapathAutomator:
def _set_window_icon(self):
icon_path = os.path.join(current_dir, "resources", "app.ico")
if os.path.exists(icon_path):
try:
self.root.iconbitmap(icon_path)
except Exception:
try:
icon = tk.PhotoImage(file=icon_path)
self.root.iconphoto(False, icon)
except Exception:
pass
def __init__(self):
self.root = tk.Tk()
self.root.title("AnderOng Deltapath Automation (CI/CD)")
self.root.geometry("950x850")
self._set_window_icon()
# Thread control
self.stop_event = threading.Event()
self.pause_event = threading.Event()
self.pause_event.set()
self.browser = None # Store browser instance for STOP button
self.page = None # Store page instance for cleanup
self.last_session = self._load_last_session()
# Task definitions
self.task_definitions = [
("Group", "task1_group", "run_group_task"),
("Context", "task2_context", "run_context_task"),
("Permission Group", "task3_perm", "run_perm_task"),
("SIP Trunk", "task4_sip_trunk", "run_sip_task"),
("Inbound Routing", "task6_inbound_routing", "run_inbound_task"),
("Caller ID", "task7_caller_id_manipulation", "run_caller_id_task"),
("ACL Group (Copy Existing)", "task8_acl_group", "run_acl_task"),
("User Profile (Copy Existing)", "task9_user_profile", "run_profile_task"),
("User", "task10_user", "run_user_task"),
("ACL User", "task11_ACL_user", "run_acl_user_task")
]
# ✅【正确】默认勾选列表(名字 100% 对应界面)
default_checked = [
"Group",
#"Context",
#"Permission Group",
"SIP Trunk",
"Inbound Routing",
"Caller ID",
"ACL Group (Copy Existing)",
"User Profile (Copy Existing)",
"User",
"ACL User"
]
self.task_vars = {}
self.task_status = {} # Status indicators: 0=idle, 1=running, 2=success, 3=failed
self.task_canvas = {} # Canvas widgets for status lights
for name, mod, func in self.task_definitions:
self.task_vars[name] = tk.BooleanVar(value=name in default_checked)
self.task_status[name] = 0 # Default: idle
# Add shared status for Outbound tasks (both Routing and Custom)
self.task_status["Outbound"] = 0
self.task_canvas["Outbound"] = None
self.custom_ob_list = self.last_session.get("custom_ob_list", [])
self.user_records = []
# Outbound 互斥变量
self.ob_normal = tk.BooleanVar(value=self.last_session.get("ob_normal", True))
self.ob_custom = tk.BooleanVar(value=self.last_session.get("ob_custom", False))
def create_gui(self):
# ========== Base Configuration ==========
login_frame = tk.LabelFrame(self.root, text="Base Configuration", padx=10, pady=5)
login_frame.pack(fill="x", padx=10, pady=5)
tk.Label(login_frame, text="URL:").grid(row=0, column=0, sticky="e")
self.url_ent = tk.Entry(login_frame, width=45)
self.url_ent.insert(0, self.last_session.get("base_url", config.base_url))
self.url_ent.grid(row=0, column=1, padx=5, pady=2)
tk.Label(login_frame, text="Username:").grid(row=0, column=2, sticky="e")
self.user_ent = tk.Entry(login_frame, width=20)
self.user_ent.insert(0, self.last_session.get("username", config.username))
self.user_ent.grid(row=0, column=3, padx=5, pady=2)
tk.Label(login_frame, text="Password:").grid(row=0, column=4, sticky="e")
self.pw_ent = tk.Entry(login_frame, width=20, show="*")
self.pw_ent.insert(0, "")
self.pw_ent.grid(row=0, column=5, padx=5, pady=2)
# ========== Middle Layout ==========
middle_frame = tk.Frame(self.root)
middle_frame.pack(fill="both", expand=True, padx=10)
# ========== Task Pipeline ==========
task_frame = tk.LabelFrame(middle_frame, text="Task Pipeline", padx=10, pady=10)
task_frame.pack(side="left", fill="both", expand=True)
btn_frame = tk.Frame(task_frame)
btn_frame.pack(anchor="w", pady=(0,8), fill="x")
tk.Button(btn_frame, text="All Tasks", width=10, command=self.select_all_tasks).pack(side="left", padx=(0,6))
tk.Button(btn_frame, text="No Task", width=10, command=self.deselect_all_tasks).pack(side="left")
for idx, (name, _, _) in enumerate(self.task_definitions):
task_row = tk.Frame(task_frame)
task_row.pack(anchor="w", pady=1, fill="x")
# Status indicator light
self.task_canvas[name] = tk.Canvas(task_row, width=24, height=24, bg="white", highlightthickness=0)
self.task_canvas[name].pack(side="left", padx=6, pady=2)
self._draw_indicator(name, 0) # Draw gray (idle)
# Checkbox
tk.Checkbutton(task_row, text=name, variable=self.task_vars[name]).pack(anchor="w", side="left")
if name == "SIP Trunk":
ob_frame = tk.Frame(task_frame)
ob_frame.pack(anchor="w", pady=3)
# Shared indicator light for Outbound options
self.task_canvas["Outbound"] = tk.Canvas(ob_frame, width=24, height=24, bg="white", highlightthickness=0)
self.task_canvas["Outbound"].pack(side="left", padx=6, pady=2)
self._draw_indicator("Outbound", 0)
tk.Checkbutton(ob_frame, text="Outbound Routing", variable=self.ob_normal,
command=self.sync_ob_mutex).pack(side="left", padx=2)
tk.Checkbutton(ob_frame, text="Custom Outbound", variable=self.ob_custom,
command=self.sync_ob_mutex).pack(side="left", padx=2)
# ========== Global Parameters ==========
param_frame = tk.LabelFrame(middle_frame, text="Global Parameters", padx=10, pady=10)
param_frame.pack(side="right", fill="both", expand=True)
self.inputs = {}
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
tk.Label(param_frame, text="Group Name(use underscore mark (_) for Space:").pack(anchor="w")
ent_gn = tk.Entry(param_frame, width=20)
ent_gn.insert(0, self.last_session.get("group_name", "CARSOME_Kajang"))
ent_gn.pack(fill="x", pady=(0,8))
self.inputs["group_name"] = ent_gn
tk.Label(param_frame, text="Group Code:").pack(anchor="w")
ent_gc = tk.Entry(param_frame, width=20)
ent_gc.insert(0, self.last_session.get("group_code", "MCBLL5248_MV_CARSOME_KJG"))
ent_gc.pack(fill="x", pady=(0,8))
self.inputs["group_code"] = ent_gc
tk.Label(param_frame, text="Max Concurrent Calls & Reg User (1-300):").pack(anchor="w")
self.unified_spin = ttk.Spinbox(param_frame, from_=1, to=300, width=20)
self.unified_spin.set(self.last_session.get("unified_limit", 10))
self.unified_spin.pack(fill="x", pady=(0,8))
self.inputs["_unified_limit"] = self.unified_spin
tk.Label(param_frame, text="SIP Trunk Host/IP Address:").pack(anchor="w")
ent_ip = tk.Entry(param_frame, width=20)
ent_ip.insert(0, self.last_session.get("host_ip", "202.179.100.99"))
ent_ip.pack(fill="x", pady=(0,8))
self.inputs["host_ip"] = ent_ip
tk.Label(param_frame, text="SIP Trunk Port:").pack(anchor="w")
ent_port = tk.Entry(param_frame, width=20)
ent_port.insert(0, self.last_session.get("port", "7978"))
ent_port.pack(fill="x", pady=(0,8))
self.inputs["port"] = ent_port
tk.Label(param_frame, text="Context Prefix (used for Context names):").pack(anchor="w")
ent_ctx = tk.Entry(param_frame, width=20)
ent_ctx.insert(0, self.last_session.get("context_prefix", "CARSOME"))
ent_ctx.pack(fill="x", pady=(0,8))
self.inputs["context_prefix"] = ent_ctx
tk.Label(param_frame, text="Permission Group Prefix (used for Permission Name + Class_1..4):").pack(anchor="w")
ent_pg = tk.Entry(param_frame, width=20)
ent_pg.insert(0, self.last_session.get("perm_group_prefix", "CARSOME"))
ent_pg.pack(fill="x", pady=(0,8))
self.inputs["perm_group_prefix"] = ent_pg
# ✅ 已经移到 SIP Trunk Port 下方(右边 Global Parameters 里)
tk.Label(param_frame, text="Custom Outbound Rules Preview:", font=('Arial',9,'bold')).pack(anchor="w", pady=(8,0))
self.custom_ob_preview = tk.Listbox(param_frame, height=2, width=20, font=('Consolas',9))
self.custom_ob_preview.pack(fill="x", pady=(0,8))
tk.Label(param_frame, text="Inbound Ranges / CallerID (603xxx-603xxx,...):").pack(anchor="w")
ent_in = tk.Entry(param_frame, width=20)
ent_in.insert(0, self.last_session.get("inbound_ranges", "60338314500-60338314509"))
ent_in.pack(fill="x", pady=(0,8))
self.inputs["inbound_ranges"] = ent_in
tk.Label(param_frame, text="User Extension / Extension Range:").pack(anchor="w")
ent_ext = tk.Entry(param_frame, width=20)
ent_ext.insert(0, self.last_session.get("user_ext", "60338314500-60338314503"))
ent_ext.pack(fill="x", pady=(0,8))
self.inputs["user_ext"] = ent_ext
tk.Label(param_frame, text="Created User Records:", font=('Arial',9,'bold')).pack(anchor="w", pady=(8,0))
self.user_record_text = tk.Text(param_frame, height=3, width=20, font=('Consolas',9))
self.user_record_text.pack(fill="x", pady=(0,8))
record_btn_frame = tk.Frame(param_frame)
record_btn_frame.pack(fill="x", pady=(0,8))
tk.Button(record_btn_frame, text="Copy Records", width=15, command=self.copy_user_records).pack(side="left", padx=2)
tk.Button(record_btn_frame, text="Export Records", width=15, command=self.export_user_records).pack(side="left", padx=2)
# ========== Control Buttons ==========
btn_frame = tk.Frame(self.root)
btn_frame.pack(fill="x", padx=10, pady=5)
self.run_btn = tk.Button(btn_frame, text="▶ Start", bg="#28a745", fg="white", width=15, command=self.start_thread)
self.run_btn.pack(side="left", padx=5)
self.pause_btn = tk.Button(btn_frame, text="⏸ Pause", bg="#ffc107", width=15, command=self.toggle_pause, state="disabled")
self.pause_btn.pack(side="left", padx=5)
self.stop_btn = tk.Button(btn_frame, text="⏹ Stop", bg="#dc3545", fg="white", width=15, command=self.stop_task, state="disabled")
self.stop_btn.pack(side="left", padx=5)
# ========== Log Area ==========
self.log_text = tk.Text(self.root, height=12, bg="#1e1e1e", fg="#00ff00", font=("Consolas",10))
self.log_text.pack(fill="both", padx=10, pady=5, expand=True)
self.root.mainloop()
def append_user_record(self, extension, login_password, pin):
record = {"extension": extension, "login_password": login_password, "pin": pin}
self.user_records.append(record)
display_line = f"{extension}\t{login_password}\t{pin}\n"
self.root.after(0, lambda: self._append_record_text(display_line))
def _append_record_text(self, line):
self.user_record_text.insert("end", line)
self.user_record_text.see("end")
def copy_user_records(self):
if not self.user_records:
self.log("⚠️ No user records to copy")
return
text = self.user_record_text.get("1.0", "end").strip()
self.root.clipboard_clear()
self.root.clipboard_append(text)
messagebox.showinfo("Copy Records", "User records copied to clipboard.")
def export_user_records(self):
if not self.user_records:
self.log("⚠️ No user records to export")
return
path = filedialog.asksaveasfilename(
defaultextension=".csv",
filetypes=[("CSV Files", "*.csv")],
title="Save User Records"
)
if not path:
return
try:
import csv
with open(path, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Extension", "Login Password", "PIN"])
for record in self.user_records:
writer.writerow([record["extension"], record["login_password"], record["pin"]])
messagebox.showinfo("Export Records", f"User records exported to {path}")
except Exception as e:
self.log(f"❌ Export failed: {e}")
# ========== Status Indicator Methods ==========
def _draw_indicator(self, task_name, status):
"""Draw status light: 0=gray(idle), 1=yellow(running), 2=green(success), 3=red(failed)"""
if task_name not in self.task_canvas or self.task_canvas[task_name] is None:
return
canvas = self.task_canvas[task_name]
canvas.delete("all")
colors = {0: "#cccccc", 1: "#ffff00", 2: "#00cc00", 3: "#ff0000"}
color = colors.get(status, "#cccccc")
width = int(canvas['width'])
height = int(canvas['height'])
padding = 2
canvas.create_oval(padding, padding, width-padding, height-padding, fill=color, outline="", width=0)
self.task_status[task_name] = status
def _update_indicator_ui(self, task_name, status):
"""Update indicator from main thread"""
self.root.after(0, lambda: self._draw_indicator(task_name, status))
# ========== Outbound 互斥逻辑 ==========
def sync_ob_mutex(self):
if self.ob_custom.get():
self.ob_normal.set(False)
self.show_custom_outbound_window()
if self.ob_normal.get():
self.ob_custom.set(False)
self.custom_ob_list.clear()
self.custom_ob_preview.delete(0, tk.END)
def select_all_tasks(self):
for name in self.task_vars:
self.task_vars[name].set(True)
self.ob_normal.set(True)
self.ob_custom.set(False)
def deselect_all_tasks(self):
for name in self.task_vars:
self.task_vars[name].set(False)
self.ob_normal.set(False)
self.ob_custom.set(False)
# ========== Custom Outbound 弹窗 ==========
def show_custom_outbound_window(self):
# Build context options from UI `context_prefix`; fall back to Group Name
ctx_base = self.inputs.get("context_prefix") and self.inputs["context_prefix"].get().strip()
if not ctx_base:
ctx_base = self.inputs["group_name"].get().strip() or "aaa"
prefix = ctx_base[:-1] if ctx_base.endswith("_") else ctx_base
ctx_options = [f"{prefix}_Internal", f"{prefix}_Fixed", f"{prefix}_Mobile", f"{prefix}_IDD"]
self.custom_ob_list = []
win = tk.Toplevel(self.root)
win.title("Custom Outbound Routing Rules")
win.geometry("700x280")
win.grab_set()
row_container = tk.Frame(win)
row_container.pack(pady=15, padx=10, fill="x")
self.row_frames = []
self.num_entries = []
self.ctx_combos = []
def add_row():
idx = len(self.row_frames)+1
row = tk.Frame(row_container, bd=1, relief="solid", padx=8, pady=8)
row.pack(side="left", padx=8)
tk.Label(row, text=f"Rule {idx}", font=('Arial',10,'bold')).pack(pady=(0,5))
tk.Label(row, text="Number:").pack(anchor="w")
ne = tk.Entry(row, width=16)
ne.pack(pady=(0,5))
tk.Label(row, text="Context:").pack(anchor="w")
ctx_var = tk.StringVar(value=ctx_options[0])
cc = ttk.Combobox(row, textvariable=ctx_var, values=ctx_options, state="readonly", width=14)
cc.pack(pady=(0,5))
def remove_row():
if len(self.row_frames)>1:
row.destroy()
self.row_frames.remove(row)
self.num_entries.remove(ne)
self.ctx_combos.remove(cc)
for i, f in enumerate(self.row_frames,1):
f.winfo_children()[0].config(text=f"Rule {i}")
tk.Button(row, text="➖", bg="#dc3545", fg="white", command=remove_row).pack(pady=3)
self.row_frames.append(row)
self.num_entries.append(ne)
self.ctx_combos.append(cc)
win.geometry(f"{600+len(self.row_frames)*180}x280")
add_row()
tk.Button(win, text="➕ Add Rule", bg="#0066cc", fg="white", command=add_row).pack(pady=5)
def save_all():
self.custom_ob_list = [{"number": ne.get().strip(), "context": cc.get()}
for ne, cc in zip(self.num_entries, self.ctx_combos)]
win.destroy()
self.log(f"✅ Saved {len(self.custom_ob_list)} Custom Outbound rule(s)")
self.custom_ob_preview.delete(0, tk.END)
for i, r in enumerate(self.custom_ob_list,1):
self.custom_ob_preview.insert(tk.END, f"Rule {i}: {r['number']} → {r['context']}")
tk.Button(win, text="✅ Save All", bg="#28a745", fg="white", width=20, command=save_all).pack(pady=10)
self.root.wait_window(win)
# ========== Log & Thread Control ==========
def log(self, msg):
self.log_text.insert("end", f"[{time.strftime('%H:%M:%S')}] {msg}\n")
self.log_text.see("end")
def start_thread(self):
if self.ob_custom.get() and not self.custom_ob_list:
self.log("❌ Please set Custom Outbound rules first!")
return
self.user_records.clear()
if hasattr(self, 'user_record_text'):
self.user_record_text.delete("1.0", "end")
self.stop_event.clear()
self.pause_event.set()
self.run_btn.config(state="disabled")
self.pause_btn.config(state="normal", text="⏸ Pause")
self.stop_btn.config(state="normal")
threading.Thread(target=self.execute_pipeline, daemon=True).start()
def toggle_pause(self):
if self.pause_event.is_set():
self.pause_event.clear()
self.pause_btn.config(text="▶ Resume", bg="#17a2b8", fg="white")
self.log("⏸ Paused after current task...")
else:
self.pause_event.set()
self.pause_btn.config(text="⏸ Pause", bg="#ffc107", fg="black")
self.log("▶ Resuming...")
def stop_task(self):
self.stop_event.set()
self.pause_event.set()
self.log("⏹ Stopping all tasks...")
# Close browser immediately to interrupt running task
if self.browser:
try:
self.browser.close()
self.log("✅ Browser closed")
except:
pass
self.browser = None
self.page = None
def execute_pipeline(self):
shared_data = {k: v.get() for k, v in self.inputs.items() if not k.startswith("_")}
uv = self.unified_spin.get()
shared_data["max_concurrent"] = uv
shared_data["max_reg_user"] = uv
shared_data["custom_outbound_rules"] = self.custom_ob_list
shared_data["user_records"] = self.user_records
shared_data["append_user_record"] = self.append_user_record
# Process group names (split by comma if multiple groups)
group_names_str = shared_data["group_name"]
group_names = [name.strip() for name in group_names_str.split(",") if name.strip()]
# If multiple groups are provided, store original group name for later use
if len(group_names) > 1:
shared_data["original_group_name"] = shared_data["group_name"]
shared_data["group_name"] = group_names[0] # Use first group initially
shared_data["additional_groups"] = group_names[1:] # Store remaining groups
else:
shared_data["additional_groups"] = []
# Reset all task status indicators to idle
for task_name in self.task_status:
self._update_indicator_ui(task_name, 0)
try:
with sync_playwright() as p:
channel = BrowserFactory.get_browser_channel(self.log)
browser = p.chromium.launch(headless=config.headless, channel=channel)
page = browser.new_page()
# Store browser and page for STOP button to close
self.browser = browser
self.page = page
login_pg = LoginPage(page, self.log)
if not login_pg.execute_login(self.url_ent.get(), self.user_ent.get(), self.pw_ent.get()):
self.log("❌ Login failed")
return
last = len(self.task_definitions)-1
for idx, (ui_name, mod_name, func_name) in enumerate(self.task_definitions):
if self.stop_event.is_set():
self._update_indicator_ui(ui_name, 3) # Mark as failed
break
if not self.pause_event.is_set():
self.log(f"⏸ Waiting... Click Resume to run: {ui_name}")
self.pause_event.wait()
if self.task_vars[ui_name].get():
# Handle multiple groups for ACL Group creation
if ui_name == "ACL Group (Copy Existing)" and shared_data["additional_groups"]:
# Process the first group
self._update_indicator_ui(ui_name, 1) # Running
self.log(f"🚀 Running: {ui_name} for {shared_data['group_name']}")
try:
mod = importlib.import_module(f"modules.{mod_name}")
importlib.reload(mod)
f = getattr(mod, func_name)
if not f(page, self.log, shared_data):
self.log(f"⚠️ {ui_name} failed for {shared_data['group_name']}")
# Don't break here - continue to process additional groups
else:
self._update_indicator_ui(ui_name, 2) # Success for first group
# Process additional groups
for additional_group in shared_data["additional_groups"]:
self.log(f"🚀 Running: {ui_name} for {additional_group}")
temp_shared_data = shared_data.copy()
temp_shared_data["group_name"] = additional_group
try:
# Before processing the next group, ensure clean state by reloading and navigating
mod = importlib.import_module(f"modules.{mod_name}")
importlib.reload(mod)
f = getattr(mod, func_name)
if not f(page, self.log, temp_shared_data):
self.log(f"⚠️ {ui_name} failed for {additional_group}")
else:
self.log(f"✅ {ui_name} succeeded for {additional_group}")
except Exception as e:
self.log(f"❌ Error in {ui_name} for {additional_group}: {e}")
# Removed IM panel shutdown between tasks
# Update indicator to show success if any group succeeded
self._update_indicator_ui(ui_name, 2)
except Exception as e:
self.log(f"❌ Error in {ui_name}: {e}")
self._update_indicator_ui(ui_name, 3) # Failed
break
else:
# Normal processing for single group or other tasks
self._update_indicator_ui(ui_name, 1) # Running
self.log(f"🚀 Running: {ui_name}")
try:
mod = importlib.import_module(f"modules.{mod_name}")
importlib.reload(mod)
f = getattr(mod, func_name)
if not f(page, self.log, shared_data):
self.log(f"⚠️ {ui_name} failed")
self._update_indicator_ui(ui_name, 3) # Failed
break
self._update_indicator_ui(ui_name, 2) # Success
# Removed IM panel shutdown between tasks
except Exception as e:
self.log(f"❌ Error in {ui_name}: {e}")
self._update_indicator_ui(ui_name, 3) # Failed
break
# 执行 Task5 Outbound / Custom Outbound
if not self.stop_event.is_set():
if self.ob_normal.get():
self._update_indicator_ui("Outbound", 1) # Running
self.log("🚀 Running: Outbound Routing")
try:
mod = importlib.import_module("modules.task5_outbound_routing")
importlib.reload(mod)
mod.run_outbound_task(page, self.log, shared_data)
self._update_indicator_ui("Outbound", 2) # Success
# Removed IM panel shutdown between tasks
except Exception as e:
self.log(f"❌ Error in Outbound Routing: {e}")
self._update_indicator_ui("Outbound", 3) # Failed
if self.ob_custom.get():
self._update_indicator_ui("Outbound", 1) # Running
self.log("🚀 Running: Custom Outbound")
try:
mod = importlib.import_module("modules.task5_custom_outbound")
importlib.reload(mod)
mod.run_custom_outbound_task(page, self.log, shared_data)
self._update_indicator_ui("Outbound", 2) # Success
# Removed IM panel shutdown between tasks
except Exception as e:
self.log(f"❌ Error in Custom Outbound: {e}")
self._update_indicator_ui("Outbound", 3) # Failed
if not self.stop_event.is_set():
self.log("🏁 All tasks completed!")
else:
self.log("⏹ Task execution stopped by user")
browser.close()
self.browser = None
self.page = None
except Exception as e:
self.log(f"🔥 Fatal error: {e}")
self.browser = None
self.page = None
finally:
self.root.after(0, self.reset_ui)
def reset_ui(self):
self.run_btn.config(state="normal")
self.pause_btn.config(state="disabled", text="⏸ Pause", bg="#ffc107")
self.stop_btn.config(state="disabled")
def _get_session_path(self):
return os.path.join(current_dir, "last_session.json")
def _load_last_session(self):
path = self._get_session_path()
if os.path.exists(path):
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
return {}
def _save_last_session(self):
data = {
"base_url": self.url_ent.get().strip(),
"username": self.user_ent.get().strip(),
"group_name": self.inputs["group_name"].get().strip(),
"group_code": self.inputs["group_code"].get().strip(),
"unified_limit": self.unified_spin.get(),
"host_ip": self.inputs["host_ip"].get().strip(),
"port": self.inputs["port"].get().strip(),
"context_prefix": self.inputs["context_prefix"].get().strip(),
"perm_group_prefix": self.inputs["perm_group_prefix"].get().strip(),
"inbound_ranges": self.inputs["inbound_ranges"].get().strip(),
"user_ext": self.inputs["user_ext"].get().strip(),
"ob_normal": self.ob_normal.get(),
"ob_custom": self.ob_custom.get(),
"custom_ob_list": self.custom_ob_list,
}
try:
with open(self._get_session_path(), "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception:
pass
def on_close(self):
self._save_last_session()
self.root.destroy()
if __name__ == "__main__":
app = DeltapathAutomator()
app.create_gui()