-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkers.py
More file actions
464 lines (378 loc) · 18.3 KB
/
workers.py
File metadata and controls
464 lines (378 loc) · 18.3 KB
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
import os
import requests
import time
import re
from PySide6.QtCore import QObject, QRunnable, Signal
class WorkerSignals(QObject):
"""Central signal hub reused by all worker types.
Keeping a single definition avoids many small QObject subclasses.
"""
auth_complete = Signal(dict)
auth_failed = Signal(str)
search_complete = Signal(list)
search_failed = Signal(str)
image_downloaded = Signal(str, str, str) # game name, image path, official game name
finished = Signal()
steam_games_found = Signal(list) # list of steam games
steam_scan_failed = Signal(str)
steam_game_added = Signal(str, str) # game name, install directory
steam_scan_progress = Signal(int, str) # progress, status message
update_available = Signal(str, str) # latest version, download url
no_update = Signal()
error = Signal(str)
class LegacyIGDBAuthWorker(QRunnable):
"""Obtain OAuth token for direct IGDB v4 access (legacy path)."""
def __init__(self, client_id, client_secret):
super().__init__()
self.client_id = client_id
self.client_secret = client_secret
self.signals = WorkerSignals()
def run(self):
"""POST client credentials; emit token or failure."""
try:
url = "https://id.twitch.tv/oauth2/token"
payload = {
"client_id": self.client_id,
"client_secret": self.client_secret,
"grant_type": "client_credentials"
}
response = requests.post(url, data=payload)
response.raise_for_status()
data = response.json()
if "access_token" in data:
auth_data = {
"client_id": self.client_id,
"access_token": data["access_token"],
"expires_at": time.time() + data["expires_in"]
}
self.signals.auth_complete.emit(auth_data)
else:
self.signals.auth_failed.emit("Authentication failed: No access token received")
except Exception as e:
self.signals.auth_failed.emit(f"Authentication failed: {str(e)}")
finally:
self.signals.finished.emit()
class LegacyIGDBGameSearchWorker(QRunnable):
"""Direct IGDB search using legacy credentials (fallback mode)."""
def __init__(self, auth_data, game_name):
super().__init__()
self.auth_data = auth_data
self.game_name = game_name
self.signals = WorkerSignals()
def run(self):
"""Send IGDB query and attach tiny thumbnails for UI list speed."""
try:
if not self.auth_data or not self.auth_data.get("client_id") or not self.auth_data.get("access_token"):
self.signals.search_failed.emit("Authentication data missing")
return
url = "https://api.igdb.com/v4/games"
query = f'search "{self.game_name}"; fields name,cover.url,cover.image_id; limit 10;'
headers = {
'Client-ID': self.auth_data["client_id"],
'Authorization': f'Bearer {self.auth_data["access_token"]}',
'Accept': 'application/json'
}
response = requests.post(url, headers=headers, data=query)
response.raise_for_status()
games = response.json()
for game in games:
if "cover" in game:
cover = game["cover"]
if "image_id" in cover:
thumb_url = f"https://images.igdb.com/igdb/image/upload/t_micro/{cover['image_id']}.jpg"
thumb_response = requests.get(thumb_url)
if thumb_response.ok:
game["thumb_data"] = thumb_response.content
self.signals.search_complete.emit(games)
except Exception as e:
self.signals.search_failed.emit(f"Game search failed: {str(e)}")
finally:
self.signals.finished.emit()
class LegacyIGDBImageDownloadWorker(QRunnable):
"""Download full cover image with retry & minimal validation."""
def __init__(self, auth_data, game_data, destination_folder):
super().__init__()
self.auth_data = auth_data
self.game_data = game_data
self.destination_folder = destination_folder
self.signals = WorkerSignals()
def make_safe_filename(self, name):
safe_name = name.lower().replace(" ", "_")
for char in [':', '/', '\\', '*', '?', '"', '<', '>', '|', '.']:
safe_name = safe_name.replace(char, "_")
safe_name = ''.join(c for c in safe_name if c.isalnum() or c in ['_', '-'])
return safe_name
def run(self):
"""Fetch large cover, validate size & basic image readability."""
try:
if not self.game_data:
self.signals.search_failed.emit("No game data available")
return
if "cover" not in self.game_data or not self.game_data["cover"]:
self.signals.search_failed.emit("No cover image available")
return
cover_data = self.game_data["cover"]
if "image_id" not in cover_data:
self.signals.search_failed.emit("Cover image ID not found")
return
image_id = cover_data["image_id"]
image_url = f"https://images.igdb.com/igdb/image/upload/t_cover_big/{image_id}.jpg"
try:
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
response = requests.get(image_url, timeout=15)
response.raise_for_status()
break
except requests.exceptions.RequestException as e:
retry_count += 1
if retry_count >= max_retries:
raise
time.sleep(1)
except requests.exceptions.RequestException as e:
self.signals.search_failed.emit(f"Failed to download image: {str(e)}")
return
try:
os.makedirs(self.destination_folder, exist_ok=True)
except OSError as e:
self.signals.search_failed.emit(f"Failed to create image directory: {str(e)}")
return
try:
safe_name = self.make_safe_filename(self.game_data["name"])
file_path = os.path.join(self.destination_folder, f"{safe_name}.jpg")
if len(response.content) < 100:
self.signals.search_failed.emit("Downloaded image is too small or empty")
return
temp_path = file_path + ".tmp"
with open(temp_path, 'wb') as f:
f.write(response.content)
if os.path.exists(file_path):
os.unlink(file_path)
os.rename(temp_path, file_path)
if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
self.signals.search_failed.emit("Failed to save image file")
return
try:
from PySide6.QtGui import QImageReader
reader = QImageReader(file_path)
if not reader.canRead():
os.unlink(file_path)
self.signals.search_failed.emit("Downloaded file is not a valid image")
return
except Exception:
pass
self.signals.image_downloaded.emit(self.game_data["name"], file_path, self.game_data["name"])
except IOError as e:
self.signals.search_failed.emit(f"Failed to save image: {str(e)}")
return
except Exception as e:
self.signals.search_failed.emit(f"Error processing image: {str(e)}")
return
except Exception as e:
self.signals.search_failed.emit(f"Image download failed: {str(e)}")
finally:
self.signals.finished.emit()
class LegacyAPITestWorker(QRunnable):
"""Simple probe to verify legacy auth token works for an endpoint."""
def __init__(self, auth_data):
super().__init__()
self.auth_data = auth_data
self.signals = WorkerSignals()
def run(self):
"""Request tiny resource; report success/failure."""
try:
url = "https://api.igdb.com/v4/platforms"
query = "fields name; limit 1;"
headers = {
'Client-ID': self.auth_data["client_id"],
'Authorization': f'Bearer {self.auth_data["access_token"]}',
'Accept': 'application/json'
}
response = requests.post(url, headers=headers, data=query)
response.raise_for_status()
data = response.json()
if isinstance(data, list) and len(data) > 0:
self.signals.auth_complete.emit(True)
else:
self.signals.auth_failed.emit("API returned unexpected data format")
except Exception as e:
self.signals.auth_failed.emit(f"API connection failed: {str(e)}")
finally:
self.signals.finished.emit()
class IGDBGameSearchWorker(QRunnable):
"""Search via ambidex proxy API (no local auth handling)."""
def __init__(self, game_name):
super().__init__()
self.game_name = game_name
self.signals = WorkerSignals()
def run(self):
"""Query proxy, add micro thumbs for snappy result rendering."""
try:
url = "https://ambidex-igdb.netlify.app/api/igdb"
params = {'search': self.game_name}
response = requests.get(url, params=params, timeout=15)
response.raise_for_status()
games = response.json()
if isinstance(games, dict) and 'error' in games:
self.signals.search_failed.emit(f"API error: {games['error']}")
return
for game in games:
if "cover" in game and "image_id" in game["cover"]:
thumb_url = f"https://images.igdb.com/igdb/image/upload/t_micro/{game['cover']['image_id']}.jpg"
try:
thumb_response = requests.get(thumb_url, timeout=10)
if thumb_response.ok:
game["thumb_data"] = thumb_response.content
except Exception:
pass
self.signals.search_complete.emit(games)
except requests.exceptions.RequestException as e:
self.signals.search_failed.emit(f"Game search failed: {str(e)}")
except ValueError as e:
self.signals.search_failed.emit(f"Invalid response from server: {str(e)}")
except Exception as e:
self.signals.search_failed.emit(f"Game search failed: {str(e)}")
finally:
self.signals.finished.emit()
class IGDBImageDownloadWorker(QRunnable):
"""Download large cover image using proxy metadata (no auth)."""
def __init__(self, game_data, destination_folder):
super().__init__()
self.game_data = game_data
self.destination_folder = destination_folder
self.signals = WorkerSignals()
def make_safe_filename(self, name):
safe_name = name.lower().replace(" ", "_")
for char in [':', '/', '\\', '*', '?', '"', '<', '>', '|', '.']:
safe_name = safe_name.replace(char, "_")
safe_name = ''.join(c for c in safe_name if c.isalnum() or c in ['_', '-'])
return safe_name
def run(self):
"""Retrieve, size‑check and basic‑validate image before emitting."""
try:
if not self.game_data:
self.signals.search_failed.emit("No game data available")
return
if "cover" not in self.game_data or not self.game_data["cover"]:
self.signals.search_failed.emit("No cover image available")
return
cover_data = self.game_data["cover"]
if "image_id" not in cover_data:
self.signals.search_failed.emit("Cover image ID not found")
return
image_id = cover_data["image_id"]
image_url = f"https://images.igdb.com/igdb/image/upload/t_cover_big/{image_id}.jpg"
try:
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
response = requests.get(image_url, timeout=15)
response.raise_for_status()
break
except requests.exceptions.RequestException as e:
retry_count += 1
if retry_count >= max_retries:
raise
time.sleep(1)
except requests.exceptions.RequestException as e:
self.signals.search_failed.emit(f"Failed to download image: {str(e)}")
return
try:
os.makedirs(self.destination_folder, exist_ok=True)
except OSError as e:
self.signals.search_failed.emit(f"Failed to create image directory: {str(e)}")
return
try:
safe_name = self.make_safe_filename(self.game_data["name"])
file_path = os.path.join(self.destination_folder, f"{safe_name}.jpg")
if len(response.content) < 100:
self.signals.search_failed.emit("Downloaded image is too small or empty")
return
temp_path = file_path + ".tmp"
with open(temp_path, 'wb') as f:
f.write(response.content)
if os.path.exists(file_path):
os.unlink(file_path)
os.rename(temp_path, file_path)
if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
self.signals.search_failed.emit("Failed to save image file")
return
try:
from PySide6.QtGui import QImageReader
reader = QImageReader(file_path)
if not reader.canRead():
os.unlink(file_path)
self.signals.search_failed.emit("Downloaded file is not a valid image")
return
except Exception:
pass
self.signals.image_downloaded.emit(self.game_data["name"], file_path, self.game_data["name"])
except IOError as e:
self.signals.search_failed.emit(f"Failed to save image: {str(e)}")
return
except Exception as e:
self.signals.search_failed.emit(f"Error processing image: {str(e)}")
return
except Exception as e:
self.signals.search_failed.emit(f"Image download failed: {str(e)}")
finally:
self.signals.finished.emit()
class UpdateCheckWorker(QRunnable):
"""Check for updates on GitHub"""
def __init__(self, current_version):
super().__init__()
self.current_version = current_version
self.signals = WorkerSignals()
def run(self):
"""Check GitHub API for latest release"""
try:
url = "https://api.github.com/repos/chwair/ambidex/releases/latest"
headers = {"Accept": "application/vnd.github.v3+json"}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
latest_version = data.get("tag_name", "").lstrip("v")
if not latest_version:
self.signals.error.emit("Could not determine latest version")
return
# Compare versions
if self.is_newer_version(latest_version, self.current_version):
# Find the installer asset
download_url = None
for asset in data.get("assets", []):
if asset["name"].endswith("-setup.exe"):
download_url = asset["browser_download_url"]
break
if download_url:
self.signals.update_available.emit(latest_version, download_url)
else:
self.signals.error.emit("Update available but no installer found")
else:
self.signals.no_update.emit()
except requests.exceptions.RequestException as e:
self.signals.error.emit(f"Network error: {str(e)}")
except Exception as e:
self.signals.error.emit(f"Update check failed: {str(e)}")
finally:
self.signals.finished.emit()
def is_newer_version(self, latest, current):
"""Compare version strings (e.g., '1.2.3' vs '1.2.0')"""
try:
# Parse versions
latest_parts = [int(x) for x in latest.split('.')]
current_parts = [int(x) for x in current.split('.')]
# Pad to same length
max_len = max(len(latest_parts), len(current_parts))
latest_parts.extend([0] * (max_len - len(latest_parts)))
current_parts.extend([0] * (max_len - len(current_parts)))
# Compare
for l, c in zip(latest_parts, current_parts):
if l > c:
return True
elif l < c:
return False
return False
except:
return False