Repository navigation
Expand file tree
/
Copy pathtool.py
More file actions
643 lines (549 loc) · 27.6 KB
/
Copy pathtool.py
File metadata and controls
643 lines (549 loc) · 27.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
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
"""
PAK ULTRA MASTER PRO - V5.0 SUPREME
Next-Generation Unreal Engine & Tencent PAK Suite
Supports all PUBG Mobile versions (Current & Future 3.x, 4.x, 5.x+)
High-speed Multi-threaded Unpacking, Full Rebuild Repack, Custom Path Injection, Game-Native SM4 Protection
"""
import os
import sys
import time
import shutil
import random
import colorsys
import subprocess
from pathlib import Path, PurePath
# ==================== AUTO-DEPENDENCY CHECK & INSTALLER ====================
def ensure_environment():
required = {
'rich': 'rich>=13.7.0',
'gmalg': 'gmalg>=1.4.0',
'Crypto': 'pycryptodome>=3.20.0',
'zstandard': 'zstandard>=0.22.0',
'requests': 'requests>=2.31.0',
'pytz': 'pytz>=2024.1',
}
missing = []
for mod, pkg in required.items():
try:
__import__(mod)
except ImportError:
missing.append(pkg)
if missing:
print("=================================================================")
print(" [PAK ULTRA MASTER PRO] First-time setup: Installing dependencies...")
print("=================================================================")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", *missing])
print("✅ All dependencies installed successfully!\n")
except Exception as e:
print(f"❌ Failed to auto-install dependencies: {e}")
print("Please run: pip install -r requirements.txt\n")
ensure_environment()
from datetime import datetime
import pytz
# Rich UI Library
from rich.console import Console, Group
from rich.table import Table
from rich.panel import Panel
from rich.progress import (
Progress, SpinnerColumn, TextColumn, BarColumn,
TaskProgressColumn, TimeElapsedColumn, TimeRemainingColumn
)
from rich.box import DOUBLE_EDGE, ROUNDED, HEAVY_EDGE
from rich.text import Text
from rich.align import Align
from rich.markup import escape
# Core Engine
from pak_engine import (
TencentPakFile, TencentPakInfo, PakCrypto,
build_reconstructed_pak, CM_NONE, CM_ZLIB, CM_ZSTD, CM_ZSTD_DICT,
EM_NONE, EM_SIMPLE1, EM_SIMPLE2, EM_SM4_2, EM_SM4_4, EM_UNKNOWN_17, EM_SM4_NEW_BASE
)
console = Console()
# ==================== BANNER & STYLING ====================
ASCII_BANNER = [
"██████╗ █████╗ ██╗ ██╗ ███╗ ███╗ █████╗ ███████╗████████╗███████╗██████╗ ",
"██╔══██╗██╔══██╗██║ ██╔╝ ████╗ ████║██╔══██╗██╔════╝╚══██╔══╝██╔════╝██╔══██╗",
"██████╔╝███████║█████╔╝ ██╔████╔██║███████║███████╗ ██║ █████╗ ██████╔╝",
"██╔═══╝ ██╔══██║██╔═██╗ ██║╚██╔╝██║██╔══██║╚════██║ ██║ ██╔══╝ ██╔══██╗",
"██║ ██║ ██║██║ ██╗ ██║ ╚═╝ ██║██║ ██║███████║ ██║ ███████╗██║ ██║",
"╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝",
]
def lerp(a, b, t):
return int(a + (b - a) * t)
def print_glowing_banner():
os.system('cls' if os.name == 'nt' else 'clear')
h1, h2 = random.random(), (random.random() + 0.5) % 1.0
c1 = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(h1, 0.9, 1.0))
c2 = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(h2, 0.9, 1.0))
h = len(ASCII_BANNER)
w = max(len(l) for l in ASCII_BANNER)
for y, line in enumerate(ASCII_BANNER):
buf = []
for x, ch in enumerate(line):
if ch == ' ':
buf.append(' ')
continue
t = ((x / w) + (y / h)) / 2.0
r, g, b = lerp(c1[0], c2[0], t), lerp(c1[1], c2[1], t), lerp(c1[2], c2[2], t)
buf.append(f"\033[38;2;{r};{g};{b}m{ch}")
print(''.join(buf) + "\033[0m")
tz = pytz.timezone("Asia/Kolkata")
now_str = datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
console.print(Align.center(
Panel(
f"[bold #00FFAA]PAK ULTRA MASTER PRO V5.0 (SUPREME)[/] [dim]•[/] [bold #FF00FF]MULTI-THREADED ULTRA SPEED[/]\n"
f"[cyan]Supports PUBG Mobile & All Unreal Engine Tencent PAK Versions (Current & Future)[/]\n"
f"[dim white]System Time: {now_str} IST[/]",
border_style="bright_blue",
box=ROUNDED,
padding=(0, 2)
)
))
def safe_input(prompt: str = '') -> str:
try:
return input(prompt)
except (EOFError, RuntimeError):
return ''
def get_base_paths() -> Dict[str, Path]:
base = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).resolve().parent
paths = {
'base': base,
'pak': base / "PAK",
'unpack': base / "UNPACK",
'edit': base / "EDIT",
'result': base / "RESULT",
'output': base / "OUTPUT",
'logs': base / "LOGS"
}
for p in paths.values():
p.mkdir(parents=True, exist_ok=True)
return paths
def human_size(size: int) -> str:
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return f"{size:.2f} {unit}"
size /= 1024.0
return f"{size:.2f} PB"
def select_pak_file(folder: Path, title: str = "Select a .PAK file") -> Optional[Path]:
files = list(folder.glob("*.pak"))
if not files:
console.print(f"[bold red]❌ No .pak files found in [yellow]{folder}[/yellow]![/bold red]")
console.print("[dim]Please copy your .pak files into the PAK folder first.[/dim]")
return None
table = Table(title=f"[bold #00FFAA]{title}[/]", box=ROUNDED, border_style="cyan", expand=True)
table.add_column("#", justify="center", style="bold yellow", width=4)
table.add_column("PAK File Name", justify="left", style="bold bright_green")
table.add_column("Size", justify="right", style="bold bright_cyan")
for i, f in enumerate(files, 1):
sz = human_size(f.stat().st_size)
table.add_row(str(i), f.name, sz)
console.print(table)
try:
choice = safe_input(f"\n[bold yellow]Select PAK number (1-{len(files)}): [/bold yellow]").strip()
idx = int(choice) - 1
if 0 <= idx < len(files):
return files[idx]
console.print("[bold red]❌ Invalid selection![/bold red]")
return None
except ValueError:
console.print("[bold red]❌ Invalid input![/bold red]")
return None
# ==================== WORKFLOW HANDLERS ====================
def handle_unpack(paths: Dict[str, Path]):
pak_file = select_pak_file(paths['pak'], "📂 SELECT PAK TO UNPACK")
if not pak_file:
safe_input("\nPress Enter to continue...")
return
console.print(f"\n[bold cyan]🚀 Initializing Multi-Threaded Unpacker for:[/] [bold green]{pak_file.name}[/]")
try:
t0 = time.time()
pak = TencentPakFile(pak_file)
unpack_dir = paths['unpack'] / pak_file.stem
unpack_dir.mkdir(parents=True, exist_ok=True)
edited_dir = unpack_dir / "edited"
edited_dir.mkdir(parents=True, exist_ok=True)
total_files = sum(len(d) for d in pak.index.values())
console.print(f"[dim]Total Assets Inside:[/] [bold yellow]{total_files:,}[/] [dim]| Mount Point:[/] [cyan]{pak.mount_point}[/]")
# Index CSV Generation
csv_path = unpack_dir / "index.csv"
with open(csv_path, 'w', encoding='utf-8') as cf:
for dp, files in pak.index.items():
for fn in files:
cf.write(f"{str(PurePath(dp) / fn).replace('\\', '/')}\n")
with Progress(
SpinnerColumn(),
TextColumn("[bold cyan][EXTRACTING][/] {task.description}"),
BarColumn(complete_style="green", finished_style="bold green"),
TaskProgressColumn(),
TimeElapsedColumn(),
TimeRemainingColumn(),
console=console
) as progress:
task = progress.add_task(f"Unpacking {pak_file.name}", total=total_files)
def _update(count):
progress.update(task, advance=count)
success, failed = pak.unpack_all(unpack_dir, progress_callback=_update, max_workers=12)
elapsed = time.time() - t0
rate = total_files / elapsed if elapsed > 0 else 0
# Debug Log Output
log_path = paths['logs'] / f"Debug_{pak_file.stem}.log"
with open(log_path, 'w', encoding='utf-8') as lf:
lf.write(f"PAK: {pak_file.name}\nVersion: {pak.pak_info.version}\nFiles: {total_files}\nMount: {pak.mount_point}\n\n")
for dp, files in pak.index.items():
for fn, e in files.items():
lf.write(f"{PurePath(dp)/fn} -> Size:{e.uncompressed_size} CompMethod:{e.compression_method} EncMethod:{e.encryption_method}\n")
console.print(Panel(
f"[bold green]✅ UNPACK COMPLETED SUCCESSFULLY![/bold green]\n"
f"[white]• Total Extracted:[/] [bold cyan]{success:,}[/bold cyan] files\n"
f"[white]• Corrupt/Raw Dumped:[/] [yellow]{failed}[/yellow]\n"
f"[white]• Time Taken:[/] [bold yellow]{elapsed:.2f}s[/bold yellow] [dim]({rate:.1f} files/sec)[/dim]\n"
f"[white]• Output Folder:[/] [cyan]{unpack_dir}[/cyan]\n"
f"[white]• Modding Folder:[/] [green]{edited_dir}[/green] [dim](put your modified files here)[/dim]\n"
f"[white]• Index CSV:[/] [cyan]{csv_path}[/cyan]",
title="🎉 UNPACK SUCCESS", border_style="green", box=ROUNDED
))
except Exception as e:
console.print(f"[bold red]❌ Unpack Failed:[/] {escape(str(e))}")
import traceback
traceback.print_exc()
safe_input("\nPress Enter to continue...")
def handle_repack(paths: Dict[str, Path]):
# Find available UNPACK folders
unpack_dirs = [p for p in paths['unpack'].iterdir() if p.is_dir()]
if not unpack_dirs:
console.print("[bold red]❌ No UNPACK folders found! Unpack a PAK first (Option 1).[/bold red]")
safe_input("\nPress Enter to continue...")
return
table = Table(title="[bold #00FFAA]📁 AVAILABLE UNPACKED PAKS TO REPACK[/]", box=ROUNDED, border_style="cyan", expand=True)
table.add_column("#", justify="center", style="bold yellow", width=4)
table.add_column("Unpack Folder Name", justify="left", style="bold bright_green")
for i, ud in enumerate(unpack_dirs, 1):
table.add_row(str(i), ud.name)
console.print(table)
try:
sel = int(safe_input(f"\n[bold yellow]Select folder (1-{len(unpack_dirs)}): [/bold yellow]").strip()) - 1
if not (0 <= sel < len(unpack_dirs)):
console.print("[bold red]❌ Invalid selection![/bold red]")
safe_input("\nPress Enter to continue...")
return
selected_unpack = unpack_dirs[sel]
except ValueError:
console.print("[bold red]❌ Invalid input![/bold red]")
safe_input("\nPress Enter to continue...")
return
# Find matching source .pak in PAK/
matched_pak = paths['pak'] / f"{selected_unpack.name}.pak"
if not matched_pak.exists():
paks = list(paths['pak'].glob("*.pak"))
if not paks:
console.print(f"[bold red]❌ Source PAK {matched_pak.name} not found in PAK folder![/bold red]")
safe_input("\nPress Enter to continue...")
return
matched_pak = paks[0]
console.print(f"\n[bold cyan]📦 Repacking using base PAK:[/] [bold green]{matched_pak.name}[/]")
# Collect files from edited/ or full tree
edited_dir = selected_unpack / "edited"
files_to_repack: Dict[str, bytes] = {}
# Load index.csv if available for flat resolving
csv_path = selected_unpack / "index.csv"
index_paths = []
if csv_path.exists():
with open(csv_path, 'r', encoding='utf-8', errors='ignore') as f:
index_paths = [line.strip().replace('\\', '/').lstrip('/') for line in f if line.strip()]
name_to_index_path = {}
for ip in index_paths:
name_to_index_path[ip.rsplit('/', 1)[-1].lower()] = ip
# 1. Check edited folder
if edited_dir.exists():
for p in edited_dir.rglob('*'):
if p.is_file():
rel_to_edited = str(p.relative_to(edited_dir)).replace('\\', '/')
if '/' in rel_to_edited:
files_to_repack[rel_to_edited] = p.read_bytes()
else:
resolved_path = name_to_index_path.get(p.name.lower(), p.name)
files_to_repack[resolved_path] = p.read_bytes()
# 2. Check full unpack folder (excluding special dirs)
for p in selected_unpack.rglob('*'):
if p.is_file() and p.name != 'index.csv' and not str(p).startswith(str(edited_dir)):
try:
rel = str(p.relative_to(selected_unpack)).replace('\\', '/')
if rel not in files_to_repack:
files_to_repack[rel] = p.read_bytes()
except Exception:
pass
if not files_to_repack:
console.print("[bold red]❌ No modified files found in UNPACK folder or edited/ subfolder![/bold red]")
safe_input("\nPress Enter to continue...")
return
console.print(f"[bold cyan]📁 Found {len(files_to_repack):,} modified/ready files to inject/rebuild.[/bold cyan]")
output_pak = paths['result'] / matched_pak.name
try:
t0 = time.time()
pak = TencentPakFile(matched_pak)
with Progress(
SpinnerColumn(),
TextColumn("[bold green][REBUILDING PAK][/] {task.description}"),
BarColumn(complete_style="cyan", finished_style="bold cyan"),
TaskProgressColumn(),
TimeElapsedColumn(),
console=console
) as progress:
task = progress.add_task(f"Repacking {matched_pak.name}", total=len(files_to_repack))
def _up(c):
progress.update(task, advance=c)
edited_c, added_c = build_reconstructed_pak(
pak=pak,
modified_files=files_to_repack,
output_pak_path=output_pak,
progress_callback=_up
)
elapsed = time.time() - t0
console.print(Panel(
f"[bold green]✅ FULL REPACK COMPLETE & SIGNED![/bold green]\n"
f"[white]• Replaced Files:[/] [bold cyan]{edited_c:,}[/bold cyan]\n"
f"[white]• Added New Files:[/] [bold green]{added_c:,}[/bold green]\n"
f"[white]• Time Taken:[/] [bold yellow]{elapsed:.2f}s[/bold yellow]\n"
f"[white]• Output Location:[/] [bold #00FFAA]{output_pak}[/bold #00FFAA]\n"
f"[bold green]🎮 GAME READY - Fully compatible with game integrity checks![/bold green]",
title="🎉 REPACK SUCCESS", border_style="green", box=ROUNDED
))
except Exception as e:
console.print(f"[bold red]❌ Repack Failed:[/] {escape(str(e))}")
import traceback
traceback.print_exc()
safe_input("\nPress Enter to continue...")
def handle_custom_path_repack(paths: Dict[str, Path]):
pak_file = select_pak_file(paths['pak'], "📂 SELECT PAK FOR CUSTOM PATH INJECTION")
if not pak_file:
safe_input("\nPress Enter to continue...")
return
console.print("\n[bold yellow]🎯 Enter the exact directory inside the PAK where your files belong:[/bold yellow]")
console.print("[dim]Example: ShadowTrackerExtra/Content/Lua/GameLua/Mod/BRMod/Gameplay/Core[/dim]")
target_path = safe_input("[bold cyan]Target Path: [/bold cyan]").strip().replace('\\', '/').strip('/')
if not target_path:
console.print("[bold red]❌ Target path cannot be empty![/bold red]")
safe_input("\nPress Enter to continue...")
return
# Check EDIT folder
edit_files = [p for p in paths['edit'].rglob('*') if p.is_file()]
if not edit_files:
console.print(f"[bold red]❌ No files found in EDIT folder ({paths['edit']})![/bold red]")
console.print("[dim]Place your modded Lua/Asset files inside EDIT folder first.[/dim]")
safe_input("\nPress Enter to continue...")
return
files_to_inject = {f"{target_path}/{p.name}": p.read_bytes() for p in edit_files}
output_pak = paths['result'] / pak_file.name
console.print(f"[bold cyan]🚀 Injecting {len(files_to_inject)} files into [yellow]{target_path}[/yellow]...[/bold cyan]")
try:
t0 = time.time()
pak = TencentPakFile(pak_file)
edited_c, added_c = build_reconstructed_pak(
pak=pak,
modified_files=files_to_inject,
output_pak_path=output_pak,
target_custom_dir=target_path
)
elapsed = time.time() - t0
console.print(Panel(
f"[bold green]✅ CUSTOM PATH INJECTION COMPLETE![/bold green]\n"
f"[white]• Injected into:[/] [cyan]{target_path}[/cyan]\n"
f"[white]• Injected Files:[/] [bold cyan]{len(files_to_inject)}[/bold cyan]\n"
f"[white]• Output PAK:[/] [bold #00FFAA]{output_pak}[/bold #00FFAA]\n"
f"[white]• Time Taken:[/] [bold yellow]{elapsed:.2f}s[/bold yellow]",
title="🎉 INJECTION SUCCESS", border_style="green", box=ROUNDED
))
except Exception as e:
console.print(f"[bold red]❌ Custom Path Injection Failed:[/] {escape(str(e))}")
import traceback
traceback.print_exc()
safe_input("\nPress Enter to continue...")
def handle_direct_inject(paths: Dict[str, Path]):
pak_file = select_pak_file(paths['pak'], "📂 SELECT PAK TO INJECT FILES INTO")
if not pak_file:
safe_input("\nPress Enter to continue...")
return
edit_files = [p for p in paths['edit'].rglob('*') if p.is_file()]
if not edit_files:
console.print(f"[bold red]❌ No files found in EDIT folder ({paths['edit']})![/bold red]")
console.print("[dim]Place files preserving relative paths in EDIT (e.g. EDIT/Content/Lua/BRMod.lua)[/dim]")
safe_input("\nPress Enter to continue...")
return
console.print(f"\n[bold yellow]🔐 Encrypt injected files with Game-Native SM4?[/bold yellow]")
enc_c = safe_input("[bold cyan]Enable SM4 Game-Native Encryption? (Y/n): [/bold cyan]").strip().lower()
do_encrypt = enc_c not in ('n', 'no')
files_map = {}
for p in edit_files:
rel = str(p.relative_to(paths['edit'])).replace('\\', '/')
files_map[rel] = p.read_bytes()
output_pak = paths['result'] / pak_file.name
try:
t0 = time.time()
pak = TencentPakFile(pak_file)
edited_c, added_c = build_reconstructed_pak(
pak=pak,
modified_files=files_map,
output_pak_path=output_pak,
force_encrypt=do_encrypt,
forced_sm4_type=47
)
elapsed = time.time() - t0
console.print(Panel(
f"[bold green]✅ DIRECT INJECTION COMPLETE![/bold green]\n"
f"[white]• Modified Files:[/] [bold cyan]{edited_c}[/bold cyan]\n"
f"[white]• Added New Files:[/] [bold green]{added_c}[/bold green]\n"
f"[white]• Encrypted (SM4):[/] [bold magenta]{'YES (Type 47)' if do_encrypt else 'NO (Plain)'}[/bold magenta]\n"
f"[white]• Output:[/] [bold #00FFAA]{output_pak}[/bold #00FFAA]\n"
f"[white]• Time:[/] [bold yellow]{elapsed:.2f}s[/bold yellow]",
title="🎉 INJECTION COMPLETE", border_style="green", box=ROUNDED
))
except Exception as e:
console.print(f"[bold red]❌ Direct Inject Failed:[/] {escape(str(e))}")
import traceback
traceback.print_exc()
safe_input("\nPress Enter to continue...")
def handle_protect_pak(paths: Dict[str, Path]):
pak_file = select_pak_file(paths['pak'], "🔒 SELECT PAK TO PROTECT / CLOAK")
if not pak_file:
safe_input("\nPress Enter to continue...")
return
console.print(Panel(
f"[bold #FF00FF]🛡️ GAME-NATIVE SM4 ENCRYPTION CLOAK[/bold #FF00FF]\n"
f"[white]• Re-encrypts all internal assets using Game-Native SM4 Cipher (Type 47 / 31-52).[/white]\n"
f"[white]• Generic unpackers will see only encrypted garbage.[/white]\n"
f"[white]• The game engine loads and decrypts it automatically with 0% ban risk.[/white]",
border_style="magenta", box=ROUNDED
))
confirm = safe_input("[bold yellow]Start Protection on this PAK? (yes/no): [/bold yellow]").strip().lower()
if confirm not in ('y', 'yes'):
console.print("[yellow]Cancelled.[/yellow]")
safe_input("\nPress Enter to continue...")
return
output_pak = paths['result'] / pak_file.name
try:
t0 = time.time()
pak = TencentPakFile(pak_file)
# Extract all files and rebuild with forced encryption
all_plain = {}
for dp, files in pak.index.items():
for fn, e in files.items():
full_rel = str(PurePath(dp) / fn).replace('\\', '/')
try:
all_plain[full_rel] = pak.extract_entry(e, full_rel)
except Exception:
pass
build_reconstructed_pak(
pak=pak,
modified_files=all_plain,
output_pak_path=output_pak,
force_encrypt=True,
forced_sm4_type=47
)
elapsed = time.time() - t0
console.print(Panel(
f"[bold green]✅ PAK PROTECTED SUCCESSFULLY![/bold green]\n"
f"[white]• Protected Assets:[/] [bold magenta]{len(all_plain):,}[/bold magenta] files re-encrypted\n"
f"[white]• Output Location:[/] [bold #00FFAA]{output_pak}[/bold #00FFAA]\n"
f"[white]• Time Taken:[/] [bold yellow]{elapsed:.2f}s[/bold yellow]",
title="🛡️ PROTECTION APPLIED", border_style="magenta", box=ROUNDED
))
except Exception as e:
console.print(f"[bold red]❌ Protection Failed:[/] {escape(str(e))}")
import traceback
traceback.print_exc()
safe_input("\nPress Enter to continue...")
def handle_diagnostics(paths: Dict[str, Path]):
pak_file = select_pak_file(paths['pak'], "🔍 SELECT PAK FOR DEEP DIAGNOSTICS")
if not pak_file:
safe_input("\nPress Enter to continue...")
return
try:
pak = TencentPakFile(pak_file)
total_files = sum(len(d) for d in pak.index.values())
total_uncompressed = sum(sum(e.uncompressed_size for e in d.values()) for d in pak.index.values())
total_compressed = sum(sum(e.size for e in d.values()) for d in pak.index.values())
# Method breakdown
comp_methods = {}
enc_methods = {}
for d in pak.index.values():
for e in d.values():
comp_methods[e.compression_method] = comp_methods.get(e.compression_method, 0) + 1
enc_methods[e.encryption_method] = enc_methods.get(e.encryption_method, 0) + 1
table = Table(title=f"[bold #00FFAA]🔍 DIAGNOSTIC REPORT: {pak_file.name}[/]", box=DOUBLE_EDGE, border_style="cyan")
table.add_column("Property", style="bold yellow")
table.add_column("Value", style="bold bright_green")
table.add_row("PAK Format Version", f"Version {pak.pak_info.version}")
table.add_row("Magic Checksum", f"0x{pak.pak_info.magic:08X}")
table.add_row("Mount Point", str(pak.mount_point))
table.add_row("Total Files", f"{total_files:,}")
table.add_row("Uncompressed Size", human_size(total_uncompressed))
table.add_row("Compressed Size", human_size(total_compressed))
if total_uncompressed > 0:
ratio = (total_compressed / total_uncompressed) * 100
table.add_row("Compression Ratio", f"{ratio:.1f}%")
table.add_row("Index Encrypted", "YES" if pak.pak_info.index_encrypted else "NO")
table.add_row("Compression Breakdown", ", ".join(f"CM_{k}:{v}" for k, v in comp_methods.items()))
table.add_row("Encryption Breakdown", ", ".join(f"EM_{k}:{v}" for k, v in enc_methods.items()))
console.print()
console.print(table)
except Exception as e:
console.print(f"[bold red]❌ Diagnostics Failed:[/] {escape(str(e))}")
safe_input("\nPress Enter to continue...")
# ==================== MAIN MENU LOOP ====================
def main():
paths = get_base_paths()
while True:
print_glowing_banner()
table = Table(title="[bold #00FFAA]⚡ MAIN CONTROL PANEL ⚡[/bold #00FFAA]", box=ROUNDED, border_style="cyan", expand=True)
table.add_column("[bold yellow]OPTION[/]", justify="center", style="bold bright_yellow", width=8)
table.add_column("[bold cyan]FEATURE / MODULE[/]", justify="left", style="bold bright_white")
table.add_column("[bold green]DESCRIPTION[/]", justify="left", style="dim white")
table.add_row("[1]", "UNPACK PAK (MULTI-THREADED)", "High-speed 12-thread parallel unpack + auto index.csv generation")
table.add_row("[2]", "REPACK PAK (SMART REBUILD)", "Clean rebuild from UNPACK folder or flat edited/ directory")
table.add_row("[3]", "REPACK TO CUSTOM PATH", "Inject modded scripts directly to any custom in-pak directory")
table.add_row("[4]", "DIRECT INJECTOR (FROM EDIT)", "Instant patch & inject from EDIT folder without unpacking")
table.add_row("[5]", "PROTECT PAK (SM4 CLOAK)", "Game-native SM4 encryption (Anti-leaking / Anti-unpack)")
table.add_row("[6]", "PAK DIAGNOSTICS & INSPECT", "Deep inspection of headers, offsets, encryptions & blocks")
table.add_row("[7]", "CLEANUP / DELETE WORKSPACE", "Interactive cleanup of temporary unpacks or logs")
table.add_row("[0]", "EXIT SUITE", "Safely close the tool")
console.print(table)
choice = safe_input("\n[bold #00FFAA]ENTER CHOICE (0-7): [/bold #00FFAA]").strip()
if choice == '1':
handle_unpack(paths)
elif choice == '2':
handle_repack(paths)
elif choice == '3':
handle_custom_path_repack(paths)
elif choice == '4':
handle_direct_inject(paths)
elif choice == '5':
handle_protect_pak(paths)
elif choice == '6':
handle_diagnostics(paths)
elif choice == '7':
console.print("[bold yellow]🧹 Cleaning workspace temporary folders...[/bold yellow]")
for k in ['unpack', 'edit', 'result']:
shutil.rmtree(paths[k], ignore_errors=True)
paths[k].mkdir(parents=True, exist_ok=True)
console.print("[bold green]✅ Cleaned successfully![/bold green]")
safe_input("\nPress Enter to continue...")
elif choice == '0':
console.print("\n[bold magenta]👋 Thank you for using PAK ULTRA MASTER PRO! Goodbye.[/bold magenta]")
time.sleep(1)
break
else:
console.print("[bold red]❌ Invalid option! Try again.[/bold red]")
time.sleep(1)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
console.print("\n[bold yellow]⚠ Operation cancelled by user. Exiting...[/bold yellow]")
sys.exit(0)
except Exception as e:
console.print(f"[bold red]💥 FATAL ERROR:[/] {escape(str(e))}")
import traceback
traceback.print_exc()
safe_input("\nPress Enter to exit...")
sys.exit(1)