forked from nyxiereal/XToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
453 lines (383 loc) · 17.1 KB
/
main.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
# User interface
from rich.console import Console
from rich.table import Table
from rich.text import Text
# Downloader
from rich.progress import Progress
from requests.adapters import HTTPAdapter
from os import remove, system, startfile
from urllib.request import urlretrieve
from urllib.parse import urlparse
from requests import Session
# Opening web pages
from webbrowser import open as webopen
# Helpers, tools and data
from tools import chooseQuotes, footers, columns
from xtools import tools, showInfo, iScrape
# User input and cooldowns
from time import sleep
from getpass import getpass
# Updater
from lastversion import latest
# Exiting from the program
from sys import exit
# Set Console object and version for the updater and UI
c = Console()
VERSION = "4.2"
###### HELPER FUNCTIONS
def fWrite(run, filename, content):
"""Write a file
Args:
run (int): Controls if the file will be ran
filename (str): File name
content (str): Content of the file
"""
fp = open(filename, 'w')
fp.write(content)
fp.close()
if run == 1: startfile(filename)
# Clear the display
def cls():
system('cls')
# Color helpers and shi
class cl():
def yellow(text):
return(f'[yellow]{text}[/yellow]')
class Printer():
def green(text):
c.print(f'[green][✓] {text}[/green]')
def yellow(text):
c.print(f'[yellow][?] {text}[/yellow]')
def red(text):
c.print(f'[red][✗] {text}[/red]')
def zpr(text):
c.print(f'[blue][>] {text}[/blue]')
def download(url: str, fnam: str, name: str):
"""Downloads a file with progress tracking
Args:
url (string): URL of the file to download
fnam (string): Filename for the outputted file
name (string): Name to show during download
"""
try:
# None handler (null safety in Python)
if name is None:
name = fnam
# Force the URL to use HTTPS
url = (urlparse(url))._replace(scheme='https').geturl()
# Add HTTPAdapter settings to increase download speed
adapter = HTTPAdapter(max_retries=3,
pool_connections=20,
pool_maxsize=10)
# Add headers to bypass simple robots.txt blocking
headers = {'Accept-Encoding': 'gzip, deflate',
'User-Agent': 'Mozilla/5.0',
'Cache-Control': 'max-age=600',
'Connection': 'keep-alive'}
# Create a new Session object
session = Session()
# Force the URL to use HTTPS and HTTPAdapter options
session.mount('https://', adapter)
# Make a head request and get the filesize
response = session.head(url, headers=headers)
total_size = int(response.headers.get("content-length", 0))
# Actually get the file contents
r = session.get(url, stream=True, headers=headers)
# Init the progress tracking task and give it an ID
progress = Progress()
# Open the file and write content to it + update the progress bar
with progress:
task_id = progress.add_task(f"[light blue]Downloading {name}...", total=total_size)
with open(fnam, 'wb') as file:
for data in r.iter_content(1024):
file.write(data)
progress.update(task_id, advance=len(data))
except KeyboardInterrupt:
# Just remove the file if the download gets cancelled
Printer.red('Aborting!')
remove(fnam)
def updater():
"""Check for updates
"""
try:
up = latest("nyxiereal/XToolBox")
if VERSION < str(up):
Printer.zpr(f'New version available: {up}, do you want to update?')
if yn():
download('https://github.com/nyxiereal/XToolBox/releases/latest/download/XTBox.exe', f'XTBox.{up}.exe', 'XToolBox Update')
Printer.green('Done!')
exit(startfile(f'XTBox.{up}.exe'))
except:
Printer.green('Done!')
# function to reduce code when using interpreter() page 97
def yn(prompt=""):
"""Simple yes/no prompt
Args:
prompt (str, optional): Anything you want to display. Defaults to "".
Returns:
bool: Return True or False.
"""
prompt += f"([green]Y[/green]/[red]n[/red]): "
goodInput, YNvalue = False, False
while not goodInput:
goodInput, YNvalue = interpreter(97, prompt)
return YNvalue
# function for multiple choice downloads interpreter() page 98
# returns the index of chosen option, it can return -1 if the user canceled selection
# tool is <Tool>, prompt is <str>
def multiChoose(tool, prompt):
# ┌──────────< B - back >──────────┐
# │ │
# │ [1] name_name_name_1 │
# │ [2] name_name_name_name_2 │
# │ ... │
# │ │
# ├────────────────────────────────┤
# │ _________Prompt_________ │
# └────────────────────────────────┘
# determining window size
size = 34 # min size
if len(prompt)+10 > size: size = len(prompt)+10 # the +10 is because of minimum space on both sides of the prompt (| |)
for ind in range(len(tool.dwn)):
if len(tool.getDesc(ind))+7+len(str(ind+1)) > size: # the +7 is because of the minimum possible space in an option (│ [] │)
size = len(tool.getDesc(ind))+7+len(str(ind+1)) # ind +1 cuz ind goes from 0 to max-1
# ensuring symmetry
if len(prompt)%2 == 0:
backMessage = "< B - back >"
if size%2==1: size+=1
else:
backMessage = "< back: B >"
if size%2==0: size+=1
# the top bar
c.print(f"┌{'─'*int((size-2-len(backMessage))/2)}{backMessage}{'─'*int((size-2-len(backMessage))/2)}┐")
# empty line cuz it looks nice :D
c.print(f"│{' '*(size-2)}│")
# options
for ind in range(len(tool.dwn)):
c.print(f"│ [{ind+1}] {tool.getDesc(ind)}{' '*int(size-6-len(tool.getDesc(ind))-len(str(ind+1)))}│")
# another empty
c.print(f"│{' '*(size-2)}│")
# prompt
c.print(f"├{'─'*(size-2)}┤")
c.print(f"│{' '*int((size-2-len(prompt))/2)}{prompt}{' '*int((size-2-len(prompt))/2)}│")
c.print(f"└{'─'*(size-2)}┘")
goodInput = False
while not goodInput:
goodInput, index = interpreter(98)
if index > len(tool.dwn): goodInput = False
return index
def dl(url, urlr, name):
"""Helper to download files
Args:
url (str): URL to the file
urlr (str): File name
name (str): Name
"""
# Before downloading files, check if the url contains a version-code
if '%UBUNTUVERSION%' in url:
url = url.replace('%UBUNTUVERSION%', iScrape.ubuntu())
elif '%POP%' in url:
url = iScrape.popOS(url.split(',')[1])
elif '%MINTVERSION%' in url:
url = url.replace('%MINTVERSION%', iScrape.mint())
elif '%ARTIX%' in url:
url = iScrape.artix(url.split(',')[1])
elif '%SOLUS%' in url:
url = iScrape.solus(url.split(',')[1])
elif '%DEBIAN%' in url:
url = iScrape.debian()
elif r'%ENDEAVOUR%' in url:
url = url.replace(r'%ENDEAVOUR%', iScrape.endeavour())
elif '%CACHYVERSION%' in url:
url = url.replace('%CACHYVERSION%', iScrape.cachy())
# make sure user understands what they are about do download
c.print(f"XTBox will download an executable from:\n\t{url}")
if not yn("Approve?"):
return
try:
download(url, urlr, name)
if urlr[-3:] != "iso":
if yn(f"Run {urlr}?"):
startfile(urlr)
except:
Printer.red( "ERROR 3: Can't download file from the server...")
getpass("\n... press ENTER to continue ...", stream=None)
pageDisplay(last)
# Nyaboom dirty fix
def pwsh(cmd, name):
c.print(f"XTBox will run the following command as powershell:\n\t{cmd}")
if not yn("Approve?"): return
system(cmd)
# If it ain't broke, don't fix it!
def checkforlinks(inp):
if r'%GHOSTSPECTRE%' in inp:
return(iScrape.ghostSpectre())
else:
return(inp)
def dwnTool(tool):
index = 0
if (len(tool.dwn)!=1):
if tool.code[0] == "l": prompt = "Choose your Distro Type"
else: prompt = "Choose Version"
index = multiChoose(tool, prompt)
if index < 0: return
if tool.command==1: dl(tool.getDwn(index), tool.getExec(index), tool.getName(index))
elif tool.command==2: pwsh(tool.getDwn(index), tool.getName(index))
elif tool.command==3:
i = checkforlinks(tool.getDwn(index))
c.print(f"XTBox will open:\n\t{i}") #webopen is used only here so no wrapper is needed for now
if yn("Approve?"): webopen(i)
elif tool.command==4:
c.print(f"XTBox will retrieve data from:\n\t{tool.getDwn(index)}")
if yn("Approve?"): urlretrieve(tool.getDwn(index), tool.getExec(index))
elif tool.command==5:
fWrite(tool.getDwn(index)) # this doesnt really run anything so no approval is neded
def helpe():
cls()
c.print(f"┌───────────────────────────────────────────────────────┐\n"
f"│ Key │ Command │\n"
f"│ H │ Help Page (this page) │\n"
f"│ N │ Next Page │\n"
f"│ B │ Previous Page (back) │\n"
f"│ 99 │ Exit │\n"
f"├───────────────────────────────────────────────────────┤\n"
f"│ Color │ Meaning │\n"
f"│ {cl.yellow('YELLOW')} │ Advanced Option │\n"
f"├───────────────────────────────────────────────────────┤\n"
f"│ Error │ Explanation │\n"
f"│ 1 │ File already exists │\n"
f"│ 2 │ Can't check for file overwrite │\n"
f"│ 3 │ Can't download file from the server │\n"
f"├───────────────────────────────────────────────────────┤\n"
f"│ If scripts won't execute, press P │\n"
f"├───────────────────────────────────────────────────────┤\n"
f"│ Press ENTER/B to go back. │\n"
f"└───────────────────────────────────────────────────────┘\n")
return interpreter(0)
# function that interprets user input
# page is what the interface is showing and *args is additional info that may be required for some pages
# !return type is based on the page number! (if not stated otherwise, returns void)
def interpreter(page, prompt="> "):
global lastPage
choose = str(c.input(prompt)).strip().lower() # lower for easier iffing
# if user inputs 99, exit the program
if choose == "99":
exit()
# if user inputs h, open help
if choose == "h" and page != 0 :
# return the correct values to prevent crashes
if page == 98 or page == 97:
if lastPage != None: # prevent getting this message in EULA and similar functions
c.print("Exit selection to access help!")
return False, False
else:
while not helpe(): pass
return
# if user uses the Info command wrong:
if choose == "i" and page > 0 and page < 20:
c.print("'i' is not a valid command, if you want info type:")
c.print("\ti <CODE>")
c.print("For example: i d2")
getpass("\n... press ENTER to continue ...", stream=None)
pageDisplay(page)
# page 0 (help)
# returns true/false which indicate if helpe should close
if page==0:
# go back
if choose == "b" or choose == "":
pageDisplay(last)
# elevate powershell execution policy
if choose == "p":
# todo: add warning message that this command is about to be run (not every1 wants it)
# function wrappers?
pwsh("Set-ExecutionPolicy Unrestricted -Scope CurrentUser", "SetExecutionPolicy")
return True
# not valid option
else:
c.print(f"No option named {choose}")
return False
#for pages 1-3 (tool pickers)
elif page >= 1 and page <= 4:
if choose == "": pass # prevent empty prompting
# next page
elif choose == "n":
if page == 1: lastPage = pageDisplay(2)
if page == 2: lastPage = pageDisplay(3)
if page == 3: lastPage = pageDisplay(1)
# previous page
elif choose == "b":
if page == 1: lastPage = pageDisplay(3)
if page == 2: lastPage = pageDisplay(1)
if page == 3: lastPage = pageDisplay(2)
# program ID entered
elif f"{choose}-{page}" in tools:
dwnTool(tools[f"{choose}-{page}"])
pageDisplay(page)
# i + program ID entered (user wants info)
elif (len(choose) > 2) and (choose[0:2] == "i ") and (f"{choose[2:]}-{page}" in tools):
showInfo(tools[f"{choose[2:]}-{page}"])
pageDisplay(page)
# bad input
else:
c.print(f"No option named {choose}")
sleep(3)
pageDisplay(page)
# page 97 (y/n)
# returns 2 bool args: correct/incorrect input, and y/n answer
elif page == 97:
if choose == "y": return True, True
elif choose == "n": return True, False
elif choose == "": return True, True
else:
c.print(f"No option named {choose}")
return False, False
# page 98 (multiple choice download)
# returns 2 args: correct/incorrect input (bool), and the chosen option (int)
# if user wants to exit selection, the second return value becomes negative
elif page==98:
# cancel (index < 0)
if choose == "b": return True, -1
# user choice
elif choose.isnumeric() and int(choose) > 0:
return True, int(choose)-1
else:
c.print(f"No option named {choose}")
return False, 0
def xget(ide):
try:
first = (f'[bold][[/bold][blue][bold]{(ide.split('-')[0])[1:]}[/blue][/bold][bold]][/bold] {Text(tools[ide].name)}')
if ide in ['t1-1', 'm6-2', 'm7-2', 't3-2', 'l4-3', 'g2-3', 'c6-3']:
return(f'{first} [yellow]ADV[/yellow]')
else:
return(first)
except:
return('')
def pageDisplay(page):
global last, welcome
last = page
cls()
# Show the predefined "quote" only the first time the program is ran.
if welcome == 0:
table = Table(title=f"XToolBox | v{VERSION}, Made by Nyxie.", show_footer=True)
welcome = 1
else:
table = Table(title=f"XToolBox | {chooseQuotes()}", show_footer=True)
table.add_column(f"[[blue]{(columns[page][0][0]).capitalize()}[/blue]] {columns[page][0][1]}", footers[0], justify='left',min_width=24)
table.add_column(f"[[blue]{(columns[page][1][0]).capitalize()}[/blue]] {columns[page][1][1]}", footers[1], justify='left',min_width=24)
table.add_column(f"[[blue]{(columns[page][2][0]).capitalize()}[/blue]] {columns[page][2][1]}", footers[2], justify='left',min_width=24)
table.add_column(f"[[blue]{(columns[page][3][0]).capitalize()}[/blue]] {columns[page][3][1]}", f'[blue]{page}/{len(columns)-1}[/blue]', min_width=24)
for i in range(15):
if i != 0:
table.add_row(xget(f'{columns[page][0][0]}{i}-{page}'), xget(f'{columns[page][1][0]}{i}-{page}'), xget(f'{columns[page][2][0]}{i}-{page}'), xget(f'{columns[page][3][0]}{i}-{page}'))
c.print(table)
interpreter(page)
# init
cls()
updater()
welcome = 0
while True:
try:
pageDisplay(1)
except KeyboardInterrupt:
print('bye!')
exit()