Skip to content

Commit 1472403

Browse files
authored
Merge pull request #74 from OpenGOAL-Mods/offline-mode
Offline mode
2 parents fa14ec6 + c00b6e0 commit 1472403

File tree

5 files changed

+225
-209
lines changed

5 files changed

+225
-209
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,5 @@ resources/utils/__pycache__/*
3030
resources.rar
3131
Launcher with autoupdater.spec
3232
resources/jak1_mods2.json
33-
jak1_mods2.json
33+
jak1_mods.json
34+
jak1_mods2.json

Launcher with autoupdater.py

Lines changed: 101 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,35 @@
1-
import PySimpleGUI as sg
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Aug 29 20:46:07 2022
4+
5+
@author: Zed
6+
"""
7+
from datetime import datetime
8+
from os.path import exists
9+
import json
210
import os
11+
import pathlib
12+
import progressbar
313
import requests
4-
import json
5-
import urllib
614
import shutil
7-
import traceback
8-
from datetime import datetime
9-
from os.path import exists
10-
from pathlib import Path
1115
import subprocess
12-
AppdataPATH = os.getenv('APPDATA') + "\\OpenGOAL-UnofficialModLauncher\\"
16+
import urllib
17+
import traceback
1318

19+
pbar = None
1420
def show_progress(block_num, block_size, total_size):
1521
if total_size > 0:
16-
try:
17-
window['progress_bar'].UpdateBar(block_num * block_size, total_size)
18-
except Exception as e:
19-
pass # Handle the exception if the window or element does not exist
22+
global pbar
23+
if pbar is None:
24+
pbar = progressbar.ProgressBar(maxval=total_size)
25+
pbar.start()
26+
27+
downloaded = block_num * block_size
28+
if downloaded < total_size:
29+
pbar.update(downloaded)
30+
else:
31+
pbar.finish()
32+
pbar = None
2033

2134
def try_remove_file(file):
2235
if exists(file):
@@ -25,117 +38,91 @@ def try_remove_file(file):
2538
def try_remove_dir(dir):
2639
if exists(dir):
2740
shutil.rmtree(dir)
28-
29-
def check_for_updates():
41+
42+
def downloadNewestLauncher():
3043

31-
32-
launch_url = "https://api.github.com/repos/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases"
33-
response = requests.get(url=launch_url, params={'address': "yolo"})
34-
44+
InstallDir = AppdataPATH
45+
46+
launchUrl ="https://api.github.com/repos/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases"
47+
response = requests.get(url = launchUrl, params = {'address':"yolo"})
3548
if response is not None and response.status_code == 200:
36-
r = json.loads(json.dumps(response.json()))
37-
latest_release = datetime.strptime(r[0].get("published_at").replace("T", " ").replace("Z", ""),
38-
'%Y-%m-%d %H:%M:%S')
39-
latest_release_assets_url = (json.loads(
40-
json.dumps(requests.get(url=r[0].get("assets_url"), params={'address': "yolo"}).json())))[0].get(
41-
"browser_download_url")
49+
# didnt get rate limited yay
50+
r = json.loads(json.dumps(response.json()))
51+
LatestRel = datetime.strptime(r[0].get("published_at").replace("T"," ").replace("Z",""),'%Y-%m-%d %H:%M:%S')
52+
LatestRelAssetsURL = (json.loads(json.dumps(requests.get(url = r[0].get("assets_url"), params = {'address':"yolo"}).json())))[0].get("browser_download_url")
4253
else:
43-
print("WARNING: Failed to query GitHub API, you might be rate-limited. Using default fallback release instead.")
44-
latest_release = datetime(2023, 7, 23)
45-
latest_release_assets_url = "https://github.com/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases/download/v1.10fixoldpckernel/openGOALModLauncher.exe"
54+
# fall back to some hard-coded release, surely we won't forget to update this occasionally
55+
print("WARNING: failed to query github API, you might be rate-limited. Using default fallback release instead.")
56+
LatestRel = datetime(2023, 7, 23)
57+
LatestRelAssetsURL = "https://github.com/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases/download/v1.10fixoldpckernel/openGOALModLauncher.exe"
4658

47-
last_write = datetime(2020, 5, 17)
48-
if os.path.exists(AppdataPATH + "\\OpengoalModLauncher.exe"):
49-
last_write = datetime.utcfromtimestamp(Path(AppdataPATH + "\\OpengoalModLauncher.exe").stat().st_mtime)
59+
LastWrite = datetime(2020, 5, 17)
60+
if (os.path.exists(AppdataPATH + "\\OpengoalModLauncher.exe")):
61+
LastWrite = datetime.utcfromtimestamp( pathlib.Path(AppdataPATH + "\\OpengoalModLauncher.exe").stat().st_mtime)
5062

51-
need_update = bool((last_write < latest_release))
52-
53-
window['installed_version'].update(f"Currently installed version created on: {last_write.strftime('%Y-%m-%d %H:%M:%S')}")
54-
window['newest_version'].update(f"Newest version created on: {latest_release.strftime('%Y-%m-%d %H:%M:%S')}")
55-
56-
if need_update:
57-
window['update_status'].update("An update is available. Click 'Update' to install.")
58-
window['update_button'].update(visible=True)
59-
window['launch_button'].update(visible=False)
60-
else:
61-
window['update_status'].update("You are up to date.")
62-
window['update_button'].update(visible=False)
63-
window['launch_button'].update(visible=True)
64-
65-
def download_newest_mod():
66-
AppdataPATH = os.getenv('APPDATA') + "\\OpenGOAL-UnofficialModLauncher\\"
67-
68-
launch_url = "https://api.github.com/repos/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases"
69-
response = requests.get(url=launch_url, params={'address': "yolo"})
70-
71-
if response is not None and response.status_code == 200:
72-
r = json.loads(json.dumps(response.json()))
73-
latest_release = datetime.strptime(r[0].get("published_at").replace("T", " ").replace("Z", ""),
74-
'%Y-%m-%d %H:%M:%S')
75-
latest_release_assets_url = (json.loads(
76-
json.dumps(requests.get(url=r[0].get("assets_url"), params={'address': "yolo"}).json())))[0].get(
77-
"browser_download_url")
78-
else:
79-
print("WARNING: Failed to query GitHub API, you might be rate-limited. Using default fallback release instead.")
80-
latest_release = datetime(2023, 7, 23)
81-
latest_release_assets_url = "https://github.com/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/releases/download/v1.10fixoldpckernel/openGOALModLauncher.exe"
63+
#update checks
8264

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

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

89-
if need_update:
90-
window['update_status'].update("Starting Update...")
70+
if (needUpdate):
71+
72+
#start the actual update method if needUpdate is true
73+
print("Starting Update...")
74+
#download update from github
75+
# Create a new directory because it does not exist
9176
try_remove_dir(AppdataPATH + "/temp")
9277
if not os.path.exists(AppdataPATH + "/temp"):
78+
print("Creating install dir: " + AppdataPATH)
9379
os.makedirs(AppdataPATH + "/temp")
9480

95-
window['update_status'].update("Downloading update from " + latest_release_assets_url)
96-
file = urllib.request.urlopen(latest_release_assets_url)
97-
urllib.request.urlretrieve(latest_release_assets_url, AppdataPATH + "/temp/OpengoalModLauncher.exe", show_progress)
98-
window['update_status'].update("Done downloading")
99-
100-
window['update_status'].update("Removing previous installation " + AppdataPATH)
101-
try_remove_dir(AppdataPATH + "/data")
102-
try_remove_file(AppdataPATH + "/gk.exe")
103-
try_remove_file(AppdataPATH + "/goalc.exe")
104-
try_remove_file(AppdataPATH + "/extractor.exe")
105-
106-
window['update_status'].update("Extracting update")
107-
temp_dir = AppdataPATH + "/temp"
108-
try_remove_file(temp_dir + "/updateDATA.zip")
109-
sub_dir = temp_dir
110-
all_files = os.listdir(sub_dir)
111-
for f in all_files:
112-
shutil.move(sub_dir + "/" + f, AppdataPATH + "/" + f)
113-
try_remove_dir(temp_dir)
114-
window['update_status'].update("Update complete")
115-
window['update_button'].update(visible=False)
116-
window['launch_button'].update(visible=True)
117-
118-
layout = [
119-
[sg.Text("OpenGOAL Mod Updater", font=("Helvetica", 16))],
120-
[sg.Text("Installed Version:", size=(20, 1)), sg.Text("", size=(20, 1), key='installed_version')],
121-
[sg.Text("Newest Version:", size=(20, 1)), sg.Text("", size=(20, 1), key='newest_version')],
122-
[sg.ProgressBar(100, orientation='h', size=(20, 20), key='progress_bar')],
123-
[sg.Text("", size=(40, 1), key='update_status')],
124-
[sg.Button("Check for Updates"), sg.Button("Update", visible=False, key='update_button'), sg.Button("Launch", visible=False, key='launch_button'), sg.Button("Exit")]
125-
]
126-
127-
window = sg.Window("OpenGOAL Mod Updater", layout, finalize=True)
128-
129-
while True:
130-
event, values = window.read()
131-
if event == sg.WIN_CLOSED or event == "Exit":
132-
break
133-
elif event == "Check for Updates":
134-
check_for_updates()
135-
elif event == "update_button":
136-
download_newest_mod()
137-
elif event == "launch_button":
138-
window.close()
139-
subprocess.call([ AppdataPATH + "openGOALModLauncher.exe"])
140-
141-
window.close()
81+
print("Downloading update from " + LatestRelAssetsURL)
82+
file = urllib.request.urlopen(LatestRelAssetsURL)
83+
print(file.length)
84+
85+
urllib.request.urlretrieve(LatestRelAssetsURL, AppdataPATH + "/temp/OpengoalModLauncher.exe", show_progress)
86+
print("Done downloading")
87+
88+
89+
#delete any previous installation
90+
print("Removing previous installation " + AppdataPATH)
91+
try_remove_dir(InstallDir + "/data")
92+
try_remove_file(InstallDir + "/gk.exe")
93+
try_remove_file(InstallDir + "/goalc.exe")
94+
try_remove_file(InstallDir + "/extractor.exe")
95+
print("Extracting update")
96+
TempDir = InstallDir + "/temp"
97+
98+
99+
#delete the update archive
100+
try_remove_file(TempDir + "/updateDATA.zip")
101+
102+
SubDir = TempDir
103+
print("Moving files from " + SubDir + " up to " + InstallDir)
104+
allfiles = os.listdir(SubDir)
105+
for f in allfiles:
106+
shutil.move(SubDir + "/" + f, InstallDir + "/" + f)
107+
try_remove_dir(TempDir)
108+
109+
# check for launcher update
110+
try:
111+
AppdataPATH = os.getenv('APPDATA') + "\\OpenGOAL-UnofficalModLauncher\\"
112+
print(AppdataPATH)
113+
114+
if os.path.exists(AppdataPATH) == False:
115+
print("Creating Directory " + AppdataPATH)
116+
os.mkdir(AppdataPATH)
117+
118+
downloadNewestLauncher()
119+
except Exception as e:
120+
print("An unexcepted error occurred: ", e)
121+
traceback.print_exc()
122+
123+
# run launcher
124+
try:
125+
subprocess.call([AppdataPATH + "OpengoalModLauncher.exe"])
126+
except Exception as e:
127+
print("An unexcepted error occurred: ", e)
128+
traceback.print_exc()

openGOALModLauncher.py

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import requests
1818
import time
1919
from datetime import datetime, timedelta
20+
import urllib.request
2021
import sys
2122
import webbrowser
2223
import os
@@ -105,9 +106,12 @@ def fetch_image(url): # Accept the URL parameter
105106
result = png_bio.getvalue() # Store the fetched image in the result variable
106107

107108
# Pass the URL as an argument
108-
thread = threading.Thread(target=fetch_image, args=(URL,))
109-
thread.start()
110-
thread.join() # Wait for the thread to finish
109+
try:
110+
thread = threading.Thread(target=fetch_image, args=(URL,))
111+
thread.start()
112+
thread.join() # Wait for the thread to finish
113+
except:
114+
print("failed to get image " + URL)
111115

112116
return result # Return the fetched image data
113117

@@ -223,7 +227,21 @@ class ColumnEnum(IntEnum):
223227

224228

225229
def getRefreshedTableData(sort_col_idx):
226-
# Load data from the local file if it exists
230+
main_file_path = f"{LauncherDir}/jak1_mods.json"
231+
232+
# try to re-download json file from the remote URL
233+
try:
234+
remote_url = "https://raw.githubusercontent.com/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/main/resources/jak1_mods.json"
235+
urllib.request.urlretrieve(
236+
remote_url, main_file_path, False
237+
)
238+
print("downloaded mod list successfully")
239+
except:
240+
print("failed to download mod list, will try to continue with local list")
241+
242+
remote_mods = json.loads(open(main_file_path, "r").read())
243+
244+
# Load data from the extra local file if it exists
227245
local_mods = None
228246
local_file_path_1 = "resources/jak1_mods2.json"
229247
local_file_path_2 = "jak1_mods2.json"
@@ -232,10 +250,6 @@ def getRefreshedTableData(sort_col_idx):
232250
elif os.path.exists(f"{LauncherDir}/{local_file_path_2}"):
233251
local_mods = json.loads(open(f"{LauncherDir}/{local_file_path_2}", "r").read())
234252

235-
# Load data from the remote URL
236-
remote_url = "https://raw.githubusercontent.com/OpenGOAL-Unofficial-Mods/OpenGoal-ModLauncher-dev/main/resources/jak1_mods.json"
237-
remote_mods = requests.get(remote_url).json()
238-
239253
# Initialize an empty dictionary to store the combined data
240254
mod_dict = {}
241255

@@ -441,7 +455,8 @@ def getRefreshedTableData(sort_col_idx):
441455
pad=(0, 0), # Set padding to 0
442456
expand_x=True,
443457
expand_y=True,
444-
)
458+
),
459+
sg.Text("~~~ LOADING ~~~", key="-LOADINGBACKUP-", visible=False)
445460
]
446461
],
447462
)
@@ -749,7 +764,7 @@ def handleModTableSelection(row):
749764
)
750765

751766
except Exception as e:
752-
print("Failed to download mod image from", mod_image_url, "error", e)
767+
print("Failed to download mod image for ", mod_name, "error", e)
753768
window["-SELECTEDMODIMAGE-"].update(
754769
githubUtils.resize_image(noimagefile, 450.0, 300.0)
755770
)
@@ -798,7 +813,13 @@ def loading_screen_with_thread(thread):
798813

799814
# hide all the buttons and display a window showing that it is installing
800815
loadingimage = getPNGFromURL(LOADING_IMAGE_URLS[random.randint(0, len(LOADING_IMAGE_URLS)-1)])
801-
window["-LOADINGIMAGE-"].update(source=githubUtils.resize_image(loadingimage, 970, 607))
816+
if loadingimage is not None:
817+
window["-LOADINGIMAGE-"].update(source=githubUtils.resize_image(loadingimage, 970, 607), visible=True)
818+
window["-LOADINGBACKUP-"].update(visible=False)
819+
else:
820+
window["-LOADINGIMAGE-"].update(visible=False)
821+
window["-LOADINGBACKUP-"].update(visible=True)
822+
802823
window["-LOADINGFRAME-"].update(visible=True)
803824
window["-LOADINGFRAME-"].unhide_row()
804825
window["-MAINFRAME-"].update(visible=False)

utils/githubUtils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,9 @@ def getLatestAvailableUpdateDatetime(URL):
155155

156156

157157
def resize_image(image_path, width, height): # image_path: "C:User/Image/img.jpg"
158+
if image_path is None:
159+
return None
160+
158161
if isinstance(image_path, str):
159162
img = PIL.Image.open(image_path)
160163
else:

0 commit comments

Comments
 (0)