#!/usr/bin/env python3 """Core (non-UI) logic for managing Proton / GE-Proton / Proton-EM releases.""" __all__ = [ "CACHE_TTL", "DEFAULT_UPSTREAM_URLS", "MACHINE_ARCH", "RATE_LIMITED_MSG", "STEAM_COMPATIBILITY_PATH", "RateLimitError", "RateLimited", "_cache_key", "_fetch_with_cache", "clear_cache", "download_and_extract", "fetch_all_releases", "fetch_releases", "get_arch_asset", "get_cache_dir", "get_installed_path", "remove_path", ] import hashlib import json import os import platform import re import shutil import tarfile import time from pathlib import Path import requests from fungus.logger import get_logger from fungus.path_manager import PathManager log = get_logger(__name__) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- STEAM_COMPATIBILITY_PATH = Path(PathManager.user_data("Steam/compatibilitytools.d")) MACHINE_ARCH = platform.machine().lower() # e.g. "x86_64", "aarch64" DEFAULT_UPSTREAM_URLS = [ "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases", "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases", ] RATE_LIMITED_MSG = ( "GitHub API rate limit reached. Please try again later or use the refresh button." ) # --------------------------------------------------------------------------- # Exceptions # --------------------------------------------------------------------------- class RateLimitError(Exception): """Raised when GitHub API returns a rate-limit response.""" pass class RateLimited(Exception): """Raised when all sources are rate-limited and no cache is available.""" pass # --------------------------------------------------------------------------- # Cache helpers # --------------------------------------------------------------------------- CACHE_TTL = 3600 # 1 hour def get_cache_dir(): """Return the cache directory for proton release data.""" cache = Path(PathManager.user_config("fungus-launcher")) / "cache" cache.mkdir(parents=True, exist_ok=True) return cache def _cache_key(url): """Generate a safe cache filename from a URL.""" h = hashlib.sha256(url.encode()).hexdigest()[:16] return f"proton-releases-{h}.json" def _fetch_with_cache(url, cache_dir=None): """Fetch releases from a URL, using cached data if still valid. Falls back to cache on network errors so callers never stay blank. """ if cache_dir is None: cache_dir = get_cache_dir() cache_path = cache_dir / _cache_key(url) now = time.time() # Try to load valid cached data first. if cache_path.exists(): try: with open(cache_path) as f: entry = json.load(f) if now - entry["time"] < CACHE_TTL: log.debug("Cache hit: %s", url) return entry["data"] log.debug("Cache expired: %s", url) except (json.JSONDecodeError, KeyError) as exc: log.warning("Corrupt cache, ignoring: %s", exc) # Fetch fresh data. log.debug("Fetching: %s", url) releases = fetch_releases(url) # Save to cache. try: with open(cache_path, "w") as f: json.dump({"time": now, "data": releases}, f) log.debug("Cached: %s (%d releases)", url, len(releases)) except OSError as exc: log.warning("Cache write failed: %s", exc) return releases # --------------------------------------------------------------------------- # Release fetching & filtering # --------------------------------------------------------------------------- def fetch_releases(url): """Fetch and filter releases from a GitHub API URL. Returns a list of release dicts. """ page = 1 releases = [] seen_tags = set() while True: response = requests.get( url, params={"page": page, "per_page": 100}, timeout=15, ) if response.status_code == 200: page_releases = response.json() if not page_releases: break releases.extend(page_releases) page += 1 elif response.status_code == 403: body = response.json() if isinstance(body, dict) and "rate limit" in body.get( "message", "" ).lower(): raise RateLimitError("GitHub API rate limit exceeded") break else: break log.info("Fetched %d raw releases from %s", len(releases), url) filtered = [] for release in releases: tag_name = release["tag_name"] if tag_name in seen_tags: continue seen_tags.add(tag_name) if "GloriousEggroll" in url: if not tag_name.startswith("GE-Proton"): log.debug("Skipping %s: doesn't start with GE-Proton", tag_name) continue try: # Two formats: "GE-Proton-9.11-1" or "GE-Proton11-1" after = tag_name[len("GE-Proton"):] nums = re.findall(r"\d+", after) if len(nums) < 2: log.debug("Skipping %s: cannot parse version", tag_name) continue major, minor = int(nums[0]), int(nums[1]) if (major, minor) < (9, 1): log.debug("Skipping %s: version (%d.%d) < 9.1", tag_name, major, minor) continue except Exception as exc: log.debug("Skipping %s: version parse error: %s", tag_name, exc) continue elif "Etaash-mathamsetty" in url: if not tag_name.startswith("EM-"): log.debug("Skipping %s: doesn't start with EM-", tag_name) continue assets = release.get("assets", []) has_valid_asset = any( asset["name"].endswith((".tar.gz", ".tar.xz")) for asset in assets ) if not has_valid_asset: log.debug("Skipping %s: no tar.gz/tar.xz asset", tag_name) continue filtered.append(release) log.info("Filtered down to %d releases", len(filtered)) return filtered # --------------------------------------------------------------------------- # Cache management # --------------------------------------------------------------------------- def clear_cache(urls=None): """Remove cached release data for given upstream URLs. Parameters ---------- urls : list[str], optional URLs to clear cache for. Defaults to all known upstreams. """ if urls is None: urls = DEFAULT_UPSTREAM_URLS for url in urls: cache_path = get_cache_dir() / _cache_key(url) try: cache_path.unlink(missing_ok=True) log.debug("Cache removed: %s", url) except OSError as exc: log.warning("Cache removal failed: %s", exc) # --------------------------------------------------------------------------- # Fetch all upstreams # --------------------------------------------------------------------------- def fetch_all_releases(): """Fetch releases from all known upstreams. Returns ------- dict[str, list[dict]] Mapping from upstream URL to its list of release dicts. """ results = {} for url in DEFAULT_UPSTREAM_URLS: results[url] = _fetch_with_cache(url) return results # --------------------------------------------------------------------------- # Asset selection # --------------------------------------------------------------------------- def get_arch_asset(assets): """Find the best asset for the machine's architecture. GE-Proton naming conventions: - Default (x86_64) build: ``GE-Proton11-1.tar.gz`` (no arch suffix) - Explicit x86_64 build: ``GE-Proton11-1-x86_64.tar.gz`` - aarch64 build: ``GE-Proton11-1-aarch64.tar.gz`` On x86_64 machines we want the default or ``-x86_64`` variant. On aarch64 machines we want the ``-aarch64`` variant. """ # First pass: look for an exact arch match. for asset in assets: name = asset["name"] if not name.endswith((".tar.gz", ".tar.xz")): continue for ext in (".tar.xz", ".tar.gz"): if name.endswith(ext): stem = name[: -len(ext)] break else: continue if stem.endswith(MACHINE_ARCH): log.debug("Selected asset for arch %s: %s", MACHINE_ARCH, name) return asset # Second pass (x86_64 only): the default build has no arch suffix. if MACHINE_ARCH == "x86_64": for asset in assets: name = asset["name"] if not name.endswith((".tar.gz", ".tar.xz")): continue for ext in (".tar.xz", ".tar.gz"): if name.endswith(ext): stem = name[: -len(ext)] break else: continue if not stem.endswith(MACHINE_ARCH) and not stem.endswith("aarch64"): log.debug("Selected default (x86_64) asset: %s", name) return asset # Fallback: return the first tar archive. for asset in assets: if asset["name"].endswith((".tar.gz", ".tar.xz")): log.warning( "No arch-specific asset found for %s, falling back to: %s", MACHINE_ARCH, asset["name"], ) return asset return None # --------------------------------------------------------------------------- # Install / removal # --------------------------------------------------------------------------- def get_installed_path(tag_name): """Return the path where a Proton version is installed, or the expected path.""" tag_lower = tag_name.lower() if STEAM_COMPATIBILITY_PATH.exists(): for folder in STEAM_COMPATIBILITY_PATH.iterdir(): folder_name_lower = folder.name.lower() if folder_name_lower.endswith(tag_lower): return folder if tag_lower.startswith("proton-"): if folder_name_lower.endswith(tag_lower[len("proton-"):]): return folder return STEAM_COMPATIBILITY_PATH / tag_name def remove_path(path): """Remove a directory tree (used for uninstalling Proton versions).""" if path and os.path.exists(path): shutil.rmtree(path) # --------------------------------------------------------------------------- # Download & extraction # --------------------------------------------------------------------------- def download_and_extract( url, filename, tag_name, progress_callback=None, progress_value_callback=None, message_callback=None, pending_callback=None, button_update_callback=None, button_enable_callback=None, ): """Download and extract a Proton release archive. Parameters ---------- url : str Direct download URL for the archive. filename : str Archive filename (used for the local temp file). tag_name : str Release tag name (used for display). progress_callback : callable(int), optional Called with 0-100 progress percentage during download/extraction. progress_value_callback : callable(float), optional Called with a 0.0-1.0 fraction during download/extraction. message_callback : callable(str), optional Called with status messages (e.g. "Downloading …"). pending_callback : callable, optional Called to pump GTK events while processing. button_update_callback : callable(str), optional Called with a new button label. button_enable_callback : callable, optional Called to re-enable all buttons. """ display_tag_name = f"proton-{tag_name}" if tag_name.startswith("EM-") else tag_name if message_callback: message_callback(f"Downloading {display_tag_name}...") if progress_callback: progress_callback(0) if progress_value_callback: progress_value_callback(0.0) if not os.path.exists(STEAM_COMPATIBILITY_PATH): os.makedirs(STEAM_COMPATIBILITY_PATH) response = requests.get(url, stream=True) total_size = int(response.headers.get("content-length", 0)) downloaded_size = 0 tar_file_path = os.path.join(os.getcwd(), filename) with open(tar_file_path, "wb") as file: for data in response.iter_content(1024): file.write(data) downloaded_size += len(data) progress = downloaded_size / total_size if total_size > 0 else 0 if progress_callback: progress_callback(int(progress * 100)) if progress_value_callback: progress_value_callback(progress) if pending_callback: pending_callback() file.flush() os.fsync(file.fileno()) # Extraction if message_callback: message_callback(f"Extracting {display_tag_name}...") if progress_callback: progress_callback(0) if progress_value_callback: progress_value_callback(0.0) if button_update_callback: button_update_callback("Extracting...") while pending_callback and pending_callback(): time.sleep(0.01) mode = "r:xz" if tar_file_path.endswith(".tar.xz") else "r:gz" temp_dir = None # cleaned up on failure try: with tarfile.open(tar_file_path, mode) as tar: total_members = len(tar.getmembers()) extracted_members = 0 temp_dir = os.path.join(STEAM_COMPATIBILITY_PATH, f"temp_{tag_name}") os.makedirs(temp_dir, exist_ok=True) for member in tar.getmembers(): tar.extract(member, path=temp_dir, filter="fully_trusted") extracted_members += 1 progress = extracted_members / total_members if progress_callback: progress_callback(int(progress * 100)) if progress_value_callback: progress_value_callback(progress) if pending_callback: pending_callback() extracted_dir = None for item in os.listdir(temp_dir): item_path = os.path.join(temp_dir, item) if os.path.isdir(item_path): extracted_dir = item_path break if extracted_dir: final_dir = os.path.join( STEAM_COMPATIBILITY_PATH, os.path.basename(extracted_dir) ) if os.path.exists(final_dir): shutil.rmtree(final_dir) shutil.move(extracted_dir, STEAM_COMPATIBILITY_PATH) shutil.rmtree(temp_dir) os.remove(tar_file_path) if button_update_callback: button_update_callback("Remove") if progress_callback: progress_callback(100) except Exception as e: log.error("Error during extraction: %s", e) if message_callback: message_callback("Error during extraction") if button_update_callback: button_update_callback("Download") # Clean up temp files on failure try: os.remove(tar_file_path) except OSError: pass if temp_dir: try: shutil.rmtree(temp_dir) except OSError: pass finally: if button_enable_callback: button_enable_callback()