Repository navigation
Expand file tree
/
Copy pathCDNSP-GUI-Bob.py
More file actions
4215 lines (3637 loc) · 177 KB
/
Copy pathCDNSP-GUI-Bob.py
File metadata and controls
4215 lines (3637 loc) · 177 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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Credit:
# Thanks to Zotan (DB and script), Big Poppa Panda, AnalogMan, F!rsT-S0uL
# Design inspiration: Lucas Rey's GUI (https://darkumbra.net/forums/topic/174470-app-cdnsp-gui-v105-download-nsp-gamez-using-a-gui/)
# Thanks to the developer(s) that worked on CDNSP_Next for the cert fix!
# Thanks to the help of devloper NighTime, kvn1351, gizmomelb, theLorknessMonster, vertigo
# CDNSP - GUI - Bob - v5
import sys
import time
import random
import gettext
import platform
import locale
import json
import os
__gui_version__ = "5.0.2"
__lang_version__ = "1.0.0"
global sys_locale
if platform.system() != 'Darwin':
sys_locale = locale.getdefaultlocale() # Detect system locale to fix Window size on Chinese Windows Computer
sys_locale = sys_locale[0]
else:
sys_locale = "Mac"
if sys_locale != "zh_CN":
main_win = "1076x684+100+100"
queue_win = "620x300+1177+100"
scan_win = "415x100+100+170"
base64_win = "497x100+95+176"
else:
main_win = "1250x684+100+100"
queue_win = "720x300+770+100"
scan_win = "420x85+100+100"
base64_win = "500x105+100+100"
config = {"Options": {
"Download_location": "",
"NSP_location": "",
"Game_location": "",
"NSP_repack": "True",
"Mute": "False",
"Titlekey_check": "True",
"noaria": "True",
"Disable_game_image": "False",
"Shorten": "False",
"Tinfoil": "False",
"SysVerZero": "False",
"Main_win": main_win,
"Queue_win": queue_win,
"Update_win": "600x400+120+200",
"Scan_win": scan_win,
"Base64_win": base64_win,
"Language": "en",
"Mode": "CDNSP",
"No_demo": "False",
"No_japanese_games": "False",
"Disable_description": "False"}
}
# Check if the GUI config JSON file has the needed keys
f = open("CDNSP-GUI-config.json", 'r')
f_load = json.load(f)
f.close()
if os.path.isfile("CDNSP-GUI-config.json"):
for json_key in config["Options"]:
if json_key not in f_load["Options"]:
print("Missing json key -",json_key,", it has been added in for you")
f_load["Options"][json_key] = config["Options"][json_key]
f = open("CDNSP-GUI-config.json", 'w')
json.dump(f_load, f, indent=4)
f.close()
else:
f = open("CDNSP-GUI-config.json", 'w')
json.dump(config, f, indent=4)
f.close()
f = open("CDNSP-GUI-config.json", 'r')
j = json.load(f)
try:
chosen_lang = j["Options"]["Language"]
except:
f.close()
j["Options"]["Language"] = "en" # Default to English language
with open("CDNSP-GUI-config.json", 'w') as f:
json.dump(j, f, indent=4)
f.close()
chosen_lang = "en"
def set_lang(default_lang = "en"):
try:
lang = gettext.translation('language', localedir='locales', languages=[default_lang])
lang.install()
print("Current language: {}".format(default_lang))
except:
lang = gettext.translation('language', localedir='locales', languages=["en"])
lang.install()
print("Language files not available yet!")
set_lang(chosen_lang)
if not os.path.isdir("Config"):
os.mkdir("Config")
build_text = _("\nBuilding the current state list... Please wait, this may take some time \
depending on how many games you have.")
# Check that user is using Python 3
if (sys.version_info > (3, 0)):
# Python 3 code in this block
pass
else:
# Python 2 code in this block
print(_("\n\nError - Application launched with Python 2, please install Python 3 and delete Python 2\n"))
time.sleep(1000)
sys.exit()
from tkinter import *
import os
from tkinter import messagebox
import tkinter.ttk as ttk
from importlib import util
import subprocess
import urllib.request
import pip
from pathlib import Path
def check_req_file(file):
if not os.path.exists(file):
url = 'https://raw.githubusercontent.com/Bob123a1/CDNSP-GUI-Files/master/{}'.format(file)
urllib.request.urlretrieve(url, file)
def install_module(module):
try:
subprocess.check_output("pip3 install {}".format(module), shell=True)
except:
print(_("Error installing {0}, close the application and you can install the module manually by typing in CMD: pip3 install {0}").format(module))
def add_to_installed(tid, ver):
print(tid, ver)
installed_tid = []
installed_ver = []
if os.path.isfile("Config/installed.txt"):
file = open("Config/installed.txt", "r", encoding="utf8")
for game in file.readlines():
installed_tid.append(game.split(",")[0].strip())
installed_ver.append(game.split(",")[1].strip())
file.close()
if tid in installed_tid:
if int(ver) > int(installed_ver[installed_tid.index(tid)]):
installed_ver[installed_tid.index(tid)] = ver
else:
installed_tid.append(tid)
installed_ver.append(ver)
file = open("Config/installed.txt", "w", encoding="utf8")
for i in range(len(installed_tid)):
file.write("{}, {}\n".format(installed_tid[i], installed_ver[i]))
file.close()
print(_("\nChecking if all required modules are installed!\n\n"))
try:
import requests
except ImportError:
install_module("requests")
import requests
try:
from tqdm import tqdm
except ImportError:
install_module("tqdm")
from tqdm import tqdm
try:
import unidecode
except ImportError:
install_module("unidecode")
import unidecode
try:
from PIL import Image, ImageTk
except ImportError:
install_module("Pillow")
from PIL import Image, ImageTk
try:
from bs4 import BeautifulSoup
except ImportError:
install_module("beautifulsoup4")
from bs4 import BeautifulSoup
try:
import ssl
except:
install_module("pyopenssl")
import ssl
ssl._create_default_https_context = ssl._create_unverified_context # Thanks to user rdmrocha on Github
req_file = ["CDNSPconfig.json", "keys.txt", "nx_tls_client_cert.pem", "titlekeys.txt",\
"titlekeys_overwrite.txt", "Nut_titlekeys.txt", "cert_dead.jpg"]
try:
for file in req_file:
check_req_file(file)
print(_("Everything looks good!"))
except Exception as e:
print(_("Unable to get required files! Check your internet connection: [{}]").format(str(e)))
# CDNSP script
import argparse
import base64
import platform
import re
import shlex
import xml.dom.minidom as minidom
import xml.etree.ElementTree as ET
from binascii import hexlify as hx, unhexlify as uhx
from io import TextIOWrapper
import os, sys
import subprocess
import urllib3
import json
import shutil
import argparse
import configparser
from hashlib import sha256
from struct import pack as pk, unpack as upk
from binascii import hexlify as hx, unhexlify as uhx
import xml.etree.ElementTree as ET, xml.dom.minidom as minidom
import re
import datetime
import calendar
import operator
import base64
import shlex
from distutils.version import StrictVersion as StrV
from tkinter import filedialog
import threading
sys_name = "Win"
global noaria
noaria = True
import webbrowser
titlekey_list = []
global tqdmProgBar
tqdmProgBar = True
sysver0 = False
#Global Vars
truncateName = False
tinfoil = False
enxhop = False
current_mode = ""
nsp_location = ""
import os, sys
import re
import shutil
import subprocess
import requests
import urllib3
import json
import argparse
import unicodedata as ud
import xml.etree.ElementTree as ET, xml.dom.minidom as minidom
from tqdm import tqdm
from hashlib import sha256
from struct import pack as pk, unpack as upk
from binascii import hexlify as hx, unhexlify as uhx
def read_at(f, off, len):
f.seek(off)
return f.read(len)
def read_u8(f, off):
return upk('<B', read_at(f, off, 1))[0]
def read_u16(f, off):
return upk('<H', read_at(f, off, 2))[0]
def read_u32(f, off):
return upk('<I', read_at(f, off, 4))[0]
def read_u48(f, off):
s = upk('<HI', read_at(f, off, 6))
return s[1] << 16 | s[0]
def read_u64(f, off):
return upk('<Q', read_at(f, off, 8))[0]
def sha256_file(fPath):
f = open(fPath, 'rb')
fSize = os.path.getsize(fPath)
hash = sha256()
if fSize >= 10000:
t = tqdm(total=fSize, unit='B', unit_scale=True, desc=os.path.basename(fPath), leave=False)
while True:
buf = f.read(4096)
if not buf:
break
hash.update(buf)
t.update(len(buf))
t.close()
else:
hash.update(f.read())
f.close()
return hash.hexdigest()
def bytes2human(n, f='%(value).3f %(symbol)s'):
n = int(n)
if n < 0:
raise ValueError('n < 0')
symbols = ('B', 'KB', 'MB', 'GB', 'TB')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i + 1) * 10
for symbol in reversed(symbols[1:]):
if n >= prefix[symbol]:
value = float(n) / prefix[symbol]
return f % locals()
return f % dict(symbol=symbols[0], value=n)
def get_name(tid):
if current_mode_global == "Nut":
try:
if tid.endswith('800'):
tid = '%s000' % tid[:-3]
name = title_list[titleID_list.index(tid.lower())]
name = re.sub(r'[/\\:*?!"|™©®()]+', "", unidecode.unidecode(name))
print(name)
return name
except:
return "UNKNOWN TITLE"
elif current_mode_global == "CDNSP":
try:
with open('titlekeys.txt',encoding="utf8") as f:
lines = f.readlines()
except Exception as e:
print("Error:", e)
exit()
for line in lines:
if line.strip() == '':
return
temp = line.split("|")
if tid.endswith('800'):
tid = '%s000' % tid[:-3]
if tid.strip() == temp[0].strip()[:16]:
return re.sub(r'[/\\:*?!"|™©®()]+', "", unidecode.unidecode(temp[2].strip()))
return "UNKNOWN TITLE"
def safe_name(name):
return re.sub('[^\x00-\x7f]', '', ud.normalize('NFD', name))
def safe_filename(safe_name):
return re.sub('[<>.:"/\\|?*]+', '', safe_name)
def check_tid(tid):
return re.match('0100[0-9a-fA-F]{12}', tid)
def check_tkey(tkey):
return re.match('[0-9a-fA-F]{32}', tkey)
def load_config(fPath):
dir = os.path.dirname(__file__)
config = {'Paths': {
'hactoolPath': 'hactool',
'keysPath': 'keys.txt',
'NXclientPath': 'nx_tls_client_cert.pem',
'ShopNPath': 'ShopN.pem'},
'Values': {
'Region': 'US',
'Firmware': '5.1.0-3',
'DeviceID': '6265A5E4140FF804',
'Environment': 'lp1',
'TitleKeysURL': '{}'.format(base64.b64decode("aHR0cDovL3NuaXAubGkvbmV3a2V5ZGI=").decode("ascii")),
'NspOut': '_NSPOUT',
'AutoUpdatedb': 'False'}}
try:
f = open(fPath, 'r')
except FileNotFoundError:
f = open(fPath, 'w')
json.dump(config, f)
f.close()
f = open(fPath, 'r')
j = json.load(f)
hactoolPath = j['Paths']['hactoolPath']
keysPath = j['Paths']['keysPath']
NXclientPath = j['Paths']['NXclientPath']
ShopNPath = j['Paths']['ShopNPath']
reg = j['Values']['Region']
fw = j['Values']['Firmware']
did = j['Values']['DeviceID']
env = j['Values']['Environment']
dbURL = j['Values']['TitleKeysURL']
nspout = j['Values']['NspOut']
if platform.system() == 'Linux':
hactoolPath = './' + hactoolPath + '_linux'
if platform.system() == 'Darwin':
hactoolPath = './' + hactoolPath + '_mac'
return hactoolPath, keysPath, NXclientPath, ShopNPath, reg, fw, did, env, dbURL, nspout
def gen_tik(fPath, rightsID, tkey, mkeyrev):
f = open(fPath, 'wb')
f.write(b'\x04\x00\x01\x00')
f.write(0x100 * b'\xFF')
f.write(0x3C * b'\x00')
f.write(b'Root-CA00000003-XS00000020')
f.write(0x6 * b'\x00')
f.write(0x20 * b'\x00')
if tkey:
f.write(uhx(tkey))
else:
f.write(0x10 * b'\x00')
f.write(0xF0 * b'\x00')
f.write(b'\x02\x00\x00\x00\x00')
f.write(pk('<B', int(mkeyrev)))
f.write(0xA * b'\x00')
f.write(0x10 * b'\x00')
f.write(uhx(rightsID))
f.write(0x8 * b'\x00')
f.write(b'\xC0\x02\x00\x00\x00\x00\x00\x00')
f.close()
return fPath
def gen_cert(fPath):
f = open(fPath, 'wb')
f.write(uhx(b'''\
00010003704138efbbbda16a987dd901
326d1c9459484c88a2861b91a312587a
e70ef6237ec50e1032dc39dde89a96a8
e859d76a98a6e7e36a0cfe352ca89305
8234ff833fcb3b03811e9f0dc0d9a52f
8045b4b2f9411b67a51c44b5ef8ce77b
d6d56ba75734a1856de6d4bed6d3a242
c7c8791b3422375e5c779abf072f7695
efa0f75bcb83789fc30e3fe4cc839220
7840638949c7f688565f649b74d63d8d
58ffadda571e9554426b1318fc468983
d4c8a5628b06b6fc5d507c13e7a18ac1
511eb6d62ea5448f83501447a9afb3ec
c2903c9dd52f922ac9acdbef58c60218
48d96e208732d3d1d9d9ea440d91621c
7a99db8843c59c1f2e2c7d9b577d512c
166d6f7e1aad4a774a37447e78fe2021
e14a95d112a068ada019f463c7a55685
aabb6888b9246483d18b9c806f474918
331782344a4b8531334b26303263d9d2
eb4f4bb99602b352f6ae4046c69a5e7e
8e4a18ef9bc0a2ded61310417012fd82
4cc116cfb7c4c1f7ec7177a17446cbde
96f3edd88fcd052f0b888a45fdaf2b63
1354f40d16e5fa9c2c4eda98e798d15e
6046dc5363f3096b2c607a9d8dd55b15
02a6ac7d3cc8d8c575998e7d796910c8
04c495235057e91ecd2637c9c1845151
ac6b9a0490ae3ec6f47740a0db0ba36d
075956cee7354ea3e9a4f2720b26550c
7d394324bc0cb7e9317d8a8661f42191
ff10b08256ce3fd25b745e5194906b4d
61cb4c2e000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
526f6f74000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000001434130303030303030330000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
000000007be8ef6cb279c9e2eee121c6
eaf44ff639f88f078b4b77ed9f9560b0
358281b50e55ab721115a177703c7a30
fe3ae9ef1c60bc1d974676b23a68cc04
b198525bc968f11de2db50e4d9e7f071
e562dae2092233e9d363f61dd7c19ff3
a4a91e8f6553d471dd7b84b9f1b8ce73
35f0f5540563a1eab83963e09be90101
1f99546361287020e9cc0dab487f140d
6626a1836d27111f2068de4772149151
cf69c61ba60ef9d949a0f71f5499f2d3
9ad28c7005348293c431ffbd33f6bca6
0dc7195ea2bcc56d200baf6d06d09c41
db8de9c720154ca4832b69c08c69cd3b
073a0063602f462d338061a5ea6c915c
d5623579c3eb64ce44ef586d14baaa88
34019b3eebeed3790001000100000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00010004969fe8288da6b9dd52c7bd63
642a4a9ae5f053eccb93613fda379920
87bd9199da5e6797618d77098133fd5b
05cd8288139e2e975cd2608003878cda
f020f51a0e5b7692780845561b31c618
08e8a47c3462224d94f736e9a14e56ac
bf71b7f11bbdee38ddb846d6bd8f0ab4
e4948c5434eaf9bf26529b7eb83671d3
ce60a6d7a850dbe6801ec52a7b7a3e5a
27bc675ba3c53377cfc372ebce02062f
59f37003aa23ae35d4880e0e4b69f982
fb1bac806c2f75ba29587f2815fd7783
998c354d52b19e3fad9fbef444c48579
288db0978116afc82ce54dacb9ed7e1b
fd50938f22f85eecf3a4f426ae5feb15
b72f022fb36ecce9314dad131429bfc9
675f58ee000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
526f6f742d4341303030303030303300
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000001585330303030303032300000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
0000000000000000d21d3ce67c1069da
049d5e5310e76b907e18eec80b337c47
23e339573f4c664907db2f0832d03df5
ea5f160a4af24100d71afac2e3ae75af
a1228012a9a21616597df71eafcb6594
1470d1b40f5ef83a597e179fcb5b57c2
ee17da3bc3769864cb47856767229d67
328141fc9ab1df149e0c5c15aeb80bc5
8fc71be18966642d68308b506934b8ef
779f78e4ddf30a0dcf93fcafbfa131a8
839fd641949f47ee25ceecf814d55b0b
e6e5677c1effec6f29871ef29aa3ed91
97b0d83852e050908031ef1abbb5afc8
b3dd937a076ff6761ab362405c3f7d86
a3b17a6170a659c16008950f7f5e06a5
de3e5998895efa7deea060be9575668f
78ab1907b3ba1b7d0001000100000000
00000000000000000000000000000000
8
div>
00000000000000000000000000000000
00000000000000000000000000000000'''.replace(b'\n', b'')))
f.close()
return fPath
def decrypt_NCA(fPath, outDir=''):
if not outDir:
outDir = os.path.splitext(fPath)[0]
os.makedirs(outDir, exist_ok=True)
commandLine = hactoolPath + ' "' + fPath + '"' + keysArg\
+ ' --exefsdir="' + outDir + '/exefs"'\
+ ' --romfsdir="' + outDir + '/romfs"'\
+ ' --section0dir="' + outDir + '/section0"'\
+ ' --section1dir="' + outDir + '/section1"'\
+ ' --section2dir="' + outDir + '/section2"'\
+ ' --section3dir="' + outDir + '/section3"'\
+ ' --header="' + outDir + '/Header.bin"'
pipes = subprocess.Popen(commandLine, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
_, std_err = pipes.communicate()
if pipes.returncode != 0:
err_msg = '%s. Code: %s' % (std_err.strip(), pipes.returncode)
raise Exception(err_msg)
elif len(std_err):
raise Exception(std_err)
return outDir
def get_name_from_nacp(fPath):
dir = decrypt_NCA(fPath)
nacpPath = os.path.join(dir, 'romfs', 'control.nacp')
try:
f = open(nacpPath, 'rb')
name = f.read(0x200).strip(b'\x00').decode()
f.close()
return safe_name(name)
except FileNotFoundError:
return ''
def cert_dead():
print("\n\n" + _('Request rejected by server! You may need a new cert.'))
messagebox.showinfo("", _('Request rejected by server! You may need a new cert.'))
if os.path.isfile('cert_dead.jpg'):
img2 = ImageTk.PhotoImage(Image.open('cert_dead.jpg'))
imageLabel_widget.configure(image=img2, text="")
imageLabel_widget.image = img2
sys.exit()
def make_request(method, url, certificate='', hdArgs={}):
if not certificate: # Workaround for defining errors
certificate = NXclientPath
reqHd = {'User-Agent': 'NintendoSDK Firmware/%s (platform:NX; did:%s; eid:%s)' % (fw, did, env),
'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*',
'Connection': 'keep-alive'}
reqHd.update(hdArgs)
r = requests.request(method, url, cert=certificate, headers=reqHd, verify=False, stream=True)
if r.status_code == 403:
cert_dead()
if r.status_code == 404:
print('Error, File doesn\'t exist on the CDN')
return None
return r
def make_request_new(method, url, certificate='', hdArgs={}):
if certificate == '': # Workaround for defining errors
certificate = NXclientPath
reqHd = {'User-Agent': 'NintendoSDK Firmware/%s (platform:NX; eid:%s)' % (fw, env),
'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*',
'Connection': 'keep-alive'}
reqHd.update(hdArgs)
r = requests.request(method, url, cert=certificate, headers=reqHd, verify=False, stream=True)
if r.status_code == 403:
cert_dead()
return r
def print_info(tid):
print('\n%s:' % tid)
if tid.endswith('000'):
basetid = tid
updatetid = '%016x' % (int(tid, 16) + 0x800)
elif tid.endswith('800'):
basetid = '%016x' % (int(tid, 16) & 0xFFFFFFFFFFFFF000)
updatetid = tid
else:
basetid = '%016x' % (int(tid, 16) - 0x1000 & 0xFFFFFFFFFFFFF000)
updatetid = basetid[:-3] + '800'
try:
_, name, size = get_info(tid=basetid)
except requests.exceptions.SSLError:
print('\tCould not get info from Shogun')
name = ''
size = 0
if name:
print('\tName: %s' % name)
if size:
print('\tSize: %s' % bytes2human(size))
if tid != basetid:
versions = get_versions(tid)
print('\n\tAvailable versions for %s:' % tid)
print('\t\tv' + ' v'.join(versions))
print('\n\tBase TID: %s' % basetid)
versions = get_versions(basetid)
print('\tAvailable versions for %s:' % basetid)
print('\t\tv' + ' v'.join(versions))
print('\n\tUpdate TID: %s' % updatetid)
versions = get_versions(updatetid)
print('\tAvailable versions for %s:' % updatetid)
if versions:
print('\t\tv' + ' v'.join(versions))
else:
print('\t\t%s has no version available' % updatetid)
def get_info(tid='', freeword=''):
print(tid)
if tid:
url = 'https://bugyo.hac.%s.eshop.nintendo.net/shogun/v1/contents/ids?shop_id=4&lang=en&country=%s&type=title&title_ids=%s'\
% (env, reg, tid)
r = make_request('GET', url, certificate=ShopNPath)
j = r.json()
nsuid = j['id_pairs'][0]['id']
print(nsuid)
elif freeword:
url = 'https://bugyo.hac.lp1.eshop.nintendo.net/shogun/v1/titles?shop_id=4&lang=en&offset=0&country=%s&limit=25&sort=popular&freeword=%s'\
% (reg, freeword)
r = make_request('GET', url, certificate=ShopNPath)
j = r.json()
nsuid = j['contents'][0]['id']
try:
url = 'https://bugyo.hac.%s.eshop.nintendo.net/shogun/v1/titles/%s?shop_id=4&lang=en&country=%s' % (env, nsuid, reg)
r = make_request('GET', url, certificate=ShopNPath)
j = r.json()
if freeword:
try:
tid = j['applications'][0]['id']
except KeyError:
print('Found no result for %s on Shogun' % freeword)
raise
try:
name = j['formal_name']
name = safe_name(name)
except IndexError:
name = ''
try:
size = j['total_rom_size']
except IndexError:
size = 0
except IndexError:
print('\tTitleID not found on Shogun!')
return tid, name, size
def get_versions(tid):
#url = 'https://tagaya.hac.%s.eshop.nintendo.net/tagaya/hac_versionlist' % env
url = 'https://superfly.hac.%s.d4c.nintendo.net/v1/t/%s/dv' % (env,tid)
r = make_request_new('GET', url)
j = r.json()
try:
if j['error']:
return ['none']
except Exception as e:
pass
try:
lastestVer = j['version']
if lastestVer < 65536:
return ['%s' % lastestVer]
else:
versionList = ('%s' % "-".join(str(i) for i in range(0x10000, lastestVer+1, 0x10000))).split('-')
return versionList
except Exception as e:
return ['none']
def check_versions(fPath):
f = open(fPath, 'r')
old = {}
for line in f.readlines():
tid, ver = line.strip().split('-')
old[tid] = ver
n = 1
new = {}
for tid in old:
sys.stdout.write('\rChecking for updates for title %s of %s...' % (n, len(old)))
sys.stdout.flush()
n += 1
latestVer = get_versions(tid)[-1]
if latestVer and int(latestVer) > int(old[tid]):
new[tid] = latestVer
if tid.endswith('000'):
updatetid = '%016x'.lower() % (int(tid, 16) + 0x800)
if updatetid not in old:
updateVer = get_versions(updatetid)
if updateVer:
new[updatetid] = updateVer[-1]
sys.stdout.write('\r\033[F')
if new:
for tid in new:
print('New update available for %s: v%s' % (tid, new[tid]))
dl = input('\nType anything to download the new updates: ')
if dl:
for tid in new:
download_game(tid, new[tid], nspRepack=True, verify=True)
else:
print('No new update was found for any of the downloaded titles!')
f.close()
def download_file(url, fPath, fSize=0):
fName = os.path.basename(fPath).split()[0]
if os.path.exists(fPath) and fSize != 0:
dlded = os.path.getsize(fPath)
if dlded == fSize:
print('\t\tDownload is already complete, skipping!')
return fPath
elif dlded < fSize:
print('\t\tResuming download...')
r = make_request('GET', url, hdArgs={'Range': 'bytes=%s-' % dlded})
f = open(fPath, 'ab')
else:
print('\t\tExisting file is bigger than expected (%s/%s), restarting download...' % (dlded, fSize))
dlded = 0
r = make_request('GET', url)
f = open(fPath, "wb")
else:
dlded = 0
r = make_request('GET', url)
fSize = int(r.headers.get('Content-Length'))
f = open(fPath, 'wb')
if fSize >= 10000:
E8AC
t = tqdm(initial=dlded, total=int(fSize), desc=fName, unit='B', unit_scale=True, leave=False, mininterval=0.5)
for chunk in r.iter_content(4096):
f.write(chunk)
dlded += len(chunk)
t.update(len(chunk))
t.close()
else:
f.write(r.content)
dlded += len(r.content)
if fSize != 0 and dlded != fSize:
raise ValueError('Downloaded data is not as big as expected (%s/%s)!' % (dlded, fSize))
f.close()
print('\r\t\tSaved to %s!' % os.path.basename(f.name))
return fPath
def download_cetk(rightsID, fPath):
url = 'https://atum.hac.%s.d4c.nintendo.net/r/t/%s?device_id=%s' % (env, rightsID, did)
r = make_request('HEAD', url)
id = r.headers.get('X-Nintendo-Content-ID')
url = 'https://atum.hac.%s.d4c.nintendo.net/c/t/%s?device_id=%s' % (env, id, did)
cetk = download_file(url, fPath, fSize=2496)
return cetk
def download_title(gameDir, tid, ver, tkey='', nspRepack=False, verify=False, n=''):
print('\n%s v%s:' % (tid, ver))
if len(tid) != 16:
tid = (16-len(tid)) * '0' + tid
url = 'https://atum%s.hac.%s.d4c.nintendo.net/t/a/%s/%s?device_id=%s' % (n, env, tid, ver, did)
r = make_request('HEAD', url)
if r == None:
return (None, "")
CNMTid = r.headers.get('X-Nintendo-Content-ID')
print('\tDownloading CNMT (%s.cnmt.nca)...' % CNMTid)
url = 'https://atum%s.hac.%s.d4c.nintendo.net/c/a/%s?device_id=%s' % (n, env, CNMTid, did)
fPath = os.path.join(gameDir, CNMTid + '.cnmt.nca')
cnmtNCA = download_file(url, fPath)
cnmtDir = decrypt_NCA(cnmtNCA)
CNMT = cnmt(os.path.join(cnmtDir, 'section0', os.listdir(os.path.join(cnmtDir, 'section0'))[0]),
os.path.join(cnmtDir, 'Header.bin'))
if nspRepack:
outf = os.path.join(gameDir, '%s.xml' % os.path.basename(cnmtNCA).strip('.nca'))
cnmtXML = CNMT.gen_xml(cnmtNCA, outf)
rightsID = '%032x' % ((int(tid, 16) << 64) + int(CNMT.mkeyrev))
tikPath = os.path.join(gameDir, rightsID+'.tik')
certPath = os.path.join(gameDir, rightsID+'.cert')
if CNMT.type == 'Application' or CNMT.type == 'AddOnContent':
gen_cert(certPath)
gen_tik(tikPath, rightsID, tkey, CNMT.mkeyrev)
print('\t\tGenerated %s and %s!' % (os.path.basename(certPath), os.path.basename(tikPath)))
elif CNMT.type == 'Patch':
print('\tDownloading CETK...')
with open(download_cetk(rightsID, os.path.join(gameDir, rightsID+'.cetk')), 'rb') as cetk:
cetk.seek(0x180)
tkey = hx(cetk.read(0x10)).decode()
print('\t\t\tTitlekey: %s' % tkey)
with open(tikPath, 'wb') as tik:
cetk.seek(0x0)
tik.write(cetk.read(0x2C0))
with open(certPath, 'wb') as cert:
cetk.seek(0x2C0)
cert.write(cetk.read(0x700))
print('\t\tExtracted %s and %s from CETK!' % (os.path.basename(certPath), os.path.basename(tikPath)))
NCAs = {
0: [],
1: [],
2: [],
3: [],
4: [],
5: [],
6: [],
}
name = ''
for type in [0, 3, 4, 5, 1, 2, 6]: # Download smaller files first
list = CNMT.parse(CNMT.contentTypes[type])
for ncaID in list:
print('\tDownloading %s entry (%s.nca)...' % (CNMT.contentTypes[type], ncaID))
url = 'https://atum%s.hac.%s.d4c.nintendo.net/c/c/%s?device_id=%s' % (n, env, ncaID, did)
fPath = os.path.join(gameDir, ncaID + '.nca')
fSize = list[ncaID][1]
NCAs[type].append(download_file(url, fPath, fSize))
print(list[ncaID][2])
if verify:
print('\t\tVerifying file...')
if sha256_file(fPath) == list[ncaID][2]:
print('\t\t\tHashes match, file is correct!')
else:
print('\t\t\t%s is corrupted, hashes don\'t match!' % os.path.basename(fPath))
if type == 3:
name = get_name_from_nacp(NCAs[type][-1])
if not name:
name = ''
if nspRepack:
files = []
if tkey:
files.append(certPath)
files.append(tikPath)
for key in [1, 5, 2, 4, 6]:
if NCAs[key]:
files.extend(NCAs[key])
files.append(cnmtNCA)
files.append(cnmtXML)
if NCAs[3]:
files.extend(NCAs[3])
return files, name
else:
return gameDir, name
def download_title_tinfoil(gameDir, tid, ver, tkey='', nspRepack=False, n='', verify=False):
print('\n%s v%s:' % (tid, ver))
tid = tid.lower();
tkey = tkey.lower();
if len(tid) != 16:
tid = (16 - len(tid)) * '0' + tid
url = 'https://atum.hac.%s.d4c.nintendo.net/t/a/%s/%s?device_id=%s' % (env, tid, ver, did)
print(url)
try:
r = make_request_new('HEAD', url)
except Exception as e:
print("Error downloading title. Check for incorrect titleid or version.")
return
CNMTid = r.headers.get('X-Nintendo-Content-ID')
if CNMTid == None:
print('title not available on CDN')
return None
print('\nDownloading CNMT (%s.cnmt.nca)...' % CNMTid)
url = 'https://atum%s.hac.%s.d4c.nintendo.net/c/a/%s?device_id=%s' % (n, env, CNMTid, did)
fPath = os.path.join(gameDir, CNMTid + '.cnmt.nca')
cnmtNCA = download_file(url, fPath)
cnmtDir = decrypt_NCA(cnmtNCA)
CNMT = cnmt(os.path.join(cnmtDir, 'section0', os.listdir(os.path.join(cnmtDir, 'section0'))[0]),
os.path.join(cnmtDir, 'Header.bin'))
if nspRepack == True:
outf = os.path.join(gameDir, '%s.xml' % os.path.basename(cnmtNCA.strip('.nca')))
cnmtXML = CNMT.gen_xml_tinfoil(cnmtNCA, outf)
rightsID = '%s%s%s' % (tid, (16 - len(CNMT.mkeyrev)) * '0', CNMT.mkeyrev)
tikPath = os.path.join(gameDir, '%s.tik' % rightsID)
certPath = os.path.join(gameDir, '%s.cert' % rightsID)
if CNMT.type == 'Application' or CNMT.type == 'AddOnContent':
shutil.copy(os.path.join(os.path.dirname(__file__), 'Certificate.cert'), certPath)
if tkey != '':
with open(os.path.join(os.path.dirname(__file__), 'Ticket.tik'), 'rb') as intik:
data = bytearray(intik.read())
data[0x180:0x190] = uhx(tkey)
data[0x286] = int(CNMT.mkeyrev)
data[0x2A0:0x2B0] = uhx(rightsID)
with open(tikPath, 'wb') as outtik:
outtik.write(data)
print('\nGenerated %s and %s!' % (os.path.basename(certPath), os.path.basename(tikPath)))
else:
print('\nGenerated %s!' % os.path.basename(certPath))
You can’t perform that action at this time.