|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Bundled Extensions Module - Download and bundle extensions from CDN manifest""" |
| 3 | + |
| 4 | +import json |
| 5 | +import sys |
| 6 | +import xml.etree.ElementTree as ET |
| 7 | +from pathlib import Path |
| 8 | +from typing import Dict, List, NamedTuple |
| 9 | + |
| 10 | +import requests |
| 11 | + |
| 12 | +from ...common.context import Context |
| 13 | +from ...common.module import CommandModule, ValidationError |
| 14 | +from ...common.utils import log_info, log_success, log_error |
| 15 | + |
| 16 | + |
| 17 | +class ExtensionInfo(NamedTuple): |
| 18 | + """Extension metadata parsed from update manifest""" |
| 19 | + id: str |
| 20 | + version: str |
| 21 | + codebase: str |
| 22 | + |
| 23 | + |
| 24 | +class BundledExtensionsModule(CommandModule): |
| 25 | + """Download extensions from CDN manifest and create bundled_extensions.json""" |
| 26 | + |
| 27 | + produces = ["bundled_extensions"] |
| 28 | + requires = [] |
| 29 | + description = "Download and bundle extensions from CDN update manifest" |
| 30 | + |
| 31 | + def validate(self, ctx: Context) -> None: |
| 32 | + if not ctx.chromium_src or not ctx.chromium_src.exists(): |
| 33 | + raise ValidationError( |
| 34 | + f"Chromium source directory not found: {ctx.chromium_src}" |
| 35 | + ) |
| 36 | + |
| 37 | + def execute(self, ctx: Context) -> None: |
| 38 | + log_info("\n📦 Bundling extensions from CDN manifest...") |
| 39 | + |
| 40 | + manifest_url = ctx.get_extensions_manifest_url() |
| 41 | + output_dir = self._get_output_dir(ctx) |
| 42 | + |
| 43 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 44 | + log_info(f" Output: {output_dir}") |
| 45 | + |
| 46 | + extensions = self._fetch_and_parse_manifest(manifest_url) |
| 47 | + if not extensions: |
| 48 | + raise RuntimeError("No extensions found in manifest") |
| 49 | + |
| 50 | + log_info(f" Found {len(extensions)} extensions in manifest") |
| 51 | + |
| 52 | + for ext in extensions: |
| 53 | + self._download_extension(ext, output_dir) |
| 54 | + |
| 55 | + self._generate_json(extensions, output_dir) |
| 56 | + |
| 57 | + log_success(f"Bundled {len(extensions)} extensions successfully") |
| 58 | + |
| 59 | + def _get_output_dir(self, ctx: Context) -> Path: |
| 60 | + """Get the bundled extensions output directory in Chromium source""" |
| 61 | + return ctx.chromium_src / "chrome" / "browser" / "browseros" / "bundled_extensions" |
| 62 | + |
| 63 | + def _fetch_and_parse_manifest(self, url: str) -> List[ExtensionInfo]: |
| 64 | + """Fetch XML manifest and parse extension information""" |
| 65 | + log_info(f" Fetching manifest: {url}") |
| 66 | + |
| 67 | + try: |
| 68 | + response = requests.get(url, timeout=30) |
| 69 | + response.raise_for_status() |
| 70 | + except requests.RequestException as e: |
| 71 | + raise RuntimeError(f"Failed to fetch manifest: {e}") |
| 72 | + |
| 73 | + return self._parse_manifest_xml(response.text) |
| 74 | + |
| 75 | + def _parse_manifest_xml(self, xml_content: str) -> List[ExtensionInfo]: |
| 76 | + """Parse Google Update protocol XML manifest |
| 77 | +
|
| 78 | + Expected format (with namespace): |
| 79 | + <gupdate xmlns="http://www.google.com/update2/response" protocol='2.0'> |
| 80 | + <app appid='extension_id'> |
| 81 | + <updatecheck codebase='https://...' version='1.0.0' /> |
| 82 | + </app> |
| 83 | + </gupdate> |
| 84 | + """ |
| 85 | + extensions = [] |
| 86 | + |
| 87 | + try: |
| 88 | + root = ET.fromstring(xml_content) |
| 89 | + except ET.ParseError as e: |
| 90 | + raise RuntimeError(f"Failed to parse manifest XML: {e}") |
| 91 | + |
| 92 | + ns = {"gupdate": "http://www.google.com/update2/response"} |
| 93 | + |
| 94 | + # Try with namespace first, then without (for flexibility) |
| 95 | + apps = root.findall(".//gupdate:app", ns) |
| 96 | + if not apps: |
| 97 | + apps = root.findall(".//app") |
| 98 | + |
| 99 | + for app in apps: |
| 100 | + app_id = app.get("appid") |
| 101 | + if not app_id: |
| 102 | + continue |
| 103 | + |
| 104 | + updatecheck = app.find("gupdate:updatecheck", ns) |
| 105 | + if updatecheck is None: |
| 106 | + updatecheck = app.find("updatecheck") |
| 107 | + if updatecheck is None: |
| 108 | + continue |
| 109 | + |
| 110 | + version = updatecheck.get("version") |
| 111 | + codebase = updatecheck.get("codebase") |
| 112 | + |
| 113 | + if version and codebase: |
| 114 | + extensions.append(ExtensionInfo( |
| 115 | + id=app_id, |
| 116 | + version=version, |
| 117 | + codebase=codebase, |
| 118 | + )) |
| 119 | + |
| 120 | + return extensions |
| 121 | + |
| 122 | + def _download_extension(self, ext: ExtensionInfo, output_dir: Path) -> None: |
| 123 | + """Download a single extension .crx file""" |
| 124 | + dest_filename = f"{ext.id}.crx" |
| 125 | + dest_path = output_dir / dest_filename |
| 126 | + |
| 127 | + log_info(f" Downloading {ext.id} v{ext.version}...") |
| 128 | + |
| 129 | + try: |
| 130 | + response = requests.get(ext.codebase, stream=True, timeout=60) |
| 131 | + response.raise_for_status() |
| 132 | + |
| 133 | + total_size = int(response.headers.get("content-length", 0)) |
| 134 | + downloaded = 0 |
| 135 | + |
| 136 | + with open(dest_path, "wb") as f: |
| 137 | + for chunk in response.iter_content(chunk_size=65536): |
| 138 | + f.write(chunk) |
| 139 | + downloaded += len(chunk) |
| 140 | + if total_size: |
| 141 | + percent = (downloaded / total_size * 100) |
| 142 | + sys.stdout.write( |
| 143 | + f"\r {dest_filename}: {percent:.0f}% " |
| 144 | + ) |
| 145 | + sys.stdout.flush() |
| 146 | + |
| 147 | + if total_size: |
| 148 | + sys.stdout.write(f"\r {dest_filename}: done ({total_size / 1024:.0f} KB)\n") |
| 149 | + else: |
| 150 | + sys.stdout.write(f"\r {dest_filename}: done\n") |
| 151 | + sys.stdout.flush() |
| 152 | + |
| 153 | + except requests.RequestException as e: |
| 154 | + raise RuntimeError(f"Failed to download {ext.id}: {e}") |
| 155 | + |
| 156 | + def _generate_json(self, extensions: List[ExtensionInfo], output_dir: Path) -> None: |
| 157 | + """Generate bundled_extensions.json""" |
| 158 | + json_path = output_dir / "bundled_extensions.json" |
| 159 | + |
| 160 | + data: Dict[str, Dict[str, str]] = {} |
| 161 | + for ext in extensions: |
| 162 | + data[ext.id] = { |
| 163 | + "external_crx": f"{ext.id}.crx", |
| 164 | + "external_version": ext.version, |
| 165 | + } |
| 166 | + |
| 167 | + with open(json_path, "w") as f: |
| 168 | + json.dump(data, f, indent=2) |
| 169 | + f.write("\n") |
| 170 | + |
| 171 | + log_info(f" Generated {json_path.name}") |
0 commit comments