diff --git a/resources/kdk_handler.py b/resources/kdk_handler.py index ee9ee977b..b0fe55bc5 100644 --- a/resources/kdk_handler.py +++ b/resources/kdk_handler.py @@ -1,8 +1,6 @@ # Kernel Debug Kit downloader import datetime -import re -import urllib.parse from pathlib import Path from typing import cast @@ -11,6 +9,8 @@ import requests import subprocess +import logging + from resources import utilities from resources.constants import Constants @@ -22,16 +22,16 @@ class kernel_debug_kit_handler: def get_available_kdks(self): KDK_API_LINK = "https://raw.githubusercontent.com/dortania/KdkSupportPkg/gh-pages/manifest.json" - print("- Fetching available KDKs") + logging.info("Fetching available KDKs") try: results = utilities.SESSION.get(KDK_API_LINK, headers={"User-Agent": f"OCLP/{self.constants.patcher_version}"}, timeout=10) except (requests.exceptions.Timeout, requests.exceptions.TooManyRedirects, requests.exceptions.ConnectionError): - print("- Could not contact KDK API") + logging.info("- Could not contact KDK API") return None if results.status_code != 200: - print("- Could not fetch KDK list") + logging.info("- Could not fetch KDK list") return None return sorted(results.json(), key=lambda x: (packaging.version.parse(x["version"]), datetime.datetime.fromisoformat(x["date"])), reverse=True) @@ -40,7 +40,7 @@ class kernel_debug_kit_handler: detected_build = build if self.is_kdk_installed(detected_build) is True: - print("- KDK is already installed") + logging.info("- KDK is already installed") self.remove_unused_kdks(exclude_builds=[detected_build]) return True, "", detected_build @@ -65,32 +65,32 @@ class kernel_debug_kit_handler: closest_build = kdk["build"] else: msg = "Could not fetch KDK list" - print(f"- {msg}") + logging.info(f"- {msg}") return False, msg, "" - print(f"- Checking for KDK matching macOS {version} build {build}") + logging.info(f"- Checking for KDK matching macOS {version} build {build}") # download_link is None if no matching KDK is found, so we'll fall back to the closest match if not download_link: - print("- Could not find KDK, finding closest match") + logging.info("- Could not find KDK, finding closest match") if self.is_kdk_installed(closest_build) is True: - print(f"- Closest build ({closest_build}) already installed") + logging.info(f"- Closest build ({closest_build}) already installed") self.remove_unused_kdks(exclude_builds=[detected_build, closest_build]) return True, "", closest_build if closest_match_download_link is None: msg = "Could not find KDK for host, nor closest match" - print(f"- {msg}") + logging.info(f"- {msg}") return False, msg, "" - print(f"- Closest match: {closest_version} build {closest_build}") + logging.info(f"- Closest match: {closest_version} build {closest_build}") download_link = closest_match_download_link if utilities.verify_network_connection(download_link): - print("- Downloading KDK") + logging.info("- Downloading KDK") else: msg = "Could not contact download site" - print(f"- {msg}") + logging.info(f"- {msg}") return False, msg, "" result = utilities.download_file(download_link, self.constants.kdk_download_path) @@ -99,15 +99,15 @@ class kernel_debug_kit_handler: # TODO: should we use the checksum from the API? result = subprocess.run(["hdiutil", "verify", self.constants.kdk_download_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.returncode != 0: - print("Error: Kernel Debug Kit checksum verification failed!") - print(f"Output: {result.stderr}") + logging.info("Error: Kernel Debug Kit checksum verification failed!") + logging.info(f"Output: {result.stderr}") msg = "Kernel Debug Kit checksum verification failed, please try again.\n\nIf this continues to fail, ensure you're downloading on a stable network connection (ie. Ethernet)" - print(f"- {msg}") + logging.info(f"- {msg}") return False, msg, "" self.remove_unused_kdks(exclude_builds=[detected_build, closest_build]) return True, "", detected_build msg = "Failed to download KDK" - print(f"- {msg}") + logging.info(f"- {msg}") return False, msg, "" def is_kdk_installed(self, build): @@ -124,7 +124,7 @@ class kernel_debug_kit_handler: if file.name.endswith(f"{build}.kdk"): for kext in kexts_to_check: if not Path(f"{file}/System/Library/Extensions/{kext}").exists(): - print(f"- Corrupted KDK found, removing due to missing: {file}/System/Library/Extensions/{kext}") + logging.info(f"- Corrupted KDK found, removing due to missing: {file}/System/Library/Extensions/{kext}") utilities.elevated(["rm", "-rf", file], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return False return True @@ -140,7 +140,7 @@ class kernel_debug_kit_handler: if exclude_builds == []: return - print("- Cleaning unused KDKs") + logging.info("- Cleaning unused KDKs") for kdk_folder in Path("/Library/Developer/KDKs").iterdir(): if kdk_folder.is_dir(): if kdk_folder.name.endswith(".kdk"): @@ -151,7 +151,7 @@ class kernel_debug_kit_handler: break if should_remove is False: continue - print(f" - Removing {kdk_folder.name}") + logging.info(f" - Removing {kdk_folder.name}") utilities.elevated(["rm", "-rf", kdk_folder], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) @@ -161,17 +161,17 @@ class kernel_debug_kit_handler: # Check if tag exists catalog = requests.get(KDK_MIRROR_REPOSITORY) if catalog.status_code != 200: - print(f"- Could not contact KDK mirror repository") + logging.info(f"- Could not contact KDK mirror repository") return None catalog = catalog.json() for release in catalog: if release["tag_name"] == build: - print(f"- Found KDK mirror for build: {build}") + logging.info(f"- Found KDK mirror for build: {build}") for asset in release["assets"]: if asset["name"].endswith(".dmg"): return asset["browser_download_url"] - print(f"- Could not find KDK mirror for build {build}") + logging.info(f"- Could not find KDK mirror for build {build}") return None \ No newline at end of file diff --git a/resources/network_handler.py b/resources/network_handler.py index 60289f7b7..f48a16471 100644 --- a/resources/network_handler.py +++ b/resources/network_handler.py @@ -102,6 +102,7 @@ class download_object: file.write(chunk) self.downloaded_file_size += len(chunk) if display_progress and i % 100: + # Don't use logging here, as we'll be spamming the log file 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}") diff --git a/resources/utilities.py b/resources/utilities.py index f9b6f5c95..721d73554 100644 --- a/resources/utilities.py +++ b/resources/utilities.py @@ -13,9 +13,10 @@ import time import atexit import requests import shutil -import urllib.parse import py_sip_xnu +import logging + from resources import constants, ioreg from data import sip_data, os_data @@ -39,8 +40,8 @@ def string_to_hex(input_string): def process_status(process_result): if process_result.returncode != 0: - print(f"Process failed with exit code {process_result.returncode}") - print(f"Please report the issue on the Discord server") + logging.info(f"Process failed with exit code {process_result.returncode}") + logging.info(f"Please report the issue on the Discord server") raise Exception(f"Process result: \n{process_result.stdout.decode()}") @@ -55,11 +56,11 @@ def human_fmt(num): def header(lines): lines = [i for i in lines if i is not None] total_length = len(max(lines, key=len)) + 4 - print("#" * (total_length)) + logging.info("#" * (total_length)) for line in lines: left_side = math.floor(((total_length - 2 - len(line.strip())) / 2)) - print("#" + " " * left_side + line.strip() + " " * (total_length - len("#" + " " * left_side + line.strip()) - 1) + "#") - print("#" * total_length) + logging.info("#" + " " * left_side + line.strip() + " " * (total_length - len("#" + " " * left_side + line.strip()) - 1) + "#") + logging.info("#" * total_length) RECOVERY_STATUS = None @@ -124,7 +125,7 @@ sleep_process = None def disable_sleep_while_running(): global sleep_process - print("- Disabling Idle Sleep") + logging.info("- Disabling Idle Sleep") if sleep_process is None: # If sleep_process is active, we'll just keep it running sleep_process = subprocess.Popen(["caffeinate", "-d", "-i", "-s"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -134,7 +135,7 @@ def disable_sleep_while_running(): def enable_sleep_after_running(): global sleep_process if sleep_process: - print("- Re-enabling Idle Sleep") + logging.info("- Re-enabling Idle Sleep") sleep_process.kill() sleep_process = None @@ -283,7 +284,7 @@ def cls(): if not check_recovery(): os.system("cls" if os.name == "nt" else "clear") else: - print("\u001Bc") + logging.info("\u001Bc") def check_command_line_tools(): # Determine whether Command Line Tools exist @@ -390,7 +391,7 @@ def download_file(link, location, is_gui=None, verify_checksum=False): # Check if we have enough space if total_file_size > get_free_space(): - print(f"Not enough space to download {base_name} ({file_size_rounded}MB)") + logging.info(f"Not enough space to download {base_name} ({file_size_rounded}MB)") return False else: file_size_string = "" @@ -420,13 +421,13 @@ def download_file(link, location, is_gui=None, verify_checksum=False): if is_gui is None: if clear: cls() - print(box_string) - print(header) - print(box_string) - print("") + logging.info(box_string) + logging.info(header) + logging.info(box_string) + logging.info("") if total_file_size > 1024: total_downloaded_string = f" ({round(float(dl / total_file_size * 100), 2)}%)" - print(f"{round(count / 1024 / 1024, 2)}MB Downloaded{file_size_string}{total_downloaded_string}\nAverage Download Speed: {round(dl//(time.perf_counter() - start) / 100000 / 8, 2)} MB/s") + logging.info(f"{round(count / 1024 / 1024, 2)}MB Downloaded{file_size_string}{total_downloaded_string}\nAverage Download Speed: {round(dl//(time.perf_counter() - start) / 100000 / 8, 2)} MB/s") enable_sleep_after_running() return checksum.hexdigest() if checksum else True @@ -435,15 +436,15 @@ def download_file(link, location, is_gui=None, verify_checksum=False): header = "# Could not establish Network Connection with provided link! #" box_length = len(header) box_string = "#" * box_length - print(box_string) - print(header) - print(box_string) + logging.info(box_string) + logging.info(header) + logging.info(box_string) if constants.Constants().url_patcher_support_pkg in link: # If we're downloading PatcherSupportPkg, present offline build - print("\nPlease grab the offline variant of OpenCore Legacy Patcher from Github:") - print(f"https://github.com/dortania/OpenCore-Legacy-Patcher/releases/download/{constants.Constants().patcher_version}/OpenCore-Patcher-TUI-Offline.app.zip") + logging.info("\nPlease grab the offline variant of OpenCore Legacy Patcher from Github:") + logging.info(f"https://github.com/dortania/OpenCore-Legacy-Patcher/releases/download/{constants.Constants().patcher_version}/OpenCore-Patcher-TUI-Offline.app.zip") else: - print(link) + logging.info(link) return None @@ -560,7 +561,7 @@ def block_os_updaters(): for bad_process in bad_processes: if bad_process in current_process: if pid != "": - print(f"- Killing Process: {pid} - {current_process.split('/')[-1]}") + logging.info(f"- Killing Process: {pid} - {current_process.split('/')[-1]}") subprocess.run(["kill", "-9", pid]) break