1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
|
#!/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():
pass
mode = "r:xz" if tar_file_path.endswith(".tar.xz") else "r:gz"
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")
finally:
if button_enable_callback:
button_enable_callback()
|