-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1676 lines (1526 loc) · 68.3 KB
/
Copy pathmain.py
File metadata and controls
1676 lines (1526 loc) · 68.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Enhanced UnityScraper - Main Module
Improved version with better error handling and configuration
"""
import argparse
import json
import logging
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import List, Optional, Dict, Any
from urllib.parse import urlparse
from datetime import datetime, timedelta
import hashlib
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from app_paths import (
CLI_LOG_PATH,
CONFIG_PATH,
DOWNLOADS_DIR,
PLUGINS_DIR,
ensure_app_dirs,
ensure_user_titleids_file,
)
from database import DatabaseManager
from knowledge_base import is_unknown
from plugins import PluginManager, load_enabled_plugin_configuration
from resume import ResumableDownloader
logger = logging.getLogger(__name__)
def configure_logging() -> None:
"""Configure console and file logging when the CLI is actually launched."""
ensure_app_dirs()
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler(CLI_LOG_PATH),
],
)
class Config:
"""Configuration management with defaults"""
def __init__(self, config_file: Optional[str] = None):
self.base_url = "http://xboxunity.net"
self.http_fallback_url = self.base_url
self.api_endpoints = {
'covers': '/Resources/Lib/CoverInfo.php?titleid=',
'updates': '/Resources/Lib/TitleUpdateInfo.php?titleid='
}
self.output_dir = DOWNLOADS_DIR
self.workers = 4
self.rate_limit = 0.35
self.timeout = 30
self.max_retries = 3
self.retry_backoff = 2.0
self.use_https = False
self.bandwidth_limit = 0 # KB/s, 0 = unlimited
self.verify_checksums = False
self.dry_run = False
self.refresh_interval_days = 0 # 0 = no auto-refresh
if config_file and Path(config_file).exists():
self.load_from_file(config_file)
self.base_url = "http://xboxunity.net"
self.http_fallback_url = self.base_url
self.use_https = False
def load_from_file(self, config_file: str):
"""Load configuration from JSON file"""
try:
with open(config_file, 'r') as f:
config_data = json.load(f)
for key, value in config_data.items():
if hasattr(self, key):
if key == "output_dir":
value = Path(value)
setattr(self, key, value)
logger.info(f"Loaded configuration from {config_file}")
except Exception as e:
logger.warning(f"Failed to load config file: {e}, using defaults")
def save_to_file(self, config_file: str = None):
"""Save current configuration to JSON file"""
if config_file is None:
config_file = str(CONFIG_PATH)
config_data = {
'output_dir': str(self.output_dir),
'workers': self.workers,
'rate_limit': self.rate_limit,
'timeout': self.timeout,
'max_retries': self.max_retries,
'retry_backoff': self.retry_backoff,
'use_https': False,
'bandwidth_limit': self.bandwidth_limit,
'verify_checksums': self.verify_checksums,
'dry_run': self.dry_run,
'refresh_interval_days': self.refresh_interval_days
}
with open(config_file, 'w') as f:
json.dump(config_data, f, indent=2)
logger.info(f"Saved configuration to {config_file}")
class RateLimiter:
"""Thread-safe rate limiter"""
def __init__(self, min_interval: float):
self.min_interval = min_interval
self.last_request = 0
import threading
self._lock = threading.Lock()
def wait(self):
"""Wait if necessary to maintain rate limit"""
with self._lock:
now = time.time()
elapsed = now - self.last_request
if elapsed < self.min_interval:
time.sleep(self.min_interval - elapsed)
self.last_request = time.time()
def load_titleids_from_json(json_file: str = None) -> List[str]:
"""Load TitleIDs from JSON.txt file (comma-separated format)"""
try:
if json_file is None:
json_file = str(ensure_user_titleids_file())
json_path = Path(json_file)
if not json_path.exists():
logger.warning(f"JSON file not found: {json_file}")
return []
with open(json_path, 'r') as f:
content = f.read().strip()
titleids = [tid.strip() for tid in content.split(',') if tid.strip()]
logger.info(f"Loaded {len(titleids)} TitleIDs from {json_file}")
return titleids
except Exception as e:
logger.error(f"Failed to load TitleIDs from {json_file}: {e}")
return []
class UnityScraper:
"""Main scraper class for XboxUnity's HTTP endpoints."""
def __init__(
self,
config: Config,
database: Optional[DatabaseManager] = None,
plugin_manager: Optional[PluginManager] = None,
):
self.config = config
self.rate_limiter = RateLimiter(config.rate_limit)
self.session = self._create_session()
self.db = database or DatabaseManager()
if plugin_manager is None:
enabled, trusted = load_enabled_plugin_configuration(
self.db.db_path, PLUGINS_DIR
)
plugin_manager = PluginManager(
str(PLUGINS_DIR), enabled_plugins=enabled, trusted_hashes=trusted
)
self.plugin_manager = plugin_manager
self.downloader = ResumableDownloader(self.session, config.timeout, config.bandwidth_limit)
self._test_connection()
def _create_session(self) -> requests.Session:
"""Create session with retry strategy"""
session = requests.Session()
retry_strategy = Retry(
total=self.config.max_retries,
backoff_factor=self.config.retry_backoff,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "POST"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def _test_connection(self):
"""Test XboxUnity HTTP connectivity."""
self.config.use_https = False
self.config.base_url = "http://xboxunity.net"
try:
response = self.session.get(
self.config.base_url,
timeout=10
)
response.raise_for_status()
logger.info("[OK] XboxUnity HTTP connection successful")
except Exception as e:
logger.error(f"Failed to connect to XboxUnity: {e}")
raise ConnectionError("Cannot connect to XboxUnity.net")
def _make_request(self, url: str, retry_count: int = 0) -> Optional[requests.Response]:
"""Make HTTP request with rate limiting and retry logic"""
self.rate_limiter.wait()
try:
response = self.session.get(url, timeout=self.config.timeout)
if response.status_code == 429:
wait_time = min(60, (2 ** retry_count) * self.config.retry_backoff)
logger.warning(f"Rate limited (429). Waiting {wait_time}s...")
time.sleep(wait_time)
if retry_count < self.config.max_retries:
return self._make_request(url, retry_count + 1)
return None
response.raise_for_status()
return response
except requests.exceptions.Timeout:
logger.error(f"Timeout fetching {url}")
if retry_count < self.config.max_retries:
time.sleep(self.config.retry_backoff * (retry_count + 1))
return self._make_request(url, retry_count + 1)
except requests.exceptions.RequestException as e:
logger.error(f"Request failed for {url}: {e}")
if retry_count < self.config.max_retries:
time.sleep(self.config.retry_backoff * (retry_count + 1))
return self._make_request(url, retry_count + 1)
return None
@staticmethod
def validate_titleid(titleid: str) -> Optional[str]:
"""Validate and normalize TitleID"""
titleid = titleid.strip().upper()
if len(titleid) == 8 and all(c in '0123456789ABCDEF' for c in titleid):
return titleid
if len(titleid) == 8 and titleid.startswith("TESTID") and titleid[-2:].isdigit():
return titleid
logger.warning(f"Invalid TitleID format: {titleid}")
return None
def get_download_size_estimate(self, titleid: str) -> Dict[str, int]:
"""Estimate total download size before downloading"""
validated_titleid = self.validate_titleid(titleid)
if not validated_titleid:
return {'covers_bytes': 0, 'updates_bytes': 0, 'total_bytes': 0}
total_covers = 0
total_updates = 0
# Estimate cover sizes
covers_data = self.fetch_json_data(self.config.api_endpoints['covers'], validated_titleid)
if covers_data:
covers_list = covers_data.get('Covers', [])
if isinstance(covers_list, list):
for cover in covers_list:
if isinstance(cover, dict):
cover_id = cover.get('CoverID')
if cover_id:
cover_url = f"{self.config.base_url}/Resources/Lib/Cover.php?size=large&cid={cover_id}"
size = self.downloader.get_remote_size(cover_url)
if size:
total_covers += size
# Estimate update sizes
updates_data = self.fetch_json_data(self.config.api_endpoints['updates'], validated_titleid)
if updates_data:
media_list = updates_data.get('MediaIDS', updates_data.get('MediaIDs', []))
if isinstance(media_list, list):
for media in media_list:
if isinstance(media, dict):
updates = media.get('Updates', [])
if isinstance(updates, list):
for update in updates:
if isinstance(update, dict):
tuid = update.get('TitleUpdateID')
if tuid:
update_url = f"{self.config.base_url}/Resources/Lib/TitleUpdate.php?tuid={tuid}"
size = self.downloader.get_remote_size(update_url)
if size:
total_updates += size
return {
'covers_bytes': total_covers,
'updates_bytes': total_updates,
'total_bytes': total_covers + total_updates
}
def fetch_json_data(self, endpoint: str, titleid: str) -> Optional[Dict[str, Any]]:
"""Fetch JSON data from API endpoint"""
url = f"{self.config.base_url}{endpoint}{titleid}"
logger.info(f"Fetching {endpoint} for {titleid}...")
response = self._make_request(url)
if response:
try:
return response.json()
except json.JSONDecodeError:
logger.error(f"Invalid JSON response from {url}")
return None
def download_file(self, url: str, dest_path: Path) -> bool:
"""Download file to destination with progress"""
if self.config.dry_run:
logger.info(f"[DRY RUN] Would download: {url} → {dest_path}")
return True
dest_path.parent.mkdir(parents=True, exist_ok=True)
response = self._make_request(url)
if not response:
return False
try:
total_size = int(response.headers.get('content-length', 0))
with open(dest_path, 'wb') as f:
if total_size == 0:
f.write(response.content)
else:
downloaded = 0
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
downloaded += len(chunk)
# Progress indicator could be added here
logger.info(f"[OK] Downloaded: {dest_path.name}")
return True
except Exception as e:
logger.error(f"Failed to download {url}: {e}")
if dest_path.exists():
dest_path.unlink()
return False
def collect_metadata(self, titleid: str) -> bool:
"""Collect and store metadata for a TitleID without downloading files"""
validated_titleid = self.validate_titleid(titleid)
if not validated_titleid:
return False
logger.info(f"{'='*60}")
logger.info(f"Collecting metadata for TitleID: {validated_titleid}")
logger.info(f"{'='*60}")
# Check if refresh is needed (feature 6)
if self.config.refresh_interval_days > 0:
titleid_info = self.db.get_titleid_info(validated_titleid)
if titleid_info and titleid_info.get('last_scraped'):
last_scraped = datetime.fromisoformat(titleid_info['last_scraped'])
days_since = (datetime.now() - last_scraped).days
if days_since < self.config.refresh_interval_days:
logger.info(f"Skipping refresh for {validated_titleid} (last scraped {days_since} days ago)")
return True
# Add TitleID to database
self.db.add_titleid(validated_titleid)
# Batch lists for concurrent inserts (feature 15)
covers_batch = []
updates_batch = []
# Fetch and store covers metadata only
covers_data = self.fetch_json_data(self.config.api_endpoints['covers'], validated_titleid)
if covers_data:
covers_list = covers_data.get('Covers', [])
if isinstance(covers_list, list):
for cover in covers_list:
if isinstance(cover, dict):
cover_id = cover.get('CoverID')
if cover_id:
# Store cover metadata WITHOUT downloading
cover_url = f"{self.config.base_url}/Resources/Lib/Cover.php?size=large&cid={cover_id}"
covers_batch.append({
'titleid': validated_titleid,
'cover_url': cover_url,
'cover_type': cover.get('CoverType', 'unknown'),
'status': 'pending',
'metadata': cover
})
logger.info(f"Stored cover metadata: {cover_id}")
# Batch insert covers
if covers_batch:
self.db.batch_insert_covers(covers_batch)
# Fetch and store updates metadata only
updates_data = self.fetch_json_data(self.config.api_endpoints['updates'], validated_titleid)
if updates_data:
media_list = updates_data.get('MediaIDS', updates_data.get('MediaIDs', []))
if isinstance(media_list, list):
for media in media_list:
if isinstance(media, dict):
media_id = media.get('MediaID')
updates = media.get('Updates', [])
if isinstance(updates, list):
for update in updates:
if isinstance(update, dict):
tuid = update.get('TitleUpdateID')
version = update.get('Version', 'unknown')
if tuid:
# Store update metadata WITHOUT downloading
update_url = f"{self.config.base_url}/Resources/Lib/TitleUpdate.php?tuid={tuid}"
updates_batch.append({
'titleid': validated_titleid,
'media_id': str(media_id),
'version': str(version),
'download_url': update_url,
'status': 'pending',
'metadata': update
})
logger.info(f"Stored update metadata: {tuid} v{version}")
# Batch insert updates
if updates_batch:
self.db.batch_insert_updates(updates_batch)
self._collect_plugin_metadata(validated_titleid)
# Update database with scrape info
self.db.update_scrape_info(validated_titleid)
logger.info(f"[OK] Collected metadata for TitleID: {titleid}")
return True
def _collect_plugin_metadata(self, titleid: str) -> None:
"""Run explicitly enabled plugins and store bounded, source-labelled results."""
for result in self.plugin_manager.collect_enabled(titleid):
plugin_id = str(result["plugin_id"])
now = datetime.now().isoformat()
status = str(result["status"])
data = result.get("data") if status == "completed" else None
error = str(result.get("error") or "")
try:
if isinstance(data, dict):
self._store_plugin_metadata(titleid, plugin_id, data)
except Exception as exc:
status = "failed"
error = str(exc)
logger.exception("Could not store plugin result from %s", plugin_id)
with self.db.get_connection() as connection:
connection.execute(
"""
INSERT INTO plugin_collection_runs(
plugin_id, titleid, status, started_at, completed_at,
result_json, error_message
) VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
plugin_id, titleid, status, now, datetime.now().isoformat(),
json.dumps(data, sort_keys=True, default=str) if data is not None else None,
error or None,
),
)
def _store_plugin_metadata(
self, titleid: str, plugin_id: str, data: Dict[str, Any]
) -> None:
title = str(data.get("title") or data.get("name") or "").strip()[:500]
publisher = str(data.get("publisher") or "").strip()[:500]
with self.db.get_connection() as connection:
row = connection.execute(
"SELECT name, publisher, metadata FROM titleids WHERE titleid=?", (titleid,)
).fetchone()
metadata: Dict[str, Any] = {}
if row and row["metadata"]:
try:
metadata = json.loads(row["metadata"])
except json.JSONDecodeError:
metadata = {}
current_name = row["name"] if row else None
current_publisher = row["publisher"] if row else None
if title and is_unknown(current_name):
current_name = title
metadata["title_source"] = f"Plugin: {plugin_id}"
if publisher and is_unknown(current_publisher):
current_publisher = publisher
metadata["publisher_source"] = f"Plugin: {plugin_id}"
plugin_sources = metadata.get("plugin_sources")
if not isinstance(plugin_sources, dict):
plugin_sources = {}
metadata["plugin_sources"] = plugin_sources
plugin_sources[plugin_id] = datetime.now().isoformat()
connection.execute(
"UPDATE titleids SET name=?, publisher=?, metadata=? WHERE titleid=?",
(current_name, current_publisher, json.dumps(metadata, sort_keys=True), titleid),
)
self.db._update_search_index(
connection, titleid, current_name, current_publisher, metadata
)
cover_items = data.get("covers", [])
if not isinstance(cover_items, list):
raise TypeError("Plugin covers must be a list")
covers = []
for item in cover_items[:200]:
if not isinstance(item, dict):
continue
url = str(item.get("cover_url") or item.get("url") or "").strip()
if urlparse(url).scheme not in {"http", "https"}:
continue
covers.append({
"titleid": titleid,
"cover_url": url,
"cover_type": str(item.get("cover_type") or item.get("type") or "plugin")[:100],
"status": "pending",
"metadata": {**item, "plugin_id": plugin_id},
})
if covers:
self.db.batch_insert_covers(covers)
update_items = data.get("updates", [])
if not isinstance(update_items, list):
raise TypeError("Plugin updates must be a list")
updates = []
for item in update_items[:500]:
if not isinstance(item, dict):
continue
url = str(item.get("download_url") or item.get("url") or "").strip()
if urlparse(url).scheme not in {"http", "https"}:
continue
updates.append({
"titleid": titleid,
"media_id": str(item.get("media_id") or item.get("MediaID") or "")[:100],
"version": str(item.get("version") or item.get("Version") or "unknown")[:100],
"download_url": url,
"status": "pending",
"metadata": {**item, "plugin_id": plugin_id},
})
if updates:
self.db.batch_insert_updates(updates)
def process_titleid(self, titleid: str) -> bool:
"""Process a single TitleID - download covers and updates"""
validated_titleid = self.validate_titleid(titleid)
if not validated_titleid:
return False
logger.info(f"{'='*60}")
logger.info(f"Downloading content for TitleID: {validated_titleid}")
logger.info(f"{'='*60}")
output_dir = self.config.output_dir / validated_titleid
output_dir.mkdir(parents=True, exist_ok=True)
# Fetch and download covers data
covers_data = self.fetch_json_data(self.config.api_endpoints['covers'], validated_titleid)
if covers_data:
with open(output_dir / 'covers_data.json', 'w') as f:
json.dump(covers_data, f, indent=2)
self._download_covers(validated_titleid, covers_data, output_dir)
# Fetch and download updates data
updates_data = self.fetch_json_data(self.config.api_endpoints['updates'], validated_titleid)
if updates_data:
with open(output_dir / 'updates_data.json', 'w') as f:
json.dump(updates_data, f, indent=2)
self._download_updates(validated_titleid, updates_data, output_dir)
self.db.add_titleid(validated_titleid)
self._collect_plugin_metadata(validated_titleid)
self.db.update_scrape_info(validated_titleid)
logger.info(f"[OK] Completed downloads for TitleID: {titleid}")
return True
def _download_covers(self, titleid: str, covers_data: Dict, output_dir: Path):
"""Download cover images and mark as downloaded in database"""
covers_list = covers_data.get('Covers', [])
if not isinstance(covers_list, list):
return
covers_dir = output_dir / 'covers'
covers_dir.mkdir(exist_ok=True)
for cover in covers_list:
if isinstance(cover, dict):
cover_id = cover.get('CoverID')
if cover_id:
# Construct the cover image download URL
cover_url = f"{self.config.base_url}/Resources/Lib/Cover.php?size=large&cid={cover_id}"
filename = f"cover_{cover_id}.jpg"
cover_path = covers_dir / filename
# Check for duplicates (feature 8)
if cover_path.exists():
existing_hash = self.downloader.calculate_checksum(cover_path)
# Download to temp, check hash, compare
temp_path = cover_path.parent / f"{cover_path.name}.tmp"
self.download_file(cover_url, temp_path)
if temp_path.exists():
new_hash = self.downloader.calculate_checksum(temp_path)
if existing_hash == new_hash:
logger.info(f"Cover {cover_id} already exists (duplicate)")
temp_path.unlink()
download_status = 'downloaded'
cover_path = cover_path # Keep existing
else:
temp_path.rename(cover_path)
download_status = 'downloaded'
else:
download_status = 'failed'
else:
success = self.download_file(cover_url, cover_path)
download_status = 'downloaded' if success else 'failed'
# Verify checksum if enabled (feature 5)
if download_status == 'downloaded' and self.config.verify_checksums:
if not cover_path.exists():
download_status = 'failed'
logger.error(f"Downloaded file missing: {cover_path}")
# Store cover metadata in database with status
self.db.add_cover(
titleid,
cover_url=cover_url,
file_path=str(cover_path) if cover_path else None,
cover_type=cover.get('CoverType', 'unknown'),
status=download_status,
metadata=cover
)
def _download_updates(self, titleid: str, updates_data: Dict, output_dir: Path):
"""Download title updates and mark as downloaded in database"""
media_list = updates_data.get('MediaIDS', updates_data.get('MediaIDs', []))
if not isinstance(media_list, list):
return
for media in media_list:
if isinstance(media, dict):
media_id = media.get('MediaID')
updates = media.get('Updates', [])
if not isinstance(updates, list):
continue
for update in updates:
if isinstance(update, dict):
tuid = update.get('TitleUpdateID')
version = update.get('Version', 'unknown')
if tuid:
# Construct the update download URL
update_url = f"{self.config.base_url}/Resources/Lib/TitleUpdate.php?tuid={tuid}"
update_dir = output_dir / str(media_id) / f"version_{version}"
filename = f"update_{tuid}.bin"
file_path = update_dir / filename
# Check for duplicates (feature 8)
if file_path.exists():
existing_hash = self.downloader.calculate_checksum(file_path)
temp_path = file_path.parent / f"{file_path.name}.tmp"
self.download_file(update_url, temp_path)
if temp_path.exists():
new_hash = self.downloader.calculate_checksum(temp_path)
if existing_hash == new_hash:
logger.info(f"Update {tuid} already exists (duplicate)")
temp_path.unlink()
download_status = 'downloaded'
file_path = file_path # Keep existing
else:
temp_path.rename(file_path)
download_status = 'downloaded'
else:
download_status = 'failed'
else:
success = self.download_file(update_url, file_path)
download_status = 'downloaded' if success else 'failed'
# Verify checksum if enabled (feature 5)
if download_status == 'downloaded' and self.config.verify_checksums:
if not file_path.exists():
download_status = 'failed'
logger.error(f"Downloaded file missing: {file_path}")
# Store update metadata in database with status
self.db.add_title_update(
titleid,
media_id=str(media_id),
version=str(version),
download_url=update_url,
file_path=str(file_path) if file_path else None,
metadata=update,
status=download_status
)
def process_multiple_titleids(self, titleids: List[str]):
"""Process multiple TitleIDs with parallel workers"""
valid_titleids = [tid for tid in titleids if self.validate_titleid(tid)]
if not valid_titleids:
logger.error("No valid TitleIDs to process")
return
logger.info(f"Processing {len(valid_titleids)} TitleIDs with {self.config.workers} workers")
with ThreadPoolExecutor(max_workers=self.config.workers) as executor:
futures = {executor.submit(self.process_titleid, tid): tid for tid in valid_titleids}
for future in as_completed(futures):
titleid = futures[future]
try:
future.result()
except Exception as e:
logger.error(f"Error processing {titleid}: {e}")
def retry_failed_downloads(self, titleid: Optional[str] = None):
"""Retry all failed downloads (feature 2)"""
logger.info(f"{'='*60}")
logger.info(f"Retrying failed downloads{f' for {titleid}' if titleid else ''}")
logger.info(f"{'='*60}")
failed_items = self.db.get_failed_items(titleid)
if not failed_items:
logger.info("No failed items to retry")
return
logger.info(f"Found {len(failed_items)} failed items to retry")
for item in failed_items:
try:
if item['type'] == 'cover':
success = self.download_file(item['url'], Path(item['url'].split('/')[-1]))
if success:
self.db.mark_for_retry('cover', item['id'])
logger.info(f"Retried cover {item['id']}: SUCCESS")
else:
logger.warning(f"Retried cover {item['id']}: FAILED")
elif item['type'] == 'update':
success = self.download_file(item['url'], Path(item['url'].split('/')[-1]))
if success:
self.db.mark_for_retry('update', item['id'])
logger.info(f"Retried update {item['id']}: SUCCESS")
else:
logger.warning(f"Retried update {item['id']}: FAILED")
except Exception as e:
logger.error(f"Error retrying {item['type']} {item['id']}: {e}")
logger.info("Retry operation completed")
def export_database(self, format: str = 'json', output_file: Optional[str] = None):
"""Export database to JSON or CSV (feature 4)"""
if not output_file:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = f"export_{timestamp}.{format}"
logger.info(f"Exporting database to {format.upper()}: {output_file}")
if format == 'json':
self.db.export_to_json(output_file)
elif format == 'csv':
self.db.export_to_csv(output_file)
else:
logger.error(f"Unknown export format: {format}")
return
logger.info(f"Export completed: {output_file}")
def main():
configure_logging()
parser = argparse.ArgumentParser(
description='UnityScraper - Download Xbox 360 content from XboxUnity',
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'titleids',
nargs='*',
help='Comma-separated TitleIDs (e.g., 555308C5,00000155)'
)
parser.add_argument(
'--out',
type=str,
help='Output directory (default: unityscrape)'
)
parser.add_argument(
'--workers',
type=int,
help='Number of parallel workers (default: 4)'
)
parser.add_argument(
'--rate',
type=float,
help='Minimum seconds between requests (default: 0.35)'
)
parser.add_argument(
'--config',
type=str,
help='Path to config.json file'
)
parser.add_argument(
'--save-config',
action='store_true',
help='Save current settings to config.json'
)
parser.add_argument(
'--log-level',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
default='INFO',
help='Logging level'
)
parser.add_argument(
'--force-http',
action='store_true',
help='Use XboxUnity HTTP endpoints (always enabled)'
)
parser.add_argument(
'--metadata-only',
action='store_true',
help='Only collect metadata without downloading files'
)
parser.add_argument(
'--retry-failed',
action='store_true',
help='Retry all failed downloads'
)
parser.add_argument(
'--estimate-size',
action='store_true',
help='Estimate download size before downloading'
)
parser.add_argument(
'--verify-checksums',
action='store_true',
help='Verify checksums after download'
)
parser.add_argument(
'--bandwidth-limit',
type=int,
default=0,
help='Bandwidth limit in KB/s (0 = unlimited)'
)
parser.add_argument(
'--export',
type=str,
choices=['json', 'csv'],
help='Export database to JSON or CSV'
)
parser.add_argument(
'--export-file',
type=str,
help='Export output file path'
)
parser.add_argument(
'--cleanup',
action='store_true',
help='Clean up old download history'
)
parser.add_argument(
'--cleanup-days',
type=int,
default=90,
help='Days of history to keep (default: 90)'
)
parser.add_argument(
'--dry-run',
action='store_true',
help='Simulate downloads without saving files'
)
parser.add_argument(
'--refresh-metadata',
type=str,
help='Refresh metadata for specific TitleIDs'
)
parser.add_argument(
'--refresh-interval',
type=int,
default=0,
help='Days between automatic refreshes (0 = disabled)'
)
parser.add_argument(
'--verify-integrity',
action='store_true',
help='Verify checksums of downloaded files'
)
parser.add_argument(
'--api-mode',
action='store_true',
help='Start REST API server instead of CLI mode'
)
parser.add_argument(
'--api-port',
type=int,
default=8000,
help='API server port (default: 8000)'
)
parser.add_argument(
'--api-host',
type=str,
default='127.0.0.1',
help='API server host (default: 127.0.0.1)'
)
parser.add_argument(
'--api-token',
type=str,
default=None,
help=(
'API authentication token; prefer the UNITYSCRAPER_API_TOKEN '
'environment variable'
)
)
parser.add_argument(
'--sync-title-catalog',
action='store_true',
help='Refresh the local XboxUnity title-name catalog for offline autocomplete'
)
parser.add_argument(
'--sync-knowledge',
action='store_true',
help='Import ConsoleMods knowledge data and enrich unknown library metadata'
)
parser.add_argument(
'--sync-wikis',
action='store_true',
help='Cache and index ConsoleMods, XenonLibrary, and Free60 wiki articles'
)
parser.add_argument(
'--wiki-limit',
type=int,
default=None,
help='Optional maximum article count per wiki source'
)
parser.add_argument(
'--build-offline-knowledge',
action='store_true',
help='Build a private offline HTML library from cached wiki pages'
)
parser.add_argument(
'--import-saved-wiki',
type=str,
help='Import a browser-saved HTML page, folder, or ZIP archive'
)
parser.add_argument(
'--saved-wiki-source',
choices=['consolemods-wiki', 'xenonlibrary', 'free60'],
help='Source attribution required by --import-saved-wiki'
)
parser.add_argument(
'--import-dat',
type=str,
help='Import a local Redump or No-Intro XML DAT file'
)
parser.add_argument(
'--dat-source',
choices=['redump', 'no-intro'],
help='Source type for --import-dat'
)
parser.add_argument('--search-all', type=str,
help='Search games, knowledge, profiles, saves, files, and tools')
parser.add_argument('--extract-knowledge', action='store_true',
help='Extract structured records from locally cached wiki documents')
parser.add_argument('--audit-storage', type=str,
help='Inspect a mounted storage path or image read-only')
parser.add_argument('--scan-original-xbox', type=str,
help='Index original Xbox default.xbe files below a folder')
parser.add_argument('--dedup-preview', type=str,
help='Create a checksum-based duplicate preview for a folder')
parser.add_argument('--dedup-apply', type=int,
help='Apply one previewed duplicate action by ID')
parser.add_argument('--dedup-restore', type=int,
help='Restore one quarantined duplicate action by ID')
parser.add_argument('--dedup-mode', choices=['quarantine', 'hardlink'],
default='quarantine', help='Action used with --dedup-apply')
parser.add_argument('--metadata-snapshot-export', type=str,
help='Export portable source-attributed metadata to a .usmeta file')
parser.add_argument('--metadata-snapshot-import', type=str,
help='Merge a portable .usmeta snapshot without personal data')
parser.add_argument('--library-audit', action='store_true',
help='Report missing names, publishers, covers, updates, and MediaIDs')
parser.add_argument('--preservation-report', type=str,
help='Export a privacy-conscious HTML preservation report')
parser.add_argument('--corrections-export', type=str,
help='Export reviewed local metadata corrections as JSON')
parser.add_argument('--extract-stfs', type=str,
help='Extract supported files read-only from an STFS package')
parser.add_argument('--extract-destination', type=str,
help='Destination folder required by --extract-stfs')
parser.add_argument(
'--scan-backups',
type=str,
help='Inventory an Xbox content, USB, or archive folder'
)
parser.add_argument(
'--backup-report',
type=str,