forked from xianwan1314/TIK4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.py
1643 lines (1540 loc) · 65.5 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 json
import os
import platform as plat
import re
import shutil
import sys
import time
import zipfile
from argparse import Namespace
from configparser import ConfigParser
from io import BytesIO
if os.name == 'nt':
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW("TIK4")
else:
sys.stdout.write("\x1b]2;TIK4\x07")
sys.stdout.flush()
import extract_dtb
import requests
from rich.progress import track
from rich.console import Console
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
from utils import gettype, simg2img, call
import opscrypto
import zip2mpk
LOCALDIR = os.getcwd()
binner = LOCALDIR + os.sep + "bin"
setfile = LOCALDIR + os.sep + "bin" + os.sep + "settings.json"
platform = plat.machine()
ostype = plat.system()
ebinner = binner + os.sep + ostype + os.sep + platform + os.sep
temp = binner + os.sep + 'temp'
def yecho(info): print(f"\033[36m[{time.strftime('%H:%M:%S')}]{info}\033[0m")
def ywarn(info): print(f"\033[31m{info}\033[0m")
def ysuc(info): print(f"\033[32m[{time.strftime('%H:%M:%S')}]{info}\033[0m")
def rmdire(path):
if os.path.exists(path):
try:
shutil.rmtree(path)
except PermissionError:
ywarn("无法删除文件夹,权限不足")
if os.name == 'posix':
try:
os.chmod(binner, 777)
except:
pass
def getprop(name, path):
with open(path, 'r') as prop:
for s in prop.readlines():
if s[:1] == '#':
continue
if name in s:
return s.strip().split('=')[1]
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)
for v in data:
setattr(self, v, data[v])
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 setting:
def settings2(self):
cls()
print('''
\033[33m > 打包设置 \033[0m
1> Brotli 压缩等级\n
----[EXT4设置]------
2> 大小处理
3> 打包方式
4> 读写状态\n
----[EROFS设置]-----
5> 压缩方式\n
----[IMG设置]-------
6> UTC时间戳
7> 创建sparse
8> 文件系统\n
0>返回上一级菜单
--------------------------
''')
op_pro = input(" 请输入编号: ")
if op_pro == "0":
return 1
try:
getattr(self, 'packset%s' % op_pro)()
self.settings2()
except AttributeError:
print("Input error!")
self.settings2()
def settings3(self):
cls()
print('''
\033[33m > 动态分区设置 \033[0m
1> dynamic_partitions簇名\n
----[Metadata设置]--
2> 元数据插槽数
3> 最大保留Size\n
----[分区设置]------
4> 默认扇区/块大小\n
----[Super设置]-----
5> 指定block大小
6> 更改物理分区名
7> 更改逻辑分区表
8> 强制烧写完整Img
9> 标记分区槽后缀\n
0>返回上一级菜单
--------------------------
''')
op_pro = input(" 请输入编号: ")
if op_pro == "0":
return 1
try:
getattr(self, 'dyset%s' % op_pro)()
self.settings3()
except AttributeError:
print("Input error!")
self.settings3()
@staticmethod
def settings1():
print(f"修改安卓端在内置存储识别ROM的路径。当前为/sdcard/{settings.mydir}")
mydir = input(' 请输入文件夹名称(英文):')
if mydir:
settings.change('mydir', mydir)
@staticmethod
def settings4_1():
print(
f" 首页banner: [1]TIK4 [2]爷 [3]电摇嘲讽 [4]镰刀斧头 [5]镰刀斧头(大) [6]TIK2旧 \n 当前:[{settings.banner}]")
banner = input(" 请输入序号: ")
if banner.isdigit():
if 0 < int(banner) < 7:
settings.change('banner', banner)
def settings4(self):
cls()
print(f'''
\033[33m > 工具设置 \033[0m\n
1>自定义首页banner\n
2>联网模式 \033[93m[{settings.online}]\033[0m\n
0>返回上级\n
--------------------------
''')
op_pro = input(" 请输入编号: ")
if op_pro == "0":
return
elif op_pro == '1':
self.settings4_1()
elif op_pro == '2':
settings.change('online', 'false' if settings.online == 'true' else 'true')
self.settings4()
@staticmethod
def settings5():
cls()
with open(binner + os.sep + 'banners' + os.sep + '1', 'r') as banner:
print(f'\033[31m {banner.read()} \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[44mDelta 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")
print('\033[31m---------------------------------\033[0m')
input('\033[97m Powered By MIO-KITCHEN-ENVS\033[0m')
@staticmethod
def packset1():
print(f" 调整brotli压缩等级(整数1-9,级别越高,压缩率越大,耗时越长),当前为:{settings.brcom}级")
brcom = input(" 请输入(1-9): ")
if brcom.isdigit():
if 0 < int(brcom) < 10:
settings.change('brcom', brcom)
else:
return
@staticmethod
def packset2():
sizediy = input(f" 打包Ext镜像大小[1]动态最小 [2]手动改: ")
if sizediy == '2':
settings.change('diysize', '1')
else:
settings.change('diysize', '')
@staticmethod
def packset3():
print(f" 当前:[{settings.pack_e2}]\n 打包方案: [1]make_ext4fs [2]mke2fs+e2fsdroid:")
pack_op = input(" 请输入序号: ")
if pack_op == '1':
settings.change('pack_e2', '0')
else:
settings.change('pack_e2', '1')
@staticmethod
def packset4():
extrw = input(" 打包EXT是否可读[1]RW [2]RO: ")
if extrw == '2':
settings.change('ext4rw', '')
else:
settings.change('ext4rw', '-s')
@staticmethod
def packset5():
erofslim = input(" 选择erofs压缩方式[1]是 [2]否: ")
if erofslim == '1':
erofslim = input(
" 选择erofs压缩方式:lz4/lz4hc/lzma/和压缩等级[1-9](数字越大耗时更长体积更小) 例如 lz4hc,8: ")
if erofslim:
settings.change("erofslim", erofslim)
else:
settings.change("erofslim", '')
@staticmethod
def packset6():
utcstamp = input(" 设置打包UTC时间戳[1]自动 [2]自定义: ")
if utcstamp == "2":
utcstamp = input(" 请输入: ")
if utcstamp.isdigit():
settings.change('utcstamp', utcstamp)
else:
settings.change('utcstamp', '')
@staticmethod
def packset7():
print(" Img是否打包为sparse(压缩体积)[1/0]")
ifpsparse = input(" 请输入序号: ")
if ifpsparse == '1':
settings.change('pack_sparse', '1')
elif ifpsparse == '0':
settings.change('pack_sparse', '0')
@staticmethod
def packset8():
typediy = input(" 打包镜像格式[1]同解包格式 [2]可选择: ")
if typediy == '2':
settings.change('diyimgtype', '1')
else:
settings.change('diyimgtype', '')
@staticmethod
def dyset1():
super_group = input(f" 当前动态分区簇名:{settings.super_group}\n 请输入(无特殊字符): ")
if super_group:
settings.change('super_group', super_group)
@staticmethod
def dyset2():
slotnumber = input(" 强制Metadata插槽数:[2] [3]: ")
if slotnumber == '3':
settings.change('slotnumber', '3')
else:
settings.change('slotnumber', '2')
@staticmethod
def dyset3():
metadatasize = input(" 设置metadata最大保留size(默认为65536,至少512) ")
if metadatasize:
settings.change('metadatasize', metadatasize)
@staticmethod
def dyset4():
BLOCKSIZE = input(f" 分区打包扇区/块大小:{settings.BLOCKSIZE}\n 请输入: ")
if BLOCKSIZE:
settings.change('BLOCKSIZE', BLOCKSIZE)
@staticmethod
def dyset5():
SBLOCKSIZE = input(f" 分区打包扇区/块大小:{settings.SBLOCKSIZE}\n 请输入: ")
if SBLOCKSIZE:
settings.change('SBLOCKSIZE', SBLOCKSIZE)
@staticmethod
def dyset6():
supername = input(f' 当前动态分区物理分区名(默认super):{settings.supername}\n 请输入(无特殊字符): ')
if supername:
settings.change('supername', supername)
@staticmethod
def dyset7():
superpart_list = input(f' 当前动态分区内逻辑分区表:{settings.superpart_list}\n 请输入(无特殊字符): ')
if superpart_list:
settings.change('superpart_list', superpart_list)
@staticmethod
def dyset8():
iffullsuper = input(" 是否创建强制刷入的Full镜像?[1/0]")
if iffullsuper != '1':
settings.change('fullsuper', '')
else:
settings.change('fullsuper', '-F')
@staticmethod
def dyset9():
autoslotsuffix = input(" 是否标记需要Slot后缀的分区?[1/0]")
if autoslotsuffix != '1':
settings.change('autoslotsuffixing', '')
else:
settings.change('autoslotsuffixing', '-x')
def __init__(self):
cls()
print('''
\033[33m > 设置 \033[0m
1>[Droid]存储ROM目录\n
2>[打包]相关细则设置\n
3>[动态分区]相关设置\n
4>工具设置\n
5>关于工具\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 main_menu():
projects = {}
gs = 0
cls()
if settings.online == 'true':
gs = 1
if gs == 1:
try:
content = json.loads(requests.get('https://v1.jinrishici.com/all.json').content.decode())
shiju = content['content']
fr = content['origin']
another = content['author']
except:
gs = 0
with open(binner + os.sep + 'banners' + os.sep + settings.banner, 'r') as banner:
print(f'\033[31m {banner.read()} \033[0m')
print("\033[92;44m Delta Edition \033[0m")
if gs == 1:
print(f"\033[36m “{shiju}”")
print(f"\033[36m---{another}《{fr}》\033[0m\n")
print(" >\033[33m 项目列表 \033[0m\n")
print("\033[31m [00] 删除项目\033[0m\n")
print(" [0] 新建项目\n")
pro = 0
if os.listdir(LOCALDIR + os.sep):
for pros in os.listdir(LOCALDIR + os.sep):
if pros == 'bin' or pros.startswith('.'):
continue
if os.path.isdir(LOCALDIR + os.sep + pros):
pro += 1
print(f" [{pro}] {pros}\n")
projects['%s' % pro] = pros
print(" --------------------------------------")
print("\033[33m [55] 解压 [66] 退出 [77] 设置 [88] 下载ROM\033[0m")
print("")
print(" \n")
op_pro = input(" 请输入序号:")
if op_pro == '55':
unpackrom()
elif op_pro == '88':
url = input("输入下载链接:")
if url:
try:
downloader.download([url], LOCALDIR)
except:
pass
unpackrom()
elif op_pro == '00':
op_pro = input(" 请输入你要删除的项目序号:")
if op_pro in projects.keys():
delr = input(f" 确认删除{projects[op_pro]}?[1/0]")
if delr == '1':
rmdire(LOCALDIR + os.sep + projects[op_pro])
ysuc(" 删除成功!")
else:
print(" 取消删除")
elif op_pro == '0':
projec = input("请输入项目名称(非中文):")
if not projec:
ywarn("Input Error!")
input("任意按钮继续")
else:
if os.path.exists(LOCALDIR + os.sep + projec):
projec = f'{projec}_{time.strftime("%m%d%H%M%S")}'
ywarn(f"项目已存在!自动命名为:{projec}")
time.sleep(1)
os.makedirs(LOCALDIR + os.sep + projec + os.sep + "config")
menu(projec)
elif op_pro == '66':
cls()
sys.exit(0)
elif op_pro == '77':
setting()
elif op_pro.isdigit():
if op_pro in projects.keys():
menu(projects[op_pro])
else:
ywarn(" Input error!")
else:
ywarn(" Input error!")
input("任意按钮继续")
main_menu()
def menu(project):
PROJECT_DIR = LOCALDIR + os.sep + project
cls()
os.chdir(PROJECT_DIR)
if not os.path.exists(os.path.abspath('config')):
ywarn("项目已损坏!")
if not os.path.exists(PROJECT_DIR + os.sep + 'TI_out'):
os.makedirs(PROJECT_DIR + os.sep + 'TI_out')
print('\n')
print(" \033[31m>ROM菜单 \033[0m\n")
print(f" 项目:{project}")
print('')
print('\033[33m 1> 回到主页 2> 解包菜单\033[0m\n')
print('\033[36m 3> 打包菜单 4> 插件菜单\033[0m\n')
print('\033[32m 5> 一键封装\033[0m\n')
print()
op_menu = input(" 请输入编号: ")
if op_menu == '1':
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':
hczip(PROJECT_DIR)
input("任意按钮继续")
else:
ywarn(' Input error!')
input("任意按钮继续")
menu(project)
def hczip(project):
cls()
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, f), os.path.join(project, 'TI_out'))
elif chose == '2':
code = input("打包卡线一体限制机型代号:")
utils.dbkxyt(os.path.join(project, 'TI_out') + os.sep, 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 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(object):
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("输入插件序号:")
if int(chose) in mysubs.keys():
unmpk(mysubs[int(chose)], names[int(chose)], binner + os.sep + "subs")
else:
print("序号错误")
elif op_pro == '0':
return
elif op_pro.isdigit():
if int(op_pro) in mysubs.keys():
if (os.path.exists(binner + os.sep + "subs" + os.sep + mysubs[int(op_pro)] + os.sep + "main.sh") and
not os.path.exists(binner + os.sep + "subs" + os.sep + mysubs[int(op_pro)] + os.sep + "main.json")):
gen = gen_sh_engine(project)
call(
f'busybox ash {gen} {(binner + os.sep + "subs" + os.sep + mysubs[int(op_pro)] + os.sep + "main.sh").replace(os.sep, "/")}')
f_remove(gen)
else:
ywarn(f"{mysubs[int(op_pro)]}为环境插件,不可运行!")
input("任意按钮返回")
subbed(project)
def gen_sh_engine(project):
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')
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('%s' % (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
----------------
MIO-PACKAGE
----------------
''')
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")
install = input("要安装吗? [1/0]")
if install == '1':
self.install()
else:
yecho("取消安装")
input("任意按钮返回")
def install(self):
try:
supports = self.mconf.get('module', 'supports').split()
except:
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:
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:
depends = ''
minfo = {"name": "%s" % (self.mconf.get('module', 'name')),
"author": "%s" % (self.mconf.get('module', 'author')),
"version": "%s" % (self.mconf.get('module', 'version')),
"identifier": "%s" % (self.mconf.get('module', 'identifier')),
"describe": "%s" % (self.mconf.get('module', 'describe')),
"depend": "%s" % 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将会同时卸载以下插件")
for i in self.arr2:
print(i)
print("\033[0m\n")
if input("确定卸载吗 [1/0]") == '1':
self.unloop()
else:
ysuc("取消")
pass
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 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)
if os.path.exists(self.moddir + os.sep + name):
ywarn(f"卸载{name}失败!")
else:
yecho(f"卸载{name}成功!")
def unpack_choo(project):
cls()
os.chdir(project)
print(" \033[31m >分解 \033[0m\n")
filen = 0
files = {}
infos = {}
ywarn(f" 请将文件放于{project}根目录下!")
print()
print(" [0]- 分解所有文件\n")
if dir_has(project, '.br'):
print("\033[33m [Br]文件\033[0m\n")
for br0 in os.listdir(project):
if br0.endswith('.br'):
if os.path.isfile(os.path.abspath(br0)):
filen += 1
print(f" [{filen}]- {br0}\n")
files[filen] = br0
infos[filen] = 'br'
if dir_has(project, '.new.dat'):
print("\033[33m [Dat]文件\033[0m\n")
for dat0 in os.listdir(project):
if dat0.endswith('.new.dat'):
if os.path.isfile(os.path.abspath(dat0)):
filen += 1
print(f" [{filen}]- {dat0}\n")
files[filen] = dat0
infos[filen] = 'dat'
if dir_has(project, '.new.dat.1'):
for dat10 in os.listdir(project):
if dat10.endswith('.dat.1'):
if os.path.isfile(os.path.abspath(dat10)):
filen += 1
print(f" [{filen}]- {dat10} <分段DAT>\n")
files[filen] = dat10
infos[filen] = 'dat.1'
if dir_has(project, '.img'):
print("\033[33m [Img]文件\033[0m\n")
for img0 in os.listdir(project):
if img0.endswith('.img'):
if os.path.isfile(os.path.abspath(img0)):
filen += 1
info = gettype(os.path.abspath(img0))
if info == "unknow":
ywarn(f" [{filen}]- {img0} <UNKNOWN>\n")
else:
print(f' [{filen}]- {img0} <{info.upper()}>\n')
files[filen] = img0
if info != 'sparse':
infos[filen] = 'img'
else:
infos[filen] = 'sparse'
if dir_has(project, '.bin'):
for bin0 in os.listdir(project):
if bin0.endswith('.bin'):
if os.path.isfile(os.path.abspath(bin0)) and gettype(os.path.abspath(bin0)) == 'payload':
filen += 1
print(f" [{filen}]- {bin0} <BIN>\n")
files[filen] = bin0
infos[filen] = 'payload'
if dir_has(project, '.ozip'):
print("\033[33m [Ozip]文件\033[0m\n")
for ozip0 in os.listdir(project):
if ozip0.endswith('.ozip'):
if os.path.isfile(os.path.abspath(ozip0)) and gettype(os.path.abspath(ozip0)) == 'ozip':
filen += 1
print(f" [{filen}]- {ozip0}\n")
files[filen] = ozip0
infos[filen] = 'ozip'
if dir_has(project, '.ofp'):
print("\033[33m [Ofp]文件\033[0m\n")
for ofp0 in os.listdir(project):
if ofp0.endswith('.ofp'):
if os.path.isfile(os.path.abspath(ofp0)):
filen += 1
print(f" [{filen}]- {ofp0}\n")
files[filen] = ofp0
infos[filen] = 'ofp'
if dir_has(project, '.ops'):
print("\033[33m [Ops]文件\033[0m\n")
for ops0 in os.listdir(project):
if ops0.endswith('.ops'):
if os.path.isfile(os.path.abspath(ops0)):
filen += 1
print(f' [{filen}]- {ops0}\n')
files[filen] = ops0
infos[filen] = 'ops'
if dir_has(project, '.win'):
print("\033[33m [Win]文件\033[0m\n")
for win0 in os.listdir(project):
if win0.endswith('.win'):
if os.path.isfile(os.path.abspath(win0)):
filen += 1
print(f" [{filen}]- {win0} <WIN> \n")
files[filen] = win0
infos[filen] = 'win'
if dir_has(project, '.win000'):
for win0000 in os.listdir(project):
if win0000.endswith('.win000'):
if os.path.isfile(os.path.abspath(win0000)):
filen += 1
print(f" [{filen}]- {win0000} <分段WIN> \n")
files[filen] = win0000
infos[filen] = 'win000'
if dir_has(project, '.dtb'):
print("\033[33m [Dtb]文件\033[0m\n")
for dtb0 in os.listdir(project):
if dtb0.endswith('.dtb'):
if os.path.isfile(os.path.abspath(dtb0)) and gettype(os.path.abspath(dtb0)) == 'dtb':
filen += 1
print(f' [{filen}]- {dtb0}\n')
files[filen] = dtb0
infos[filen] = 'dtb'
print()
print("\033[33m [00] 返回 [11] 循环解包 \033[0m")
print(" --------------------------------------")
filed = input(" 请输入对应序号:")
if filed == '0':
print()
for v in files.keys():
unpack(files[v], infos[v], project)
elif filed == '11':
print()
imgcheck = 0
upacall = input(" 是否解包所有文件? [1/0]")
for v in files.keys():
if upacall != '1':
imgcheck = input(f" 是否解包{files[v]}?[1/0]")
if upacall == "1" or imgcheck != "0":
unpack(files[v], infos[v], project)
elif filed == '00':
return
elif filed.isdigit():
if int(filed) in files.keys():
unpack(files[int(filed)], infos[int(filed)], project)
else:
ywarn("Input error!")
input("任意按钮继续")
else:
ywarn("Input error!")
input("任意按钮继续")
unpack_choo(project)
def packChoo(project):
cls()
print(" \033[31m >打包 \033[0m\n")
partn = 0
parts = {}
types = {}
if not os.path.exists(project + os.sep + "config"):
os.makedirs(project + os.sep + "config")
if project:
print(" [0]- 打包所有镜像\n")
for packs in os.listdir(project):
if os.path.isdir(project + os.sep + packs):
if os.path.exists(project + os.sep + "config" + os.sep + packs + "_fs_config"):
partn += 1
parts[partn] = packs
if os.path.exists(project + os.sep + "config" + os.sep + packs + "_erofs"):
typeo = 'erofs'
else:
typeo = 'ext'
types[partn] = typeo
print(f" [{partn}]- {packs} <{typeo}>\n")
elif os.path.exists(project + os.sep + packs + os.sep + "comp"):
partn += 1
parts[partn] = packs
types[partn] = 'bootimg'
print(f" [{partn}]- {packs} <bootimg>\n")
elif os.path.exists(project + os.sep + "config" + os.sep + "dtbinfo_" + packs):
partn += 1
parts[partn] = packs
types[partn] = 'dtb'
print(f" [{partn}]- {packs} <dtb>\n")
elif os.path.exists(project + os.sep + "config" + os.sep + "dtboinfo_" + packs):
partn += 1
parts[partn] = packs
types[partn] = 'dtbo'
print(f" [{partn}]- {packs} <dtbo>\n")
print()
print("\033[33m [55] 循环打包 [66] 打包Super [77] 打包Payload [88]返回\033[0m")
print(" --------------------------------------")
filed = input(" 请输入对应序号:")
if filed == '0':
op_menu = input(" 输出文件格式[1]br [2]dat [3]img:")
if op_menu == '1':
form = 'br'
elif op_menu == '2':
form = 'dat'
else:
form = 'img'
if settings.diyimgtype == '1':
syscheck = input("手动打包所有分区格式为:[1]ext4 [2]erofs")
if syscheck == '2':
imgtype = "erofs"
else:
imgtype = "ext"
else:
imgtype = 'ext'
for f in parts.keys():
yecho(f"打包{parts[f]}...")
if types[f] == 'bootimg':
dboot(project + os.sep + parts[f], project + os.sep + parts[f] + ".img")
elif types[f] == 'dtb':
makedtb(project + os.sep + parts[f], project)
elif types[f] == 'dtbo':
makedtbo(parts[f], project)
else:
inpacker(parts[f], project, form, imgtype)
elif filed == '55':
pacall = input(" 是否打包所有镜像? [1/0] ")
op_menu = input(" 输出所有文件格式[1]br [2]dat [3]img:")
if op_menu == '1':
form = 'br'
elif op_menu == '2':
form = 'dat'
else:
form = 'img'
if settings.diyimgtype == '1':
syscheck = input("手动打包所有分区格式为:[1]ext4 [2]erofs")
if syscheck == '2':
imgtype = "erofs"
else:
imgtype = "ext"
else:
imgtype = 'ext'
for f in parts.keys():
if pacall != '1':
imgcheck = input(f" 是否打包{parts[f]}?[1/0] ")
else:
imgcheck = '1'
if not imgcheck == '1':
continue
yecho(f"打包{parts[f]}...")
if types[f] == 'bootimg':
dboot(project + os.sep + parts[f], project + os.sep + parts[f] + ".img")
elif types[f] == 'dtb':
makedtb(project + os.sep + parts[f], project)
pass
elif types[f] == 'dtbo':
makedtbo(parts[f], project)
else:
pass
inpacker(parts[f], project, form, imgtype)
elif filed == '66':
packsuper(project)
elif filed == '77':
packpayload(project)
elif filed == '88':
return
elif filed.isdigit():
if int(filed) in parts.keys():
if settings.diyimgtype == '1' and types[int(filed)] not in ['bootimg', 'dtb', 'dtbo']:
syscheck = input(" 手动打包所有分区格式为:[1]ext4 [2]erofs")
if syscheck == '2':
imgtype = "erofs"