offline-minecraft-launcher/offline-minecraft-launcher.py

445 lines
14 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 urllib.request
import re
def download(url,decode = "utf-8"):
request = urllib.request.Request(url,headers={"User-Agent":"Mozilla/5.0"})
response = urllib.request.urlopen(request)
rt = response.read()
if decode == False: return rt
return response.read().decode(decode)
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 fileDl(url,file,read = True,decode = "utf-8"):
if os.path.isfile(file):
if read == True:
return readFile(file,decode)
return
print(url)
data = download(url,False)
fileh = open(tmpFile,"wb")
fileh.write(data)
fileh.close()
if pUp(file) != "" and not os.path.isdir(pUp(file)): os.makedirs(pUp(file))
os.rename(tmpFile,file)
if read == False: return
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 findArgument(args,searchFor):
for arg in args:
if arg.startswith(searchFor): return True
return False
def findInChain(versionsPath,version,path):
versionPath = p(versionsPath,version)
clientJson = readJsonFile(p(versionPath,version + ".json"))
curPath = clientJson.copy()
success = True
for dir in path:
if dir in curPath:
curPath = curPath[dir]
else:
success = False
break
if success == False:
return findInChain(versionsPath,clientJson["inheritsFrom"],path)
return curPath
def findInChainDeepest(versionsPath,version,path):
found = False
while True:
versionPath = p(versionsPath,version)
clientJson = readJsonFile(p(versionPath,version + ".json"))
curPath = clientJson.copy()
for dir in path:
if dir in curPath:
curPath = curPath[dir]
else:
if "inheritsFrom" in clientJson:
version = clientJson["inheritsFrom"]
continue
else:
curPath = False
break
found = curPath
if "inheritsFrom" in clientJson:
version = clientJson["inheritsFrom"]
continue
else:
break
if found == False: raise
return found
def parseJavaLibraryName(libName):
libSplit = libName.split(":",2)
libPackage = libSplit[0]
libName = libSplit[1]
libVersion = libSplit[2]
libFilePath = libPackage.replace(".","/") + "/" +libName+ "/" +libVersion+ "/" +libName+ "-" +libVersion+ ".jar"
return libPackage,libName,libVersion,libFilePath
def checkRules(ruleList):
action = "disallow"
for rule in ruleList:
if "os" in rule:
if "name" in rule["os"]:
rule["os"]["name"] = rule["os"]["name"].replace("osx","macos")
if not re.search(rule["os"]["name"],lv["osName"]): continue
if "arch" in rule["os"]:
if not re.search(rule["os"]["arch"],lv["jvmArch"]): continue
if "version" in rule["os"]:
if not re.search(rule["os"]["version"],lv["osVersion"]): continue
action = rule["action"]
else:
action = rule["action"]
return action
def processVersion(versionsPath,libraryPath,nativePath,version):
versionPath = p(versionsPath,version)
clientJson = readJsonFile(p(versionPath,version + ".json"))
libraries = []
arguments = []
jvmArguments = []
if "inheritsFrom" in clientJson:
_,libraries,arguments,jvmArguments = processVersion(versionsPath,libraryPath,nativePath,clientJson["inheritsFrom"])
for library in clientJson["libraries"]:
l = {}
l["package"],l["name"],l["version"],l["filePath"] = parseJavaLibraryName(library["name"])
l["type"] = "library"
l["data"] = library
l["dumb"] = True
# Dumb-detection
if "downloads" in library: l["dumb"] = False
# Type-detection
if not l["dumb"]:
if "classifiers" in library["downloads"]:
l["type"] = "native"
else:
if "natives" in library:
l["type"] = "native"
# Libraries
if l["type"] == "library":
if not l["dumb"]:
if "artifact" in library["downloads"]:
if "path" in library["downloads"]["artifact"]:
l["filePathOS"] = p(libraryPath,library["downloads"]["artifact"]["path"].replace("/",os.path.sep))
if "url" in library["downloads"]["artifact"] and library["downloads"]["artifact"]["url"] != "":
l["url"] = library["downloads"]["artifact"]["url"]
libraries.append(l)
else:
if not "url" in library: library["url"] = "https://libraries.minecraft.net"
l["url"] = library["url"]
while len(l["url"]) > 0 and l["url"][-1] == "/": l["url"] = l["url"][:-1]
l["url"] = l["url"] + "/" + l["filePath"]
l["filePathOS"] = p(libraryPath,l["filePath"].replace("/",os.path.sep))
libraries.append(l)
# Natives
if l["type"] == "native":
if not l["dumb"]:
for classifier in library["downloads"]["classifiers"]:
native = library["downloads"]["classifiers"][classifier]
l["nativeOS"] = classifier.replace("natives-","",1)
l["filePathOS"] = p(nativePath,native["path"].replace("/",os.path.sep))
if "url" in native and native["url"] != "":
l["url"] = native["url"]
libraries.append(l)
else:
if not "url" in library: library["url"] = "https://libraries.minecraft.net"
l["url"] = library["url"]
while len(l["url"]) > 0 and l["url"][-1] == "/": l["url"] = l["url"][:-1]
l["url"] = l["url"] + "/" + l["filePath"]
lcopy = l.copy()
for native in library["natives"]:
l = lcopy.copy()
l["nativeOS"] = native
native = "natives-" + native
l["filePath"] = l["filePath"][:-4] + "-" + native + ".jar"
l["url"] = l["url"][:-4] + "-" + native + ".jar"
l["filePathOS"] = p(nativePath,l["filePath"].replace("/",os.path.sep))
libraries.append(l)
if os.path.isfile(p(versionPath,version + ".jar")):
libraries.append({"type":"client","filePathOS":p(versionPath,version + ".jar")})
if "arguments" in clientJson:
if "game" in clientJson["arguments"]:
for arg in clientJson["arguments"]["game"]:
if type(arg) != str: continue
arguments.append(arg)
if "jvm" in clientJson["arguments"]:
for arg in clientJson["arguments"]["jvm"]:
if type(arg) != str:
if "value" in arg:
if type(arg["value"]) != list:
arg["value"] = [arg["value"]]
if "rules" in arg:
if checkRules(arg["rules"]) == "allow":
for value in arg["value"]:
jvmArguments.append(value)
else:
for value in arg["value"]:
jvmArguments.append(value)
else:
jvmArguments.append(arg)
elif "minecraftArguments" in clientJson:
margs = clientJson["minecraftArguments"].replace('"',"").split(" ")
for arg in margs:
if type(arg) != str: continue
arguments.append(arg)
return clientJson,libraries,arguments,jvmArguments
def main():
print("Reading config...")
config = configparser.ConfigParser()
config.optionxform = str
config.read(os.path.splitext(s)[0] + ".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"] == "":
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(setting+ "=" +str(lv[setting]))
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
argSplit = arg.split("=",1)
if len(argSplit) > 1:
lv[argSplit[0]] = argSplit[1]
else:
lv[argSplit[0]] = True
json.loads(lv["jvmArguments"])
if not lv["osName"] in ["windows","linux","macos"]:
print("\nWarning, unsupported OS detected: '" +lv["osName"]+ "'")
print("Needs to be either windows, linux or macos. Define it with osName=name in the config.")
print("")
if not "version" in lv: lv["version"] = input("Version ID: ")
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)
print("Scanning .json(s)...")
versionsPath = p(lv["gamePath"],"versions")
libraryPath = p(lv["gamePath"],"libraries")
nativePath = p(lv["gamePath"],"natives")
clientJson,libraries,arguments,jvmArguments = processVersion(versionsPath,libraryPath,nativePath,lv["version"])
versionPath = p(lv["gamePath"],"versions",lv["version"])
nativesOutPath = p(versionPath,"natives-" +lv["osName"]+ "." +lv["jvmArch"])
assetsPath = p(lv["gamePath"],"assets")
print("\nDownloading libraries...")
for library in libraries:
if "url" in library:
try:
fileDl(library["url"],library["filePathOS"],read = False)
except Exception as e:
print("Could not download: " +str(e))
loadLibraries = {}
for library in libraries:
if library["type"] == "client":
loadLibraries["client:" +library["filePathOS"]] = library
elif library["type"] == "library":
if "rules" in library["data"] and checkRules(library["data"]["rules"]) == "disallow": continue
loadLibraries[library["package"] + ":" +library["name"]] = library
separator = ";"
libraryList = ""
if lv["osName"] != "windows": separator = ":"
print("\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("- " +library["package"]+ ":" +library["name"]+ ":" +library["version"])
else:
print("Lib not found: " +library["package"]+ ":" + +library["name"]+ ":" +library["version"])
continue
libraryList += library["filePathOS"] + separator
libraryList = libraryList[:-1]
print("\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("Native not found: " +library["package"]+ ":" +library["name"]+ ":" +library["version"])
continue
proc = subprocess.Popen(["7z","x",library["filePathOS"],"-o" +nativesOutPath,"-aos"],stdout=subprocess.DEVNULL)
rtn = proc.wait()
if rtn != 0: raise Exception("process","return code isn't 0")
print("\nSetting up launcher variables...")
launcherVariables = {}
launcherVariables["auth_player_name"] = lv["name"]
launcherVariables["version_name"] = findInChainDeepest(versionsPath,lv["version"],["id"])
launcherVariables["game_directory"] = lv["gamePath"]
launcherVariables["assets_root"] = assetsPath
try:
launcherVariables["assets_index_name"] = findInChain(versionsPath,lv["version"],["assets"])
except:
print("> Could not find assets_index_name, assuming pre-1.6")
launcherVariables["assets_index_name"] = "pre-1.6"
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"])
# 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"])
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("\nLaunching Minecraft...")
if lv["console"] == "1":
proc = subprocess.Popen([lv["java"]] + args)
rtn = proc.wait()
if rtn != 0: raise Exception("process","return code isn't 0")
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()