Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / shop / generate_merchant_links.py

generate_merchant_links.py89 lines · 3.5 KiBRaw
1#!/usr/bin/env python3
2"""Regenerate the Shop app's merchant link intent-filter from the upstream directory.
3
4Android only lets an app become the default handler for web links whose hosts are
5declared in the manifest. Merchant sites can't host our assetlinks.json, so the
6filter is unverified and users approve it once in "Open by default".
7
8Source: the server's own upstream merchant directory (UCPList) — the same feed
9the server merges for search-time merchant matching. It returns a bare JSON
10array of listing objects; the merchant host is derived from each listing's
11`ucpEndpoint` (falling back to `url`), and `ucpStatus` names its standing.
12
13Rerun before each release: python3 scripts/shop/generate_merchant_links.py
14"""
15
16import json
17import pathlib
18import re
19import sys
20import urllib.parse
21import urllib.request
22
23DIRECTORY_URL = "https://ucplist.ai/api/listings?category=merchants"
24MANIFEST = pathlib.Path(__file__).resolve().parents[2] / "shop/src/main/AndroidManifest.xml"
25BEGIN = "<!-- BEGIN MERCHANT LINKS (generated by scripts/shop/generate_merchant_links.py) -->"
26END = "<!-- END MERCHANT LINKS -->"
27HOST = re.compile(r"^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$")
28INDENT = " " * 12
29
30
31def fetch_domains() -> list[str]:
32 request = urllib.request.Request(
33 DIRECTORY_URL, headers={"Accept": "application/json", "User-Agent": "ModernApps-build/1.0"}
34 )
35 with urllib.request.urlopen(request, timeout=60) as response:
36 listings = json.load(response)
37 if isinstance(listings, dict):
38 listings = listings.get("merchants", [])
39 hosts = set()
40 for merchant in listings:
41 if not isinstance(merchant, dict):
42 continue
43 # Only the curated UCPList entries ("live"/"announced"); the ~10k directly verified
44 # seed stores ("verified") would make Android's open-by-default list unusable.
45 if merchant.get("ucpStatus") == "verified":
46 continue
47 endpoint = str(merchant.get("ucpEndpoint") or merchant.get("url") or "")
48 domain = urllib.parse.urlparse(endpoint).hostname or ""
49 domain = domain.strip().lower()
50 if not HOST.match(domain):
51 continue
52 bare = domain.removeprefix("www.")
53 hosts.update({bare, f"www.{bare}"})
54 return sorted(hosts)
55
56
57def render(hosts: list[str]) -> str:
58 lines = [
59 BEGIN,
60 '<intent-filter android:autoVerify="false" tools:ignore="AppLinkUrlError,AppLinkWarning">',
61 ' <action android:name="android.intent.action.VIEW" />',
62 ' <category android:name="android.intent.category.DEFAULT" />',
63 ' <category android:name="android.intent.category.BROWSABLE" />',
64 ' <data android:scheme="https" />',
65 ' <data android:scheme="http" />',
66 *[f' <data android:host="{host}" />' for host in hosts],
67 "</intent-filter>",
68 END,
69 ]
70 return "\n".join(INDENT + line for line in lines)
71
72
73def main() -> int:
74 hosts = fetch_domains()
75 if not hosts:
76 print("Directory returned no usable domains; manifest left unchanged.", file=sys.stderr)
77 return 1
78 text = MANIFEST.read_text()
79 start, end = text.find(INDENT + BEGIN), text.find(END)
80 if start < 0 or end < 0:
81 print(f"Markers not found in {MANIFEST}", file=sys.stderr)
82 return 1
83 MANIFEST.write_text(text[:start] + render(hosts) + text[end + len(END):])
84 print(f"Wrote {len(hosts)} hosts to {MANIFEST}")
85 return 0
86
87
88if __name__ == "__main__":
89 sys.exit(main())