|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Shared provider branding layer used by every reconstructed NiakVIO provider. |
| 3 | +
|
| 4 | +Provider artwork stays in the native scraper.logo field. Until Nuvio exposes that |
| 5 | +logo on local stream rows, one committed emoji per provider gives the textual |
| 6 | +stream title a stable visual identity. The mapping is data-only and shared by all |
| 7 | +providers; no provider bundle owns its own presentation exception. |
| 8 | +""" |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import hashlib |
| 12 | +import json |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any |
| 15 | + |
| 16 | +MARKER = "NUVIO_GLOBAL_PROVIDER_BRANDING_V1" |
| 17 | +ROOT = Path(__file__).resolve().parents[2] |
| 18 | +BRANDING = ROOT / "assets" / "providers" / "emojis.json" |
| 19 | + |
| 20 | + |
| 21 | +def _load_provider(provider_id: str) -> dict[str, str]: |
| 22 | + payload = json.loads(BRANDING.read_text(encoding="utf-8")) |
| 23 | + if payload.get("policy") != "committed-provider-default-emoji": |
| 24 | + raise ValueError("provider emoji map must declare committed-provider-default-emoji policy") |
| 25 | + providers = payload.get("providers") |
| 26 | + if not isinstance(providers, dict): |
| 27 | + raise ValueError("provider emoji map providers must be an object") |
| 28 | + row = providers.get(str(provider_id or "").strip().casefold()) |
| 29 | + if not isinstance(row, dict): |
| 30 | + raise ValueError(f"provider emoji map is missing {provider_id}") |
| 31 | + name = str(row.get("name") or "").strip() |
| 32 | + emoji = str(row.get("emoji") or "").strip() |
| 33 | + if not name or not emoji: |
| 34 | + raise ValueError(f"provider emoji map row is incomplete: {provider_id}") |
| 35 | + return {"name": name, "emoji": emoji} |
| 36 | + |
| 37 | + |
| 38 | +def _strip_existing(text: str) -> str: |
| 39 | + start = text.find(f"/* {MARKER}:") |
| 40 | + if start < 0: |
| 41 | + return text |
| 42 | + call = text.find('})(typeof globalThis!=="undefined"?globalThis:this,', start) |
| 43 | + end = text.find(");", call) if call >= 0 else -1 |
| 44 | + if call < 0 or end < 0: |
| 45 | + raise ValueError("unterminated global provider branding wrapper") |
| 46 | + return (text[:start] + text[end + 2 :]).rstrip() |
| 47 | + |
| 48 | + |
| 49 | +def apply(text: str, options: dict[str, Any] | None = None, **kwargs: Any) -> str: |
| 50 | + context = kwargs.get("context") if isinstance(kwargs.get("context"), dict) else {} |
| 51 | + provider_id = str(context.get("provider_id") or "").strip().casefold() |
| 52 | + if not provider_id: |
| 53 | + # Synthetic tests that do not represent a published provider must remain |
| 54 | + # valid without inventing branding data. |
| 55 | + return text |
| 56 | + try: |
| 57 | + row = _load_provider(provider_id) |
| 58 | + except ValueError: |
| 59 | + # The global hook also runs in synthetic Core tests. Published coverage is |
| 60 | + # fail-closed separately by the branding contract test and normalizer. |
| 61 | + if provider_id.startswith("synthetic-"): |
| 62 | + return text |
| 63 | + raise |
| 64 | + |
| 65 | + payload = { |
| 66 | + "providerId": provider_id, |
| 67 | + "providerName": row["name"], |
| 68 | + "providerEmoji": row["emoji"], |
| 69 | + "implementationRevision": "committed-emoji-stream-label-v1", |
| 70 | + } |
| 71 | + serialized = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) |
| 72 | + marker = f"{MARKER}:{hashlib.sha256(serialized.encode('utf-8')).hexdigest()[:12]}" |
| 73 | + text = _strip_existing(text) |
| 74 | + |
| 75 | + wrapper = r''' |
| 76 | +/* MARKER_PLACEHOLDER */ |
| 77 | +;(function(g,c){"use strict"; |
| 78 | +function slot(v){if(Array.isArray(v))return{key:null,list:v};if(v&&typeof v==="object"){for(var i=0;i<3;i++){var k=["streams","results","data"][i];if(Array.isArray(v[k]))return{key:k,list:v[k]}}}return null} |
| 79 | +function rebuild(v,x,list){if(x.key===null)return list;var o=Object.assign({},v);o[x.key]=list;return o} |
| 80 | +function label(){return String(c.providerEmoji||"").trim()+" "+String(c.providerName||c.providerId||"Source").trim()} |
| 81 | +function brand(r){if(!r||typeof r!=="object")return r;var o=Object.assign({},r),v=label().trim();if(v)o.name=v;return o} |
| 82 | +function install(o,k){if(!o||typeof o[k]!=="function"||o[k].__nuvioGlobalProviderBrandingV1)return false;var native=o[k];var wrap=async function(){var v=await native.apply(this,arguments),x=slot(v);if(!x||!x.list.length)return v;return rebuild(v,x,x.list.map(brand))};wrap.__nuvioGlobalProviderBrandingV1=true;o[k]=wrap;return true} |
| 83 | +var ok=false;try{if(typeof module!=="undefined"&&module.exports){ok=install(module.exports,"getStreams")||install(module.exports,"streams")}}catch(_e){}try{if(g&&typeof g.getStreams==="function"){if(ok&&typeof module!=="undefined"&&module.exports)g.getStreams=module.exports.getStreams;else install(g,"getStreams")}}catch(_e){} |
| 84 | +})(typeof globalThis!=="undefined"?globalThis:this,CONFIG_PLACEHOLDER); |
| 85 | +'''.replace("MARKER_PLACEHOLDER", marker).replace("CONFIG_PLACEHOLDER", serialized) |
| 86 | + return text.rstrip() + "\n" + wrapper.strip() + "\n" |
0 commit comments