Skip to content

Commit

Permalink
Merge pull request #39 from OpenGOAL-Unofficial-Mods/rewrite
Browse files Browse the repository at this point in the history
Rewrite
  • Loading branch information
Zedb0T authored Sep 22, 2023
2 parents d7f9244 + 3acb2a9 commit b8fe693
Show file tree
Hide file tree
Showing 10 changed files with 926 additions and 349 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
dist/*
build/*
.env
utils/launcherUtilsbackup.py
twitchcommands.spec
resources/data/decompiler_out/*
resources/data/iso_data/*
Expand Down
210 changes: 114 additions & 96 deletions Launcher with autoupdater.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,22 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 29 20:46:07 2022
@author: Zed
"""
from datetime import datetime
from os.path import exists
import json
import PySimpleGUI as sg
import os
import pathlib
import progressbar
import requests
import shutil
import subprocess
import json
import urllib
import shutil
import traceback
from datetime import datetime
from os.path import exists
from pathlib import Path
import subprocess
AppdataPATH = os.getenv('APPDATA') + "\\OpenGOAL-UnofficialModLauncher\\"

pbar = None
def show_progress(block_num, block_size, total_size):
if total_size > 0:
global pbar
if pbar is None:
pbar = progressbar.ProgressBar(maxval=total_size)
pbar.start()

downloaded = block_num * block_size
if downloaded < total_size:
pbar.update(downloaded)
else:
pbar.finish()
pbar = None
try:
window['progress_bar'].UpdateBar(block_num * block_size, total_size)
except Exception as e:
pass # Handle the exception if the window or element does not exist

def try_remove_file(file):
if exists(file):
Expand All @@ -38,86 +25,117 @@ def try_remove_file(file):
def try_remove_dir(dir):
if exists(dir):
shutil.rmtree(dir)

def downloadNewestmod():

InstallDir = AppdataPATH

def check_for_updates():

launchUrl ="https://api.github.com/repos/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases"
response = requests.get(url = launchUrl, params = {'address':"yolo"})

launch_url = "https://api.github.com/repos/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases"
response = requests.get(url=launch_url, params={'address': "yolo"})

if response is not None and response.status_code == 200:
# didnt get rate limited yay
r = json.loads(json.dumps(response.json()))
LatestRel = datetime.strptime(r[0].get("published_at").replace("T"," ").replace("Z",""),'%Y-%m-%d %H:%M:%S')
LatestRelAssetsURL = (json.loads(json.dumps(requests.get(url = r[0].get("assets_url"), params = {'address':"yolo"}).json())))[0].get("browser_download_url")
r = json.loads(json.dumps(response.json()))
latest_release = datetime.strptime(r[0].get("published_at").replace("T", " ").replace("Z", ""),
'%Y-%m-%d %H:%M:%S')
latest_release_assets_url = (json.loads(
json.dumps(requests.get(url=r[0].get("assets_url"), params={'address': "yolo"}).json())))[0].get(
"browser_download_url")
else:
# fall back to some hard-coded release, surely we won't forget to update this occasionally
print("WARNING: failed to query github API, you might be rate-limited. Using default fallback release instead.")
LatestRel = datetime(2023, 7, 23)
LatestRelAssetsURL = "https://github.com/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases/download/v1.10fixoldpckernel/openGOALModLauncher.exe"
print("WARNING: Failed to query GitHub API, you might be rate-limited. Using default fallback release instead.")
latest_release = datetime(2023, 7, 23)
latest_release_assets_url = "https://github.com/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases/download/v1.10fixoldpckernel/openGOALModLauncher.exe"

LastWrite = datetime(2020, 5, 17)
if (os.path.exists(AppdataPATH + "\\OpengoalModLauncher.exe")):
LastWrite = datetime.utcfromtimestamp( pathlib.Path(AppdataPATH + "\\OpengoalModLauncher.exe").stat().st_mtime)
last_write = datetime(2020, 5, 17)
if os.path.exists(AppdataPATH + "\\OpengoalModLauncher.exe"):
last_write = datetime.utcfromtimestamp(Path(AppdataPATH + "\\OpengoalModLauncher.exe").stat().st_mtime)

#update checks
need_update = bool((last_write < latest_release))

window['installed_version'].update(f"Currently installed version created on: {last_write.strftime('%Y-%m-%d %H:%M:%S')}")
window['newest_version'].update(f"Newest version created on: {latest_release.strftime('%Y-%m-%d %H:%M:%S')}")

if need_update:
window['update_status'].update("An update is available. Click 'Update' to install.")
window['update_button'].update(visible=True)
window['launch_button'].update(visible=False)
else:
window['update_status'].update("You are up to date.")
window['update_button'].update(visible=False)
window['launch_button'].update(visible=True)

def download_newest_mod():
AppdataPATH = os.getenv('APPDATA') + "\\OpenGOAL-UnofficialModLauncher\\"

launch_url = "https://api.github.com/repos/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases"
response = requests.get(url=launch_url, params={'address': "yolo"})

if response is not None and response.status_code == 200:
r = json.loads(json.dumps(response.json()))
latest_release = datetime.strptime(r[0].get("published_at").replace("T", " ").replace("Z", ""),
'%Y-%m-%d %H:%M:%S')
latest_release_assets_url = (json.loads(
json.dumps(requests.get(url=r[0].get("assets_url"), params={'address': "yolo"}).json())))[0].get(
"browser_download_url")
else:
print("WARNING: Failed to query GitHub API, you might be rate-limited. Using default fallback release instead.")
latest_release = datetime(2023, 7, 23)
latest_release_assets_url = "https://github.com/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases/download/v1.10fixoldpckernel/openGOALModLauncher.exe"

needUpdate = bool((LastWrite < LatestRel))
last_write = datetime(2020, 5, 17)
if os.path.exists(AppdataPATH + "\\OpengoalModLauncher.exe"):
last_write = datetime.utcfromtimestamp(Path(AppdataPATH + "\\OpengoalModLauncher.exe").stat().st_mtime)

print("Currently installed version created on: " + LastWrite.strftime('%Y-%m-%d %H:%M:%S'))
print("Newest version created on: " + LatestRel.strftime('%Y-%m-%d %H:%M:%S'))
need_update = bool((last_write < latest_release))

if (needUpdate):

#start the actual update method if needUpdate is true
print("Starting Update...")
#download update from github
# Create a new directory because it does not exist
if need_update:
window['update_status'].update("Starting Update...")
try_remove_dir(AppdataPATH + "/temp")
if not os.path.exists(AppdataPATH + "/temp"):
print("Creating install dir: " + AppdataPATH)
os.makedirs(AppdataPATH + "/temp")

print("Downloading update from " + LatestRelAssetsURL)
file = urllib.request.urlopen(LatestRelAssetsURL)
print(file.length)

urllib.request.urlretrieve(LatestRelAssetsURL, AppdataPATH + "/temp/OpengoalModLauncher.exe", show_progress)
print("Done downloading")


#delete any previous installation
print("Removing previous installation " + AppdataPATH)
try_remove_dir(InstallDir + "/data")
try_remove_file(InstallDir + "/gk.exe")
try_remove_file(InstallDir + "/goalc.exe")
try_remove_file(InstallDir + "/extractor.exe")
print("Extracting update")
TempDir = InstallDir + "/temp"


#delete the update archive
try_remove_file(TempDir + "/updateDATA.zip")

SubDir = TempDir
print("Moving files from " + SubDir + " up to " + InstallDir)
allfiles = os.listdir(SubDir)
for f in allfiles:
shutil.move(SubDir + "/" + f, InstallDir + "/" + f)
try_remove_dir(TempDir)

try:
AppdataPATH = os.getenv('APPDATA') + "\\OpenGOAL-UnofficalModLauncher\\"
print(AppdataPATH)

if os.path.exists(AppdataPATH) == False:
print("Creating Directory " + AppdataPATH)
os.mkdir(AppdataPATH)


downloadNewestmod()

subprocess.call([AppdataPATH + "OpengoalModLauncher.exe"])
except Exception as e:
print("An unexcepted error occurred: ", e)
traceback.print_exc()
window['update_status'].update("Downloading update from " + latest_release_assets_url)
file = urllib.request.urlopen(latest_release_assets_url)
urllib.request.urlretrieve(latest_release_assets_url, AppdataPATH + "/temp/OpengoalModLauncher.exe", show_progress)
window['update_status'].update("Done downloading")

window['update_status'].update("Removing previous installation " + AppdataPATH)
try_remove_dir(AppdataPATH + "/data")
try_remove_file(AppdataPATH + "/gk.exe")
try_remove_file(AppdataPATH + "/goalc.exe")
try_remove_file(AppdataPATH + "/extractor.exe")

window['update_status'].update("Extracting update")
temp_dir = AppdataPATH + "/temp"
try_remove_file(temp_dir + "/updateDATA.zip")
sub_dir = temp_dir
all_files = os.listdir(sub_dir)
for f in all_files:
shutil.move(sub_dir + "/" + f, AppdataPATH + "/" + f)
try_remove_dir(temp_dir)
window['update_status'].update("Update complete")
window['update_button'].update(visible=False)
window['launch_button'].update(visible=True)

layout = [
[sg.Text("OpenGOAL Mod Updater", font=("Helvetica", 16))],
[sg.Text("Installed Version:", size=(20, 1)), sg.Text("", size=(20, 1), key='installed_version')],
[sg.Text("Newest Version:", size=(20, 1)), sg.Text("", size=(20, 1), key='newest_version')],
[sg.ProgressBar(100, orientation='h', size=(20, 20), key='progress_bar')],
[sg.Text("", size=(40, 1), key='update_status')],
[sg.Button("Check for Updates"), sg.Button("Update", visible=False, key='update_button'), sg.Button("Launch", visible=False, key='launch_button'), sg.Button("Exit")]
]

window = sg.Window("OpenGOAL Mod Updater", layout, finalize=True)

while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == "Exit":
break
elif event == "Check for Updates":
check_for_updates()
elif event == "update_button":
download_newest_mod()
elif event == "launch_button":
window.close()
subprocess.call([ AppdataPATH + "openGOALModLauncher.exe"])

window.close()
8 changes: 4 additions & 4 deletions buildlaunchercoreEXE.bat
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@

set mypath=%~dp0
pyinstaller --onefile openGOALModLauncher.py --icon resources\appicon.ico
pyinstaller --onefile openGOALModLauncher.py --icon resources\appicon.ico --noconsole
move "%mypath%dist\openGOALModLauncher.exe" "%mypath%/"
RENAME "%mypath%\openGOALModLauncher.exe" "openGOALModLauncher.exe"
@RD /S /Q "%mypath%/build"
@RD /S /Q "%mypath%/dist"
DEL /S /Q "%mypath%/openGOALModLauncher.spec"
REM @RD /S /Q "%mypath%/build"
REM @RD /S /Q "%mypath%/dist"
REM DEL /S /Q "%mypath%/openGOALModLauncher.spec"
2 changes: 1 addition & 1 deletion buildlauncherupdaterexe.bat
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

set mypath=%~dp0
pyinstaller --onefile "Launcher with autoupdater.py" --icon resources\appicon.ico
pyinstaller --onefile "Launcher with autoupdater.py" --icon resources\appicon.ico --noconsole
move "%mypath%dist\Launcher with autoupdater.exe" "%mypath%/"
@RD /S /Q "%mypath%/build"
@RD /S /Q "%mypath%/dist"
Expand Down
Loading

0 comments on commit b8fe693

Please sign in to comment.