-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutnf.py
More file actions
274 lines (259 loc) · 11.1 KB
/
utnf.py
File metadata and controls
274 lines (259 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# TNFlasher.exe Alternative Universal Tool
# Tool version 1.0.2
# Written by MeowIce
# Works with TN 3.2 (Pre-February Reupload) ROMs.
import os,sys,subprocess,shutil,platform,time,webbrowser,urllib.request,json
appID = 102
appVer = "1.0.2"
GREEN = "\033[32m"
RESET = "\033[0m"
CYAN = "\033[36m"
YELLOW = "\033[33m"
RED = "\033[31m"
def checkForUpdates():
try:
with urllib.request.urlopen("https://mirror.meowsmp.net/Apps/UniversalTNFlash/update.json", timeout=5) as response:
data = json.loads(response.read().decode('utf-8'))
serverVerID = int(data.get("appVerID", 0))
serverVer = data.get("appVer", "Unknown")
if serverVerID > appID:
print(YELLOW + f"New update available: Version {serverVer}" + RESET)
print(YELLOW + "Visit https://mirror.meowsmp.net/Apps/UniversalTNFlash/ to download the latest version." + RESET)
time.sleep(3)
except Exception as e:
print(RED + "Unable to check for updates" + RESET)
def getOsType():
global s
s=platform.system()
if s=="Windows":
return "windows"
if s=="Darwin":
return "macos"
if s=="Linux":
return "linux"
return None
def setWindowTitle(title):
osType=getOsType()
if osType=="windows":
os.system(f"title {title}")
if osType in ("macos","linux"):
sys.stdout.write(f"\33]0;{title}\a")
sys.stdout.flush()
setWindowTitle(f"Universal TNFlash Tool Version {appVer}")
def getBaseDir():
return os.path.dirname(os.path.abspath(sys.argv[0]))
baseDir=getBaseDir()
firmwareDir=os.path.join(baseDir,"firmware-update")
superDir=os.path.join(baseDir,"super")
def findFastboot(baseDir):
osType=getOsType()
if osType=="windows":
p=os.path.join(baseDir,"utils","fastboot_win.exe")
if os.path.isfile(p):
return p
if osType=="macos":
p=os.path.join(baseDir,"utils","fastboot_mac")
if os.path.isfile(p):
return p
if osType=="linux":
p=os.path.join(baseDir,"utils","fastboot_tux")
if os.path.isfile(p):
return p
print("fastboot not found, have you extracted the package ?")
time.sleep(10)
sys.exit(1)
def find7za(baseDir):
osType=getOsType()
if osType=="windows":
p=os.path.join(baseDir,"bin","lib","x86","7za.exe")
if os.path.isfile(p):
return p
print("7za.exe not found in bin\\lib\\x86, place it there")
time.sleep(10)
sys.exit(1)
if osType in ("macos","linux"):
found=shutil.which("7za")
if found:
return found
print("7za not found, have you installed it ?")
print("On terminal, run:")
print("For macOS: brew install p7zip")
print("For Linux: sudo apt install p7zip-full (Debian based) OR sudo dnf install p7zip (RedHat based)")
time.sleep(30)
sys.exit(1)
print("Unsupported OS")
time.sleep(10)
sys.exit(1)
fastboot=findFastboot(baseDir)
def run(cmd, check=True):
result = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False
)
out = result.stdout or ""
if out:
print(out, end="")
low = out.lower()
if result.returncode != 0:
if "no such partition" in low or "partition does not exist" in low:
return out
if check:
sys.exit(result.returncode)
return out
def detectChipType(baseDir):
path=os.path.join(baseDir,"bin","check","ChipType")
if not os.path.isfile(path):
print("Cannot detect CPU brand")
time.sleep(10)
sys.exit(1)
with open(path,"r",encoding="utf-8") as f:
v=f.read().strip().upper()
if v not in ("SNAP","MTK"):
print("Unsupported CPU",v)
time.sleep(10)
sys.exit(1)
return v
chipType=detectChipType(baseDir)
print(GREEN + " +=====================================================================+" + RESET)
print(GREEN + " |" + RESET + " " + GREEN + "|" + RESET)
print(GREEN + " |" + RESET + CYAN + " UNIVERSIAL HYPERTN | MIUITN FLASH TOOL " + GREEN + "|" + RESET)
print(GREEN + " |" + RESET + CYAN + f" VERSION {appVer} " + GREEN + "|" + RESET)
print(GREEN + " |" + RESET + " " + GREEN + "|" + RESET)
print(GREEN + " +=====================================================================+" + RESET)
print(GREEN + " |" + RESET + " >> Universial Flash Tool by @meowice " + GREEN + "|" + RESET)
print(GREEN + " |" + RESET + " >> Telegram: https://t.me/tnfbp " + GREEN + "|" + RESET)
print(GREEN + " +=====================================================================+" + RESET)
checkForUpdates()
def printRomInfo(baseDir):
path=os.path.join(baseDir,"RomInfo.txt")
if not os.path.isfile(path):
print("Cannot read ROM information, continue with cautions !")
return
print(CYAN + "-- ROM Information ---------------------------------------------------" + RESET)
with open(path,"r",encoding="utf-8") as f:
for line in f:
print(line.rstrip())
printRomInfo(baseDir)
print("- Chip Type:",chipType + "\n")
print(CYAN + "-- System Checks -----------------------------------------------------" + RESET)
def waitForDeviceWithTimeout(fastboot, timeout=10):
start=time.time()
while True:
r=subprocess.run([fastboot,"devices"], capture_output=True, text=True)
print("Waiting for device...", end="\r")
if r.stdout.strip():
break
if time.time()-start>timeout:
print("No device detected in 10 seconds, please connect device in FASTBOOT mode and try again.")
time.sleep(10)
sys.exit(1)
time.sleep(1)
def checkDeviceCodename(fastboot, baseDir):
deviceCodePath = os.path.join(baseDir, "bin", "check", "DeviceCode")
if not os.path.isfile(deviceCodePath):
print("Cannot read device codename file")
time.sleep(10)
sys.exit(1)
with open(deviceCodePath, "r", encoding="utf-8") as f:
expectedCodename = f.read().strip().lower()
try:
result = subprocess.run(
[fastboot, "getvar", "product"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False
)
except FileNotFoundError:
print("fastboot executable not found !")
time.sleep(10)
sys.exit(1)
actualCodename = ""
for line in result.stdout.splitlines():
line = line.strip().lower()
if line.startswith("product:"):
actualCodename = line.split(":", 1)[1].strip()
break
if not actualCodename:
print("Cannot detect device codename via fastboot. Make sure the device is in FASTBOOT mode and try again.")
time.sleep(10)
sys.exit(1)
if actualCodename != expectedCodename:
print(RED + "ERROR: Device codename mismatch !!! DO NOT CONTINUE" + RESET)
print(CYAN + f"This ROM is for: {expectedCodename}" + RESET)
print(YELLOW + f"But you got: {actualCodename}\n" + RESET)
print(YELLOW + "Please download the correct ROM for your device. Refer to https://www.hypertn.io.vn" + RESET)
time.sleep(10)
sys.exit(1)
else:
print(f"Codename check OK: {actualCodename}")
waitForDeviceWithTimeout(fastboot, timeout=10)
checkDeviceCodename(fastboot, baseDir)
# print(YELLOW + "Choose data options:" + RESET)
print(CYAN + "-- Choose Data Options -----------------------------------------------" + RESET)
print(YELLOW + "1. Keep my data (dirty flash)" + RESET)
print(RED + "2. Delete ALL of my data (clean flash)" + RESET)
choice=input("Select: ").strip()
if choice not in ("1","2"):
print("Invalid choice")
time.sleep(2)
sys.exit(1)
print(CYAN + " [Stage 1/3] Flashing firmware images..." + RESET)
def discoverFirmwareFiles(firmwareDir):
flashPairs = []
for f in os.listdir(firmwareDir):
path = os.path.join(firmwareDir, f)
if os.path.isfile(path) and f.lower().endswith(".img"):
part = os.path.splitext(f)[0]
flashPairs.append((part, f))
return flashPairs
flashPairs = discoverFirmwareFiles(firmwareDir)
singleSlotPartitions = ("cust", "preloader1", "preloader2")
for part, img in flashPairs:
if part.lower() in singleSlotPartitions:
continue
path = os.path.join(firmwareDir, img)
run([fastboot, "flash", f"{part}_a", path])
run([fastboot, "flash", f"{part}_b", path])
for part, img in flashPairs:
if part.lower() not in singleSlotPartitions:
continue
path = os.path.join(firmwareDir, img)
run([fastboot, "flash", part, path])
print(CYAN + " [Stage 2/3] Flashing super partition..." + RESET)
run([fastboot,"flash","super",os.path.join(firmwareDir,"not_modernmfw.img")])
def getSuperChunks(dirPath):
flashOrder = [7,14,2,13,9,12,0,10,6,5,15,3,11,8,1,16,17,18,19,20,21,22,23]
chunks = {}
for f in os.listdir(dirPath):
if f.startswith("superTN.img."):
suf = f.split(".")[-1]
if suf.isdigit():
chunks[int(suf)] = f
orderedChunks = []
for i in flashOrder:
if i in chunks:
orderedChunks.append(os.path.join(dirPath, chunks[i]))
return orderedChunks
superChunks=getSuperChunks(superDir)
for img in superChunks:
run([fastboot,"flash","super",img])
print(CYAN + " [Stage 3/3] Finalizing flash process..." + RESET)
if choice=="1":
print(YELLOW + "Skipping data wipe as per user choice" + RESET)
if choice=="2":
for p in ["userdata","metadata","frp"]:
run([fastboot,"erase",p])
run([fastboot,"set_active","a"])
print(GREEN + " +=====================================================================+" + RESET)
print(GREEN + " |" + RESET + " ALL DONE, DEVICE WILL RESTART NOW " + GREEN + "|" + RESET)
print(GREEN + " +=====================================================================+" + RESET)
run([fastboot,"reboot"])
print("WARNING ! MUST READ !\n\nTo prevent bootloop in TN 3.1+ when using TNToolbox, do the following:\n1. Open Settings\n2. Tap \"More connectivity options\" located under the VPN section\n3. Tap \"Private DNS\" located below Airplane mode\n4. Select the last option and paste 9d6f1c.dns.nextdns.io\n5. Save and you are done !\n\nThis will block TNToolbox server connection so it will not brick your device.\n\n\nCẢNH BÁO ! PHẢI ĐỌC !\n\nĐể tránh bootloop trên TN 3.1+ khi sử dụng TNToolbox, bạn làm theo các bước sau:\n1. Mở Cài đặt\n2. Ấn vào \"Thêm tuỳ chọn kết nối\" nằm dưới mục VPN\n3. Ấn vào \"DNS cá nhân\" nằm dưới chế độ máy bay\n4. Chọn dòng cuối và dán 9d6f1c.dns.nextdns.io\n5. Lưu lại là xong rồi đó !\n\nLàm vậy sẽ chặn kết nối tới server TNToolbox, tránh ăn brick.")
input("Press Enter to exit")
def openTelegram():
webbrowser.open_new_tab("https://t.me/tnfbp/")
openTelegram()