Files
TiropitLauncher/CLI/Init.py

456 lines
13 KiB
Python

#it Wasnt the venv .... 😁🔫 --> 🏠🔥 --> 👶🏻👷🏻💀
APP_VERSION = 1.21
import zipfile
import configparser
import os
from pathlib import Path
import requests
import argparse
import sys
import tkinter as tk
from tkinter import filedialog
parser = argparse.ArgumentParser(description='TiropitLauncher CLI & Back-End')
parser.add_argument('-backend', help="Runs the app in backend mode (no UI)", action="store_true")
#declare default vars
class Config():
AccountKey = "NK"
AccountID = "NA"
version = APP_VERSION
class ServerObj():
def __init__(self, isReachable=False):
self.host = "0.0.0.0"
self.isReachable = False
self.state = "Resolving IP"
@property
def Icon(self):
if self.isReachable:
return "🌐"
else:
return ""
args = parser.parse_args()
Server = ServerObj()
class TiropitCliObj:
_server_instance = Server
@property
def url(self):
return f"http://{self._server_instance.host}:5000"
@property
def isReachable(self):
return self._server_instance.isReachable
TiropitCLI = TiropitCliObj()
#declare files
config = configparser.ConfigParser()
configPath = Path("Config.ini")
class Display():
def Clear():
os.system('cls' if os.name == 'nt' else 'clear')
def showIntroText():
print("Tiropit Launcher CLI - Release Branch")
print(f"[TCLI]=============[Select option]==============[{Config.version}]")
def WarnMissingConfig(ConfigError):
print(f"[⚠️ WARNING ⚠️] - Your config file is corrupt , something that has to do with {ConfigError}")
print("Program will exit before it crashes :)")
reset = input("It is recommended that you reset the app data (you will be logged out) y (reset) / n (exit)")
if reset == "y":
os.remove(configPath)
print("[⚠️ WARNING ⚠️] - Reset Done, Re-Open TiropitCLI")
exit(0)
def makeConfig():
config['DEFAULT'] = {'Version': Config.version}
config['ACCOUNT'] = {}
config['ACCOUNT']['KEY'] = "NK"
config['ACCOUNT']["ID"] = "NA"
with open('Config.ini', 'w') as configfile:
config.write(configfile)
def select_folder():
root = tk.Tk()
root.withdraw()
folder_path = filedialog.askdirectory()
if folder_path:
print(f"Selected folder: {folder_path}")
else:
print("No folder was selected.")
return folder_path
def TiropitLogin():
class menuData():
def menuInstructions():
Display.Clear()
showIntroText()
print("|[About: Login Instructions] |")
print("|1. Enter your username & password |")
print("|2. Enter your pin (if you have) |")
print("|3. Save Login key (autologin) |")
print("|[e] Exit [Any] Login > |")
print("======================================================")
def menuUsername():
Display.Clear()
showIntroText()
print(f"|[LogIn: Login page] [{Server.Icon}]|")
print("| Enter your username |")
print("| |")
print("| |")
print("| |")
print("======================================================")
menuData.menuInstructions()
option = input(">> ")
match option:
case "e":
showMenu(1)
return 0
case _:
menuData.menuUsername()
def loadConfig():
try:
config.read(configPath)
Config.version = config["DEFAULT"]["Version"]
if float(Config.version) != float(APP_VERSION):
WarnMissingConfig("Outdated Config")
Config.AccountID = config["ACCOUNT"]["ID"]
Config.AccountID = config["ACCOUNT"]["KEY"]
except Exception as e:
WarnMissingConfig(e)
# [Update Functions] <------------------------------------------------------------------------------------------------------------ [Begin]
def CheckForUpdate(log=False):
if log: print("Connecting....")
if log:print(f"Request Version from API@{TiropitCLI.url}")
response = requests.get(TiropitCLI.url + "/api/getTiropitVersion")
if log:print(f"ResponseCode:{response.status_code}")
data = response.json()
if log:print(f"ResponseJSON:{data}")
version = float(data["Version"])
currentVersion = float(Config.version)
if log:print(f"Recieved Version {version} - Current Version {currentVersion}")
if float(version) > float(currentVersion):
if log:print(f"Downloading & Installing Update {version}")
download_file("https://kevinblog.sytes.net/APIS/TiropitLauncher/Tiri.zip", "update.zip")
unzipFile("update.zip", ".")
print("Assuming Update Done - Exiting , Restart Tiropit")
else:
if log:print(f"Already using latest version -> {currentVersion}")
def unzipFile(filename,path):
os.makedirs(path, exist_ok=True)
with zipfile.ZipFile(filename, "r") as zf:
zf.extractall(path)
print(f"Extract Done :) to {path}")
def download_file(url, filename):
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print(f"[Downloader] File downloaded at {filename}")
# [Update Functions] <-------------------------------------------------------------------------------------------------------------- [End]
def disconnect():
Server.host = "0.0.0.0"
Server.state = "Offline"
Server.isReachable = False
if args.backend: print("4:OFFLINE")
def grabServerResolver():
Server.state = "Resolving IP"
try:
response = requests.get("https://kevinblog.sytes.net/APIS/test1.php")
response.raise_for_status()
data = response.json()
server_ip = data.get("HostIp")
Server.isReachable = True
Server.state = "Connected"
Server.host = server_ip
if args.backend: print(f"2:CONNECTED TO: {server_ip}")
return server_ip
except requests.exceptions.RequestException as e:
Server.isReachable = False
Server.state = f"Failed/Timed Out - {e}"
if args.backend: print(f"3:FAILED CONN TO: {e}")
else: print("Error resolving a host, Considering service is offline.")
pass
def checkConfig():
if configPath.exists():
print("The Config file exists.")
loadConfig()
else:
print("The file Config does not exist. - Creating")
makeConfig()
def debugMenu():
class menuData():
def mainMenu():
Display.Clear()
showIntroText()
print(f"|[DBG] [{Server.Icon}]|")
print("|1. Read Server Data |")
print("|2. |")
print("|3. |")
print("|[e] Exit |")
print("======================================================")
option = input(">> ")
if option == "": menuData.mainMenu()
match option:
case "e":
showMenu(1)
return 0
case "1":
menuData.menuServerData()
case _:
menuData.mainMenu()
def menuServerData():
Display.Clear()
showIntroText()
print(f"|[DBG: Login page] [{Server.Icon}]|")
print(f"| IsReachable : {Server.isReachable}")
print(f"| Host : {Server.host}")
print(f"| State : {Server.state}")
print("[e] Exit | [R] Reconnect | [O] Offline (Disconnect)")
print("======================================================")
option = input(">> ")
if option == "": menuData.menuServerData()
match option:
case "e":
showMenu(1)
return 0
case "r":
grabServerResolver()
menuData.menuServerData()
case "o":
disconnect()
menuData.menuServerData()
case _:
menuData.menuServerData()
menuData.mainMenu()
option = input(">> ")
if option == "": menuData.mainMenu()
match option:
case "e":
showMenu(1)
return 0
case "1":
menuData.menuServerData()
case _:
menuData.mainMenu()
def Gamesmenu():
class menuData():
def mainMenu():
Display.Clear()
showIntroText()
print(f"|[Games] [{Server.Icon}]|")
print("|1. Minecraft Tiropit |")
print("|2. CS2 (Comming Soon) |")
print("| |")
print("|[e] Exit |")
print("======================================================")
option = input(">> ")
if option == "": menuData.mainMenu()
match option:
case "e":
showMenu(1)
return 0
case "1":
menuData.MinecraftMenu()
case _:
menuData.mainMenu()
def MinecraftMenu():
Display.Clear()
showIntroText()
print(f"|[Minecraft] [{Server.Icon}]|")
print("|1. Update |")
print("|2. Install |")
print("| |")
print("|[e] Exit |")
print("======================================================")
option = input(">> ")
if option == "": menuData.mainMenu()
match option:
case "e":
menuData.mainMenu()
return 0
case "2":
menuData.installMenu()
case _:
menuData.MinecraftMenu()
def installMenu():
Display.Clear()
showIntroText()
print(f"|[Minecraft] [{Server.Icon}]|")
print("|1. Select Install Location |")
print("======================================================")
print(select_folder())
print("| |")
print("|[e] Exit |")
print("======================================================")
menuData.mainMenu()
def showMenu(menuID):
Display.Clear()
showIntroText()
match menuID:
case 1:
print("|[Main menu] |")
print("|[1] Log in to tiropit | [2] Reset Data & Config |")
print("|[3] Send / Get Request| [4] My Profile |")
print("|[5] Debug Data | [6] Games |")
print("|[e] Exit | [7] Update |")
print("======================================================")
option = input(">> ")
if option == "": showMenu(1)
print(option)
match option:
case "1":
TiropitLogin()
case "5":
debugMenu()
case "7":
CheckForUpdate()
case "6":
Gamesmenu()
case "e":
print("Cya!")
exit();
case _:
showMenu(1)
pass
#Begin
if not args.backend:
grabServerResolver()
checkConfig()
showMenu(1)
else:
print("1:=== BACKEND MODE ===")
grabServerResolver()