diff --git a/scripts/refresh_device_plugin_catalog.py b/scripts/refresh_device_plugin_catalog.py new file mode 100644 index 00000000..3a652f94 --- /dev/null +++ b/scripts/refresh_device_plugin_catalog.py @@ -0,0 +1,212 @@ +"""Rebuild the built-in device plugin catalog of a region from the Roborock cloud. + +Without a cloud snapshot, the server answers /api/v5/product and +/api/v1/appplugin from the catalog of its cloud region. Any Roborock account +of the region works, also one without devices: + + uv run python scripts/refresh_device_plugin_catalog.py --email you@example.com + uv run python scripts/refresh_device_plugin_catalog.py --source-json login.json + +The first form asks Roborock for a login code and reads it from the terminal. +The second form reuses a stored login, in the formats that +import_web_inventory_from_cloud.py --source-json accepts. A raw user data file +has no username, so it needs --email too. The script makes two cloud requests +and writes no login data. + +The region comes from the cloud host, for example eu for euiot.roborock.com. +The script writes shared/device_plugin_catalog_.json. For an unknown +host, pass --region. +""" + +from __future__ import annotations + +import argparse +import asyncio +import importlib +import json +import sys +from collections.abc import Awaitable, Callable +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import aiohttp +from roborock.data import UserData +from roborock.web_api import RoborockApiClient + +# The script edits the catalog in this checkout. It does not import the server, +# because the server needs the catalog to start. +BACKEND_PATH = Path(__file__).resolve().parents[1] / "src" / "roborock_local_server" / "bundled_backend" +if str(BACKEND_PATH) not in sys.path: + sys.path.insert(0, str(BACKEND_PATH)) +# Loaded after the path change above. +importer = importlib.import_module("import_web_inventory_from_cloud") +data_helpers = importlib.import_module("shared.data_helpers") +as_int = data_helpers.as_int + +# shared/device_plugin_catalog.py reads each device_plugin_catalog_.json here. +CATALOG_DIR = BACKEND_PATH / "shared" + +PRODUCTS_PATH = "/api/v5/product" +APPPLUGIN_PATH = "/api/v1/appplugin" +# The Android app 4.60.06 sends type 2 and apilevel 10046. The cloud answers +# the newest plugin that this app can load. +APP_TYPE_ANDROID = 2 +APP_API_LEVEL = 10046 + +CloudCall = Callable[..., Awaitable[Any]] + + +def _product_entries(products: Any) -> list[tuple[str, dict[str, Any]]]: + entries: list[tuple[str, dict[str, Any]]] = [] + category_details = products.get("categoryDetailList") if isinstance(products, dict) else None + for category_detail in category_details or []: + category = (category_detail or {}).get("category") or {} + for product in (category_detail or {}).get("productList") or []: + model = str(product.get("model") or "").strip().lower() + product_id = as_int(product.get("id"), 0) + if model and product_id > 0: + entry = { + "id": product_id, + "name": str(product.get("name") or ""), + "category": str(category.get("code") or ""), + } + entries.append((model, entry)) + return entries + + +async def fetch_cloud_answers(call: CloudCall) -> tuple[Any, Any]: + """Fetch the product list, then the Android plugin records of all its products in one request.""" + products = await call(PRODUCTS_PATH) + product_ids = sorted({entry["id"] for _, entry in _product_entries(products)}) + if not product_ids: + raise RuntimeError(f"{PRODUCTS_PATH} listed no product with a numeric id") + body = {"type": APP_TYPE_ANDROID, "apilevel": APP_API_LEVEL, "productids": product_ids} + records = await call(APPPLUGIN_PATH, method="post", json_body=body) + # An answer that is not a list of records would give a catalog without + # plugin records. + if not isinstance(records, list) or not any(isinstance(record, dict) for record in records): + raise RuntimeError(f"{APPPLUGIN_PATH} answered no plugin record") + return products, records + + +def catalog_region(base_url: str, region: str | None = None) -> str: + """Return the region of the catalog: --region if given, else the region of the cloud host.""" + host_region = data_helpers.cloud_region_from_base_url(base_url) + if region: + if host_region and host_region != region: + raise RuntimeError(f"--region {region} does not match the {host_region} cloud at {base_url}") + return region + if host_region is None: + raise RuntimeError(f"The region of {base_url} is unknown. Pass --region.") + return host_region + + +def catalog_path(region: str) -> Path: + return CATALOG_DIR / f"device_plugin_catalog_{region}.json" + + +def write_catalog(path: Path, catalog: dict[str, Any]) -> None: + """Write the catalog through a temporary file, so a crash keeps the old file. + + The server loads every device_plugin_catalog_*.json at import time, and a + truncated file would stop it from starting. Its glob skips the .tmp file. + """ + tmp_path = path.with_name(f"{path.name}.tmp") + try: + tmp_path.write_text(json.dumps(catalog, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + tmp_path.replace(path) + except BaseException: + # The package build would ship a leftover .tmp file. + tmp_path.unlink(missing_ok=True) + raise + + +def build_catalog(products: Any, records: Any, *, base_url: str, region: str, fetched_at_utc: str) -> dict[str, Any]: + plugin_records = [dict(record) for record in records or [] if isinstance(record, dict)] + return { + "_comment": "Generated by scripts/refresh_device_plugin_catalog.py. Do not edit by hand.", + "source": { + "base_url": base_url, + "region": region, + "fetched_at_utc": fetched_at_utc, + "products": f"GET {PRODUCTS_PATH}", + "appplugin": f"POST {APPPLUGIN_PATH} with type {APP_TYPE_ANDROID} and apilevel {APP_API_LEVEL}", + }, + "products": dict(sorted(_product_entries(products), key=lambda item: item[0])), + "appplugin": sorted(plugin_records, key=lambda record: as_int(record.get("productid"), 0)), + } + + +async def _login(args: argparse.Namespace, session: aiohttp.ClientSession) -> tuple[RoborockApiClient, UserData]: + if args.source_json: + username, base_url, user_data = importer._load_source_from_json_file( + source_file=args.source_json, + username_override=args.email, + base_url_override=args.base_url, + ) + api = RoborockApiClient(username=username, base_url=base_url, session=session) + return api, UserData.from_dict(user_data) + email = (args.email or input("Roborock account email: ")).strip() + api = RoborockApiClient(username=email, base_url=args.base_url, session=session) + await api.request_code_v4() + code = input("Login code from the Roborock email: ").strip() + return api, await api.code_login_v4(code) + + +async def _main_async(args: argparse.Namespace) -> None: + timeout = aiohttp.ClientTimeout(total=120) + async with aiohttp.ClientSession(timeout=timeout) as session: + api, user_data = await _login(args, session) + base_url = str(await api.base_url) + region = catalog_region(base_url, args.region) + + async def call(path: str, *, method: str = "get", json_body: dict[str, Any] | None = None) -> Any: + return await importer._request_cloud_api_data(api, user_data, path, method=method, json_body=json_body) + + products, records = await fetch_cloud_answers(call) + catalog = build_catalog( + products, + records, + base_url=base_url, + region=region, + fetched_at_utc=datetime.now(UTC).isoformat(), + ) + output = args.output or catalog_path(region) + write_catalog(output, catalog) + + ids_with_record = {as_int(record.get("productid"), 0) for record in catalog["appplugin"]} + without_record = [model for model, entry in catalog["products"].items() if entry["id"] not in ids_with_record] + print(f"Wrote {output}: {len(catalog['products'])} products, {len(catalog['appplugin'])} plugin records.") + if without_record: + print(f"No Android plugin record: {', '.join(without_record)}") + + +def _parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--email", + help="Roborock account email for a code login. With --source-json, it replaces the stored username.", + ) + parser.add_argument("--source-json", type=Path, help="Stored login, as for import_web_inventory_from_cloud.py.") + parser.add_argument("--base-url", help="Cloud API base URL, for example https://euiot.roborock.com.") + parser.add_argument( + "--region", + type=lambda value: value.strip().lower(), + help="Region of the catalog, for example eu. Needed only for an unknown cloud host.", + ) + parser.add_argument( + "--output", + type=Path, + help="Catalog to write (default: shared/device_plugin_catalog_.json in the bundled backend).", + ) + return parser.parse_args() + + +def main() -> int: + asyncio.run(_main_async(_parse_args())) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py b/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py index e0987da0..6a393fa8 100644 --- a/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py +++ b/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py @@ -7,9 +7,9 @@ import time from typing import Any, Callable, Sequence -from shared.constants import DEFAULT_HOME_NAME, DEFAULT_PRODUCT_SCHEMA, DEFAULT_TIMEZONE, MODEL_PRODUCT_ID_OVERRIDES +from shared.constants import DEFAULT_HOME_NAME, DEFAULT_PRODUCT_SCHEMA, DEFAULT_TIMEZONE from shared.context import ServerContext -from shared.data_helpers import as_bool, as_int, default_home_id, default_product_name, get_value, stable_int +from shared.data_helpers import as_bool, as_int, default_home_id, default_product_name, get_value from shared.http_helpers import wrap_response from shared.inventory_io import WEB_API_INVENTORY_FILE, load_inventory, write_inventory @@ -451,101 +451,6 @@ def _build_web_state(ctx: ServerContext) -> dict[str, Any]: } -def _device_has_runtime_did(ctx: ServerContext, duid: str) -> bool: - runtime_credentials = getattr(ctx, "runtime_credentials", None) - if runtime_credentials is None: - return False - try: - credential_device = runtime_credentials.resolve_device(duid=duid) - except Exception: - return False - if credential_device is None: - return False - did = str(credential_device.get("did") or "").strip() - mqtt_user = str(credential_device.get("device_mqtt_usr") or "").strip() - return bool(did or mqtt_user) - - -def _filter_home_data_to_runtime_devices(ctx: ServerContext, home_data: dict[str, Any]) -> dict[str, Any]: - filtered_home = dict(home_data) - allowed_product_ids: set[str] = set() - - for collection_key in ("devices", "receivedDevices", "received_devices"): - devices_value = home_data.get(collection_key) - if not isinstance(devices_value, list): - filtered_home.pop(collection_key, None) - continue - devices = devices_value - filtered_devices: list[dict[str, Any]] = [] - for device in devices: - if not isinstance(device, dict): - continue - duid = str(get_value(device, "duid", "did", default="")).strip() - if not duid or not _device_has_runtime_did(ctx, duid): - continue - filtered_devices.append(dict(device)) - product_id = str(get_value(device, "productId", "product_id", default="")).strip() - if product_id: - allowed_product_ids.add(product_id) - filtered_home[collection_key] = filtered_devices - - products_value = home_data.get("products") - products = products_value if isinstance(products_value, list) else [] - filtered_products: list[dict[str, Any]] = [] - for product in products: - if not isinstance(product, dict): - continue - product_id = str(get_value(product, "id", "productId", "product_id", default="")).strip() - if not product_id or product_id not in allowed_product_ids: - continue - filtered_products.append(dict(product)) - filtered_home["products"] = filtered_products - return filtered_home - - -def _build_product_response(ctx: ServerContext, home_data: dict[str, Any]) -> dict[str, Any]: - filtered_home_data = _filter_home_data_to_runtime_devices(ctx, home_data) - products_value = filtered_home_data.get("products") - products = products_value if isinstance(products_value, list) else [] - categories: dict[str, dict[str, Any]] = {} - for product in products: - if not isinstance(product, dict): - continue - raw_product_id = str(product.get("id") or "") - category_name = str(product.get("category") or "robot.vacuum.cleaner") - if category_name not in categories: - category_id = len(categories) + 1 - categories[category_name] = { - "category": { - "id": category_id, - "displayName": category_name, - "iconUrl": "", - }, - "productList": [], - } - model = str(product.get("model") or "roborock.vacuum.a117") - model_key = model.strip().lower() - product_id = MODEL_PRODUCT_ID_OVERRIDES.get( - model_key, - as_int(raw_product_id, stable_int(raw_product_id or category_name) % 1_000_000), - ) - product_entry = { - "id": product_id, - "name": str(product.get("name") or default_product_name(model)), - "model": model, - "packagename": f"com.roborock.{model.split('.')[-1]}", - "ncMode": "global", - "status": 10, - } - icon_url = product.get("iconUrl") - if isinstance(icon_url, str) and icon_url: - product_entry["picurl"] = icon_url - product_entry["cardPicUrl"] = icon_url - product_entry["pluginPicUrl"] = icon_url - categories[category_name]["productList"].append(product_entry) - return {"categoryDetailList": list(categories.values())} - - @dataclass(frozen=True) class EndpointRule: """Describes when a path matches and how to build its response.""" diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py index e450d8e9..1cc72396 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py @@ -2,26 +2,38 @@ from typing import Any -from shared.constants import MODEL_PRODUCT_ID_OVERRIDES from shared.context import ServerContext -from shared.data_helpers import as_int, default_product_name, model_product_ids, stable_int +from shared.data_helpers import default_product_name, model_product_ids +from shared.device_plugin_catalog import DevicePluginCatalog, product_fields, resolve_product_ids -from ..plugin.common import snapshot_plugin_catalog_data +from ..plugin.common import built_in_catalog, snapshot_plugin_catalog_data, snapshot_plugin_record_owners from ..user.homes.service import home_payload -def build_product_response(ctx: ServerContext) -> dict[str, Any]: - home_data = home_payload(ctx) - products_value = home_data.get("products") +def _served_products(ctx: ServerContext, catalog: DevicePluginCatalog) -> list[tuple[dict[str, Any], int]]: + """Pair each home data product with the numeric product id of /api/v5/product.""" + products_value = home_payload(ctx).get("products") products = products_value if isinstance(products_value, list) else [] + products = [product for product in products if isinstance(product, dict)] cloud_product_ids = model_product_ids(snapshot_plugin_catalog_data(ctx, "product")) + product_ids = resolve_product_ids(products, cloud_product_ids, catalog, snapshot_plugin_record_owners(ctx)) + return list(zip(products, product_ids)) + + +def served_models_by_product_id(ctx: ServerContext, catalog: DevicePluginCatalog) -> dict[int, set[str]]: + """Map each product id that /api/v5/product answers to the models that get it.""" + models: dict[int, set[str]] = {} + for product, product_id in _served_products(ctx, catalog): + model, _, _ = product_fields(product) + models.setdefault(product_id, set()).add(model.strip().lower()) + return models + + +def build_product_response(ctx: ServerContext) -> dict[str, Any]: categories: dict[str, dict[str, Any]] = {} - for product in products: - if not isinstance(product, dict): - continue - raw_product_id = str(product.get("id") or "") - category_name = str(product.get("category") or "robot.vacuum.cleaner") + for product, product_id in _served_products(ctx, built_in_catalog(ctx)): + model, raw_product_id, category_name = product_fields(product) if category_name not in categories: category_id = len(categories) + 1 categories[category_name] = { @@ -35,15 +47,6 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]: }, "productList": [], } - model = str(product.get("model") or "roborock.vacuum.a117") - model_key = model.strip().lower() - # String product ids (e.g. a226) take the cloud's numeric id for the model; - # plugins are keyed by it, so a hashed id gets the app no device plugin. - product_id = MODEL_PRODUCT_ID_OVERRIDES.get( - model_key, - cloud_product_ids.get(model_key) - or as_int(raw_product_id, stable_int(raw_product_id or category_name) % 1_000_000), - ) product_entry = { "id": product_id, "name": str(product.get("name") or default_product_name(model)), diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/api/v1/appplugin.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/v1/appplugin.py index 4df6a990..025f18be 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/api/v1/appplugin.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/api/v1/appplugin.py @@ -7,7 +7,12 @@ from shared.data_helpers import as_int from ...auth.service import ok -from ...plugin.common import APPPLUGIN_LIST, proxied_plugin_records, snapshot_plugin_records +from ...plugin.common import ( + built_in_catalog, + proxied_plugin_records, + snapshot_plugin_records, +) +from ..product_service import served_models_by_product_id # Request "type" of the iOS app; Android sends 2. IOS_APP_TYPE = 1 @@ -59,6 +64,27 @@ def _product_id(record: dict[str, Any]) -> int: return as_int(record.get("productid"), 0) +def _built_in_records(ctx: ServerContext, product_ids: set[int]) -> list[dict[str, Any]]: + # Product ids differ by cloud region, so the built-in record is looked up + # by the model that /api/v5/product gives the id to. An id that no device + # has, or that names two models, gets no record. + catalog = built_in_catalog(ctx) + served_models = served_models_by_product_id(ctx, catalog) + records = [] + for product_id in sorted(product_ids): + models = served_models.get(product_id, set()) + if len(models) != 1: + continue + [model] = models + record = catalog.records_by_model.get(model) + if record is None: + continue + # The answer carries the id that the app requested. The record can + # come from the catalog of another region; see catalog_for_region. + records.append(dict(record, productid=product_id)) + return records + + def build( ctx: ServerContext, _query_params: dict[str, list[str]], @@ -72,17 +98,19 @@ def build( snapshot_records = snapshot_plugin_records(ctx, "appplugin_ios") or snapshot_records product_ids = _requested_product_ids(body_params) if product_ids is None: - return ok(proxied_plugin_records(ctx, snapshot_records or APPPLUGIN_LIST)) + return ok(proxied_plugin_records(ctx, snapshot_records or built_in_catalog(ctx).appplugin_records)) # When the app opens a device, it installs the first record without # checking its productid. So a device must only get the records for the # product ids it asked for. If no record matches, the answer is an empty # list. matching = [record for record in snapshot_records if _product_id(record) in product_ids] # A device added after the snapshot import has no snapshot record, so the - # ids that the snapshot lacks come from the built-in list. The built-in list - # is the same for both platforms. So an iOS request can get an Android zip - # here, which the iOS app cannot load. The fallback to the Android catalog - # above has the same limitation if the snapshot has no iOS catalog. + # ids that the snapshot lacks get the built-in record of their model. The + # built-in list is the same for both platforms. So an iOS request can get + # an Android zip here, which the iOS app cannot load. The fallback to the + # Android catalog above has the same limitation if the snapshot has no iOS + # catalog. missing_ids = product_ids - {_product_id(record) for record in snapshot_records} - matching += [record for record in APPPLUGIN_LIST if _product_id(record) in missing_ids] + if missing_ids: + matching += _built_in_records(ctx, missing_ids) return ok(proxied_plugin_records(ctx, matching)) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/common.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/common.py index 1783813d..343015b3 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/common.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/common.py @@ -11,6 +11,8 @@ from fastapi.responses import Response from shared.context import ServerContext +from shared.data_helpers import as_int, cloud_region_from_base_url, known_cloud_region +from shared.device_plugin_catalog import FALLBACK_REGION, DevicePluginCatalog, catalog_for_region from ..auth.service import load_cloud_full_snapshot PLUGIN_PROXY_ALLOWED_HOSTS = { @@ -82,29 +84,9 @@ }, ] -APPPLUGIN_LIST = [ - { - "version": 6058, - "url": "https://files.roborock.com/iot/plugin/ea53983b82e948638904d9154bb7f474.zip", - "pluginLevel": 3001, - "productid": 110, - "apilevel": 10028, - }, - { - "version": 5208, - "url": "https://cdn.awsusor0.fds.api.mi-img.com/resources/iot/plugin/7cf4eb4c705c420483741189be389927.zip", - "pluginLevel": 3001, - "productid": 23, - "apilevel": 10028, - }, - { - "version": 90, - "url": "https://rrpkg-us.roborock.com/iot/plugin/019b4e083fbe7f81a28d79756be6f0ed.zip", - "pluginLevel": 3001, - "productid": 10001, - "apilevel": 10028, - }, -] +# Android device plugin records of the EU catalog. /api/v1/appplugin answers +# all of them to a request without product ids. +APPPLUGIN_LIST = catalog_for_region(FALLBACK_REGION).appplugin_records def plugin_proxy_url(ctx: ServerContext, source_url: str) -> str: @@ -134,13 +116,39 @@ def proxied_plugin_records( return proxied +def _dict_value(data: Any, key: str) -> dict[str, Any]: + value = data.get(key) if isinstance(data, dict) else None + return value if isinstance(value, dict) else {} + + +def server_cloud_region(ctx: ServerContext) -> str: + """Return the cloud region of the account's cloud import, else the configured region.""" + # The import's product ids come from the cloud of its region. Without an + # import, or if its region is unknown, network.region of the config decides. + snapshot = load_cloud_full_snapshot(ctx) + if snapshot is not None: + user_data = _dict_value(snapshot, "user_data") + region = ( + cloud_region_from_base_url(_dict_value(snapshot, "meta").get("base_url")) + or known_cloud_region(user_data.get("region")) + or known_cloud_region(_dict_value(_dict_value(user_data, "rriot"), "r").get("r")) + ) + if region: + return region + return ctx.region + + +def built_in_catalog(ctx: ServerContext) -> DevicePluginCatalog: + """Return the built-in plugin catalog for the cloud region of this server.""" + return catalog_for_region(server_cloud_region(ctx)) + + +def _plugin_catalogs(snapshot: dict[str, Any]) -> dict[str, Any]: + return _dict_value(_dict_value(snapshot, "web_api_cache"), "plugin_catalogs") + + def _snapshot_plugin_catalogs(ctx: ServerContext) -> dict[str, Any]: - snapshot = load_cloud_full_snapshot(ctx) or {} - web_cache = snapshot.get("web_api_cache") - if not isinstance(web_cache, dict): - return {} - catalogs = web_cache.get("plugin_catalogs") - return catalogs if isinstance(catalogs, dict) else {} + return _plugin_catalogs(load_cloud_full_snapshot(ctx) or {}) def _catalog_data(catalogs: dict[str, Any], name: str) -> Any: @@ -160,6 +168,24 @@ def snapshot_plugin_catalog_data(ctx: ServerContext, catalog_name: str) -> Any: return _catalog_data(_snapshot_plugin_catalogs(ctx), catalog_name) +def snapshot_plugin_record_owners(ctx: ServerContext) -> dict[int, str | None]: + """Map the product id of each Android and iOS snapshot plugin record to its model. + + The model comes from the products of the snapshot's home data, else it is None. + """ + snapshot = load_cloud_full_snapshot(ctx) or {} + catalogs = _plugin_catalogs(snapshot) + records = [ + record for name in ("appplugin", "appplugin_ios") for record in _dict_records(_catalog_data(catalogs, name)) + ] + models = { + as_int(product.get("id"), 0): str(product.get("model") or "").strip().lower() + for product in _dict_records(_dict_value(snapshot, "home_data").get("products")) + } + product_ids = {as_int(record.get("productid"), 0) for record in records} - {0} + return {product_id: models.get(product_id) or None for product_id in product_ids} + + def snapshot_plugin_records( ctx: ServerContext, catalog_name: str, diff --git a/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py b/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py index c371cfb4..43cd7a27 100644 --- a/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py +++ b/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py @@ -21,7 +21,7 @@ from roborock.exceptions import RoborockRateLimit from roborock.web_api import PreparedRequest, RoborockApiClient, _get_hawk_authentication -from shared.data_helpers import model_product_ids +from shared.data_helpers import as_int, model_product_ids def _find_repo_root() -> Path: @@ -380,22 +380,19 @@ async def _request_cloud_api_data( def _plugin_product_ids(home_data: HomeData, cloud_products: Any = None) -> list[int]: - # Newer models (e.g. roborock.vacuum.a226) carry a string product id in home - # data; the numeric id the plugin catalog is keyed by comes from /api/v5/product. + # The local /api/v5/product gives each model the id of the cloud's product + # list, else the numeric id in home data. The app requests the device plugin + # with that id, so the import fetches the plugins by the same id. Newer + # models (e.g. roborock.vacuum.a226) have a string product id in home data. ids_by_model = model_product_ids(cloud_products) - product_ids: set[int] = set() + ids_by_home_data_id: dict[str, int] = {} for product in home_data.products or []: - try: - product_ids.add(int(product.id)) - except (TypeError, ValueError): - model_id = ids_by_model.get(str(product.model or "").strip().lower()) - if model_id: - product_ids.add(model_id) + model_id = ids_by_model.get(str(product.model or "").strip().lower()) + ids_by_home_data_id[str(product.id)] = model_id or as_int(product.id, 0) + product_ids = set(ids_by_home_data_id.values()) for device in _all_home_devices(home_data): - try: - product_ids.add(int(getattr(device, "product_id", 0) or 0)) - except (TypeError, ValueError): - continue + home_data_id = str(getattr(device, "product_id", "") or "") + product_ids.add(ids_by_home_data_id.get(home_data_id) or as_int(home_data_id, 0)) return sorted(product_id for product_id in product_ids if product_id > 0) diff --git a/src/roborock_local_server/bundled_backend/shared/constants.py b/src/roborock_local_server/bundled_backend/shared/constants.py index 561bb070..37a0d197 100644 --- a/src/roborock_local_server/bundled_backend/shared/constants.py +++ b/src/roborock_local_server/bundled_backend/shared/constants.py @@ -127,12 +127,6 @@ }, ] -MODEL_PRODUCT_ID_OVERRIDES = { - "roborock.vacuum.a87": 110, - "roborock.vacuum.a15": 23, - "roborock.vacuum.sc05": 10001, -} - MQTT_TYPES = { 1: "CONNECT", 2: "CONNACK", diff --git a/src/roborock_local_server/bundled_backend/shared/data_helpers.py b/src/roborock_local_server/bundled_backend/shared/data_helpers.py index b0b90629..4bb5378e 100644 --- a/src/roborock_local_server/bundled_backend/shared/data_helpers.py +++ b/src/roborock_local_server/bundled_backend/shared/data_helpers.py @@ -3,6 +3,7 @@ import hashlib from datetime import datetime, timezone from typing import Any, TYPE_CHECKING +from urllib.parse import urlsplit if TYPE_CHECKING: from .context import ServerContext @@ -57,6 +58,23 @@ def model_product_ids(cloud_products: Any) -> dict[str, int]: return ids +# First label of the Roborock cloud API host -> cloud region. +CLOUD_REGIONS_BY_HOST = {"euiot": "eu", "usiot": "us", "cniot": "cn", "ruiot": "ru"} + + +def cloud_region_from_base_url(base_url: Any) -> str | None: + """Return the cloud region of a cloud API base URL, or None for an unknown host.""" + url = str(base_url or "").strip() + host = urlsplit(url if "//" in url else f"//{url}").hostname or "" + return CLOUD_REGIONS_BY_HOST.get(host.split(".")[0]) + + +def known_cloud_region(value: Any) -> str | None: + """Return a region code like "EU" in lower case, or None if no cloud host has it.""" + region = str(value or "").strip().lower() + return region if region in CLOUD_REGIONS_BY_HOST.values() else None + + def default_home_id(ctx: ServerContext) -> int: return stable_int(f"{ctx.duid}:home") diff --git a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py new file mode 100644 index 00000000..88e2875b --- /dev/null +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py @@ -0,0 +1,189 @@ +"""Built-in numeric product ids and Android device plugin records, per cloud region. + +The data comes from the Roborock cloud of a region: GET /api/v5/product gives +the numeric product id of each model, and POST /api/v1/appplugin gives the +Android plugin record of each product id. scripts/refresh_device_plugin_catalog.py +writes device_plugin_catalog_.json with any cloud login of that region. + +The server falls back to this data. The product ids and plugin records of a +cloud import keep precedence, because product ids differ by cloud region. +catalog_for_region merges the catalogs of all regions per model. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from .data_helpers import as_int, stable_int + +CATALOG_DIR = Path(__file__).parent +CATALOG_FILE_PREFIX = "device_plugin_catalog_" +# A model that the catalog of the server's region lacks takes its record from +# this catalog first. +FALLBACK_REGION = "eu" + + +@dataclass(frozen=True) +class DevicePluginCatalog: + # The region of the catalog file. For a merged catalog, the region of the + # catalog whose list answers a request without product ids. + region: str + # Model -> numeric product id. /api/v5/product answers it as the product + # "id", and the app requests the device plugin with it. + product_ids: dict[str, int] + # Android (type 2) records in the shape of the /api/v1/appplugin answer. + appplugin_records: list[dict[str, Any]] + # Model -> its Android record. /api/v1/appplugin looks the record up by the + # model that /api/v5/product gives the requested id to. + records_by_model: dict[str, dict[str, Any]] + + +def catalog_from_data(region: str, data: Mapping[str, Any]) -> DevicePluginCatalog: + product_ids = {model: int(entry["id"]) for model, entry in data["products"].items()} + records = [dict(record) for record in data["appplugin"]] + records_by_id = {as_int(record.get("productid"), 0): record for record in records} + return DevicePluginCatalog( + region=region, + product_ids=product_ids, + appplugin_records=records, + records_by_model={ + model: records_by_id[product_id] for model, product_id in product_ids.items() if product_id in records_by_id + }, + ) + + +def _load_catalogs() -> dict[str, DevicePluginCatalog]: + catalogs: dict[str, DevicePluginCatalog] = {} + for path in sorted(CATALOG_DIR.glob(f"{CATALOG_FILE_PREFIX}*.json")): + region = path.stem.removeprefix(CATALOG_FILE_PREFIX) + catalogs[region] = catalog_from_data(region, json.loads(path.read_text(encoding="utf-8"))) + return catalogs + + +# Region -> catalog, for each catalog file in this directory. +CATALOGS: dict[str, DevicePluginCatalog] = _load_catalogs() + + +# Region -> the merged catalog of catalog_for_region. CATALOGS does not change +# at runtime, so each merged catalog is built once. +_MERGED_CATALOGS: dict[str, DevicePluginCatalog] = {} + + +def catalog_for_region(region: str | None) -> DevicePluginCatalog: + """Return the built-in catalog for a server of a cloud region. + + It merges the catalogs of all regions per model. A model takes its record + and its id from the first catalog that has a record for it: the catalog of + the region, then the EU catalog, then the other catalogs by region name. + A model without any record takes its id the same way. A request without + product ids gets the list of the region's catalog, else the EU list. + """ + region_key = str(region or "").strip().lower() + if region_key not in _MERGED_CATALOGS: + _MERGED_CATALOGS[region_key] = _merge_catalogs(region_key) + return _MERGED_CATALOGS[region_key] + + +def _merge_catalogs(region_key: str) -> DevicePluginCatalog: + # Each region hosts its own plugin files. For the a87 and the a15, the old + # non-EU list and the EU catalog have the same versions (6058, 5208) but + # different files, and the sc05 differs (90 against 108). So a record from + # the catalog of another region is not verified for the server's region, + # but without it the device would get no plugin. + names = [region_key, FALLBACK_REGION, *sorted(CATALOGS)] + catalogs = [CATALOGS[name] for name in dict.fromkeys(names) if name in CATALOGS] + sources: dict[str, DevicePluginCatalog] = {} + for catalog in catalogs: + for model in catalog.records_by_model: + sources.setdefault(model, catalog) + for catalog in catalogs: + for model in catalog.product_ids: + sources.setdefault(model, catalog) + product_ids: dict[str, int] = {} + taken_ids: set[int] = set() + records_by_model: dict[str, dict[str, Any]] = {} + for catalog in catalogs: + for model, product_id in catalog.product_ids.items(): + if sources[model] is not catalog: + continue + if model in catalog.records_by_model: + records_by_model[model] = catalog.records_by_model[model] + # Product ids differ by cloud region. In the EU catalog, 199 is the + # a226, and in the US cloud it is the a199. A model whose id an + # earlier catalog gives to another model gets no id here. + # resolve_product_ids then gives it a hashed id, and + # /api/v1/appplugin still finds its record by model. + if product_id not in taken_ids: + product_ids[model] = product_id + taken_ids.add(product_id) + return DevicePluginCatalog( + region=catalogs[0].region, + product_ids=product_ids, + appplugin_records=catalogs[0].appplugin_records, + records_by_model=records_by_model, + ) + + +def product_fields(product: Mapping[str, Any]) -> tuple[str, str, str]: + """Return the model, the home data product id and the category of a home data product.""" + return ( + str(product.get("model") or "roborock.vacuum.a117"), + str(product.get("id") or ""), + str(product.get("category") or "robot.vacuum.cleaner"), + ) + + +def resolve_product_ids( + products: Sequence[Mapping[str, Any]], + import_ids: Mapping[str, int], + catalog: DevicePluginCatalog, + record_owners: Mapping[int, str | None], +) -> list[int]: + """Return the numeric product id that /api/v5/product gives each home data product. + + The app requests the device plugin with this id. /api/v1/appplugin matches + a snapshot record by the id alone, and it finds a built-in record by the + model that holds the id. So each id must name one model. Product ids + differ by cloud region. So a model gets the id of the account's cloud + import (model -> id) first, then a numeric id in home data, then its + built-in id, then a hashed id. Newer models (e.g. a226) have a string id + in home data. record_owners maps the product id of each snapshot plugin + record to its model. + """ + fields = [product_fields(product) for product in products] + model_keys = [model.strip().lower() for model, _, _ in fields] + # The fixed ids skip the holders check. A numeric home data id could be the + # import id of another model, but only if the inventory and the import come + # from different regions. The import has the product list of its region, + # or none, so its id comes first for every model that the list has. + fixed_ids = [import_ids.get(key) or as_int(raw_id, 0) for key, (_, raw_id, _) in zip(model_keys, fields)] + holders: dict[int, set[str | None]] = {} + for key, product_id in [*import_ids.items(), *zip(model_keys, fixed_ids)]: + if product_id: + holders.setdefault(product_id, set()).add(key) + # A snapshot record also holds its id. This matters if the import has no + # product list, because the import then fetched the records by the home + # data ids. A device holds no id here if it has not paired with the + # server or has left the inventory. Its record still holds the id for the + # model that the snapshot's home data names. None stands for a model that + # the snapshot does not name. + for product_id, owner in record_owners.items(): + holders.setdefault(product_id, {owner}) + product_ids: list[int] = [] + for key, fixed_id, (_, raw_id, category) in zip(model_keys, fixed_ids, fields): + built_in_id = catalog.product_ids.get(key) + if fixed_id: + product_ids.append(fixed_id) + # Product ids differ by cloud region. Another model can hold the + # built-in id in the import, in home data or by a snapshot record, + # like the a199 holds 199 in the US cloud and the a226 in the EU + # cloud. Then the id would name two models. + elif built_in_id and holders.get(built_in_id, set()) <= {key}: + product_ids.append(built_in_id) + else: + product_ids.append(stable_int(raw_id or category) % 1_000_000) + return product_ids diff --git a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog_eu.json b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog_eu.json new file mode 100644 index 00000000..96c8e0f4 --- /dev/null +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog_eu.json @@ -0,0 +1,972 @@ +{ + "_comment": "Generated by scripts/refresh_device_plugin_catalog.py. Do not edit by hand.", + "source": { + "base_url": "https://euiot.roborock.com", + "region": "eu", + "fetched_at_utc": "2026-11-21T01:28:17.326319+00:00", + "products": "GET /api/v5/product", + "appplugin": "POST /api/v1/appplugin with type 2 and apilevel 10046" + }, + "products": { + "roborock.mowbs.a355": { + "id": 314, + "name": "WiFi Amplifier Charging Station", + "category": "roborock.mowbs" + }, + "roborock.mowbs.a384": { + "id": 345, + "name": "WiFi Amplifier Charging Station", + "category": "roborock.mowbs" + }, + "roborock.mower.a222": { + "id": 224, + "name": "RockNeo Q1", + "category": "roborock.mower" + }, + "roborock.mower.a235": { + "id": 227, + "name": "RockMow Z1", + "category": "roborock.mower" + }, + "roborock.mower.a266": { + "id": 237, + "name": "RockMow S1", + "category": "roborock.mower" + }, + "roborock.mower.a282": { + "id": 246, + "name": "RockMow Z1 LiDAR", + "category": "roborock.mower" + }, + "roborock.mower.a333": { + "id": 287, + "name": "RockNeo Q208 LiDAR", + "category": "roborock.mower" + }, + "roborock.mower.a385": { + "id": 347, + "name": "RockNeo Q1", + "category": "roborock.mower" + }, + "roborock.vacuum.a08": { + "id": 11, + "name": "S6 Pure", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a10": { + "id": 21, + "name": "S6 MaxV", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a101": { + "id": 109, + "name": "Roborock Qrevo Pro", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a104": { + "id": 111, + "name": "Roborock Qrevo S", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a117": { + "id": 126, + "name": "Roborock Qrevo Master", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a123": { + "id": 135, + "name": "Roborock Qrevo Plus", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a125": { + "id": 133, + "name": "Q5 Max+", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a135": { + "id": 139, + "name": "Roborock Qrevo Curv", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a144": { + "id": 146, + "name": "Saros 10R", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a147": { + "id": 148, + "name": "Saros 10", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a15": { + "id": 23, + "name": "S7", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a156": { + "id": 154, + "name": "Roborock Qrevo Edge", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a159": { + "id": 156, + "name": "Roborock Qrevo Curv Series", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a168": { + "id": 163, + "name": "Roborock Qrevo L", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a170": { + "id": 165, + "name": "Roborock Qrevo C", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a179": { + "id": 179, + "name": "Saros Z70", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a185": { + "id": 175, + "name": "Roborock Qrevo CurvX", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a187": { + "id": 177, + "name": "Roborock Qrevo Edge Series", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a19": { + "id": 26, + "name": "S4 Max", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a197": { + "id": 183, + "name": "Roborock Qrevo EdgeT", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a199": { + "id": 185, + "name": "Roborock QV 35A", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a205": { + "id": 189, + "name": "Roborock QR 598", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a21": { + "id": 35, + "name": "Roborock Qrevo Slim", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a226": { + "id": 199, + "name": "Qrevo Curv 2 Pro", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a232": { + "id": 242, + "name": "Saros 10Rcomplete", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a245": { + "id": 209, + "name": "Qrevo Curv 2 Flow", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a27": { + "id": 41, + "name": "S7 MaxV", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a279": { + "id": 244, + "name": "Saros 20 Sonic", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a288": { + "id": 251, + "name": "Saros 20", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a294": { + "id": 255, + "name": "Qrevo 2 Pro Series", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a296": { + "id": 257, + "name": "Qrevo Edge 3 Pro", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a298": { + "id": 259, + "name": "Qrevo Edge 2", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a30": { + "id": 80, + "name": "Roborock G10", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a307": { + "id": 263, + "name": "Saros 20 Flow", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a326": { + "id": 273, + "name": "Qrevo S Pro Series", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a328": { + "id": 276, + "name": "Qrevo Edge 2 Flow", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a38": { + "id": 56, + "name": "Q7 Max", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a389": { + "id": 359, + "name": "Roborock Robotic Vacuum Cleaner", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a40": { + "id": 60, + "name": "Q7", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a51": { + "id": 88, + "name": "S8", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a62": { + "id": 78, + "name": "S7 Pro Ultra", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a65": { + "id": 92, + "name": "S7 Max Ultra", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a70": { + "id": 91, + "name": "S8 Pro Ultra", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a72": { + "id": 84, + "name": "Q5 Pro", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a73": { + "id": 82, + "name": "Q8 Max", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a75": { + "id": 81, + "name": "Roborock Qrevo", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a87": { + "id": 103, + "name": "Roborock Qrevo MaxV", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a95": { + "id": 121, + "name": "S8 Max Ultra", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.a97": { + "id": 105, + "name": "S8 MaxV Ultra", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.s4": { + "id": 5, + "name": "Roborock S4", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.s5e": { + "id": 13, + "name": "S5 Max", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.s6": { + "id": 4, + "name": "Roborock S6", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.sc01": { + "id": 10000, + "name": "Roborock Q7 Series", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.sc05": { + "id": 10001, + "name": "Roborock Q7 Series", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.ss07": { + "id": 10002, + "name": "Roborock Q10 Series", + "category": "robot.vacuum.cleaner" + }, + "roborock.vacuum.ss09": { + "id": 10003, + "name": "Roborock Q10 Series", + "category": "robot.vacuum.cleaner" + }, + "roborock.wdv.a194": { + "id": 180, + "name": "Roborock F25 Ultra", + "category": "roborock.wetdryvac" + }, + "roborock.wdv.a260": { + "id": 230, + "name": "Roborock F25 ACE Pro", + "category": "roborock.wetdryvac" + }, + "roborock.wdv.a300": { + "id": 261, + "name": "Roborock F25 Ultra Steam Gen 2", + "category": "roborock.wetdryvac" + }, + "roborock.wdv.a320": { + "id": 269, + "name": "Roborock F25 Pro Turbo", + "category": "roborock.wetdryvac" + }, + "roborock.wdv.a342": { + "id": 307, + "name": "Roborock F25 Pro Turbo Combo", + "category": "roborock.wetdryvac" + }, + "roborock.wetdryvac.a107": { + "id": 113, + "name": "Dyad Air", + "category": "roborock.wetdryvac" + }, + "roborock.wetdryvac.a111": { + "id": 117, + "name": "Roborock Flexi Pro", + "category": "roborock.wetdryvac" + }, + "roborock.wetdryvac.a132": { + "id": 137, + "name": "Roborock Flexi", + "category": "roborock.wetdryvac" + }, + "roborock.wetdryvac.a151": { + "id": 150, + "name": "Roborock F25 ACE", + "category": "roborock.wetdryvac" + }, + "roborock.wetdryvac.a174": { + "id": 169, + "name": "Roborock F25 ACE Combo", + "category": "roborock.wetdryvac" + }, + "roborock.wetdryvac.a238": { + "id": 207, + "name": "Roborock F25 XT", + "category": "roborock.wetdryvac" + }, + "roborock.wetdryvac.a56": { + "id": 86, + "name": "Dyad Pro", + "category": "roborock.wetdryvac" + }, + "roborock.wetdryvac.a83": { + "id": 99, + "name": "Dyad Pro Combo", + "category": "roborock.wetdryvac" + }, + "roborock.wm.a102": { + "id": 108, + "name": "Zeo One", + "category": "roborock.wm" + }, + "roborock.wm.a230": { + "id": 201, + "name": "Roborock Zeo X", + "category": "roborock.wm" + }, + "roborock.wm.a91": { + "id": 110, + "name": "Zeo Lite", + "category": "roborock.wm" + }, + "roborock.wm.a93": { + "id": 112, + "name": "Zeo mini", + "category": "roborock.wm" + } + }, + "appplugin": [ + { + "version": 5162, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/4fe2f92352d948119ecf3f8f269ddb4f.zip", + "pluginLevel": 3001, + "productid": 4, + "apilevel": 10028 + }, + { + "version": 5162, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/4fe2f92352d948119ecf3f8f269ddb4f.zip", + "pluginLevel": 3001, + "productid": 5, + "apilevel": 10028 + }, + { + "version": 5162, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/4fe2f92352d948119ecf3f8f269ddb4f.zip", + "pluginLevel": 3001, + "productid": 11, + "apilevel": 10028 + }, + { + "version": 5162, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/4fe2f92352d948119ecf3f8f269ddb4f.zip", + "pluginLevel": 3001, + "productid": 13, + "apilevel": 10028 + }, + { + "version": 5162, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/4fe2f92352d948119ecf3f8f269ddb4f.zip", + "pluginLevel": 3001, + "productid": 21, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 23, + "apilevel": 10028 + }, + { + "version": 5162, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/4fe2f92352d948119ecf3f8f269ddb4f.zip", + "pluginLevel": 3001, + "productid": 26, + "apilevel": 10028 + }, + { + "version": 6058, + "url": "https://app-files.roborock.com/iot/plugin/fd579761a6ad44b09671e0fde167130e.zip", + "pluginLevel": 3001, + "productid": 35, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 41, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://app-files.roborock.com/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 56, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 60, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 78, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 80, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://app-files.roborock.com/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 81, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://app-files.roborock.com/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 82, + "apilevel": 10028 + }, + { + "version": 5530, + "url": "https://files.roborock.com/iot/plugin/f93144e1d22b4e039163cbc85c0da084.zip", + "pluginLevel": 3001, + "productid": 84, + "apilevel": 10028 + }, + { + "version": 1471, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/e1e549e6face4e1a8fdee2b58ab076b2.zip", + "pluginLevel": 1, + "productid": 86, + "apilevel": 10028 + }, + { + "version": 5438, + "url": "https://app-files.roborock.com/iot/plugin/2555c48943ff4064956764dca33c814f.zip", + "pluginLevel": 3001, + "productid": 88, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://app-files.roborock.com/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 91, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://app-files.roborock.com/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 92, + "apilevel": 10028 + }, + { + "version": 1492, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/9b71c7b63e8d45bfa4bbc87d1f65ded9.zip", + "pluginLevel": 1, + "productid": 99, + "apilevel": 10028 + }, + { + "version": 6058, + "url": "https://app-files.roborock.com/iot/plugin/fd579761a6ad44b09671e0fde167130e.zip", + "pluginLevel": 3001, + "productid": 103, + "apilevel": 10028 + }, + { + "version": 6362, + "url": "https://app-files.roborock.com/iot/plugin/1075c089da784a11a47ea74d4c0e04a4.zip", + "pluginLevel": 3002, + "productid": 105, + "apilevel": 10030 + }, + { + "version": 2312, + "url": "https://files.roborock.com/iot/plugin/d0a37f0c539b447b9bbee0a952ad065c.zip", + "pluginLevel": 1, + "productid": 108, + "apilevel": 10028 + }, + { + "version": 5736, + "url": "https://files.roborock.com/iot/plugin/e6dbdb9b4e694113b675d80ca6891220.zip", + "pluginLevel": 3001, + "productid": 109, + "apilevel": 10028 + }, + { + "version": 2740, + "url": "https://app-files.roborock.com/iot/plugin/d899a088af654bc99212657349251e64.zip", + "pluginLevel": 3002, + "productid": 110, + "apilevel": 10028 + }, + { + "version": 5888, + "url": "https://app-files.roborock.com/iot/plugin/d701602b488943168fde708bbe245131.zip", + "pluginLevel": 3001, + "productid": 111, + "apilevel": 10028 + }, + { + "version": 2310, + "url": "https://files.roborock.com/iot/plugin/bfc676cc23eb44bbb07340f62b1606a9.zip", + "pluginLevel": 1, + "productid": 112, + "apilevel": 10028 + }, + { + "version": 1471, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/dec529abbe67467a835cdafdc2ef1fc1.zip", + "pluginLevel": 1, + "productid": 113, + "apilevel": 10028 + }, + { + "version": 2198, + "url": "https://files.roborock.com/iot/plugin/c37d5d4059da448caffff31874db0e02.zip", + "pluginLevel": 1, + "productid": 117, + "apilevel": 10028 + }, + { + "version": 5530, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/f93144e1d22b4e039163cbc85c0da084.zip", + "pluginLevel": 3001, + "productid": 121, + "apilevel": 10028 + }, + { + "version": 6058, + "url": "https://app-files.roborock.com/iot/plugin/fd579761a6ad44b09671e0fde167130e.zip", + "pluginLevel": 3001, + "productid": 126, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://app-files.roborock.com/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 133, + "apilevel": 10028 + }, + { + "version": 5208, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/1f88b45ca1084da6bce5872eff687a36.zip", + "pluginLevel": 3001, + "productid": 135, + "apilevel": 10028 + }, + { + "version": 2198, + "url": "https://files.roborock.com/iot/plugin/541114c5a19d4b95968683db2c58c63a.zip", + "pluginLevel": 1, + "productid": 137, + "apilevel": 10028 + }, + { + "version": 5964, + "url": "https://files.roborock.com/plugin/qrevocurv/b75783df0d544d78b61bdf9df4ad95cf.zip", + "pluginLevel": 3001, + "productid": 139, + "apilevel": 10028 + }, + { + "version": 6844, + "url": "https://app-files.roborock.com/iot/plugin/1305aec64736420abd73acf1ef481cb4.zip", + "pluginLevel": 3002, + "productid": 146, + "apilevel": 10030 + }, + { + "version": 6006, + "url": "https://app-files.roborock.com/iot/plugin/f81b7ea821f2483aae6910d60ec9ed10.zip", + "pluginLevel": 3001, + "productid": 148, + "apilevel": 10028 + }, + { + "version": 2676, + "url": "https://app-files.roborock.com/iot/plugin/5a03d81dd6434dfabedbb5bab05aa0a0.zip", + "pluginLevel": 3002, + "productid": 150, + "apilevel": 10028 + }, + { + "version": 5888, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/d701602b488943168fde708bbe245131.zip", + "pluginLevel": 3001, + "productid": 154, + "apilevel": 10028 + }, + { + "version": 6848, + "url": "https://app-files.roborock.com/iot/plugin/d2bf7b0f610a47b5a7aec248add5690c.zip", + "pluginLevel": 3002, + "productid": 156, + "apilevel": 10030 + }, + { + "version": 6836, + "url": "https://app-files.roborock.com/iot/plugin/4136925303644c9abbc36d9414a2a784.zip", + "pluginLevel": 3002, + "productid": 163, + "apilevel": 10030 + }, + { + "version": 6844, + "url": "https://app-files.roborock.com/iot/plugin/1305aec64736420abd73acf1ef481cb4.zip", + "pluginLevel": 3002, + "productid": 165, + "apilevel": 10030 + }, + { + "version": 2676, + "url": "https://app-files.roborock.com/iot/plugin/558064d459c14389b9e19cf0d7e6c83c.zip", + "pluginLevel": 3002, + "productid": 169, + "apilevel": 10028 + }, + { + "version": 6940, + "url": "https://app-files.roborock.com/iot/plugin/e408c264ad034f5da8b5c7d3585c9611.zip", + "pluginLevel": 3002, + "productid": 175, + "apilevel": 10030 + }, + { + "version": 6848, + "url": "https://app-files.roborock.com/iot/plugin/d2bf7b0f610a47b5a7aec248add5690c.zip", + "pluginLevel": 3002, + "productid": 177, + "apilevel": 10030 + }, + { + "version": 6848, + "url": "https://app-files.roborock.com/iot/plugin/d2bf7b0f610a47b5a7aec248add5690c.zip", + "pluginLevel": 3002, + "productid": 179, + "apilevel": 10030 + }, + { + "version": 2674, + "url": "https://app-files.roborock.com/iot/plugin/6d5e1e8589e54a1e81351ee54b75eed7.zip", + "pluginLevel": 3002, + "productid": 180, + "apilevel": 10028 + }, + { + "version": 6082, + "url": "https://files.roborock.com/iot/plugin/d17ec108f39445bfaea5c60f1e882984.zip", + "pluginLevel": 3001, + "productid": 183, + "apilevel": 10028 + }, + { + "version": 5312, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/76edbac1b68d4d71abeabe3633d0ea2e.zip", + "pluginLevel": 3001, + "productid": 185, + "apilevel": 10028 + }, + { + "version": 5312, + "url": "https://cdn.awsde0.fds.api.mi-img.com/resources/iot/plugin/76edbac1b68d4d71abeabe3633d0ea2e.zip", + "pluginLevel": 3001, + "productid": 189, + "apilevel": 10028 + }, + { + "version": 6846, + "url": "https://app-files.roborock.com/iot/plugin/69588500d2c54b0bb154a967646dd57b.zip", + "pluginLevel": 3002, + "productid": 199, + "apilevel": 10030 + }, + { + "version": 2302, + "url": "https://files.roborock.com/iot/plugin/78f42532ac4e4f8f99ce538c805c5771.zip", + "pluginLevel": 1, + "productid": 201, + "apilevel": 10028 + }, + { + "version": 2680, + "url": "https://app-files.roborock.com/iot/plugin/6c6dcf90501e40cba6cb89f1b0caf884.zip", + "pluginLevel": 3002, + "productid": 207, + "apilevel": 10028 + }, + { + "version": 7006, + "url": "https://app-files.roborock.com/iot/plugin/fb6c50cf562442028f2b2a0f620eb553.zip", + "pluginLevel": 3002, + "productid": 209, + "apilevel": 10030 + }, + { + "version": 856, + "url": "https://app-files.roborock.com/iot/plugin/9dbe90bcb3b343458086800d7f556ab2.zip", + "pluginLevel": 3002, + "productid": 224, + "apilevel": 10042 + }, + { + "version": 856, + "url": "https://app-files.roborock.com/iot/plugin/9dbe90bcb3b343458086800d7f556ab2.zip", + "pluginLevel": 3002, + "productid": 227, + "apilevel": 10042 + }, + { + "version": 2507, + "url": "https://app-files.roborock.com/iot/plugin/82b3efd07f2843b6aeed6899a12d0320.zip", + "pluginLevel": 3002, + "productid": 230, + "apilevel": 10028 + }, + { + "version": 856, + "url": "https://app-files.roborock.com/iot/plugin/9dbe90bcb3b343458086800d7f556ab2.zip", + "pluginLevel": 3002, + "productid": 237, + "apilevel": 10042 + }, + { + "version": 6844, + "url": "https://app-files.roborock.com/iot/plugin/1305aec64736420abd73acf1ef481cb4.zip", + "pluginLevel": 3002, + "productid": 242, + "apilevel": 10030 + }, + { + "version": 7076, + "url": "https://app-files.roborock.com/iot/plugin/187b0182481849f7874048a96c2d43d8.zip", + "pluginLevel": 3002, + "productid": 244, + "apilevel": 10030 + }, + { + "version": 856, + "url": "https://app-files.roborock.com/iot/plugin/9dbe90bcb3b343458086800d7f556ab2.zip", + "pluginLevel": 3002, + "productid": 246, + "apilevel": 10042 + }, + { + "version": 6848, + "url": "https://app-files.roborock.com/iot/plugin/d2bf7b0f610a47b5a7aec248add5690c.zip", + "pluginLevel": 3002, + "productid": 251, + "apilevel": 10030 + }, + { + "version": 6934, + "url": "https://app-files.roborock.com/iot/plugin/77bc3f4a000249a48fd676504538cb02.zip", + "pluginLevel": 3002, + "productid": 255, + "apilevel": 10030 + }, + { + "version": 7052, + "url": "https://app-files.roborock.com/iot/plugin/74d2029938b847e1bb2cc68db7a6f39f.zip", + "pluginLevel": 3002, + "productid": 257, + "apilevel": 10030 + }, + { + "version": 6848, + "url": "https://app-files.roborock.com/iot/plugin/d2bf7b0f610a47b5a7aec248add5690c.zip", + "pluginLevel": 3002, + "productid": 259, + "apilevel": 10030 + }, + { + "version": 2718, + "url": "https://app-files.roborock.com/iot/plugin/203d4e4a6a4d47af9e5c287b5c800df6.zip", + "pluginLevel": 3002, + "productid": 261, + "apilevel": 10028 + }, + { + "version": 7046, + "url": "https://app-files.roborock.com/iot/plugin/de0ceb1351854a819a0374fdcbf17831.zip", + "pluginLevel": 3002, + "productid": 263, + "apilevel": 10030 + }, + { + "version": 2755, + "url": "https://app-files.roborock.com/iot/plugin/7ea88012da2c4fd689a50de4c595ba79.zip", + "pluginLevel": 3002, + "productid": 269, + "apilevel": 10028 + }, + { + "version": 6834, + "url": "https://app-files.roborock.com/iot/plugin/96dd3581ff354992acf0895e07d43143.zip", + "pluginLevel": 3002, + "productid": 273, + "apilevel": 10030 + }, + { + "version": 7050, + "url": "https://app-files.roborock.com/iot/plugin/b0b26465205848158ea36102cfbeb98c.zip", + "pluginLevel": 3002, + "productid": 276, + "apilevel": 10030 + }, + { + "version": 856, + "url": "https://app-files.roborock.com/iot/plugin/9dbe90bcb3b343458086800d7f556ab2.zip", + "pluginLevel": 3002, + "productid": 287, + "apilevel": 10042 + }, + { + "version": 2766, + "url": "https://app-files.roborock.com/iot/plugin/2df4cbbeebcb40c5a1b230cddff061fa.zip", + "pluginLevel": 3002, + "productid": 307, + "apilevel": 10028 + }, + { + "version": 854, + "url": "https://app-files.roborock.com/iot/plugin/1ed3f355055c4b399b26bcb2eaee625e.zip", + "pluginLevel": 3002, + "productid": 347, + "apilevel": 10042 + }, + { + "version": 7202, + "url": "https://app-files.roborock.com/iot/plugin/4e10b1f7814049a2944b76456980072b.zip", + "pluginLevel": 3002, + "productid": 359, + "apilevel": 10030 + }, + { + "version": 108, + "url": "https://app-files.roborock.com/iot/plugin/01a19a568c3272578b7b9882ec3bf2fe.zip", + "pluginLevel": 3001, + "productid": 10000, + "apilevel": 10028 + }, + { + "version": 108, + "url": "https://app-files.roborock.com/iot/plugin/01a19a521dd87116a7e77cfd5def01e7.zip", + "pluginLevel": 3001, + "productid": 10001, + "apilevel": 10028 + }, + { + "version": 78, + "url": "https://app-files.roborock.com/iot/plugin/019ffe4567ae7649b1acc6e88de6c769.zip", + "pluginLevel": 3001, + "productid": 10002, + "apilevel": 10028 + }, + { + "version": 78, + "url": "https://app-files.roborock.com/iot/plugin/019ffe44c79875afb41fe3fe179f1345.zip", + "pluginLevel": 3001, + "productid": 10003, + "apilevel": 10028 + } + ] +} diff --git a/tests/test_cloud_plugin_catalogs.py b/tests/test_cloud_plugin_catalogs.py index 8f8a1699..b4337668 100644 --- a/tests/test_cloud_plugin_catalogs.py +++ b/tests/test_cloud_plugin_catalogs.py @@ -51,3 +51,77 @@ async def fake_request(_api, _user_data, path, *, method="get", params=None, jso assert all(body["productids"] == [199] for body in app_plugin_bodies) assert catalogs["appplugin"]["data"][0]["url"].endswith("/type2.zip") assert catalogs["appplugin_ios"]["data"][0]["url"].endswith("/type1.zip") + + +def test_plugin_catalogs_fetch_the_product_list_id_over_the_home_data_id(monkeypatch) -> None: + # The local /api/v5/product gives the a307 the id 263 of the cloud's product + # list, not the id 4242 in home data. The app requests its plugin with 263. + cloud_products = { + "categoryDetailList": [{"category": {"id": 1}, "productList": [{"id": 263, "model": "roborock.vacuum.a307"}]}] + } + home_data = HomeData.from_dict( + { + "id": 1, + "name": "Home", + "products": [{"id": "4242", "name": "Saros 20 Flow", "model": "roborock.vacuum.a307", "category": "robot.vacuum.cleaner"}], + "devices": [{"duid": "duid-1", "name": "Vacuum", "productId": "4242", "localKey": "key"}], + } + ) + requests: list[tuple[str, dict[str, Any] | None]] = [] + + async def fake_request(_api, _user_data, path, *, method="get", params=None, json_body=None): + requests.append((path, json_body)) + return cloud_products if path == "/api/v5/product" else [] + + monkeypatch.setattr(importer, "_request_cloud_api_data", fake_request) + + asyncio.run(importer._fetch_plugin_catalogs(None, None, home_data)) + + app_plugin_bodies = [body for path, body in requests if path == "/api/v1/appplugin"] + assert [body["productids"] for body in app_plugin_bodies] == [[263], [263]] + + +def _failing_product_list(requests: list[tuple[str, dict[str, Any] | None]]): + async def fake_request(_api, _user_data, path, *, method="get", params=None, json_body=None): + requests.append((path, json_body)) + if path == "/api/v5/product": + raise RuntimeError("Cloud request failed for /api/v5/product") + return [] if path == "/api/v1/appplugin" else {} + + return fake_request + + +def test_plugin_catalogs_store_errors_if_the_product_list_fails_for_string_ids(monkeypatch) -> None: + requests: list[tuple[str, dict[str, Any] | None]] = [] + monkeypatch.setattr(importer, "_request_cloud_api_data", _failing_product_list(requests)) + + catalogs = asyncio.run(importer._fetch_plugin_catalogs(None, None, _home_data())) + + # The a226 has only a string id in home data. Without the product list, + # the import has no product id to fetch the plugins with. + assert "data" not in catalogs["product"] + assert catalogs["product"]["error"] == "Cloud request failed for /api/v5/product" + assert [path for path, _ in requests if path == "/api/v1/appplugin"] == [] + for name in ("appplugin", "appplugin_ios"): + assert "data" not in catalogs[name] + assert catalogs[name]["error"] == "no product ids available" + + +def test_plugin_catalogs_fetch_the_numeric_home_data_id_if_the_product_list_fails(monkeypatch) -> None: + home_data = HomeData.from_dict( + { + "id": 1, + "name": "Home", + "products": [{"id": "4242", "name": "Saros 20 Flow", "model": "roborock.vacuum.a307", "category": "robot.vacuum.cleaner"}], + "devices": [{"duid": "duid-1", "name": "Vacuum", "productId": "4242", "localKey": "key"}], + } + ) + requests: list[tuple[str, dict[str, Any] | None]] = [] + monkeypatch.setattr(importer, "_request_cloud_api_data", _failing_product_list(requests)) + + catalogs = asyncio.run(importer._fetch_plugin_catalogs(None, None, home_data)) + + app_plugin_bodies = [body for path, body in requests if path == "/api/v1/appplugin"] + assert [body["productids"] for body in app_plugin_bodies] == [[4242], [4242]] + assert "error" in catalogs["product"] + assert catalogs["appplugin"]["data"] == [] diff --git a/tests/test_plugin_routes.py b/tests/test_plugin_routes.py index 1c65e70b..962c6de7 100644 --- a/tests/test_plugin_routes.py +++ b/tests/test_plugin_routes.py @@ -18,6 +18,24 @@ def _build_supervisor(tmp_path: Path) -> ReleaseSupervisor: return ReleaseSupervisor(config=config, paths=paths) +def _pair_devices(supervisor: ReleaseSupervisor, *models: str) -> None: + # /api/v1/appplugin answers a built-in record only for a product id that + # /api/v5/product gives to the model of the record. /api/v5/product lists + # the inventory devices that have paired with the server. + devices = [ + {"duid": f"duid-{index}", "name": model, "model": model, "product_id": f"rriot-{model}"} + for index, model in enumerate(models) + ] + supervisor.paths.inventory_path.write_text(json.dumps({"devices": devices}) + "\n", encoding="utf-8") + for device in devices: + supervisor.runtime_credentials.ensure_device( + did=f"did-{device['duid']}", + duid=device["duid"], + model=device["model"], + product_id=device["product_id"], + ) + + def _source_from_proxied_url(url: str) -> str: parsed = urllib.parse.urlsplit(url) return urllib.parse.parse_qs(parsed.query).get("src", [""])[0] @@ -135,6 +153,7 @@ def _app_plugin_product_ids(payload: dict) -> list[int]: def test_app_plugin_answers_only_requested_product_ids(tmp_path: Path) -> None: supervisor = _build_supervisor(tmp_path) + _pair_devices(supervisor, "roborock.vacuum.a15") client = TestClient(supervisor.app) # The app posts this JSON body and installs the first record it gets back. @@ -148,6 +167,7 @@ def test_app_plugin_answers_only_requested_product_ids(tmp_path: Path) -> None: def test_app_plugin_reads_product_ids_from_form_body(tmp_path: Path) -> None: supervisor = _build_supervisor(tmp_path) + _pair_devices(supervisor, "roborock.vacuum.a15", "roborock.vacuum.sc05") client = TestClient(supervisor.app) repeated = client.post("/api/v1/appplugin", data={"type": "2", "productids": ["23", "10001"]}) @@ -253,25 +273,29 @@ def test_app_plugin_filters_cloud_snapshot_catalog(tmp_path: Path) -> None: def test_app_plugin_falls_back_to_built_in_list_for_ids_missing_from_snapshot(tmp_path: Path) -> None: + from https_server.routes.plugin import common as plugin_common + supervisor = _build_supervisor(tmp_path) # A device added after the snapshot import has no record in the snapshot. _write_android_app_plugin_snapshot(supervisor, [_SNAPSHOT_APP_PLUGIN_RECORD]) + _pair_devices(supervisor, "roborock.vacuum.a15") client = TestClient(supervisor.app) missing = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [23], "type": 2}) mixed = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [23, 4242], "type": 2}) [record] = missing.json()["data"] + [built_in_23] = [item for item in plugin_common.APPPLUGIN_LIST if item["productid"] == 23] assert record["productid"] == 23 - assert record["version"] == 5208 - assert _source_from_proxied_url(record["url"]) == ( - "https://cdn.awsusor0.fds.api.mi-img.com/resources/iot/plugin/7cf4eb4c705c420483741189be389927.zip" - ) + assert record["version"] == built_in_23["version"] + assert _source_from_proxied_url(record["url"]) == built_in_23["url"] # Snapshot records come first, built-in records after them. assert _app_plugin_product_ids(mixed.json()) == [4242, 23] def test_app_plugin_prefers_snapshot_record_over_built_in_record(tmp_path: Path) -> None: + from https_server.routes.plugin import common as plugin_common + supervisor = _build_supervisor(tmp_path) _write_android_app_plugin_snapshot( supervisor, @@ -285,12 +309,17 @@ def test_app_plugin_prefers_snapshot_record_over_built_in_record(tmp_path: Path) } ], ) + _pair_devices(supervisor, "roborock.vacuum.a15", "roborock.vacuum.sc05") client = TestClient(supervisor.app) response = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [23, 10001], "type": 2}) records = response.json()["data"] - assert [(item["productid"], item["version"]) for item in records] == [(23, 9999), (10001, 90)] + [built_in_10001] = [item for item in plugin_common.APPPLUGIN_LIST if item["productid"] == 10001] + assert [(item["productid"], item["version"]) for item in records] == [ + (23, 9999), + (10001, built_in_10001["version"]), + ] assert _source_from_proxied_url(records[0]["url"]) == "https://rrpkg-us.roborock.com/iot/plugin/cloud-23.zip" @@ -467,11 +496,14 @@ def _app_plugin_record(product_id: int, url: str) -> dict: def _ios_app_plugin_client(tmp_path: Path) -> TestClient: # Product 199 is in both catalogs, and 300 is only in the iOS catalog. Products 23 - # and 4242 are only in the Android catalog. The built-in list also has 23. + # and 4242 are only in the Android catalog. The import gives 23 to the paired + # a15, and the built-in list also has 23. supervisor = _build_supervisor(tmp_path) + a15_product = {"id": 23, "model": "roborock.vacuum.a15"} _write_app_plugin_snapshot( supervisor, { + "product": {"data": {"categoryDetailList": [{"productList": [a15_product]}]}}, "appplugin": { "data": [ _app_plugin_record(199, ANDROID_ZIP), @@ -482,6 +514,7 @@ def _ios_app_plugin_client(tmp_path: Path) -> TestClient: "appplugin_ios": {"data": [_app_plugin_record(199, IOS_ZIP), _app_plugin_record(300, IOS_ONLY_ZIP)]}, }, ) + _pair_devices(supervisor, "roborock.vacuum.a15") return TestClient(supervisor.app) @@ -529,3 +562,142 @@ def test_app_plugin_ios_answers_full_ios_catalog_without_product_ids(tmp_path: P assert _app_plugin_sources(no_ids.json()) == [(199, IOS_ZIP), (300, IOS_ONLY_ZIP)] assert _app_plugin_sources(empty_ids.json()) == [(199, IOS_ZIP), (300, IOS_ONLY_ZIP)] + + +@pytest.mark.parametrize( + ("model", "product_id", "version", "source"), + [ + # Saros 20 Flow + ("roborock.vacuum.a307", 263, 7046, "https://app-files.roborock.com/iot/plugin/de0ceb1351854a819a0374fdcbf17831.zip"), + # Qrevo Curv 2 Pro + ("roborock.vacuum.a226", 199, 6846, "https://app-files.roborock.com/iot/plugin/69588500d2c54b0bb154a967646dd57b.zip"), + # F25 Ultra + ("roborock.wdv.a194", 180, 2674, "https://app-files.roborock.com/iot/plugin/6d5e1e8589e54a1e81351ee54b75eed7.zip"), + # RockNeo Q1 + ("roborock.mower.a222", 224, 856, "https://app-files.roborock.com/iot/plugin/9dbe90bcb3b343458086800d7f556ab2.zip"), + ], +) +def test_app_plugin_answers_built_in_record_without_cloud_snapshot( + tmp_path: Path, model: str, product_id: int, version: int, source: str +) -> None: + supervisor = _build_supervisor(tmp_path) + _pair_devices(supervisor, model) + client = TestClient(supervisor.app) + + response = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [product_id], "type": 2}) + + [record] = response.json()["data"] + assert record["productid"] == product_id + assert record["version"] == version + assert _source_from_proxied_url(record["url"]) == source + + +def test_app_plugin_cloud_snapshot_wins_over_built_in_records(tmp_path: Path) -> None: + supervisor = _build_supervisor(tmp_path) + snapshot = { + "web_api_cache": { + "plugin_catalogs": { + "appplugin": { + "data": [ + { + "version": 9999, + "url": "https://app-files.roborock.com/iot/plugin/cloud-a307.zip", + "pluginLevel": 3002, + "productid": 263, + "apilevel": 10030, + } + ] + }, + } + } + } + supervisor.paths.cloud_snapshot_path.write_text(json.dumps(snapshot) + "\n", encoding="utf-8") + client = TestClient(supervisor.app) + + response = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [263], "type": 2}) + + [record] = response.json()["data"] + assert record["version"] == 9999 + assert _source_from_proxied_url(record["url"]) == "https://app-files.roborock.com/iot/plugin/cloud-a307.zip" + + + +def _cloud_product_catalog(products: dict[str, int]) -> dict: + product_list = [{"id": product_id, "model": model} for model, product_id in products.items()] + return {"data": {"categoryDetailList": [{"category": {"id": 1}, "productList": product_list}]}} + + +@pytest.mark.parametrize( + ("model", "import_id"), + [ + # The EU ids 199 and 110 belong to the a226 and the roborock.wm.a91. + ("roborock.vacuum.a199", 199), + ("roborock.vacuum.a87", 110), + ], +) +def test_app_plugin_answers_built_in_record_of_the_model_that_gets_the_id( + tmp_path: Path, model: str, import_id: int +) -> None: + from shared.device_plugin_catalog import catalog_for_region + + # The import of another region gives the id to another model than the + # built-in list. The device was added after the import, so the snapshot + # has no record for it. + supervisor = _build_supervisor(tmp_path) + _write_app_plugin_snapshot( + supervisor, + { + "product": _cloud_product_catalog({model: import_id, "roborock.vacuum.a15": 23}), + "appplugin": {"data": [_app_plugin_record(23, ANDROID_23_ZIP)]}, + }, + ) + _pair_devices(supervisor, model) + client = TestClient(supervisor.app) + + response = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [import_id], "type": 2}) + + # No catalog of the import's region exists, so the record comes from the EU catalog. + eu_record = catalog_for_region("eu").records_by_model[model] + assert _app_plugin_sources(response.json()) == [(import_id, eu_record["url"])] + + +def test_app_plugin_answers_built_in_record_if_import_ids_agree(tmp_path: Path) -> None: + from https_server.routes.plugin import common as plugin_common + + # The import gives the a307 the same id as the built-in list. The device + # was added after the import, so the snapshot has no record for it. + supervisor = _build_supervisor(tmp_path) + _write_app_plugin_snapshot( + supervisor, + { + "product": _cloud_product_catalog({"roborock.vacuum.a307": 263, "roborock.vacuum.a226": 199}), + "appplugin": {"data": [_app_plugin_record(199, ANDROID_ZIP)]}, + }, + ) + _pair_devices(supervisor, "roborock.vacuum.a307") + client = TestClient(supervisor.app) + [built_in_263] = [record for record in plugin_common.APPPLUGIN_LIST if record["productid"] == 263] + + response = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [263], "type": 2}) + + assert _app_plugin_sources(response.json()) == [(263, built_in_263["url"])] + + +def test_built_in_plugin_records_match_built_in_products() -> None: + from https_server.routes.plugin.common import is_allowed_plugin_source + from shared import device_plugin_catalog + + assert "eu" in device_plugin_catalog.CATALOGS + for region, catalog in device_plugin_catalog.CATALOGS.items(): + product_ids = list(catalog.product_ids.values()) + record_ids = [record["productid"] for record in catalog.appplugin_records] + + # The app installs the first record for its product id, so each id + # needs one model and at most one record. + assert len(product_ids) == len(set(product_ids)) + assert len(record_ids) == len(set(record_ids)) + assert set(record_ids) <= set(product_ids) + for record in catalog.appplugin_records: + assert is_allowed_plugin_source(record["url"]) + path = device_plugin_catalog.CATALOG_DIR / f"device_plugin_catalog_{region}.json" + assert json.loads(path.read_text(encoding="utf-8"))["source"]["region"] == region diff --git a/tests/test_product_response.py b/tests/test_product_response.py index 35c05ebb..3b46e26d 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -1,6 +1,8 @@ import json from pathlib import Path +import pytest + from roborock_local_server.backend import ( ServerContext, default_endpoint_rules, @@ -18,12 +20,12 @@ def __getattr__(self, _name): return lambda *args, **kwargs: None -def _make_context(tmp_path: Path) -> ServerContext: +def _make_context(tmp_path: Path, region: str = "us") -> ServerContext: return ServerContext( api_host="api.example.com", mqtt_host="mqtt.example.com", wood_host="wood.example.com", - region="us", + region=region, protocol_login_email="user@example.com", localkey="key123", duid="duid-1", @@ -39,11 +41,12 @@ def _make_context(tmp_path: Path) -> ServerContext: ) -def _products_v5(tmp_path: Path, devices: list[dict[str, object]]) -> dict: - (tmp_path / "web_api_inventory.json").write_text( - json.dumps({"home": {"id": 424242, "name": "Test Home"}, "devices": devices}) + "\n", - encoding="utf-8", - ) +def _products_v5( + tmp_path: Path, devices: list[dict[str, object]], **shared_devices: list[dict[str, object]] +) -> dict: + # The keyword names the inventory list of the shared devices, like receivedDevices=[...]. + inventory = {"home": {"id": 424242, "name": "Test Home"}, "devices": devices, **shared_devices} + (tmp_path / "web_api_inventory.json").write_text(json.dumps(inventory) + "\n", encoding="utf-8") route, payload = resolve_route( rules=default_endpoint_rules(), context=_make_context(tmp_path), @@ -141,3 +144,538 @@ def test_string_product_id_uses_cloud_numeric_id_by_model(tmp_path: Path) -> Non [product] = data["categoryDetailList"][0]["productList"] assert product["id"] == 199 assert product["rriotid"] == "30uADinyLKa3Qpga60B1Ke" + + +@pytest.mark.parametrize( + ("model", "rriotid", "expected_id"), + [ + # The rriotids are the ones in product_catalog.json, which onboarding stores. + ("roborock.vacuum.a307", "4J89YHjAc2uUG9W0HLxKPP", 263), + ("roborock.vacuum.a87", "5gUei3OIJIXVD3eD85Balg", 103), + ("roborock.vacuum.a15", "1YYW18rpgyAJTISwb1NM91", 23), + ("roborock.vacuum.sc05", "5ayEx3aKgStqZZ0v5IpMBP", 10001), + ("roborock.wdv.a194", "MUKZV1YH7JkqlXXjJnO64", 180), + ], +) +def test_product_uses_built_in_cloud_product_id(tmp_path: Path, model: str, rriotid: str, expected_id: int) -> None: + device = dict(_DEVICE, model=model, product_id=rriotid) + + data = _products_v5(tmp_path, [device]) + + [product] = data["categoryDetailList"][0]["productList"] + # The app requests the device plugin with this id. + assert product["id"] == expected_id + assert product["rriotid"] == rriotid + + +def test_product_of_unknown_model_keeps_hashed_id(tmp_path: Path) -> None: + from shared.data_helpers import stable_int + + device = dict(_DEVICE, model="roborock.vacuum.zz99", product_id="iot-product-z") + + data = _products_v5(tmp_path, [device]) + + [product] = data["categoryDetailList"][0]["productList"] + assert product["id"] == stable_int("iot-product-z") % 1_000_000 + + +def test_numeric_inventory_product_id_wins_over_built_in_id(tmp_path: Path) -> None: + device = dict(_DEVICE, model="roborock.vacuum.a307", product_id="4242") + + data = _products_v5(tmp_path, [device]) + + [product] = data["categoryDetailList"][0]["productList"] + assert product["id"] == 4242 + + +def _write_cloud_products( + tmp_path: Path, + products: dict[str, int], + app_plugin_records: list[dict[str, object]] | None = None, + *, + base_url: str | None = None, +) -> None: + # The import stores the cloud's /api/v5/product answer in the snapshot, and + # the /api/v1/appplugin answer for the account's product ids. + product_list = [{"id": product_id, "model": model} for model, product_id in products.items()] + catalogs: dict[str, object] = { + "product": {"data": {"categoryDetailList": [{"category": {"id": 1}, "productList": product_list}]}} + } + if app_plugin_records is not None: + catalogs["appplugin"] = {"data": app_plugin_records} + snapshot: dict[str, object] = {"web_api_cache": {"plugin_catalogs": catalogs}} + if base_url is not None: + snapshot["meta"] = {"base_url": base_url} + (tmp_path / "web_api_inventory_full_snapshot.json").write_text(json.dumps(snapshot), encoding="utf-8") + + +@pytest.mark.parametrize( + ("model", "rriotid", "import_id"), + [ + # The built-in ids come from the EU cloud: 185 for the a199 and 103 for the a87. + ("roborock.vacuum.a199", "3PWf17rt73QjM3F1DaZelu", 199), + ("roborock.vacuum.a87", "5gUei3OIJIXVD3eD85Balg", 110), + # A hardcoded 110 for the a87 used to win over the import. + ("roborock.vacuum.a87", "5gUei3OIJIXVD3eD85Balg", 103), + # The import also wins over a numeric id in home data. + ("roborock.vacuum.a307", "4242", 263), + ], +) +def test_cloud_import_product_id_wins_over_built_in_id( + tmp_path: Path, model: str, rriotid: str, import_id: int +) -> None: + # Product ids differ by cloud region, so the account's own import decides. + _write_cloud_products(tmp_path, {model: import_id}) + device = dict(_DEVICE, model=model, product_id=rriotid) + + data = _products_v5(tmp_path, [device]) + + [product] = data["categoryDetailList"][0]["productList"] + assert product["id"] == import_id + + +def test_model_missing_from_cloud_import_gets_built_in_id_and_record(tmp_path: Path) -> None: + _write_cloud_products(tmp_path, {"roborock.vacuum.a226": 199}, base_url="https://euiot.roborock.com") + device = dict(_DEVICE, model="roborock.vacuum.a307", product_id="4J89YHjAc2uUG9W0HLxKPP") + + data = _products_v5(tmp_path, [device]) + + [product] = data["categoryDetailList"][0]["productList"] + assert product["id"] == 263 + assert _plugin_sources(tmp_path, 263) == [(263, _built_in_source("roborock.vacuum.a307"))] + + +def test_app_gets_a307_plugin_without_cloud_import(tmp_path: Path) -> None: + import urllib.parse + + from https_server.routes.plugin.common import APPPLUGIN_LIST + + device = dict(_DEVICE, model="roborock.vacuum.a307", product_id="4J89YHjAc2uUG9W0HLxKPP") + [product] = _products_v5(tmp_path, [device])["categoryDetailList"][0]["productList"] + # The app requests its device plugin with the product id from /api/v5/product. + body = {"apilevel": 10046, "productids": [product["id"]], "type": 2} + route, payload = resolve_route( + rules=default_endpoint_rules(), + context=_make_context(tmp_path), + clean_path="/api/v1/appplugin", + query_params={}, + body_params={"__json": [json.dumps(body)]}, + method="POST", + ) + + assert product["id"] == 263 + assert route == "download_code" + [record] = payload["data"] + [a307_record] = [item for item in APPPLUGIN_LIST if item["productid"] == 263] + assert record["productid"] == 263 + assert record["version"] == a307_record["version"] + assert urllib.parse.parse_qs(urllib.parse.urlsplit(record["url"]).query)["src"] == [a307_record["url"]] + + +def _app_plugin_records(tmp_path: Path, product_id: int) -> list[dict]: + # The app requests its device plugin with the product id from /api/v5/product. + body = {"apilevel": 10046, "productids": [product_id], "type": 2} + route, payload = resolve_route( + rules=default_endpoint_rules(), + context=_make_context(tmp_path), + clean_path="/api/v1/appplugin", + query_params={}, + body_params={"__json": [json.dumps(body)]}, + method="POST", + ) + assert route == "download_code" + return payload["data"] + + +def _v5_product_list(tmp_path: Path, device: dict[str, object]) -> list[dict]: + return _products_v5(tmp_path, [device])["categoryDetailList"][0]["productList"] + + +def _product_ids_by_model(data: dict) -> dict[str, int]: + return { + product["model"]: product["id"] for category in data["categoryDetailList"] for product in category["productList"] + } + + +def _built_in_source(model: str) -> str: + from shared.device_plugin_catalog import catalog_for_region + + return catalog_for_region("eu").records_by_model[model]["url"] + + +def _plugin_sources(tmp_path: Path, product_id: int) -> list[tuple[int, str]]: + import urllib.parse + + return [ + (record["productid"], urllib.parse.parse_qs(urllib.parse.urlsplit(record["url"]).query)["src"][0]) + for record in _app_plugin_records(tmp_path, product_id) + ] + + +_A87 = dict(_DEVICE, model="roborock.vacuum.a87", product_id="5gUei3OIJIXVD3eD85Balg") +_A199 = dict(_DEVICE, model="roborock.vacuum.a199", product_id="3PWf17rt73QjM3F1DaZelu") +_A226 = dict(_DEVICE, duid="device-b", model="roborock.vacuum.a226", product_id="30uADinyLKa3Qpga60B1Ke") +_WASHER = dict(_DEVICE, duid="device-b", model="roborock.wm.a91", product_id="rriot-wm-a91") + + +def test_built_in_id_that_the_import_gives_another_model_is_skipped(tmp_path: Path) -> None: + from shared.data_helpers import stable_int + + # The import gives 199 to the a199, as the US cloud does, and lacks the + # a226. The built-in id of the a226 comes from the EU cloud, and it is 199. + _write_cloud_products(tmp_path, {"roborock.vacuum.a199": 199}) + + [product] = _v5_product_list(tmp_path, _A226) + + assert product["id"] == stable_int(_A226["product_id"]) % 1_000_000 + + +def test_devices_after_a_us_import_get_the_built_in_record_of_their_model(tmp_path: Path) -> None: + from shared.data_helpers import stable_int + + _write_cloud_products(tmp_path, {"roborock.vacuum.a199": 199}, base_url="https://usiot.roborock.com") + hashed_id = stable_int(_A226["product_id"]) % 1_000_000 + + product_ids = _product_ids_by_model(_products_v5(tmp_path, [_A199, _A226])) + + assert product_ids == {"roborock.vacuum.a199": 199, "roborock.vacuum.a226": hashed_id} + assert _plugin_sources(tmp_path, hashed_id) == [(hashed_id, _built_in_source("roborock.vacuum.a226"))] + # The snapshot has no record for 199, and in the EU cloud 199 is the a226. + assert _plugin_sources(tmp_path, 199) == [(199, _built_in_source("roborock.vacuum.a199"))] + + +def test_snapshot_record_wins_over_the_built_in_record_of_the_model(tmp_path: Path) -> None: + a199_record = {"version": 1, "url": "https://app-files.roborock.com/iot/plugin/a199.zip", "productid": 199} + _write_cloud_products(tmp_path, {"roborock.vacuum.a199": 199}, [a199_record]) + _products_v5(tmp_path, [_A199, _A226]) + + assert _plugin_sources(tmp_path, 199) == [(199, a199_record["url"])] + + +def test_a87_with_the_us_import_id_110_gets_the_a87_record(tmp_path: Path) -> None: + # In the EU cloud, and so in the EU catalog, 110 is the roborock.wm.a91 washer. + _write_cloud_products(tmp_path, {"roborock.vacuum.a87": 110}, base_url="https://usiot.roborock.com") + [product] = _v5_product_list(tmp_path, _A87) + + assert product["id"] == 110 + assert _plugin_sources(tmp_path, 110) == [(110, _built_in_source("roborock.vacuum.a87"))] + + +def test_a87_with_the_numeric_inventory_id_110_gets_the_a87_record(tmp_path: Path) -> None: + from shared.device_plugin_catalog import catalog_for_region + + # An older import stored the US id 110 of the a87 in home data. There is + # no snapshot. + [product] = _v5_product_list(tmp_path, dict(_A87, product_id="110")) + + assert product["id"] == 110 + assert _plugin_sources(tmp_path, 110) == [(110, _built_in_source("roborock.vacuum.a87"))] + # The answer is a copy, so the built-in record keeps its own id. + assert catalog_for_region("eu").records_by_model["roborock.vacuum.a87"]["productid"] == 103 + + +def test_built_in_id_that_another_model_holds_in_home_data_is_skipped(tmp_path: Path) -> None: + from shared.data_helpers import stable_int + + # The a87 holds 110 in home data, which is the built-in id of the washer. + hashed_id = stable_int(_WASHER["product_id"]) % 1_000_000 + + product_ids = _product_ids_by_model(_products_v5(tmp_path, [dict(_A87, product_id="110"), _WASHER])) + + assert product_ids == {"roborock.vacuum.a87": 110, "roborock.wm.a91": hashed_id} + assert _plugin_sources(tmp_path, 110) == [(110, _built_in_source("roborock.vacuum.a87"))] + assert _plugin_sources(tmp_path, hashed_id) == [(hashed_id, _built_in_source("roborock.wm.a91"))] + + +def test_app_gets_no_built_in_plugin_for_an_id_of_two_models(tmp_path: Path) -> None: + # The import gives 110 to the washer, and the a87 keeps 110 in home data. + # The app requests 110 for both, so the server cannot tell them apart. + _write_cloud_products(tmp_path, {"roborock.wm.a91": 110}) + + product_ids = _product_ids_by_model(_products_v5(tmp_path, [dict(_A87, product_id="110"), _WASHER])) + + assert product_ids == {"roborock.vacuum.a87": 110, "roborock.wm.a91": 110} + assert _app_plugin_records(tmp_path, 110) == [] + + +def test_app_gets_no_built_in_plugin_for_an_id_without_inventory_device(tmp_path: Path) -> None: + # The app requests the ids that /api/v5/product answers. No device has 263. + device = dict(_DEVICE, model="roborock.vacuum.a15", product_id="1YYW18rpgyAJTISwb1NM91") + [product] = _v5_product_list(tmp_path, device) + + assert product["id"] == 23 + assert _app_plugin_records(tmp_path, 263) == [] + + +@pytest.mark.parametrize( + ("snapshot", "expected"), + [ + ({"meta": {"base_url": "https://usiot.roborock.com"}, "user_data": {"region": "eu"}}, "us"), + ({"meta": {"base_url": "https://euiot.roborock.com"}}, "eu"), + ({"meta": {"base_url": None}, "user_data": {"region": "cn"}}, "cn"), + ({"user_data": {"rriot": {"r": {"r": "EU"}}}}, "eu"), + # An import of an unknown region, and no import at all, take network.region. + ({"meta": {"base_url": "https://example.com"}}, "ru"), + (None, "ru"), + ], + ids=["base_url_wins", "base_url", "user_data_region", "rriot_region", "unknown_import_region", "no_import"], +) +def test_server_cloud_region(tmp_path: Path, snapshot: dict | None, expected: str) -> None: + from https_server.routes.plugin.common import server_cloud_region + + if snapshot is not None: + (tmp_path / "web_api_inventory_full_snapshot.json").write_text(json.dumps(snapshot), encoding="utf-8") + + assert server_cloud_region(_make_context(tmp_path, region="ru")) == expected + + +_US_A307_ZIP = "https://rrpkg-us.roborock.com/iot/plugin/us-a307.zip" + + +def test_us_server_takes_ids_and_records_from_the_us_catalog(tmp_path: Path, monkeypatch) -> None: + from shared import device_plugin_catalog + + us_catalog = device_plugin_catalog.catalog_from_data( + "us", + { + "products": {"roborock.vacuum.a307": {"id": 9263}}, + "appplugin": [{"version": 1, "url": _US_A307_ZIP, "productid": 9263}], + }, + ) + monkeypatch.setitem(device_plugin_catalog.CATALOGS, "us", us_catalog) + monkeypatch.setattr(device_plugin_catalog, "_MERGED_CATALOGS", {}) + # Without an import, network.region decides, and it is us here. + device = dict(_DEVICE, model="roborock.vacuum.a307", product_id="4J89YHjAc2uUG9W0HLxKPP") + + [product] = _v5_product_list(tmp_path, device) + + assert product["id"] == 9263 + assert _plugin_sources(tmp_path, 9263) == [(9263, _US_A307_ZIP)] + + +def test_merged_catalog_is_built_once_per_region() -> None: + from shared.device_plugin_catalog import catalog_for_region + + assert catalog_for_region("eu") is catalog_for_region(" EU ") + + +def test_us_import_without_us_catalog_gets_the_eu_catalog_by_model(tmp_path: Path) -> None: + from shared import device_plugin_catalog + + assert "us" not in device_plugin_catalog.CATALOGS + # The US import lacks the a307. + _write_cloud_products(tmp_path, {"roborock.vacuum.a199": 199}, base_url="https://usiot.roborock.com") + device = dict(_DEVICE, model="roborock.vacuum.a307", product_id="4J89YHjAc2uUG9W0HLxKPP") + + [product] = _v5_product_list(tmp_path, device) + + assert product["id"] == 263 + assert _plugin_sources(tmp_path, 263) == [(263, _built_in_source("roborock.vacuum.a307"))] + + +def _region_zip(region: str, model: str) -> str: + return f"https://rrpkg-{region}.roborock.com/iot/plugin/{region}-{model}.zip" + + +def _add_region_catalog(monkeypatch, region: str, product_ids: dict[str, int], without_record: tuple = ()) -> None: + from shared import device_plugin_catalog + + catalog = device_plugin_catalog.catalog_from_data( + region, + { + "products": {model: {"id": product_id} for model, product_id in product_ids.items()}, + "appplugin": [ + {"version": 1, "url": _region_zip(region, model), "productid": product_id} + for model, product_id in product_ids.items() + if model not in without_record + ], + }, + ) + monkeypatch.setitem(device_plugin_catalog.CATALOGS, region, catalog) + monkeypatch.setattr(device_plugin_catalog, "_MERGED_CATALOGS", {}) + + +def test_model_missing_from_the_region_catalog_gets_the_eu_record(tmp_path: Path, monkeypatch) -> None: + # Without an import, network.region decides, and it is us here. + _add_region_catalog(monkeypatch, "us", {"roborock.vacuum.a307": 9263}) + + [product] = _v5_product_list(tmp_path, _A87) + + assert product["id"] == 103 + assert _plugin_sources(tmp_path, 103) == [(103, _built_in_source("roborock.vacuum.a87"))] + + +def test_model_missing_from_the_region_and_eu_catalogs_gets_the_record_of_another_region( + tmp_path: Path, monkeypatch +) -> None: + # After the region and EU, the other catalogs follow by region name. + model = "roborock.vacuum.x9" + _add_region_catalog(monkeypatch, "us", {"roborock.vacuum.a307": 9263}) + _add_region_catalog(monkeypatch, "ru", {model: 7009}) + _add_region_catalog(monkeypatch, "cn", {model: 8009}) + device = dict(_DEVICE, model=model, product_id="rriot-x9") + + [product] = _v5_product_list(tmp_path, device) + + assert product["id"] == 8009 + assert _plugin_sources(tmp_path, 8009) == [(8009, _region_zip("cn", model))] + + +def test_record_of_another_region_wins_over_an_id_without_record(tmp_path: Path, monkeypatch) -> None: + _add_region_catalog(monkeypatch, "us", {"roborock.vacuum.a87": 9087}, without_record=("roborock.vacuum.a87",)) + + [product] = _v5_product_list(tmp_path, _A87) + + assert product["id"] == 103 + assert _plugin_sources(tmp_path, 103) == [(103, _built_in_source("roborock.vacuum.a87"))] + + +def test_id_that_the_region_catalog_gives_another_model_is_skipped(tmp_path: Path, monkeypatch) -> None: + # In the US cloud, 199 is the a199. The US catalog lacks the a226, whose EU + # id is also 199. + _add_region_catalog(monkeypatch, "us", {"roborock.vacuum.a199": 199}) + + products = _products_v5(tmp_path, [_A199, _A226])["categoryDetailList"][0]["productList"] + product_ids = {product["model"]: product["id"] for product in products} + + hashed_id = product_ids["roborock.vacuum.a226"] + assert product_ids["roborock.vacuum.a199"] == 199 + assert hashed_id != 199 + assert _plugin_sources(tmp_path, 199) == [(199, _region_zip("us", "roborock.vacuum.a199"))] + assert _plugin_sources(tmp_path, hashed_id) == [(hashed_id, _built_in_source("roborock.vacuum.a226"))] + + +_A307 = dict(_DEVICE, model="roborock.vacuum.a307", product_id="4J89YHjAc2uUG9W0HLxKPP") + + +def test_two_devices_of_one_model_get_one_product_and_its_record(tmp_path: Path) -> None: + devices = [_A307, dict(_A307, duid="device-b", name="Vacuum B")] + + [product] = _products_v5(tmp_path, devices)["categoryDetailList"][0]["productList"] + + assert (product["id"], product["rriotid"]) == (263, _A307["product_id"]) + # Both devices get 263, but 263 names one model. + assert _plugin_sources(tmp_path, 263) == [(263, _built_in_source("roborock.vacuum.a307"))] + + +@pytest.mark.parametrize("numeric_id", ["263", "4242"], ids=["built_in_id", "other_id"]) +def test_devices_of_one_model_with_two_home_data_ids_get_two_products(tmp_path: Path, numeric_id: str) -> None: + # One device has the rriotid in home data, the other a numeric id. The app + # finds the product of a device by rriotid, so each home data id gets its + # own product. Each of the product ids names only the a307. + devices = [_A307, dict(_A307, duid="device-b", product_id=numeric_id)] + + products = _products_v5(tmp_path, devices)["categoryDetailList"][0]["productList"] + + assert [(product["rriotid"], product["id"]) for product in products] == [ + (_A307["product_id"], 263), + (numeric_id, int(numeric_id)), + ] + for product_id in {263, int(numeric_id)}: + assert _plugin_sources(tmp_path, product_id) == [(product_id, _built_in_source("roborock.vacuum.a307"))] + + +@pytest.mark.parametrize("inventory_key", ["receivedDevices", "received_devices"]) +def test_shared_device_gets_the_built_in_id_and_record(tmp_path: Path, inventory_key: str) -> None: + # The a307 is shared with the account, and the account's own device is the a15. + shared_a307 = dict(_A307, duid="device-b", name="Shared Vacuum") + + data = _products_v5(tmp_path, [_DEVICE], **{inventory_key: [shared_a307]}) + + assert _product_ids_by_model(data) == {"roborock.vacuum.a15": 23, "roborock.vacuum.a307": 263} + assert _plugin_sources(tmp_path, 263) == [(263, _built_in_source("roborock.vacuum.a307"))] + + +# The import stores a catalog request that failed in this shape, without "data". +_PRODUCT_CATALOG_ERROR = { + "path": "/api/v5/product", + "method": "GET", + "params": {}, + "json": {}, + "error": "Cloud request failed for /api/v5/product: {'code': 500}", +} +_APP_PLUGIN_CATALOG_ERROR = { + "path": "/api/v1/appplugin", + "method": "POST", + "json": {"type": 2, "apilevel": 10043, "productids": []}, + "error": "no product ids available", +} + + +@pytest.mark.parametrize( + "catalogs", + [ + {"product": _PRODUCT_CATALOG_ERROR}, + {"appplugin": _APP_PLUGIN_CATALOG_ERROR}, + { + "product": _PRODUCT_CATALOG_ERROR, + "appplugin": _APP_PLUGIN_CATALOG_ERROR, + "appplugin_ios": dict(_APP_PLUGIN_CATALOG_ERROR, json={"type": 1, "apilevel": 10043, "productids": []}), + }, + ], + ids=["product", "appplugin", "all"], +) +def test_snapshot_catalog_error_gets_the_built_in_id_and_record(tmp_path: Path, catalogs: dict) -> None: + snapshot = {"web_api_cache": {"plugin_catalogs": catalogs}} + (tmp_path / "web_api_inventory_full_snapshot.json").write_text(json.dumps(snapshot), encoding="utf-8") + + [product] = _v5_product_list(tmp_path, _A307) + + assert product["id"] == 263 + assert _plugin_sources(tmp_path, 263) == [(263, _built_in_source("roborock.vacuum.a307"))] + + +def _write_snapshot_without_product_list( + tmp_path: Path, catalog_name: str, records: list[dict], home_products: list[dict] +) -> None: + # The import has no product list, so it fetched the plugins by the numeric + # home data ids. The snapshot keeps the cloud's home data. + catalogs = {"product": _PRODUCT_CATALOG_ERROR, catalog_name: {"data": records}} + snapshot = {"home_data": {"products": home_products}, "web_api_cache": {"plugin_catalogs": catalogs}} + (tmp_path / "web_api_inventory_full_snapshot.json").write_text(json.dumps(snapshot), encoding="utf-8") + + +_A199_RECORD = {"version": 1, "url": "https://app-files.roborock.com/iot/plugin/a199.zip", "productid": 199} + + +@pytest.mark.parametrize( + "home_products", [[{"id": "199", "model": "roborock.vacuum.a199"}], []], ids=["named_model", "unknown_model"] +) +@pytest.mark.parametrize("catalog_name", ["appplugin", "appplugin_ios"]) +def test_built_in_id_of_a_snapshot_record_without_inventory_device_is_skipped( + tmp_path: Path, catalog_name: str, home_products: list[dict] +) -> None: + from shared.data_helpers import stable_int + + # The a199 had 199, as in the US cloud, and has left the inventory since. + # The snapshot's home data names it or not. The built-in id of the a226 + # comes from the EU cloud, and it is 199. + _write_snapshot_without_product_list(tmp_path, catalog_name, [_A199_RECORD], home_products) + + [product] = _v5_product_list(tmp_path, _A226) + + assert product["id"] == stable_int(_A226["product_id"]) % 1_000_000 + + +def test_device_next_to_a_snapshot_record_without_inventory_device_gets_its_built_in_record(tmp_path: Path) -> None: + home_products = [{"id": "199", "model": "roborock.vacuum.a199"}] + _write_snapshot_without_product_list(tmp_path, "appplugin", [_A199_RECORD], home_products) + + [product] = _v5_product_list(tmp_path, _A226) + + assert _plugin_sources(tmp_path, product["id"]) == [(product["id"], _built_in_source("roborock.vacuum.a226"))] + + +def test_device_of_the_model_that_the_snapshot_names_keeps_the_built_in_id_and_the_record(tmp_path: Path) -> None: + # The cloud a15 had 23 in home data and has not paired with the server. + # The paired a15 has the string id that local onboarding writes. Its + # built-in id is 23 too. + a15_record = {"version": 1, "url": "https://app-files.roborock.com/iot/plugin/a15.zip", "productid": 23} + home_products = [{"id": "23", "model": "roborock.vacuum.a15"}] + _write_snapshot_without_product_list(tmp_path, "appplugin", [a15_record], home_products) + device = dict(_DEVICE, product_id="1YYW18rpgyAJTISwb1NM91") + + [product] = _v5_product_list(tmp_path, device) + + assert product["id"] == 23 + assert _plugin_sources(tmp_path, 23) == [(23, a15_record["url"])] diff --git a/tests/test_refresh_device_plugin_catalog.py b/tests/test_refresh_device_plugin_catalog.py new file mode 100644 index 00000000..fd46928b --- /dev/null +++ b/tests/test_refresh_device_plugin_catalog.py @@ -0,0 +1,160 @@ +import argparse +import asyncio +import json +import types +from pathlib import Path +from typing import Any + +import pytest + +import scripts.refresh_device_plugin_catalog as refresh +from scripts.refresh_device_plugin_catalog import ( + build_catalog, + catalog_path, + catalog_region, + fetch_cloud_answers, + write_catalog, +) + +CLOUD_PRODUCTS = { + "categoryDetailList": [ + { + "category": {"id": 1, "code": "robot.vacuum.cleaner"}, + "productList": [ + {"id": 263, "model": "roborock.vacuum.a307", "name": "Saros 20 Flow", "rriotid": "rriot-a307"}, + {"id": 23, "model": "roborock.vacuum.a15", "name": "S7", "rriotid": "rriot-a15"}, + ], + }, + { + "category": {"id": 9, "code": "roborock.mowbs"}, + "productList": [{"id": 314, "model": "roborock.mowbs.a355", "name": "WiFi Amplifier Charging Station"}], + }, + ] +} + +CLOUD_RECORDS = [ + {"version": 7046, "url": "https://app-files.roborock.com/iot/plugin/a307.zip", "pluginLevel": 3002, "productid": 263, "apilevel": 10030}, + {"version": 5208, "url": "https://app-files.roborock.com/iot/plugin/a15.zip", "pluginLevel": 3001, "productid": 23, "apilevel": 10028}, +] + + +def test_refresh_requests_all_product_ids_and_sorts_the_catalog() -> None: + requests: list[tuple[str, str, dict[str, Any] | None]] = [] + + async def fake_call(path: str, *, method: str = "get", json_body: dict[str, Any] | None = None) -> Any: + requests.append((path, method, json_body)) + return CLOUD_PRODUCTS if path == "/api/v5/product" else CLOUD_RECORDS + + products, records = asyncio.run(fetch_cloud_answers(fake_call)) + catalog = build_catalog( + products, + records, + base_url="https://euiot.roborock.com", + region="eu", + fetched_at_utc="2026-11-21T00:00:00+00:00", + ) + + # The app sends this body; one request covers every product. + assert requests[1] == ( + "/api/v1/appplugin", + "post", + {"type": 2, "apilevel": 10046, "productids": [23, 263, 314]}, + ) + assert list(catalog["products"]) == ["roborock.mowbs.a355", "roborock.vacuum.a15", "roborock.vacuum.a307"] + assert catalog["products"]["roborock.vacuum.a307"] == { + "id": 263, + "name": "Saros 20 Flow", + "category": "robot.vacuum.cleaner", + } + assert [record["productid"] for record in catalog["appplugin"]] == [23, 263] + assert catalog["source"]["base_url"] == "https://euiot.roborock.com" + assert catalog["source"]["region"] == "eu" + # The catalog in the checkout has the same source keys as a new one. + eu_catalog = json.loads(catalog_path("eu").read_text(encoding="utf-8")) + assert list(eu_catalog["source"]) == list(catalog["source"]) + assert catalog["source"]["fetched_at_utc"] == "2026-11-21T00:00:00+00:00" + + +def test_stored_login_of_raw_user_data_takes_the_email_as_username(tmp_path: Path, monkeypatch) -> None: + clients: list[tuple[str, str | None]] = [] + + class FakeApiClient: + def __init__(self, *, username: str, base_url: str | None, session: Any) -> None: + clients.append((username, base_url)) + + monkeypatch.setattr(refresh, "RoborockApiClient", FakeApiClient) + monkeypatch.setattr(refresh, "UserData", types.SimpleNamespace(from_dict=lambda data: data)) + # Raw user data, as the app stores it, has no username. + source = tmp_path / "raw-user-data.json" + source.write_text(json.dumps({"uid": 1, "rruid": "rr-user"}), encoding="utf-8") + args = argparse.Namespace(source_json=source, email="user@example.com", base_url="https://euiot.roborock.com") + + _api, user_data = asyncio.run(refresh._login(args, session=None)) + + assert clients == [("user@example.com", "https://euiot.roborock.com")] + assert user_data == {"uid": 1, "rruid": "rr-user"} + + +@pytest.mark.parametrize( + ("base_url", "region", "expected"), + [ + ("https://euiot.roborock.com", None, "eu"), + ("https://usiot.roborock.com", None, "us"), + ("https://cniot.roborock.com", None, "cn"), + ("https://ruiot.roborock.com", None, "ru"), + ("https://usiot.roborock.com", "us", "us"), + ("https://newiot.roborock.com", "sg", "sg"), + ], +) +def test_catalog_region_comes_from_the_cloud_host(base_url: str, region: str | None, expected: str) -> None: + assert catalog_region(base_url, region) == expected + + +def test_catalog_region_of_an_unknown_host_needs_the_region_option() -> None: + with pytest.raises(RuntimeError, match="Pass --region"): + catalog_region("https://newiot.roborock.com") + with pytest.raises(RuntimeError, match="does not match"): + catalog_region("https://euiot.roborock.com", "us") + + +def test_catalog_path_is_the_file_that_the_server_loads() -> None: + from shared import device_plugin_catalog + + assert catalog_path("us").name == "device_plugin_catalog_us.json" + assert catalog_path("eu") == device_plugin_catalog.CATALOG_DIR / "device_plugin_catalog_eu.json" + assert catalog_path("eu").exists() + + +@pytest.mark.parametrize("answer", [{"list": []}, [], None, ["not a record"]]) +def test_refresh_fails_if_the_cloud_answers_no_plugin_record(answer: Any) -> None: + async def fake_call(path: str, *, method: str = "get", json_body: dict[str, Any] | None = None) -> Any: + return CLOUD_PRODUCTS if path == "/api/v5/product" else answer + + with pytest.raises(RuntimeError, match="no plugin record"): + asyncio.run(fetch_cloud_answers(fake_call)) + + +def test_write_catalog_replaces_the_file_and_leaves_no_temporary_file(tmp_path: Path) -> None: + path = tmp_path / "device_plugin_catalog_eu.json" + path.write_text('{"old": true}\n', encoding="utf-8") + + write_catalog(path, {"products": {}, "appplugin": []}) + + assert json.loads(path.read_text(encoding="utf-8")) == {"products": {}, "appplugin": []} + assert [file.name for file in tmp_path.iterdir()] == ["device_plugin_catalog_eu.json"] + + +def test_failed_write_keeps_the_old_catalog_and_leaves_no_temporary_file(tmp_path: Path, monkeypatch) -> None: + path = tmp_path / "device_plugin_catalog_eu.json" + path.write_text('{"old": true}\n', encoding="utf-8") + + def fail_replace(self: Path, target: Path) -> Path: + raise OSError("disk full") + + # The .tmp file is complete, and the replace fails. + monkeypatch.setattr(Path, "replace", fail_replace) + with pytest.raises(OSError, match="disk full"): + write_catalog(path, {"products": {}, "appplugin": []}) + + assert json.loads(path.read_text(encoding="utf-8")) == {"old": True} + assert [file.name for file in tmp_path.iterdir()] == ["device_plugin_catalog_eu.json"]