diff --git a/scripts/acquire/fetch.py b/scripts/acquire/fetch.py index e86e7da5f..086f272bd 100644 --- a/scripts/acquire/fetch.py +++ b/scripts/acquire/fetch.py @@ -242,8 +242,34 @@ def step3b_software_heritage(entry: dict) -> bytes | None: return None +def archive_org_by_sha1(sha1: str) -> bytes | None: + """The first archive.org file whose metadata names sha1, read and checked. + + The member is chosen by its recorded sha1, never by its name: an item + may store the dump under any path (bios/SCPH1001.BIN for scph1001.bin). + """ + search = ("https://archive.org/advancedsearch.php?q=" + f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5") + docs = _get_json(search).get("response", {}).get("docs", []) + for doc in docs: + identifier = doc.get("identifier") + if not identifier: + continue + files = _get_json(f"https://archive.org/metadata/{identifier}/files").get("result", []) + for item in files: + if str(item.get("sha1", "")).lower() != sha1: + continue + url = (f"https://archive.org/download/{identifier}/" + f"{urllib.parse.quote(item['name'])}") + data = _get(url, timeout=60) + if data is not None and hashlib.sha1(data).hexdigest() == sha1: + return data + return None + + def step4_search_archive_org(entry: dict) -> bytes | None: - """Search archive.org firmware collections by direct download.""" + """Search archive.org firmware collections by direct download, then + every item by each accepted sha1.""" name = entry["name"] for collection_id in ARCHIVE_ORG_COLLECTIONS: @@ -252,21 +278,8 @@ def step4_search_archive_org(entry: dict) -> bytes | None: if data is not None and verify_content(data, entry): return data - sha1s = sorted(parse_hash_list(entry.get("sha1"))) - if not sha1s: - return None - # Each accepted revision is a query of its own: archive.org matches one. - sha1 = " OR ".join(f"sha1:{value}" for value in sha1s) - - search_url = ( - "https://archive.org/advancedsearch.php?q=" - f"{urllib.parse.quote(sha1)}&output=json&rows=1" - ) - - docs = _get_json(search_url).get("response", {}).get("docs", []) - identifier = docs[0].get("identifier") if docs else None - if identifier: - data = _get(f"https://archive.org/download/{identifier}/{name}") + for sha1 in sorted(parse_hash_list(entry.get("sha1"))): + data = archive_org_by_sha1(sha1) if data is not None and verify_content(data, entry): return data return None @@ -435,7 +448,7 @@ def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False) -> int: data = step3b_software_heritage(entry) where = "Software Heritage" if data is None: - data, where = _archive_org_by_sha1(sha1), "archive.org" + data, where = archive_org_by_sha1(sha1), "archive.org" if data is None: note = f", {len(_UNANSWERED)} source(s) did not answer" if _UNANSWERED else "" print(f" {sha1}: not found{note}") @@ -448,25 +461,6 @@ def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False) -> int: return 1 if missing else 0 -def _archive_org_by_sha1(sha1: str) -> bytes | None: - """The first archive.org file whose metadata names sha1, read and checked.""" - search = ("https://archive.org/advancedsearch.php?q=" - f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5") - docs = _get_json(search).get("response", {}).get("docs", []) - for doc in docs: - identifier = doc.get("identifier") - files = _get_json(f"https://archive.org/metadata/{identifier}/files").get("result", []) - for item in files: - if str(item.get("sha1", "")).lower() != sha1: - continue - url = (f"https://archive.org/download/{identifier}/" - f"{urllib.parse.quote(item['name'])}") - data = _get(url, timeout=60) - if data is not None and hashlib.sha1(data).hexdigest() == sha1: - return data - return None - - CONTRIBUTING_URL = "https://github.com/Abdess/retrobios/blob/main/CONTRIBUTING.md" diff --git a/tests/test_auto_fetch_lookup.py b/tests/test_auto_fetch_lookup.py index 1e5810741..552094356 100644 --- a/tests/test_auto_fetch_lookup.py +++ b/tests/test_auto_fetch_lookup.py @@ -161,6 +161,51 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase): self.assertEqual(len(asked), 2) +class ArchiveOrgAnswersByHash(unittest.TestCase): + """The platform search asked archive.org for the first item and then + downloaded the platform's name from it: an item storing the dump under + another path was a 404, and the file went to the issue asking the public + for it while --sha1 found it.""" + + def setUp(self): + fetch._UNANSWERED.clear() + self.addCleanup(fetch._UNANSWERED.clear) + + def _archive(self): + import json + + return _serving({ + "https://archive.org/advancedsearch.php": json.dumps( + {"response": {"docs": [{"identifier": "psx-bios"}]}}).encode(), + "https://archive.org/metadata/psx-bios/files": json.dumps( + {"result": [{"name": "readme.txt", "sha1": "0" * 40}, + {"name": "bios/SCPH1001.BIN", "sha1": SHA1}]}).encode(), + "https://archive.org/download/psx-bios/bios/SCPH1001.BIN": PAYLOAD, + }) + + def test_the_member_is_found_by_its_sha1_whatever_its_name(self): + urlopen, asked = self._archive() + with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen): + data = fetch.step4_search_archive_org( + {"name": "scph1001.bin", "sha1": SHA1.upper()}) + self.assertEqual(data, PAYLOAD) + self.assertNotIn("https://archive.org/download/psx-bios/scph1001.bin", asked) + + def test_the_platform_search_and_the_sha1_search_agree(self): + urlopen, _asked = self._archive() + with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen): + by_platform = fetch.step4_search_archive_org({"name": "scph1001.bin", "sha1": SHA1}) + by_sha1 = fetch.archive_org_by_sha1(SHA1) + self.assertEqual((by_platform, by_sha1), (PAYLOAD, PAYLOAD)) + + def test_a_declared_md5_still_has_to_hold(self): + urlopen, _asked = self._archive() + with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen): + data = fetch.step4_search_archive_org( + {"name": "scph1001.bin", "sha1": SHA1, "md5": "f" * 32}) + self.assertIsNone(data) + + class OptionalDatabase(unittest.TestCase): """auto_fetch --sha1 read a mistyped --db as an empty collection and asked Software Heritage for a file already held."""