network_handler: Add link validation

This commit is contained in:
Mykola Grymalyuk
2023-02-04 14:46:25 -07:00
parent 6c294902c2
commit 08710bc47b
4 changed files with 50 additions and 19 deletions

View File

@@ -2301,7 +2301,7 @@ class wx_python_gui:
# - When running from source/unable to find on Github, use the nightly.link variant
# - If nightly also fails, fall back to the manually uploaded variant
link = self.constants.installer_pkg_url
if utilities.validate_link(link) is False:
if network_handler.NetworkUtilities(link).validate_link() is False:
logging.info("- Stock Install.pkg is missing on Github, falling back to Nightly")
link = self.constants.installer_pkg_url_nightly
@@ -2313,13 +2313,19 @@ class wx_python_gui:
autopkg_download = network_handler.DownloadObject(link, path)
autopkg_download.download(spawn_thread=False)
if autopkg_download.download_complete is True:
# Download thread will re-enable Idle Sleep after downloading
utilities.disable_sleep_while_running()
if str(path).endswith(".zip"):
if Path(self.constants.installer_pkg_path).exists():
subprocess.run(["rm", self.constants.installer_pkg_path])
subprocess.run(["ditto", "-V", "-x", "-k", "--sequesterRsrc", "--rsrc", self.constants.installer_pkg_zip_path, self.constants.payload_path])
if autopkg_download.download_complete is False:
logging.warning("- Failed to download Install.pkg")
logging.warning(autopkg_download.error_msg)
return
# Download thread will re-enable Idle Sleep after downloading
utilities.disable_sleep_while_running()
if not str(path).endswith(".zip"):
return
if Path(self.constants.installer_pkg_path).exists():
subprocess.run(["rm", self.constants.installer_pkg_path])
subprocess.run(["ditto", "-V", "-x", "-k", "--sequesterRsrc", "--rsrc", self.constants.installer_pkg_zip_path, self.constants.payload_path])
def install_installer_pkg(self, disk):
disk = disk + "s2" # ESP sits at 1, and we know macOS will have created the main partition at 2

View File

@@ -6,6 +6,7 @@ from pathlib import Path
import time
import threading
import logging
import traceback
from resources import cli_menu, constants, utilities, device_probe, os_probe, defaults, arguments, install, tui_helpers, reroute_payloads, commit_info
from resources.build import build
@@ -36,6 +37,8 @@ class OpenCoreLegacyPatcher:
# Likely in an installer environment, store in /Users/Shared
LOG_FILEPATH = Path("/Users/Shared") / LOG_FILENAME
self.implement_custom_traceback_handler()
logging.basicConfig(
level=logging.NOTSET,
format="%(asctime)s - %(filename)s (%(lineno)d): %(message)s",
@@ -48,6 +51,16 @@ class OpenCoreLegacyPatcher:
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().handlers[1].maxBytes = 1024 * 1024 * 10
def implement_custom_traceback_handler(self):
# TODO: Support thread exceptions
def custom_excepthook(type, value, tb):
logging.error("Uncaught exception", exc_info=(type, value, tb))
traceback.print_exception(type, value, tb)
sys.excepthook = custom_excepthook
def generate_base_data(self):
self.constants.detected_os = os_probe.detect_kernel_major()
self.constants.detected_os_minor = os_probe.detect_kernel_minor()

View File

@@ -48,7 +48,24 @@ class NetworkUtilities:
"""
try:
return True if requests.head(self.url, timeout=5, allow_redirects=True) else False
requests.head(self.url, timeout=5, allow_redirects=True)
return True
except (
requests.exceptions.Timeout,
requests.exceptions.TooManyRedirects,
requests.exceptions.ConnectionError,
requests.exceptions.HTTPError
):
return False
def validate_link(self):
# Check if link is 404
try:
response = SESSION.head(self.url, timeout=5, allow_redirects=True)
if response.status_code == 404:
return False
else:
return True
except (
requests.exceptions.Timeout,
requests.exceptions.TooManyRedirects,
@@ -274,6 +291,11 @@ class DownloadObject:
print(f"Downloaded {self.get_percent():.2f}% of {self.filename} ({utilities.human_fmt(self.get_speed())}/s) ({self.get_time_remaining():.2f} seconds remaining)")
self.download_complete = True
logging.info(f"Download complete: {self.filename}")
logging.info("Stats:")
logging.info(f" Downloaded size: {utilities.human_fmt(self.downloaded_file_size)}")
logging.info(f" Time elapsed: {time.time() - self.start_time} seconds")
logging.info(f" Speed: {utilities.human_fmt(self.downloaded_file_size / (time.time() - self.start_time))}/s")
logging.info(f" Location: {self.filepath}")
except Exception as e:
self.error = True
self.error_msg = str(e)

View File

@@ -441,16 +441,6 @@ def monitor_disk_output(disk):
output = output[-2]
return output
def validate_link(link):
# Check if link is 404
try:
response = SESSION.head(link, timeout=5, allow_redirects=True)
if response.status_code == 404:
return False
else:
return True
except (requests.exceptions.Timeout, requests.exceptions.TooManyRedirects, requests.exceptions.ConnectionError, requests.exceptions.HTTPError):
return False
def block_os_updaters():
# Disables any processes that would be likely to mess with