-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathrun.py
2070 lines (1952 loc) · 88.7 KB
/
run.py
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 python
import hashlib
import json
import platform as plat
import re
import shutil
import subprocess
import sys
import time
import zipfile
from argparse import Namespace
from configparser import ConfigParser
from io import BytesIO
from os import path as o_path
from src import languages
from src import banner
from src import ext4
from src.Magisk import Magisk_patch
import os
from src.dumper import Dumper
import builtins
if os.name == 'nt':
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW("TIK5_Alpha")
else:
sys.stdout.write("\x1b]2;TIK5_Alpha\x07")
sys.stdout.flush()
import extract_dtb
import requests
from rich.progress import track
from src import contextpatch
from src import downloader
from src import fspatch
from src import imgextractor
from src import lpunpack
from src import mkdtboimg
from src import ofp_mtk_decrypt
from src import ofp_qc_decrypt
from src import ozipdecrypt
from src import utils
from src.api import cls, dir_has, cat, dirsize, re_folder, f_remove
from src.log import LOGS, LOGE, ysuc, yecho, ywarn
from src.utils import gettype, simg2img, call
from src import opscrypto
from src import zip2mpk
from rich.table import Table
from rich.console import Console
LOCALDIR = os.getcwd()
binner = o_path.join(LOCALDIR, "bin")
setfile = o_path.join(LOCALDIR, "bin", "settings.json")
platform = plat.machine()
ostype = plat.system()
if os.getenv('PREFIX'):
if os.getenv('PREFIX') == "/data/data/com.termux/files/usr":
ostype = 'Android'
ebinner = o_path.join(binner, ostype, platform) + os.sep
temp = o_path.join(binner, 'temp')
class json_edit:
def __init__(self, j_f):
self.file = j_f
def read(self):
if not os.path.exists(self.file):
return {}
with open(self.file, 'r+', encoding='utf-8') as pf:
try:
return json.loads(pf.read())
except (Exception, BaseException):
return {}
def write(self, data):
with open(self.file, 'w+', encoding='utf-8') as pf:
json.dump(data, pf, indent=4)
def edit(self, name, value):
data = self.read()
data[name] = value
self.write(data)
def rmdire(path):
if o_path.exists(path):
if os.name == 'nt':
for r, d, f in os.walk(path):
for i in d:
if i.endswith('.'):
call(['mv', str(os.path.join(r, i)), str(os.path.join(r, i[:1]))])
for i in f:
if i.endswith('.'):
call(['mv', os.path.join(r, i), os.path.join(r, i[:1])])
try:
shutil.rmtree(path)
except PermissionError:
ywarn('Cannot Remove The Folder, Permission denied.')
else:
ysuc("Remove Successful!")
def error(exception_type, exception, traceback):
cls()
table = Table()
try:
version = settings.version
except:
version = 'Unknown'
table.add_column(f'[red]ERROR:{exception_type.__name__}[/]', justify="center")
table.add_row(f'[yellow]Describe:{exception}')
table.add_row(
f'[yellow]Lines:{exception.__traceback__.tb_lineno}\tModule:{exception.__traceback__.tb_frame.f_globals["__name__"]}')
table.add_section()
table.add_row(
f'[blue]Platform:[purple]{plat.machine()}\t[blue]System:[purple]{plat.uname().system} {plat.uname().release}')
table.add_row(f'[blue]Python:[purple]{sys.version[:6]}\t[blue]Tool Version:[purple]{version}')
table.add_section()
table.add_row(f'[green]Report:https://github.com/ColdWindScholar/TIK/issues')
Console().print(table)
input()
sys.exit(1)
# sys.excepthook = error
def sha1(file_path):
if os.path.exists(file_path):
with open(file_path, 'rb') as f:
return hashlib.sha1(f.read()).hexdigest()
else:
return ''
if not os.path.exists(ebinner):
raise Exception("Binary not found\nMay Not Support Your Device?")
try:
if os.path.basename(sys.argv[0]) == f'run_new{str() if os.name == "posix" else ".exe"}':
os.remove(os.path.join(LOCALDIR, f'run{str() if os.name == "posix" else ".exe"}'))
shutil.copyfile(os.path.join(LOCALDIR, f'run_new{str() if os.name == "posix" else ".exe"}'),
os.path.join(LOCALDIR, f'run{str() if os.name == "posix" else ".exe"}'))
elif os.path.basename(sys.argv[0]) == f'run{str() if os.name == "posix" else ".exe"}':
new = os.path.join(LOCALDIR, f'run_new{str() if os.name == "posix" else ".exe"}')
if os.path.exists(new):
if sha1(os.path.join(LOCALDIR, f'run{str() if os.name == "posix" else ".exe"}')) == sha1(new):
os.remove(new)
else:
subprocess.Popen([new])
sys.exit()
except (Exception, BaseException):
...
sys_stdout_write_ = sys.stdout.write
input_old = builtins.input
class Welcome:
def __init__(self, step:int=None):
if step is None:
self.step = 0
else:
self.step = step
self.steps = {
0: self.welcome,
1: self.language,
2: self.done
}
self.change_page()
def change_page(self):
cls()
for step in self.steps:
if step < self.step:
continue
page = self.steps.get(step, 0)
cls()
settings.change('oobe', str(step))
print(f"\033[34m {banner.banner1} \033[0m")
page()
return
def welcome(self):
print("\033[33mHello! Welcome to TIK5!\033[0m")
input("\033[32m Enter to continue. \033[0m")
def language(self):
language_list = {index + 1: lan for index, lan in enumerate(dir(languages)) if
lan != 'default' and not lan.startswith("_") and not lan.endswith('_')}
for index, lan in language_list.items():
print(f'{index} >\033[93m{lan}\033[0m')
input_value = "None"
while not input_value.isdigit():
input_value = input("\033[94mSelect Your Language:\033[0m")
try:
int(input_value)
except Exception:
continue
input_value = int(input_value)
language = language_list.get(input_value, languages.default)
settings.change('language', language)
def done(self):
input("Well Done! Let's Try New Tik!")
class set_utils:
def __init__(self, path):
self.path = path
self.language_dict = {}
def load_set(self):
with open(self.path, 'r') as ss:
data = json.load(ss)
[setattr(self, v, data[v]) for v in data]
if hasattr(languages, settings.language):
self.language_dict = getattr(languages, settings.language)
def sys_stdout_write(s: str):
t = self.language_dict.get(s, s)
if s != t:
s = t
else:
for i in self.language_dict:
if i in s:
s = s.replace(i, self.language_dict.get(i, i))
sys_stdout_write_(s)
def new_input(prompt: object = ''):
t = self.language_dict.get(prompt, prompt)
if prompt != t:
prompt = t
else:
for i in self.language_dict:
if i in prompt:
prompt = prompt.replace(i, self.language_dict.get(i, i))
return input_old(prompt)
builtins.input = new_input
sys.stdout.write = sys_stdout_write
def change(self, name, value):
with open(self.path, 'r') as ss:
data = json.load(ss)
with open(self.path, 'w', encoding='utf-8') as ss:
data[name] = value
json.dump(data, ss, ensure_ascii=False, indent=4)
self.load_set()
settings = set_utils(setfile)
settings.load_set()
if int(settings.oobe) < 2:
Welcome(step=int(settings.oobe))
class upgrade:
update_json = 'https://mirror.ghproxy.com/https://raw.githubusercontent.com/ColdWindScholar/Upgrade/main/TIK.json'
def __init__(self):
if not os.path.exists(temp):
os.makedirs(temp)
cls()
with Console().status(f"[blue]Detecting new version...[/]"):
try:
data = requests.get(self.update_json).json()
except (Exception, BaseException):
data = None
if not data:
input("Connect to server failed, press any button to return")
return
else:
if data.get('version', settings.version) != settings.version:
print(f'\033[31m {banner.banner1} \033[0m')
print(
f"\033[0;32;40mNew Version:\033[0m\033[0;36;40m{settings.version} --> {data.get('version')}\033[0m")
print(f"\033[0;32;40mChangeLog:\n\033[0m\033[0;36;40m{data.get('log', '1.Fix Some Bugs')}\033[0m")
input(
"Please note that the builds in the communication group and release are always the latest development environment version. This feature is only used to detect recent stable builds")
try:
link = data['link'][plat.system()][plat.machine()]
except (Exception, BaseException):
input(
"No updates found for your device, please go to https://github.com/ColdWindScholar/TIK update it yourself")
return
if not link:
input(
"No updates found for your device, please go to https://github.com/ColdWindScholar/TIK update it yourself")
return
if input("\033[0;33;40mUpdate it?[1/0]\033[0m") == '1':
print("Downloading...")
try:
downloader.download([link], temp)
except (BaseException, Exception):
input("Download error, please try again later")
return
print("Starting update, please do not close the tool...")
upgrade_pkg = os.path.join(temp, os.path.basename(link))
extract_path = os.path.join(temp, 'update')
if os.path.exists(extract_path):
rmdire(extract_path)
try:
zipfile.ZipFile(upgrade_pkg).extractall(extract_path)
except (Exception, BaseException):
input("The update file is damaged and cannot be updated")
return
self.settings = json_edit(setfile).read()
json2 = json_edit(os.path.join(extract_path, 'bin', 'settings.json')).read()
for i in self.settings.keys():
json2[i] = self.settings.get(i, json2.get(i, ''))
json2['version'] = data.get('version', settings.version)
self.settings = json2
shutil.copytree(os.path.join(extract_path, 'bin'), os.path.join(LOCALDIR, 'bin2'),
dirs_exist_ok=True)
shutil.move(os.path.join(extract_path, f'run{str() if os.name == "posix" else ".exe"}'),
os.path.join(LOCALDIR, f'run_new{str() if os.name == "posix" else ".exe"}'))
shutil.rmtree(os.path.join(LOCALDIR, 'bin'))
shutil.copytree(os.path.join(LOCALDIR, 'bin2'), os.path.join(LOCALDIR, 'bin'))
shutil.rmtree(os.path.join(LOCALDIR, 'bin2'))
json_edit(setfile).write(json2)
input("Update completed, any button to start a new program...")
subprocess.Popen([os.path.join(LOCALDIR, f'run_new{str() if os.name == "posix" else ".exe"}')])
sys.exit()
else:
input("\033[0;32;40mYou are using the latest version! Any button returns!\033[0m")
return
class setting:
def settings1(self):
actions = {
"1": lambda: settings.change('brcom', brcom if (brcom := input(
" Adjust the brotli compression level (integers 1-9):")).isdigit() and 0 < int(
brcom) < 10 else '1'),
"2": lambda: settings.change('diysize',
"1" if input(" Package Ext image size: [1]Auto [2]Origin:") == '2' else ''),
"3": lambda: settings.change('pack_e2', '0' if input(
" Packing Method: [1]make_ext4fs [2]mke2fs+e2fsdroid:") == '1' else '1'),
"6": lambda: settings.change('pack_sparse', '1' if input(
" Pack to Sparse:[1/0]:") == '1' else "0"),
"7": lambda: settings.change('diyimgtype',
'1' if input(
f" Packaging Image Format [1]Origin [2]Selectable:") == '2' else ''),
"8": lambda: settings.change('erofs_old_kernel',
'1' if input(f" EROFS Support old Kernel[1/0]") == '1' else '0')
}
cls()
print(f'''
\033[33m > Packing Settings \033[0m
1> Brotli Level \033[93m[{settings.brcom}]\033[0m\n
----[EXT4 Settings]------
2> Size Handle \033[93m[{settings.diysize}]\033[0m
3> Packing Method \033[93m[{settings.pack_e2}]\033[0m\n
----[EROFS Settings]-----
4> Packing Format \033[93m[{settings.erofslim}]\033[0m\n
----[IMG Settings]-------
5> UTC Timestamp \033[93m[{settings.utcstamp}]\033[0m
6> Pack to sparse \033[93m[{settings.pack_sparse}]\033[0m
7> File System \033[93m[{settings.diyimgtype}]\033[0m
8> Support old Kernel \033[93m[{settings.erofs_old_kernel}]\033[0m\n
0> Previous Menu
--------------------------
''')
op_pro = input(" Please enter the number:")
if op_pro == "0":
return
elif op_pro in actions.keys():
actions[op_pro]()
elif op_pro == '4':
if input(" Optional erofs compression method[1]Yes [2]No:") == '1':
erofslim = input(
" Choose erofs compression method:lz4/lz4hc/lzma/and Level[1-9] such as lz4hc,8:")
settings.change("erofslim", erofslim if erofslim else 'lz4hc,8')
else:
settings.change("erofslim", 'lz4hc,8')
elif op_pro == '5':
if input(" Set packaging UTC timestamp [1] automatic [2] customization:") == "2":
utcstamp = input(" Enter: ")
settings.change('utcstamp', utcstamp if utcstamp.isdigit() else '1717840117')
else:
settings.change('utcstamp', '')
else:
print("Input error!")
self.settings1()
def settings2(self):
cls()
actions = {
'1': lambda: settings.change('super_group', super_group if (
super_group := input(f" Enter:")) else "qti_dynamic_partitions"),
'2': lambda: settings.change('metadatasize', metadatasize if (
metadatasize := input(
" Set the maximum reserved size for metadata (default to 65536, at least 512):")) else '65536'),
'3': lambda: settings.change('BLOCKSIZE', BLOCKSIZE if (
BLOCKSIZE := input(
f" Partition packaging sector/block size::{settings.BLOCKSIZE}\n Enter: ")) else "4096"),
'4': lambda: settings.change('BLOCKSIZE', SBLOCKSIZE if (
SBLOCKSIZE := input(
f" Partition packaging sector/block size:{settings.SBLOCKSIZE}\n Enter: ")) else "4096"),
'5': lambda: settings.change('supername', supername if (supername := input(
f' Current dynamic partition physical partition name (default super):{settings.supername}\n Enter: ')) else "super"),
'6': lambda: settings.change('fullsuper', '' if input(
" Do you want to force the creation of Super images?[1/0]") != '1' else '-F'),
'7': lambda: settings.change('autoslotsuffixing',
'' if input(
" Mark partitions that require a Slot suffix?[1/0]") != '1' else '-x')
}
print(f'''
\033[33m > Dynamic partition settings \033[0m
1> Super group name \033[93m[{settings.super_group}]\033[0m\n
----[Metadata settings]--
2> Maximum reserved size \033[93m[{settings.metadatasize}]\033[0m\n
----[Partition settings]------
3> Default sector/block size for partition settings \033[93m[{settings.BLOCKSIZE}]\033[0m\n
----[Super settings]-----
4> Specify block size \033[93m[{settings.SBLOCKSIZE}]\033[0m
5> Change physical partition name \033[93m[{settings.supername}]\033[0m
6> Force complete generation Img \033[93m[{settings.fullsuper}]\033[0m
7> Mark partition slot suffix \033[93m[{settings.autoslotsuffixing}]\033[0m\n
0>Previous Menu
--------------------------
''')
op_pro = input(" Please enter the number: ")
if op_pro == "0":
return
elif op_pro in actions.keys():
actions[op_pro]()
else:
ywarn("Input error!")
self.settings2()
def settings3(self):
cls()
print(f'''
\033[33m > Tool settings \033[0m\n
1>Banner \033[93m[{settings.banner}]\033[0m\n
2>Online Mode \033[93m[{settings.online}]\033[0m\n
3>Contexts Patcher \033[93m[{settings.context}]\033[0m\n
4>Language \033[93m[{settings.language}]\033[0m\n
5>Check Update \n
0>Previous Menu\n
--------------------------
''')
op_pro = input(" Please enter the number: ")
if op_pro == "0":
return
elif op_pro == '1':
print(f" Banner: [1]TIK5 [2]Sickle and axe head [3]TIK2 [4]YuanSheng [5]DXY [6]None")
banner_i = input(" Please enter the number: ")
if banner_i.isdigit():
if 0 < int(banner_i) < 7:
settings.change('banner', banner_i)
elif op_pro == '2':
settings.change('online', 'false' if settings.online == 'true' else 'true')
elif op_pro == '3':
settings.change('context', 'false' if settings.context == 'true' else 'true')
elif op_pro == '4':
language_list = {index + 1: lan for index, lan in enumerate(dir(languages)) if
lan != 'default' and not lan.startswith("_") and not lan.endswith('_')}
print("Select Your Language:")
for index, lan in language_list.items():
print(f'{index}>{lan}')
language = language_list.get(int(input("Select Your Language:")), languages.default)
settings.change('language', language)
elif op_pro == '5':
upgrade()
self.settings3()
@staticmethod
def settings4():
cls()
print(f'\033[31m {banner.banner1} \033[0m')
print('\033[96m Open source Android full version ROM processing tool\033[0m')
print('\033[31m---------------------------------\033[0m')
print(f"\033[93mAuthor:\033[0m \033[92mColdWindScholar\033[0m")
print(f"\033[93mOpen Source Link:\033[0m \033[91mhttps://github.com/ColdWindScholar/TIK\033[0m")
print(f"\033[93mVersion:\033[0m \033[44mAlpha Edition\033[0m")
print(f"\033[93mOpen Source License:\033[0m \033[68mGNU General Public License v3.0 \033[0m")
print('\033[31m---------------------------------\033[0m')
print(f"\033[93mThanks to:\033[0m")
print('\033[94mAffggh')
print("Yeliqin666")
print('YukongA')
print("\033[0m")
input('\033[31m---------------------------------\033[0m')
def __init__(self):
cls()
print('''
\033[33m > Settings \033[0m
1>[Packaging] Related Settings\n
2>[Dynamic Partition] Related Settings\n
3>Tool settings\n
4>About\n
0>Home
--------------------------
''')
op_pro = input(" Please enter the number: ")
if op_pro == "0":
return
try:
getattr(self, 'settings%s' % op_pro)()
self.__init__()
except AttributeError as e:
print(f"Input error!{e}")
self.__init__()
def plug_parse(js_on):
class parse:
gavs = {}
def __init__(self, jsons):
self.value = []
print("""
------------------
MIO-PACKAGE-PARSER
------------------
""")
with open(jsons, 'r', encoding='UTF-8') as f:
try:
data_ = json.load(f)
except Exception as e:
ywarn("Parse Error %s" % e)
return
plugin_title = data_['main']['info']['title']
print("----------" + plugin_title + "----------")
for group_name, group_data in data_['main'].items():
if group_name != "info":
for con in group_data['controls']:
if 'set' in con:
self.value.append(con['set'])
if con["type"] == "text":
if con['text'] != plugin_title:
print("----------" + con['text'] + "----------")
elif con["type"] == "filechose":
file_var_name = con['set']
ysuc("Please drag the file below or enter the path")
self.gavs[file_var_name] = input(con['text'])
elif con["type"] == "radio":
gavs = {}
radio_var_name = con['set']
options = con['opins'].split()
cs = 0
print("-------Options---------")
for option in options:
cs += 1
text, value = option.split('|')
self.gavs[radio_var_name] = value
print(f"[{cs}] {text}")
gavs[str(cs)] = value
print("---------------------------")
op_in = input("Please Enter:")
self.gavs[radio_var_name] = gavs[op_in] if op_in in gavs.keys() else gavs["1"]
elif con["type"] == 'input':
input_var_name = con['set']
if 'text' in con:
print(con['text'])
self.gavs[input_var_name] = input("Please Enter A Value:")
elif con['type'] == 'checkbutton':
b_var_name = con['set']
text = 'M.K.C' if 'text' not in con else con['text']
self.gavs[b_var_name] = 1 if input(text + "[1/0]:") == '1' else 0
else:
print("Unsupported Widget:%s" % con['type'])
data = parse(js_on)
return data.gavs, data.value
class Tool:
"""
Free Android Rom Tool
"""
def __init__(self):
self.pro = None
def main(self):
projects = {}
pro = 0
cls()
if settings.banner != "6":
print(f'\033[31m {getattr(banner, "banner%s" % settings.banner)} \033[0m')
else:
print("=" * 50)
print("\033[93;44m Alpha Edition \033[0m")
if settings.online == 'true':
try:
content = json.loads(requests.get('https://v1.jinrishici.com/all.json', timeout=2).content.decode())
shiju = content['content']
fr = content['origin']
another = content['author']
except (Exception, BaseException):
print(f"\033[36m “Open source is a journey without any questions”\033[0m\n")
else:
print(f"\033[36m “{shiju}”")
print(f"\033[36m---{another}《{fr}》\033[0m\n")
else:
print(f"\033[36m “Open source is a journey without any questions”")
print(" >\033[33m Project List \033[0m\n")
print("\033[31m [00] Remove Project\033[0m\n\n", " [0] New Project\n")
for pros in os.listdir(LOCALDIR):
if pros in ['bin', 'src'] or pros.startswith('.'):
continue
if os.path.isdir(o_path.join(LOCALDIR, pros)):
pro += 1
print(f" [{pro}] {pros}\n")
projects[str(pro)] = pros
print(" --------------------------------------")
print("\033[33m [55] Unpack [66] Exit [77] Settings [88] Download ROM\033[0m\n")
op_pro = input(" Please enter the number:")
if op_pro == '55':
self.unpackrom()
elif op_pro == '88':
url = input("Enter download link:")
if url:
try:
downloader.download([url], LOCALDIR)
except (Exception, BaseException):
...
self.unpackrom()
elif op_pro == '00':
op_pro = input(" Please enter the project number you want to delete:")
op_pro = op_pro.split() if " " in op_pro else [op_pro]
for op in op_pro:
if op in projects.keys():
if input(f" Sure Delete {projects[op]}?[1/0]") == '1':
rmdire(o_path.join(LOCALDIR, projects[op]))
else:
ywarn("Undelete")
elif op_pro == '0':
projec = input("Please Enter Project Name:")
if projec:
if os.path.exists(o_path.join(LOCALDIR, projec)):
projec = f'{projec}_{time.strftime("%m%d%H%M%S")}'
ywarn(f"Project Already exists! Automatically named as:{projec}")
time.sleep(1)
os.makedirs(o_path.join(LOCALDIR, projec, "config"))
self.pro = projec
self.project()
else:
ywarn(" Input error!")
input("Enter to continue")
elif op_pro == '66':
cls()
ysuc("\nThank you for using TI-KITCHEN4. Goodbye!")
sys.exit(0)
elif op_pro == '77':
setting()
elif op_pro.isdigit():
if op_pro in projects.keys():
self.pro = projects[op_pro]
self.project()
else:
ywarn(" Input error!")
input("Enter to continue")
else:
ywarn(" Input error!")
input("Enter to continue")
self.main()
@staticmethod
def dis_avb(fstab):
print(f"Processing: {fstab}")
if not os.path.exists(fstab):
return
with open(fstab, "r") as sf:
details = sf.read()
if not re.search(",avb=vbmeta_system", details):
# it may be "system /system erofs ro avb=vbmeta_system,..."
details = re.sub("avb=vbmeta_system,", "", details)
else:
details = re.sub(",avb=vbmeta_system", ",", details)
if not re.search(",avb", details):
# it may be "product /product ext4 ro avb,..."
details = re.sub("avb,", "", details)
else:
details = re.sub(",avb", "", details)
details = re.sub(",avb_keys=.*avbpubkey", "", details)
details = re.sub(",avb=vbmeta_vendor", "", details)
details = re.sub(",avb=vbmeta", "", details)
with open(fstab, "w") as tf:
tf.write(details)
@staticmethod
def dis_data_encryption(fstab):
print(f"Processing: {fstab}")
if not os.path.exists(fstab):
return
with open(fstab, "r") as sf:
details = re.sub(",fileencryption=aes-256-xts:aes-256-cts:v2+inlinecrypt_optimized+wrappedkey_v0", "",
sf.read())
details = re.sub(",fileencryption=aes-256-xts:aes-256-cts:v2+emmc_optimized+wrappedkey_v0", ",", details)
details = re.sub(",fileencryption=aes-256-xts:aes-256-cts:v2", "", details)
details = re.sub(",metadata_encryption=aes-256-xts:wrappedkey_v0", "", details)
details = re.sub(",fileencryption=aes-256-xts:wrappedkey_v0", "", details)
details = re.sub(",metadata_encryption=aes-256-xts", "", details)
details = re.sub(",fileencryption=aes-256-xts", "", details)
details = re.sub(",fileencryption=ice", "", details)
details = re.sub('fileencryption', 'encryptable', details)
with open(fstab, "w") as tf:
tf.write(details)
def project(self):
project_dir = LOCALDIR + os.sep + self.pro
cls()
os.chdir(project_dir)
print(" \n\033[31m>Project Menu \033[0m\n")
print(f" Project:{self.pro}\033[91m(Incomplete)\033[0m\n") if not os.path.exists(
os.path.abspath('config')) else print(
f" Project:{self.pro}\n")
if not os.path.exists(project_dir + os.sep + 'TI_out'):
os.makedirs(project_dir + os.sep + 'TI_out')
print('\033[33m 0> Home 2> Unpack Menu\033[0m\n')
print('\033[36m 3> Pack Menu 4> Plugin Menu\033[0m\n')
print('\033[32m 5> Pack Rom 6> Other Tools\033[0m\n')
op_menu = input(" Please enter the number: ")
if op_menu == '0':
os.chdir(LOCALDIR)
return
elif op_menu == '2':
unpack_choo(project_dir)
elif op_menu == '3':
packChoo(project_dir)
elif op_menu == '4':
subbed(project_dir)
elif op_menu == '5':
self.hczip()
elif op_menu == '6':
self.custom_rom()
else:
ywarn(' Input error!')
input("Enter to continue")
self.project()
def custom_rom(self):
cls()
print(" \033[31m>Other Tools \033[0m\n")
print(f" Project: {self.pro}\n")
print('\033[33m 0> Previous Menu 1> Magisk Patcher\033[0m\n')
print('\033[33m 2> Disable avb(fstab) 3> Disable data_encryption(fstab)\033[0m\n')
op_menu = input(" Please enter the number: ")
if op_menu == '0':
return
elif op_menu == '1':
self.magisk_patch()
elif op_menu == '2':
for root, dirs, files in os.walk(LOCALDIR + os.sep + self.pro):
for file in files:
if file.startswith("fstab."):
self.dis_avb(os.path.join(root, file))
elif op_menu == '3':
for root, dirs, files in os.walk(LOCALDIR + os.sep + self.pro):
for file in files:
if file.startswith("fstab."):
self.dis_data_encryption(os.path.join(root, file))
else:
ywarn(' Input error!')
input("Enter to continue")
self.custom_rom()
def magisk_patch(self):
cls()
cs = 0
project = LOCALDIR + os.sep + self.pro
os.chdir(LOCALDIR)
print(" \n\033[31m>Magisk Patcher \033[0m\n")
print(f" Project: {self.pro}\n")
print(f" Please place the image to be patched in {project}")
boots = {}
for i in os.listdir(project):
if os.path.isdir(os.path.join(project, i)):
continue
if gettype(os.path.join(project, i)) in ['boot', 'vendor_boot']:
cs += 1
boots[str(cs)] = os.path.join(project, i)
print(f' [{cs}]--{i}')
print("\033[33m-------------------------------\033[0m")
print("\033[33m [00] Return\033[0m\n")
op_menu = input(" Please enter the number: ")
if op_menu in boots.keys():
mapk = input(" Enter the Magisk.apk path:")
if not os.path.isfile(mapk):
ywarn('Input Error!')
else:
patch = Magisk_patch(boots[op_menu], '', MAGISAPK=mapk)
patch.auto_patch()
if os.path.exists(os.path.join(LOCALDIR, 'new-boot.img')):
out = os.path.join(project, "boot_patched.img")
shutil.move(os.path.join(LOCALDIR, 'new-boot.img'), out)
LOGS(f"Moved to:{out}")
LOGS("Patched Successful")
else:
LOGE("Patched Fail")
elif op_menu == '00':
os.chdir(project)
return
else:
ywarn('Input Error!')
input("Enter to continue")
self.magisk_patch()
def hczip(self):
cls()
project = LOCALDIR + os.sep + self.pro
print(" \033[31m>Pack ROM \033[0m\n")
print(f" Project: {os.path.basename(project)}\n")
print('\033[33m 1> Pack Directly 2> Pack Hybrid Rom \n 3> Return\033[0m\n')
chose = input(" Please enter the number: ")
if chose == '1':
print("Preparing For Packing...")
for v in ['firmware-update', 'META-INF', 'exaid.img', 'dynamic_partitions_op_list']:
if os.path.isdir(os.path.join(project, v)):
if not os.path.isdir(os.path.join(project, 'TI_out' + os.sep + v)):
shutil.copytree(os.path.join(project, v), os.path.join(project, 'TI_out' + os.sep + v))
elif os.path.isfile(os.path.join(project, v)):
if not os.path.isfile(os.path.join(project, 'TI_out' + os.sep + v)):
shutil.copy(os.path.join(project, v), os.path.join(project, 'TI_out'))
for root, dirs, files in os.walk(project):
for f in files:
if f.endswith('.br') or f.endswith('.dat') or f.endswith('.list'):
if not os.path.isfile(os.path.join(project, 'TI_out' + os.sep + f)) and os.access(
os.path.join(project, f), os.F_OK):
shutil.copy(os.path.join(project, str(f)), os.path.join(project, 'TI_out'))
elif chose == '2':
utils.dbkxyt(os.path.join(project, 'TI_out') + os.sep, input("Device Code:"),
binner + os.sep + 'extra_flash.zip')
else:
return
zip_file(os.path.basename(project) + ".zip", project + os.sep + 'TI_out', project + os.sep, LOCALDIR + os.sep)
def unpackrom(self):
cls()
zipn = 0
zips = {}
print(" \033[31m >ROM List \033[0m\n")
ywarn(f" Please place the ROM in {LOCALDIR}!\n")
if dir_has(LOCALDIR, '.zip'):
for zip0 in os.listdir(LOCALDIR):
if zip0.endswith('.zip'):
if os.path.isfile(os.path.abspath(zip0)):
if os.path.getsize(os.path.abspath(zip0)):
zipn += 1
print(f" [{zipn}]- {zip0}\n")
zips[zipn] = zip0
else:
ywarn(" No Files!")
print("--------------------------------------------------\n")
zipd = input("Please Enter:")
if zipd.isdigit():
if int(zipd) in zips.keys():
projec = input("Enter Project Name (Can Empty):")
project = "TI_%s" % projec if projec else "TI_%s" % os.path.basename(zips[int(zipd)]).replace('.zip',
'')
if os.path.exists(LOCALDIR + os.sep + project):
project = project + time.strftime("%m%d%H%M%S")
ywarn(f"Project Already exists! Automatically named as:{project}")
os.makedirs(LOCALDIR + os.sep + project)
print(f"Create {project} Successful!")
with Console().status("[yellow]Unzipping Rom...[/]"):
zipfile.ZipFile(os.path.abspath(zips[int(zipd)])).extractall(LOCALDIR + os.sep + project)
yecho("Decomposing ROM...")
autounpack(LOCALDIR + os.sep + project)
self.pro = project
self.project()
else:
ywarn("Input Error")
input("Enter to continue")
else:
ywarn("Input error!")
input("Enter to continue")
def get_all_file_paths(directory) -> Ellipsis:
# 初始化文件路径列表
for root, directories, files in os.walk(directory):
for filename in files:
yield os.path.join(root, filename)
class zip_file:
def __init__(self, file, dst_dir, local, path=None):
if not path:
path = LOCALDIR + os.sep
os.chdir(dst_dir)
relpath = str(path + file)
if os.path.exists(relpath):
ywarn(
f"A file with the same name exists:{file},Automatically renamed to {(relpath := path + utils.v_code() + file)}")
with zipfile.ZipFile(relpath, 'w', compression=zipfile.ZIP_DEFLATED,
allowZip64=True) as zip_:
# 遍历写入文件
for file in get_all_file_paths('.'):
print(f"Writing:%s" % file)
try:
zip_.write(file)
except Exception as e:
print(f"Cannot Write {file}.", e)
if os.path.exists(relpath):
print(f'Complete:{relpath}')
os.chdir(local)
def subbed(project):
if not os.path.exists(binner + os.sep + "subs"):
os.makedirs(binner + os.sep + "subs")
cls()
subn = 0
mysubs = {}
names = {}
print(" >\033[31mPlugin List \033[0m\n")
for sub in os.listdir(binner + os.sep + "subs"):
if os.path.isfile(binner + os.sep + "subs" + os.sep + sub + os.sep + "info.json"):
with open(binner + os.sep + "subs" + os.sep + sub + os.sep + "info.json") as l_info:
name = json.load(l_info)['name']
subn += 1
print(f" [{subn}]- {name}\n")
mysubs[subn] = sub
names[subn] = name
print("----------------------------------------------\n")
print("\033[33m> [66]-Install [77]-Uninstall [0]-Return\033[0m")
op_pro = input("Please enter the number:")
if op_pro == '66':
path = input("Please Enter Path of mpk:")
if os.path.exists(path) and not path.endswith('.zip2'):
installmpk(path)
elif path.endswith('.zip2'):
installmpk(zip2mpk.main(path, os.getcwd()))
else:
ywarn(f"{path}Not Exist!")
input("Enter to continue")
elif op_pro == '77':
chose = input("Enter the plugin serial number:")
unmpk(mysubs[int(chose)], names[int(chose)], binner + os.sep + "subs") if int(
chose) in mysubs.keys() else ywarn("Invalid Number")
elif op_pro == '0':
return
elif op_pro.isdigit():
if int(op_pro) in mysubs.keys():
plugin_path = os.path.join(binner, 'subs', mysubs[int(op_pro)])
if os.path.exists(plugin_path + os.sep + "main.sh"):
if os.path.exists(plugin_path + os.sep + "main.json"):
gavs, value = plug_parse(
os.path.join(plugin_path, "main.json"))
gen = gen_sh_engine(project, gavs, value)
else:
gen = gen_sh_engine(project)
call(["busybox", 'ash', gen, os.path.join(plugin_path, "main.sh").replace(os.sep, "/")])
f_remove(gen)
else:
ywarn(f"{mysubs[int(op_pro)]} is a environment, Cannot run!")
input("Enter to continue")
subbed(project)
def gen_sh_engine(project, gavs=None, value=None):
if not os.path.exists(temp):
os.makedirs(temp)
engine = temp + os.sep + utils.v_code()
with open(engine, 'w', encoding='utf-8', newline='\n') as en:
en.write(f"export project={project.replace(os.sep, '/')}\n")
en.write(f'export tool_bin={ebinner.replace(os.sep, "/")}\n')
if gavs or value:
for i in value:
en.write(f"export {i}='{gavs[i]}'\n")
en.write(f'source $1\n')
return engine.replace(os.sep, '/')
class installmpk:
def __init__(self, mpk):
super().__init__()
self.mconf = ConfigParser()
if not mpk:
ywarn("The plugin does not exist")
return
if not zipfile.is_zipfile(mpk):
ywarn("Non plugin!")
input("Enter to return")
with zipfile.ZipFile(mpk, 'r') as myfile:
with myfile.open('info') as info_file:
self.mconf.read_string(info_file.read().decode('utf-8'))
with myfile.open(self.mconf.get('module', 'resource'), 'r') as inner_file:
self.inner_zipdata = inner_file.read()
self.inner_filenames = zipfile.ZipFile(BytesIO(self.inner_zipdata)).namelist()
print('''
\033[36m
----------------
Install Mpk
----------------
''')
print("Name:" + self.mconf.get('module', 'name'))
print("Version:%s\nAuthor:%s" % (self.mconf.get('module', 'version'), (self.mconf.get('module', 'author'))))