-
Notifications
You must be signed in to change notification settings - Fork 7
/
run.py
1926 lines (1821 loc) · 83.8 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
import banner
import ext4
from Magisk import Magisk_patch
import os
from dumper import Dumper
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
import contextpatch
import downloader
import fspatch
import imgextractor
import lpunpack
import mkdtboimg
import ofp_mtk_decrypt
import ofp_qc_decrypt
import ozipdecrypt
import utils
from api import cls, dir_has, cat, dirsize, re_folder, f_remove
from log import LOGS, LOGE, ysuc, yecho, ywarn
from utils import gettype, simg2img, call
import opscrypto
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 {} {}'.format(os.path.join(r, i), os.path.join(r, i[:1])))
for i in f:
if i.endswith('.'):
call('mv {} {}'.format(os.path.join(r, i), os.path.join(r, i[:1])))
try:
shutil.rmtree(path)
except PermissionError:
ywarn("无法删除文件夹,权限不足")
else:
ysuc("删除成功!")
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):
...
class set_utils:
def __init__(self, path):
self.path = path
def load_set(self):
with open(self.path, 'r') as ss:
data = json.load(ss)
[setattr(self, v, data[v]) for v in data]
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()
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]正在检测新版本...[/]"):
try:
data = requests.get(self.update_json).json()
except (Exception, BaseException):
data = None
if not data:
input("连接服务器失败, 按任意按钮返回")
return
else:
if data.get('version', settings.version) != settings.version:
print(f'\033[31m {banner.banner1} \033[0m')
print(
f"\033[0;32;40m发现版本:\033[0m\033[0;36;40m{settings.version} --> {data.get('version')}\033[0m")
print(f"\033[0;32;40m更新日志:\n\033[0m\033[0;36;40m{data.get('log', '1.Fix Some Bugs')}\033[0m")
input("注意,交流群与release中的构建始终为最新开发环境版本,本功能仅用于检测近期较为稳定的构建")
try:
link = data['link'][plat.system()][plat.machine()]
except (Exception, BaseException):
input("未发现适用于您设备的更新,请前往https://github.com/ColdWindScholar/TIK下载源代码自行更新")
return
if not link:
input("未发现适用于您设备的更新,请前往https://github.com/ColdWindScholar/TIK下载源代码自行更新")
return
if input("\033[0;33;40m是否更新?[1/0]\033[0m") == '1':
print("正在下载新版本...")
try:
downloader.download([link], temp)
except (BaseException, Exception):
input("下载错误,请稍后重试")
return
print("开始更新,请不要关闭工具...")
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("更新文件损坏, 无法更新")
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("更新完毕, 任意按钮启动新程序...")
subprocess.Popen([os.path.join(LOCALDIR, f'run_new{str() if os.name == "posix" else ".exe"}')])
sys.exit()
else:
input("\033[0;32;40m你正在使用最新版本!任意按钮返回!\033[0m")
return
class setting:
def settings1(self):
actions = {
"1": lambda: settings.change('brcom', brcom if (brcom := input(
f" 调整brotli压缩等级(整数1-9,级别越高,压缩率越大,耗时越长):")).isdigit() and 0 < int(
brcom) < 10 else '1'),
"2": lambda: settings.change('diysize',
"1" if input(" 打包Ext镜像大小[1]动态最小 [2]原大小:") == '2' else ''),
"3": lambda: settings.change('pack_e2', '0' if input(
" 打包方案: [1]make_ext4fs [2]mke2fs+e2fsdroid:") == '1' else '1'),
"6": lambda: settings.change('pack_sparse', '1' if input(
" Img是否打包为sparse镜像(压缩体积)[1/0]\n 请输入序号:") == '1' else "0"),
"7": lambda: settings.change('diyimgtype',
'1' if input(f" 打包镜像系统[1]同解包格式 [2]可选择:") == '2' else ''),
"8": lambda: settings.change('erofs_old_kernel',
'1' if input(f" EROFS打包是否支持旧内核[1/0]") == '1' else '0')
}
cls()
print(f'''
\033[33m > 打包设置 \033[0m
1> Brotli 压缩等级 \033[93m[{settings.brcom}]\033[0m\n
----[EXT4设置]------
2> 大小处理 \033[93m[{settings.diysize}]\033[0m
3> 打包方式 \033[93m[{settings.pack_e2}]\033[0m\n
----[EROFS设置]-----
4> 压缩方式 \033[93m[{settings.erofslim}]\033[0m\n
----[IMG设置]-------
5> UTC时间戳 \033[93m[{settings.utcstamp}]\033[0m
6> 创建sparse \033[93m[{settings.pack_sparse}]\033[0m
7> 文件系统 \033[93m[{settings.diyimgtype}]\033[0m
8> 支持旧内核 \033[93m[{settings.erofs_old_kernel}]\033[0m\n
0>返回上一级菜单
--------------------------
''')
op_pro = input(" 请输入编号:")
if op_pro == "0":
return
elif op_pro in actions.keys():
actions[op_pro]()
elif op_pro == '4':
if input(" 选择erofs压缩方式[1]是 [2]否:") == '1':
erofslim = input(
" 选择erofs压缩方式:lz4/lz4hc/lzma/和压缩等级[1-9](数字越大耗时更长体积更小) 例如 lz4hc,8:")
settings.change("erofslim", erofslim if erofslim else 'lz4hc,8')
else:
settings.change("erofslim", 'lz4hc,8')
elif op_pro == '5':
if input(" 设置打包UTC时间戳[1]自动 [2]自定义:") == "2":
utcstamp = input(" 请输入: ")
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" 请输入(无特殊字符):")) else "qti_dynamic_partitions"),
'2': lambda: settings.change('metadatasize', metadatasize if (
metadatasize := input(" 设置metadata最大保留size(默认为65536,至少512):")) else '65536'),
'3': lambda: settings.change('BLOCKSIZE', BLOCKSIZE if (
BLOCKSIZE := input(f" 分区打包扇区/块大小:{settings.BLOCKSIZE}\n 请输入: ")) else "4096"),
'4': lambda: settings.change('BLOCKSIZE', SBLOCKSIZE if (
SBLOCKSIZE := input(f" 分区打包扇区/块大小:{settings.SBLOCKSIZE}\n 请输入: ")) else "4096"),
'5': lambda: settings.change('supername', supername if (supername := input(
f' 当前动态分区物理分区名(默认super):{settings.supername}\n 请输入(无特殊字符): ')) else "super"),
'6': lambda: settings.change('fullsuper', '' if input(" 是否强制创建Super镜像?[1/0]") != '1' else '-F'),
'7': lambda: settings.change('autoslotsuffixing',
'' if input(" 是否标记需要Slot后缀的分区?[1/0]") != '1' else '-x')
}
print(f'''
\033[33m > 动态分区设置 \033[0m
1> Super簇名 \033[93m[{settings.super_group}]\033[0m\n
----[Metadata设置]--
2> 最大保留Size \033[93m[{settings.metadatasize}]\033[0m\n
----[分区设置]------
3> 默认扇区/块大小 \033[93m[{settings.BLOCKSIZE}]\033[0m\n
----[Super设置]-----
4> 指定block大小 \033[93m[{settings.SBLOCKSIZE}]\033[0m
5> 更改物理分区名 \033[93m[{settings.supername}]\033[0m
6> 强制生成完整Img \033[93m[{settings.fullsuper}]\033[0m
7> 标记分区槽后缀 \033[93m[{settings.autoslotsuffixing}]\033[0m\n
0>返回上一级菜单
--------------------------
''')
op_pro = input(" 请输入编号: ")
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 > 工具设置 \033[0m\n
1>自定义首页banner \033[93m[{settings.banner}]\033[0m\n
2>联网模式 \033[93m[{settings.online}]\033[0m\n
3>Contexts修补 \033[93m[{settings.context}]\033[0m\n
4>检查更新 \n
0>返回上级\n
--------------------------
''')
op_pro = input(" 请输入编号: ")
if op_pro == "0":
return
elif op_pro == '1':
print(f" 首页banner: [1]TIK5 [2]镰刀斧头 [3]TIK2 [4]原神 [5]DXY [6]None")
banner_i = input(" 请输入序号: ")
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':
upgrade()
self.settings3()
@staticmethod
def settings4():
cls()
print(f'\033[31m {banner.banner1} \033[0m')
print('\033[96m 开源的安卓全版本ROM处理工具\033[0m')
print('\033[31m---------------------------------\033[0m')
print(f"\033[93m作者:\033[0m \033[92mColdWindScholar\033[0m")
print(f"\033[93m开源地址:\033[0m \033[91mhttps://github.com/ColdWindScholar/TIK\033[0m")
print(f"\033[93m软件版本:\033[0m \033[44mAlpha Edition\033[0m")
print(f"\033[93m开源协议:\033[0m \033[68mGNU General Public License v3.0 \033[0m")
print('\033[31m---------------------------------\033[0m')
print(f"\033[93m特别鸣谢:\033[0m")
print('\033[94mAffggh')
print("Yeliqin666")
print('YukongA')
print("\033[0m")
input('\033[31m---------------------------------\033[0m')
def __init__(self):
cls()
print('''
\033[33m > 设置 \033[0m
1>[打包]相关设置\n
2>[动态分区]相关设置\n
3>工具设置\n
4>关于工具\n
0>返回主页
--------------------------
''')
op_pro = input(" 请输入编号: ")
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("解析错误 %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("请在下方拖入文件或输入路径")
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("-------选项---------")
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("请输入您的选择:")
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("请输入一个值:")
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("不支持的解析:%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 “开源,是一场无问西东的前行”\033[0m\n")
else:
print(f"\033[36m “{shiju}”")
print(f"\033[36m---{another}《{fr}》\033[0m\n")
else:
print(f"\033[36m “开源,是一场无问西东的前行”")
print(" >\033[33m 项目列表 \033[0m\n")
print("\033[31m [00] 删除项目\033[0m\n\n", " [0] 新建项目\n")
for pros in os.listdir(LOCALDIR):
if pros == 'bin' 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] 解压 [66] 退出 [77] 设置 [88] 下载ROM\033[0m\n")
op_pro = input(" 请输入序号:")
if op_pro == '55':
self.unpackrom()
elif op_pro == '88':
url = input("输入下载链接:")
if url:
try:
downloader.download([url], LOCALDIR)
except (Exception, BaseException):
...
self.unpackrom()
elif op_pro == '00':
op_pro = input(" 请输入你要删除的项目序号:")
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" 确认删除{projects[op]}?[1/0]") == '1':
rmdire(o_path.join(LOCALDIR, projects[op]))
else:
ywarn("取消删除")
elif op_pro == '0':
projec = input("请输入项目名称(非中文):")
if projec:
if os.path.exists(o_path.join(LOCALDIR, projec)):
projec = f'{projec}_{time.strftime("%m%d%H%M%S")}'
ywarn(f"项目已存在!自动命名为:{projec}")
time.sleep(1)
os.makedirs(o_path.join(LOCALDIR, projec, "config"))
self.pro = projec
self.project()
else:
ywarn(" Input error!")
input("任意按钮继续")
elif op_pro == '66':
cls()
ysuc("\n感谢使用TI-KITCHEN5,再见!")
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("任意按钮继续")
else:
ywarn(" Input error!")
input("任意按钮继续")
self.main()
@staticmethod
def dis_avb(fstab):
print(f"正在处理: {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"正在处理: {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>项目菜单 \033[0m\n")
print(f" 项目:{self.pro}\033[91m(不完整)\033[0m\n") if not os.path.exists(
os.path.abspath('config')) else print(
f" 项目:{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> 回到主页 2> 解包菜单\033[0m\n')
print('\033[36m 3> 打包菜单 4> 插件菜单\033[0m\n')
print('\033[32m 5> 一键封装 6> 定制功能\033[0m\n')
op_menu = input(" 请输入编号: ")
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("任意按钮继续")
self.project()
def custom_rom(self):
cls()
print(" \033[31m>定制菜单 \033[0m\n")
print(f" 项目:{self.pro}\n")
print('\033[33m 0> 返回上级 1> 面具修补\033[0m\n')
print('\033[33m 2> 去除avb 3> 去除data加密\033[0m\n')
op_menu = input(" 请输入编号: ")
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("任意按钮继续")
self.custom_rom()
def magisk_patch(self):
cls()
cs = 0
project = LOCALDIR + os.sep + self.pro
os.chdir(LOCALDIR)
print(" \n\033[31m>面具修补 \033[0m\n")
print(f" 项目:{self.pro}\n")
print(f" 请将要修补的镜像放入{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] 返回\033[0m\n")
op_menu = input(" 请输入编号: ")
if op_menu in boots.keys():
mapk = input(" 请输入Magisk.apk路径:")
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("修补完成")
else:
LOGE("修补失败")
elif op_menu == '00':
os.chdir(project)
return
else:
ywarn('Input Error!')
input("任意按钮继续")
self.magisk_patch()
def hczip(self):
cls()
project = LOCALDIR + os.sep + self.pro
print(" \033[31m>打包ROM \033[0m\n")
print(f" 项目:{os.path.basename(project)}\n")
print('\033[33m 1> 直接打包 2> 卡线一体 \n 3> 返回\033[0m\n')
chose = input(" 请输入编号: ")
if chose == '1':
print("正在准备打包...")
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("打包卡线一体限制机型代号:"),
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列表 \033[0m\n")
ywarn(f" 请将ROM置于{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(" 没有ROM文件!")
print("--------------------------------------------------\n")
zipd = input("请输入对应序列号:")
if zipd.isdigit():
if int(zipd) in zips.keys():
projec = input("请输入项目名称(可留空):")
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}")
os.makedirs(LOCALDIR + os.sep + project)
print(f"创建{project}成功!")
with Console().status("[yellow]解压刷机包中...[/]"):
zipfile.ZipFile(os.path.abspath(zips[int(zipd)])).extractall(LOCALDIR + os.sep + project)
yecho("分解ROM中...")
autounpack(LOCALDIR + os.sep + project)
self.pro = project
self.project()
else:
ywarn("Input Error")
input("任意按钮继续")
else:
ywarn("Input error!")
input("任意按钮继续")
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"存在同名文件:{file},已自动重命名为{(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"正在写入:%s" % file)
try:
zip_.write(file)
except Exception as e:
print("写入{}时错误{}".format(file, e))
if os.path.exists(relpath):
print(f'打包完成:{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[31m插件列表 \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]-安装 [77]-删除 [0]-返回\033[0m")
op_pro = input("请输入序号:")
if op_pro == '66':
path = input("请输入插件路径或[拖入]:")
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}不存在!")
input("任意按钮继续")
elif op_pro == '77':
chose = input("输入插件序号:")
unmpk(mysubs[int(chose)], names[int(chose)], binner + os.sep + "subs") if int(
chose) in mysubs.keys() else ywarn("序号错误")
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(
f'busybox ash {gen} {os.path.join(plugin_path, "main.sh").replace(os.sep, "/")}')
f_remove(gen)
else:
ywarn(f"{mysubs[int(op_pro)]}为环境插件,不可运行!")
input("任意按钮返回")
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("插件不存在")
return
if not zipfile.is_zipfile(mpk):
ywarn("非插件!")
input("任意按钮返回")
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
----------------
安装新插件
----------------
''')
print("插件名称:" + self.mconf.get('module', 'name'))
print("版本:%s\n作者:%s" % (self.mconf.get('module', 'version'), (self.mconf.get('module', 'author'))))
print("介绍:")
print(self.mconf.get('module', 'describe'))
print("\033[0m\n")
if input("要安装吗? [1/0]") == '1':
self.install()
else:
yecho("取消安装")
input("任意按钮返回")
def install(self):
try:
supports = self.mconf.get('module', 'supports').split()
except (Exception, BaseException):
supports = [sys.platform]
if sys.platform not in supports:
ywarn(f"[!]安装失败:不支持的系统{sys.platform}")
input("任意按钮返回")
return False
for dep in self.mconf.get('module', 'depend').split():
if not os.path.isdir(binner + os.sep + "subs" + os.sep + dep):
ywarn(f"[!]安装失败:不满足依赖{dep}")
input("任意按钮返回")
return False
if os.path.exists(binner + os.sep + "subs" + os.sep + self.mconf.get('module', 'identifier')):
shutil.rmtree(binner + os.sep + "subs" + os.sep + self.mconf.get('module', 'identifier'))
fz = zipfile.ZipFile(BytesIO(self.inner_zipdata), 'r')
for file in track(self.inner_filenames, description="正在安装..."):
try:
file = str(file).encode('cp437').decode('gbk')
except (Exception, BaseException):
file = str(file).encode('utf-8').decode('utf-8')
fz.extract(file, binner + os.sep + "subs" + os.sep + self.mconf.get('module', 'identifier'))
try:
depends = self.mconf.get('module', 'depend')
except (Exception, BaseException):
depends = ''
minfo = {"name": self.mconf.get('module', 'name'),
"author": self.mconf.get('module', 'author'),
"version": self.mconf.get('module', 'version'),
"identifier": self.mconf.get('module', 'identifier'),
"describe": self.mconf.get('module', 'describe'),
"depend": depends}
with open(binner + os.sep + "subs" + os.sep + self.mconf.get('module', 'identifier') + os.sep + "info.json",
'w') as f:
json.dump(minfo, f, indent=2)
class unmpk:
def __init__(self, plug, name, moduledir):
self.arr = []
self.arr2 = []
if plug:
self.value = plug
self.value2 = name
self.moddir = moduledir
self.lfdep()
self.ask()
else:
ywarn("请选择插件!")
input("任意按钮继续")
def ask(self):
cls()
print(f"\033[31m >删除{self.value2} \033[0m\n")
if self.arr2:
print("\033[36m将会同时卸载以下插件")
print("\n".join(self.arr2))
print("\033[0m\n")
self.unloop() if input("确定卸载吗 [1/0]") == '1' else ysuc("取消")
input("任意按钮继续")
def lfdep(self, name=None):
if not name:
name = self.value
for i in [i for i in os.listdir(self.moddir) if os.path.isdir(self.moddir + os.sep + i)]:
with open(self.moddir + os.sep + i + os.sep + "info.json", 'r', encoding='UTF-8') as f:
data = json.load(f)
for n in data['depend'].split():
if name == n:
self.arr.append(i)
self.arr2.append(data['name'])
self.lfdep(i)
break
self.arr = sorted(set(self.arr), key=self.arr.index)
self.arr2 = sorted(set(self.arr2), key=self.arr2.index)
def unloop(self):
for i in track(self.arr):
self.umpk(i)
self.umpk(self.value)
def umpk(self, name=None) -> None:
if name:
print(f"正在卸载:{name}")
if os.path.exists(self.moddir + os.sep + name):
shutil.rmtree(self.moddir + os.sep + name)
ywarn(f"卸载{name}失败!") if os.path.exists(self.moddir + os.sep + name) else yecho(f"卸载{name}成功!")
def unpack_choo(project):
cls()
os.chdir(project)
print(" \033[31m >分解 \033[0m\n")