Commit 281749441c

281749441ca32bd3aa039b1627274d2b12f9d3d7

parent: 3ecb71ee10

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-06-09 13:42 UTC

Unified API client for PR check and review report

Layout: unified · split

.github/workflows/health-check.yml +1
@@ -37,6 +37,7 @@ jobs:
3737 continue-on-error: true
3838 env:
3939 GITHUB_TOKEN: ${{ github.token }}
40 API_TOKEN: ${{ secrets.API_TOKEN }}
4041 CATEGORY: ${{ inputs.category }}
4142 SECTION: ${{ inputs.section }}
4243 SERVICE: ${{ inputs.service }}
lib/checks/make-info-stats.py +16 −16
@@ -44,27 +44,14 @@ RESTRICTIVE_LICENSES = {
4444
4545SESSION = utils.make_session(user_agent=USER_AGENT)
4646
47API_URL = os.environ.get("API_URL", "https://api.awesome-privacy.xyz").rstrip("/")
4847API_TOKEN = os.environ.get("API_TOKEN", "")
4948
5049GREEN, ORANGE, RED, BLUE, WHITE = "\U0001f7e2", "\U0001f7e0", "\U0001f534", "\U0001f535", "\u26aa"
5150
5251
53def _api_get(url, params=None, timeout=TIMEOUT, headers=None):
54 """GET a URL, return parsed JSON on 200, else None."""
55 try:
56 resp = SESSION.get(url, headers=headers, timeout=timeout, params=params)
57 if resp.status_code == 200:
58 return resp.json()
59 except Exception as e:
60 logger.warning("Fetch failed for %s: %s", url, e)
61 return None
62
63
6452def _enrich_get(path, params=None, timeout=TIMEOUT):
65 """GET an enrichment endpoint on the unified API, adding auth when configured."""
66 headers = {"Authorization": f"Bearer {API_TOKEN}"} if API_TOKEN else None
67 return _api_get(f"{API_URL}/v1/enrich/{path}", params=params, headers=headers, timeout=timeout)
53 """GET a unified-API enrichment endpoint with this script's session and token."""
54 return utils.enrich_get(path, params=params, token=API_TOKEN, session=SESSION, timeout=timeout)
6855
6956
7057def relative_time(iso_str):
@@ -271,7 +258,7 @@ def grade_stats(data):
271258 if adv is None:
272259 stats.append((WHITE, "Security Advisories", "Unknown"))
273260 elif adv > 0:
274 stats.append((ORANGE, "Security Advisories", f"{adv} unpatched CVEs"))
261 stats.append((ORANGE, "Security Advisories", f"{adv} potentially unpatched CVEs"))
275262 else:
276263 stats.append((GREEN, "Security Advisories", "No unpatched active CVEs found"))
277264
@@ -421,6 +408,14 @@ def fetch_android_data(package_id):
421408 return data if data and not data.get("error") else None
422409
423410
411_DEGOOGLED = {
412 "gold": (GREEN, "Gold (works)"),
413 "silver": (GREEN, "Silver (minor issues)"),
414 "bronze": (ORANGE, "Bronze (limited)"),
415 "broken": (RED, "Broken"),
416}
417
418
424419def grade_android_stats(data):
425420 """Grade Android app stats."""
426421 stats = []
@@ -443,6 +438,11 @@ def grade_android_stats(data):
443438 stats.append(_info_or_unknown("Created", _friendly_date(data.get("created"))))
444439 stats.append(_info_or_unknown("Last Updated", _friendly_date(data.get("updated"))))
445440
441 status = utils.degoogled_status(data)
442 if status:
443 color, label = _DEGOOGLED.get(status, (BLUE, status.title()))
444 stats.append((color, "De-Googled", label))
445
446446 return stats
447447
448448
lib/review-listings.py +196 −32
@@ -6,10 +6,10 @@ Checks:
66- https-url: homepage URL uses HTTPS
77- icon-reachable: icon URL does not 404
88- description-len: description is 50 to 280 chars (over 420 escalates to warn)
9- opensource-github: openSource listings include a github, codeberg or git field
9- opensource-github: openSource listings include a repo link (error); not open source is noted (info)
1010- duplicate-url: no URL appears in more than one listing
1111- androidApp-valid: androidApp is a package name, not a URL
12- iosApp-reachable: App Store URL resolves
12- iosApp-valid: iosApp is a valid App Store URL with an app id
1313- subreddit-exists: subreddit page exists on reddit.com
1414- tosdr-valid: tosdrId still resolves on tosdr.org
1515- discord-invite-valid: Discord invite code is still valid
@@ -18,10 +18,16 @@ Checks:
1818- github-activity: github repo was pushed recently (needs token)
1919- github-license: github repo has a license (needs token)
2020- github-fork: github repo is not a fork (needs token)
21- security-advisories: no open unpatched CVEs (needs API_TOKEN)
22- android-trackers: android app has few trackers (1 info, 2+ warn) (needs API_TOKEN)
23- ios-app: iOS app exists, is maintained and rated (missing/stale/low-rating warn) (needs API_TOKEN)
24- degoogled-compat: android app works on de-googled android (needs API_TOKEN)
25- privacy-grade: tosdr privacy grade is B or better (C info, D/E warn) (needs API_TOKEN)
2126
2227Findings have three severities: error (must fix), warn (should review), info (FYI).
2328HTTP 403/406/429 (and 404 on known bot-blocking hosts such as play.google.com) on
24reachability checks is demoted from error to warn.
29reachability checks means the probe was rate-limited or blocked, not that the resource is
30missing, so it is logged during the run but left out of the results.
2531
2632Exit codes:
2733 1 when pass rate drops below FAIL_PASS_RATE or errors exceed FAIL_MAX_ERRORS (5)
@@ -52,7 +58,7 @@ import sys
5258from concurrent.futures import ThreadPoolExecutor, as_completed
5359from dataclasses import asdict, dataclass, field
5460from datetime import datetime, timezone
55from threading import Lock
61from threading import Lock, local
5662from time import monotonic
5763from typing import Callable, Iterable
5864from urllib.parse import urlparse
@@ -111,12 +117,26 @@ class Finding:
111117
112118@dataclass
113119class Context:
114 session: object
115120 token: str
116121 timeout: int
122 api_token: str = ""
117123 url_occurrences: dict = field(default_factory=dict)
118124 repo_cache: dict = field(default_factory=dict)
125 security_cache: dict = field(default_factory=dict)
126 android_cache: dict = field(default_factory=dict)
127 privacy_cache: dict = field(default_factory=dict)
128 ios_cache: dict = field(default_factory=dict)
119129 repo_lock: Lock = field(default_factory=Lock)
130 _sessions: local = field(default_factory=local)
131
132 @property
133 def session(self):
134 """Per-thread session, since a requests.Session is not safe to share across threads."""
135 session = getattr(self._sessions, "value", None)
136 if session is None:
137 session = utils.make_session()
138 self._sessions.value = session
139 return session
120140
121141
122142@dataclass
@@ -124,6 +144,7 @@ class CheckSpec:
124144 name: str
125145 scope: str
126146 needs_github: bool
147 needs_api: bool
127148 fn: Callable
128149 doc: str
129150
@@ -131,9 +152,11 @@ class CheckSpec:
131152CHECKS: dict[str, CheckSpec] = {}
132153
133154
134def check(name, *, scope="service", needs_github=False):
155def check(name, *, scope="service", needs_github=False, needs_api=False):
135156 def deco(fn):
136 CHECKS[name] = CheckSpec(name, scope, needs_github, fn, (fn.__doc__ or "").strip())
157 CHECKS[name] = CheckSpec(
158 name, scope, needs_github, needs_api, fn, (fn.__doc__ or "").strip()
159 )
137160 return fn
138161 return deco
139162
@@ -160,21 +183,74 @@ def _get_repo(entry: Entry, ctx: Context):
160183 return data
161184
162185
163def _unreachable(field, url, status, default_sev):
164 """Return (severity, message). Bot-blocking signatures demote error to warn."""
165 host = urlparse(url).netloc.lower()
166 soft = status in _SOFT_HTTP or (status == 404 and host in _SOFT_404_HOSTS)
167 sev = "warn" if default_sev == "error" and soft else default_sev
168 detail = f"{url} returned HTTP {status}" if status else f"{url} could not be reached"
169 return sev, f"{field} is unreachable, {detail}"
186def _get_security_report(entry: Entry, ctx: Context):
187 owner, repo = utils.parse_github_field(entry.service.get("github"))
188 if not owner:
189 return None
190 key = f"{owner}/{repo}"
191 with ctx.repo_lock:
192 if key in ctx.security_cache:
193 return ctx.security_cache[key]
194 data = utils.fetch_security_report(owner, repo, ctx.api_token,
195 session=ctx.session, label=entry.name)
196 with ctx.repo_lock:
197 ctx.security_cache[key] = data
198 return data
199
200
201def _get_android(entry: Entry, ctx: Context):
202 pkg = entry.service.get("androidApp")
203 if not pkg:
204 return None
205 with ctx.repo_lock:
206 if pkg in ctx.android_cache:
207 return ctx.android_cache[pkg]
208 data = utils.fetch_android_app(pkg, ctx.api_token, session=ctx.session, label=entry.name)
209 with ctx.repo_lock:
210 ctx.android_cache[pkg] = data
211 return data
212
213
214def _get_privacy(entry: Entry, ctx: Context):
215 tid = entry.service.get("tosdrId")
216 if not tid:
217 return None
218 key = str(tid)
219 with ctx.repo_lock:
220 if key in ctx.privacy_cache:
221 return ctx.privacy_cache[key]
222 data = utils.fetch_privacy(tid, ctx.api_token, session=ctx.session, label=entry.name)
223 with ctx.repo_lock:
224 ctx.privacy_cache[key] = data
225 return data
226
227
228def _get_ios(entry: Entry, ctx: Context):
229 """Return (report, http_status) for the listing's iOS app, both None if no valid id."""
230 app_id = utils.ios_app_id(entry.service.get("iosApp"))
231 if not app_id:
232 return None, None
233 with ctx.repo_lock:
234 if app_id in ctx.ios_cache:
235 return ctx.ios_cache[app_id]
236 result = utils.fetch_ios(entry.service.get("iosApp"), ctx.api_token,
237 session=ctx.session, label=entry.name, return_status=True)
238 with ctx.repo_lock:
239 ctx.ios_cache[app_id] = result
240 return result
170241
171242
172243def _reachability_finding(entry, check_name, field, url, default_sev, ctx):
173244 ok, status = utils.check_url(url, ctx.session, ctx.timeout)
174245 if ok:
175246 return None
176 sev, msg = _unreachable(field, url, status, default_sev)
177 return _finding(entry, check_name, sev, msg)
247 host = urlparse(url).netloc.lower()
248 if status in _SOFT_HTTP or (status == 404 and host in _SOFT_404_HOSTS):
249 # Rate-limited or bot-blocked probe, inconclusive so log it but do not report
250 logging.info("%s for %s inconclusive (HTTP %s) possibly just rate-limited/blocked", check_name, url, status)
251 return None
252 detail = f"{url} returned HTTP {status}" if status else f"{url} could not be reached"
253 return _finding(entry, check_name, default_sev, f"{field} is unreachable, {detail}")
178254
179255
180256@check("url-reachable")
@@ -222,14 +298,16 @@ def _description_len(entry: Entry, ctx: Context) -> Iterable[Finding]:
222298
223299@check("opensource-github")
224300def _opensource_github(entry: Entry, ctx: Context) -> Iterable[Finding]:
225 """openSource: true services must include a github, codeberg or git field."""
301 """openSource: true needs a repo link (error); not open source is noted (info)."""
226302 svc = entry.service
227 if svc.get("openSource") is True and not (
228 svc.get("github") or svc.get("codeberg") or svc.get("git")
229 ):
303 has_repo = svc.get("github") or svc.get("codeberg") or svc.get("git")
304 if svc.get("openSource") is True and not has_repo:
230305 yield _finding(entry, "opensource-github", "error",
231 "marked openSource but missing a repository link "
232 "(`github`, `codeberg` or `git`)")
306 "marked openSource but missing a repository link ")
307 elif svc.get("openSource") is False or not has_repo:
308 reason = "openSource is false" if svc.get("openSource") is False else "no repository linked"
309 yield _finding(entry, "opensource-github", "info",
310 f"not open source ({reason})")
233311
234312
235313@check("androidApp-valid")
@@ -241,14 +319,13 @@ def _android_app_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
241319 f"androidApp {val} is not a package name (expected com.example.app)")
242320
243321
244@check("iosApp-reachable")
245def _iosapp_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
246 """iOS App Store link must resolve."""
322@check("iosApp-valid")
323def _iosapp_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
324 """iosApp must be an App Store URL with an app id."""
247325 url = entry.service.get("iosApp")
248 if url:
249 f = _reachability_finding(entry, "iosApp-reachable", "iosApp", url, "warn", ctx)
250 if f:
251 yield f
326 if url and not utils.ios_app_id(url):
327 yield _finding(entry, "iosApp-valid", "warn",
328 f"iosApp {url} is not a valid App Store URL (expected .../idNNNN)")
252329
253330
254331@check("subreddit-exists")
@@ -344,6 +421,81 @@ def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]:
344421 yield _finding(entry, "github-license", "warn", "repository has no declared license")
345422
346423
424@check("security-advisories", needs_api=True)
425def _security_advisories(entry: Entry, ctx: Context) -> Iterable[Finding]:
426 """No open unpatched CVEs (low/medium warn, high/critical error)."""
427 if not entry.service.get("github"):
428 return
429 low_med, high_crit = utils.unpatched_advisories(_get_security_report(entry, ctx))
430 if high_crit:
431 yield _finding(entry, "security-advisories", "error",
432 f"{high_crit} open high/critical "
433 f"advisor{'ies' if high_crit != 1 else 'y'}")
434 if low_med:
435 yield _finding(entry, "security-advisories", "warn",
436 f"{low_med} open low/medium "
437 f"advisor{'ies' if low_med != 1 else 'y'}")
438
439
440@check("android-trackers", needs_api=True)
441def _android_trackers(entry: Entry, ctx: Context) -> Iterable[Finding]:
442 """Android app has few trackers (1 info, 2+ warn)."""
443 if not entry.service.get("androidApp"):
444 return
445 count = utils.tracker_count(_get_android(entry, ctx))
446 if not count:
447 return
448 sev = "info" if count == 1 else "warn"
449 yield _finding(entry, "android-trackers", sev,
450 f"Android app reports {count} tracker{'s' if count != 1 else ''}")
451
452
453@check("ios-app", needs_api=True)
454def _ios_app(entry: Entry, ctx: Context) -> Iterable[Finding]:
455 """iOS app exists, is maintained and rated (missing/stale/<2 stars warn)."""
456 if not utils.ios_app_id(entry.service.get("iosApp")):
457 return
458 report, status = _get_ios(entry, ctx)
459 if status == 404:
460 yield _finding(entry, "ios-app", "warn",
461 "iOS app not found on the App Store (may have been removed)")
462 return
463 days = utils.ios_days_since_update(report)
464 if days is not None and days >= 365:
465 yield _finding(entry, "ios-app", "warn",
466 f"iOS app not updated in over a year (last release {days} days ago)")
467 rating, count = utils.ios_rating(report)
468 if count and rating is not None and rating < 2:
469 yield _finding(entry, "ios-app", "warn",
470 f"iOS app is rated below 2 stars ({rating:.1f} from {count:,} ratings)")
471
472
473@check("degoogled-compat", needs_api=True)
474def _degoogled_compat(entry: Entry, ctx: Context) -> Iterable[Finding]:
475 """Android app works on de-Googled Android (broken warn, limited info)."""
476 if not entry.service.get("androidApp"):
477 return
478 status = utils.degoogled_status(_get_android(entry, ctx))
479 if status == "broken":
480 yield _finding(entry, "degoogled-compat", "warn",
481 "Android app is broken on de-Googled Android")
482 elif status == "bronze":
483 yield _finding(entry, "degoogled-compat", "info",
484 "Android app has limited de-Googled support")
485
486
487@check("privacy-grade", needs_api=True)
488def _privacy_grade(entry: Entry, ctx: Context) -> Iterable[Finding]:
489 """ToS;DR privacy grade is B or better (C info, D/E warn)."""
490 if not entry.service.get("tosdrId"):
491 return
492 grade = utils.privacy_grade(_get_privacy(entry, ctx))
493 if grade == "C":
494 yield _finding(entry, "privacy-grade", "info", "privacy policy has minor concerns")
495 elif grade in ("D", "E"):
496 yield _finding(entry, "privacy-grade", "warn", f"privacy policy has major issues (graded: {grade})")
497
498
347499@check("duplicate-url", scope="global")
348500def _duplicate_url(entries, ctx: Context) -> Iterable[Finding]:
349501 """No two listings share the same homepage URL."""
@@ -375,11 +527,11 @@ def _install_sigint():
375527 signal.signal(signal.SIGINT, handler)
376528
377529
378def build_context(args, data, token):
530def build_context(args, data, token, api_token):
379531 ctx = Context(
380 session=utils.make_session(),
381532 token=token,
382533 timeout=args.timeout,
534 api_token=api_token,
383535 )
384536 for cat, sec, svc in utils.iter_services(data):
385537 url = _normalize_url(svc.get("url"))
@@ -654,11 +806,13 @@ def main():
654806 if args.list_checks:
655807 for name, spec in CHECKS.items():
656808 tag = colors["dim"](" (needs GITHUB_TOKEN)") if spec.needs_github else ""
809 tag += colors["dim"](" (needs API_TOKEN)") if spec.needs_api else ""
657810 print(f" {colors['cyan'](name.ljust(22))} {spec.doc}{tag}")
658811 return
659812
660813 enabled = resolve_enabled(args.only, args.skip)
661814 token = args.token or os.environ.get("GITHUB_TOKEN", "")
815 api_token = os.environ.get("API_TOKEN", "")
662816
663817 if not token:
664818 gh_checks = [n for n in enabled if CHECKS[n].needs_github]
@@ -670,6 +824,16 @@ def main():
670824 )
671825 enabled = [n for n in enabled if not CHECKS[n].needs_github]
672826
827 if not api_token:
828 api_checks = [n for n in enabled if CHECKS[n].needs_api]
829 if api_checks:
830 logging.warning(
831 "API_TOKEN not set, skipping API checks (%s). "
832 "Export API_TOKEN to enable them.",
833 ", ".join(api_checks),
834 )
835 enabled = [n for n in enabled if not CHECKS[n].needs_api]
836
673837 if not enabled:
674838 logging.error("No checks to run after filters.")
675839 sys.exit(2)
@@ -689,7 +853,7 @@ def main():
689853 args.category, args.section, args.service)
690854 sys.exit(2)
691855
692 ctx = build_context(args, data, token)
856 ctx = build_context(args, data, token, api_token)
693857 logging.info("Reviewing %d service(s) with %d check(s): %s",
694858 len(entries), len(enabled), ", ".join(enabled))
695859
lib/utils/__init__.py +29 −2
@@ -8,6 +8,20 @@ imports are skipped there, letting `setup_logging()` work without them.
88from .term import make_colors, setup_logging
99
1010try:
11 from .api import (
12 degoogled_status,
13 enrich_get,
14 fetch_android_app,
15 fetch_ios,
16 fetch_privacy,
17 fetch_security_report,
18 ios_app_id,
19 ios_days_since_update,
20 ios_rating,
21 privacy_grade,
22 tracker_count,
23 unpatched_advisories,
24 )
1125 from .data import DATA_PATH, PROJECT_ROOT, iter_services, load_yaml, slugify
1226 from .github import (
1327 AI_BOT_AUTHORS,
@@ -23,8 +37,9 @@ try:
2337 repo_status,
2438 )
2539 from .http import DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, check_url, make_session
26except ImportError:
27 pass
40except ImportError as exc:
41 if exc.name not in ("requests", "yaml"):
42 raise
2843
2944__all__ = [
3045 "AI_BOT_AUTHORS",
@@ -34,8 +49,18 @@ __all__ = [
3449 "PROJECT_ROOT",
3550 "check_url",
3651 "commit_has_bot",
52 "degoogled_status",
53 "enrich_get",
54 "fetch_android_app",
55 "fetch_ios",
56 "fetch_privacy",
3757 "fetch_repo",
58 "fetch_security_report",
3859 "gh_get",
60 "ios_app_id",
61 "ios_days_since_update",
62 "ios_rating",
63 "privacy_grade",
3964 "iter_services",
4065 "load_yaml",
4166 "make_colors",
@@ -49,4 +74,6 @@ __all__ = [
4974 "repo_status",
5075 "setup_logging",
5176 "slugify",
77 "tracker_count",
78 "unpatched_advisories",
5279]
lib/utils/api.py added +133
@@ -0,0 +1,133 @@
1"""Helpers for the unified Awesome Privacy API (enrichment endpoints)."""
2
3import logging
4import os
5import re
6from datetime import datetime, timezone
7
8from .http import DEFAULT_TIMEOUT, make_session
9
10API_URL = os.environ.get("API_URL", "https://api.awesome-privacy.xyz").rstrip("/")
11
12_HIGH_SEVERITIES = {"high", "critical"}
13_LOW_SEVERITIES = {"low", "medium"}
14
15
16def enrich_get(path, params=None, token=None, session=None, timeout=DEFAULT_TIMEOUT,
17 label=None, return_status=False):
18 """GET a unified-API enrichment endpoint. Returns parsed JSON on 200, else None.
19
20 With return_status=True, returns (data, http_status), where http_status is None on a
21 network error, letting callers tell a genuine 404 apart from a transient failure.
22 """
23 session = session or make_session()
24 headers = {"Authorization": f"Bearer {token}"} if token else None
25 tag = f" ({label})" if label else ""
26 data, status = None, None
27 try:
28 resp = session.get(f"{API_URL}/v1/enrich/{path}",
29 headers=headers, params=params, timeout=timeout)
30 status = resp.status_code
31 if status == 200:
32 try:
33 data = resp.json()
34 except ValueError:
35 logging.warning("[enrich] empty or invalid JSON body for %s%s", path, tag)
36 else:
37 logging.warning("[enrich] HTTP %d for %s%s", status, path, tag)
38 except Exception as exc:
39 logging.warning("[enrich] request error for %s%s: %s", path, tag, exc)
40 return (data, status) if return_status else data
41
42
43def fetch_security_report(owner, repo, token, session=None, timeout=DEFAULT_TIMEOUT, label=None):
44 """Fetch a repo's security report from the unified API. Returns JSON or None."""
45 return enrich_get(f"security/{owner}/{repo}",
46 token=token, session=session, timeout=timeout, label=label)
47
48
49def fetch_android_app(pkg, token, session=None, timeout=DEFAULT_TIMEOUT, label=None):
50 """Fetch an Android app's privacy report from the unified API. Returns JSON or None."""
51 return enrich_get(f"android/{pkg}",
52 token=token, session=session, timeout=timeout, label=label)
53
54
55def fetch_privacy(tosdr_id, token, session=None, timeout=DEFAULT_TIMEOUT, label=None):
56 """Fetch a service's ToS;DR privacy report from the unified API. Returns JSON or None."""
57 return enrich_get(f"privacy/{tosdr_id}",
58 token=token, session=session, timeout=timeout, label=label)
59
60
61def unpatched_advisories(report):
62 """Return (low_medium, high_critical) counts of open, unpatched advisories."""
63 items = (report.get("advisories") or {}).get("items") or [] if report else []
64 low_med = high_crit = 0
65 for adv in items:
66 if adv.get("isPatched"):
67 continue
68 sev = str(adv.get("severity", "")).lower()
69 if sev in _HIGH_SEVERITIES:
70 high_crit += 1
71 elif sev in _LOW_SEVERITIES:
72 low_med += 1
73 return low_med, high_crit
74
75
76def tracker_count(report):
77 """Number of trackers in an Android app report, or None if unavailable."""
78 trackers = report.get("trackers") if report else None
79 return len(trackers) if isinstance(trackers, list) else None
80
81
82def privacy_grade(report):
83 """ToS;DR letter grade for a service (e.g. A to E), or None if absent."""
84 grade = (report or {}).get("rating")
85 return str(grade).upper() if grade else None
86
87
88def degoogled_status(report):
89 """Plexus de-Googled (no microG) status from an android report, or None."""
90 native = ((report or {}).get("degoogled") or {}).get("native") or {}
91 return native.get("status") if native.get("available") else None
92
93
94_IOS_ID_RE = re.compile(r"(?:apps|itunes)\.apple\.com/\S*\bid(\d+)")
95_IOS_COUNTRY_RE = re.compile(r"(?:apps|itunes)\.apple\.com/([a-z]{2})/")
96
97
98def ios_app_id(app_url):
99 """Numeric App Store id from an iosApp URL, or None if not a valid store URL."""
100 match = _IOS_ID_RE.search(app_url or "")
101 return match.group(1) if match else None
102
103
104def fetch_ios(app_url, token, session=None, timeout=DEFAULT_TIMEOUT, label=None,
105 return_status=False):
106 """Fetch iTunes app info for an App Store URL from the unified API, or None."""
107 app_id = ios_app_id(app_url)
108 if not app_id:
109 return (None, None) if return_status else None
110 country = _IOS_COUNTRY_RE.search(app_url or "")
111 return enrich_get(f"ios/{app_id}", params={"country": country.group(1) if country else "us"},
112 token=token, session=session, timeout=timeout, label=label,
113 return_status=return_status)
114
115
116def ios_days_since_update(report):
117 """Days since the iOS app's current version was released, or None."""
118 raw = (report or {}).get("currentVersionReleaseDate")
119 if not raw:
120 return None
121 try:
122 dt = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
123 except ValueError:
124 return None
125 if dt.tzinfo is None:
126 dt = dt.replace(tzinfo=timezone.utc)
127 return (datetime.now(timezone.utc) - dt).days
128
129
130def ios_rating(report):
131 """(averageUserRating, userRatingCount) from an iOS report, each None if absent."""
132 data = report or {}
133 return data.get("averageUserRating"), data.get("userRatingCount")