offline-minecraft-launcher/offline-minecraft-launcher.py
2022-05-13 13:17:54 +02:00

325 lines
11 KiB
Python

#!/usr/bin/env python3
import sys
oldexcepthook = sys.excepthook
def newexcepthook(type,value,traceback):
oldexcepthook(type,value,traceback)
input("Press ENTER to quit.")
sys.excepthook = newexcepthook
import os
p = os.path.join
pUp = os.path.dirname
s = False
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
s = os.path.realpath(sys.executable)
else:
s = os.path.realpath(__file__)
sp = pUp(s)
import configparser
import subprocess
import json
import hashlib
import platform
import copy
omlPath = p(sp,"oml")
def runCode(str, lcs = False, description = "loose-code"):
if lcs == False: lcs = {}
code = compile(str,description,"exec")
exec(code,globals(),lcs)
return lcs
def runScript(sf, lcs = False):
if lcs == False: lcs = {}
code = False
with open(sf,"r",encoding="utf-8") as script:
code = script.read()
runCode(code,lcs,sf)
return lcs
def readGenericListFile(path):
rtn = []
with open(path,"r",encoding="utf-8") as listf:
for line in listf:
line = line.split("#",1)[0]
line = line.strip(" \t\r\n")
if line == "": continue
rtn.append(line)
return rtn
def readFile(file,decode = "utf-8"):
fileh = False
fileh = open(file,"rb")
data = fileh.read()
fileh.close()
if decode == False: return data
return data.decode(decode)
def readJsonFile(file):
fileh = open(file,"r")
data = fileh.read()
fileh.close()
return json.loads(data)
def main():
print("Running modules...")
for root,dirs,files in os.walk(p(omlPath,"modules")):
for file in files:
sfile = file.rsplit(".",1)
if len(sfile) < 2: continue
if sfile[1] != "modlist": continue
ffile = p(root,file)
lfile = ffile.replace(p(omlPath,"modules") + os.path.sep,"",1)
print("> " +lfile)
for mod in readGenericListFile(ffile):
print(">> " +mod+ " ...")
runScript(p(omlPath,"modules",mod))
break
print("")
print(colored(colorama.Fore.GREEN,"Reading config..."))
config = configparser.ConfigParser()
config.optionxform = str
config.read(p(omlPath,"config.ini"))
global lv
lv = config["default"]
for var in lv:
glbs = globals()
for glb in glbs:
lv[var] = lv[var].replace("$+" +glb+ "$",str(glbs[glb]))
lcs = locals()
for lc in lcs:
lv[var] = lv[var].replace("$" +lc+ "$",str(lcs[lc]))
if lv["osName"] == "":
lv["osName"] = platform.system().lower()
if lv["osName"] == "darwin": lv["osName"] = "macos"
if lv["osVersion"] == "":
lv["osVersion"] = platform.version()
if lv["jvmArch"] == "":
print(colored(colorama.Fore.GREEN,"Querying JVM architecture..."))
if "64-Bit" in subprocess.check_output([lv["java"],"-version"]).decode("utf-8"):
lv["jvmArch"] = "amd64"
else:
lv["jvmArch"] = "x86"
print("")
for setting in lv:
print(colored(colorama.Fore.BLACK,setting+ "=" +str(lv[setting])))
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if arg.startswith("-"): continue
argSplit = arg.split("=",1)
if len(argSplit) > 1:
lv[argSplit[0]] = argSplit[1]
else:
lv[argSplit[0]] = True
if not lv["osName"] in ["windows","linux","macos"]:
print(colored(colorama.Fore.YELLOW,"\nWarning, unsupported OS detected: '" +lv["osName"]+ "'"),file=sys.stderr)
print("Needs to be either windows, linux or macos. Define it with osName=name in the config.",file=sys.stderr)
print("")
if not "version" in lv: lv["version"] = input("Version ID: ")
if "-downloadonly" in sys.argv: lv["name"] = "Player"
if not "name" in lv: lv["name"] = input("Player name: ")
global tmpFile
tmpFile = p(lv["gamePath"],"file.tmp")
if os.path.isfile(tmpFile): os.remove(tmpFile)
launcherVariables = {}
versionsPath = p(lv["gamePath"],"versions")
libraryPath = p(lv["gamePath"],"libraries")
nativePath = p(lv["gamePath"],"natives")
versionPath = p(lv["gamePath"],"versions",lv["version"])
nativesOutPath = p(lv["gamePath"],"natives-extracted",lv["version"],lv["osName"]+ "." +lv["jvmArch"])
assetsPath = p(lv["gamePath"],"assets")
print(colored(colorama.Fore.GREEN,"Scanning .json(s)..."))
clientJson,libraries,arguments,jvmArguments = processVersion(versionsPath,libraryPath,nativePath,lv["version"])
try:
launcherVariables["assets_index_name"] = findInChain(versionsPath,lv["version"],["assets"])
except:
print(colored(colorama.Fore.YELLOW,"> Could not find assets_index_name, assuming pre-1.6"),file=sys.stderr)
launcherVariables["assets_index_name"] = "pre-1.6"
input()
print(colored(colorama.Fore.GREEN,"\nDownloading libraries..."))
for library in libraries:
if "url" in library:
print(colored(colorama.Fore.BLACK,getLibraryPrettyName(library)))
try:
fileDl(library["url"],library["filePathOS"],read = False)
except Exception as e:
print(colored(colorama.Fore.RED,"> Could not download: ") +str(e),file=sys.stderr)
else:
if library["dumb"] == True:
try:
fileDl(library["url"] + ".sha1",library["filePathOS"] + ".sha1",read = False)
except Exception as e:
print(colored(colorama.Fore.RED,"> Could not download sha1 hash: ") +str(e),file=sys.stderr)
if "-verifydata" in sys.argv: checkLibraryHash(library)
if "-verifydata" in sys.argv: # assets
print(colored(colorama.Fore.GREEN,"\nVerifying assets..."))
assetJson = False
with open(p(assetsPath,"indexes",launcherVariables["assets_index_name"] + ".json"),"r") as fileh: assetJson = json.loads(fileh.read())
for asset in assetJson["objects"]:
hash = assetJson["objects"][asset]["hash"]
assetp = p(assetsPath,"objects",hash[:2],hash)
if not os.path.isfile(assetp):
print(colored(colorama.Fore.RED,assetp+ " is missing!"),file=sys.stderr)
continue
if hash != getFileHash(assetp):
print(colored(colorama.Fore.RED,assetp+ " is corrupt!"),file=sys.stderr)
if "-downloadonly" in sys.argv:
exit(0)
loadLibraries = {}
for library in libraries:
if "data" in library and "rules" in library["data"] and checkRules(library["data"]["rules"]) == "disallow": continue
if library["type"] == "client":
loadLibraries["client:" +library["filePathOS"]] = library
elif library["type"] == "library":
loadLibraries[library["package"] + ":" +library["name"]] = library
separator = ";"
libraryList = ""
if lv["osName"] != "windows": separator = ":"
print(colored(colorama.Fore.GREEN,"\nLoaded libraries:"))
clientJar = ""
for libraryID in loadLibraries:
library = loadLibraries[libraryID]
if os.path.isfile(library["filePathOS"]):
if library["type"] == "client":
print("Client: " +library["filePathOS"])
clientJar = library["filePathOS"]
else:
print(colored(colorama.Fore.BLACK,getLibraryPrettyName(library)))
else:
print(colored(colorama.Fore.RED,"> Lib not found: ") +getLibraryPrettyName(library),file=sys.stderr)
continue
libraryList += library["filePathOS"] + separator
libraryList = libraryList[:-1]
print(colored(colorama.Fore.GREEN,"\nExtracting natives..."))
if not os.path.isdir(nativesOutPath): os.makedirs(nativesOutPath)
for library in libraries:
if library["type"] == "native":
if "rules" in library["data"] and checkRules(library["data"]["rules"]) == "disallow": continue
if lv["osName"] != "macos":
if library["nativeOS"] != lv["osName"]: continue
else:
if not library["nativeOS"] in ["macos","osx"]: continue
if not os.path.isfile(library["filePathOS"]):
print(colored(colorama.Fore.RED,"> Native not found: ") +getLibraryPrettyName(library),file=sys.stderr)
continue
print(colored(colorama.Fore.BLACK,getLibraryPrettyName(library)))
proc = subprocess.Popen(["7z","x",library["filePathOS"],"-o" +nativesOutPath,"-aos"],stdout=subprocess.DEVNULL)
rtn = proc.wait()
if rtn != 0:
print(colored(colorama.Fore.RED,"> Native could not be extracted: ") +getLibraryPrettyName(library),file=sys.stderr)
print(colored(colorama.Fore.GREEN,"\nSetting up launcher variables..."))
launcherVariables["auth_player_name"] = lv["name"]
launcherVariables["version_name"] = findInChainDeepest(versionsPath,lv["version"],["id"])
launcherVariables["game_directory"] = lv["gamePath"]
launcherVariables["assets_root"] = assetsPath
launcherVariables["auth_access_token"] = "-"
launcherVariables["auth_uuid"] = hashlib.md5(lv["name"].encode('utf-8')).hexdigest()
launcherVariables["user_type"] = "offline"
launcherVariables["version_type"] = clientJson["type"]
launcherVariables["natives_directory"] = nativesOutPath
launcherVariables["launcher_name"] = "offline-minecraft-launcher"
launcherVariables["launcher_version"] = "0.0"
launcherVariables["classpath"] = libraryList
launcherVariables["game_assets"] = assetsPath
launcherVariables["auth_session"] = "-"
launcherVariables["user_properties"] = "{}"
if lv["profileFolder"] == "1":
profilePath = p(lv["gamePath"],"profiles")
launcherVariables["game_directory"] = p(profilePath,lv["name"],lv["version"],".minecraft")
if not os.path.isdir(launcherVariables["game_directory"]): os.makedirs(launcherVariables["game_directory"])
os.chdir(launcherVariables["game_directory"])
if launcherVariables["game_directory"].replace(pUp(launcherVariables["game_directory"]) + os.sep,"",1) == ".minecraft":
print(colored(colorama.Fore.MAGENTA,"> game_directory is called .minecraft, setting APPDATA/HOME environment variables to parent directory."))
os.environ["APPDATA"] = pUp(launcherVariables["game_directory"])
os.environ["HOME"] = os.environ["APPDATA"]
# JVM arguments:
args = []
if not findArgument(jvmArguments,"-Djava-library.path="):
args.append("-Djava.library.path=" +nativesOutPath)
if not findArgument(jvmArguments,"-Dminecraft.launcher.brand="):
args.append("-Dminecraft.launcher.brand=" +launcherVariables["launcher_name"])
if not findArgument(jvmArguments,"-Dminecraft.launcher.version="):
args.append("-Dminecraft.launcher.version=" +launcherVariables["launcher_version"])
if lv["osName"] == "windows":
if not findArgument(jvmArguments,"-XX:HeapDumpPath="):
args.append("-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump")
args.append("-Dminecraft.client.jar=" +clientJar)
if not findArgument(jvmArguments,"-cp"):
args.append("-cp")
args.append(libraryList)
for arg in jvmArguments:
for var in launcherVariables:
arg = arg.replace("${" +var+ "}",launcherVariables[var])
args.append(arg)
args = args + json.loads(lv["jvmArguments"])
args.append(clientJson["mainClass"])
for arg in arguments:
for var in launcherVariables:
arg = arg.replace("${" +var+ "}",launcherVariables[var])
args.append(arg)
if not findArgument(args,"--gameDir"):
args.append("--gameDir")
args.append(launcherVariables["game_directory"])
if not findArgument(args,"--assetsDir"):
args.append("--assetsDir")
args.append(launcherVariables["assets_root"])
print(colored(colorama.Fore.GREEN,"\nLaunching Minecraft..."))
if lv["console"] == "1":
proc = subprocess.Popen([lv["java"]] + args)
rtn = proc.wait()
if rtn != 0: print(colored(colorama.Fore.RED,"> Launch failed: ") +"return isn't 0",file=sys.stderr)
else:
pkwargs = {
"stdout": subprocess.DEVNULL,
"stdin": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL
}
if lv["osName"] == "windows": pkwargs["creationflags"] = 0x00000008
subprocess.Popen([lv["java"] + "w"] + args,**pkwargs)
main()