From 3ac27b7e7e5679b48a64c4d151f1f7369f291fc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Sat, 21 Nov 2026 22:19:54 +0100 Subject: [PATCH 01/12] feat(plugin): serve the device plugin of every cloud model without a cloud import Without a cloud import, the server knew the numeric product id and the Android plugin record of three models only (a87, a15, sc05). Every other model got a hashed product id in /api/v5/product, and /api/v1/appplugin had no record for it. The new shared/device_plugin_catalog.json holds the EU cloud's numeric product id of 81 models in five categories, and the Android plugin record of the 79 products that have one. It replaces MODEL_PRODUCT_ID_OVERRIDES and the hardcoded APPPLUGIN_LIST. scripts/refresh_device_plugin_catalog.py rebuilds it with any cloud login, in two requests. /api/v5/product takes the product id from the account's cloud import first, then a numeric id in home data, then the catalog id of the model, then the hashed id. Product ids differ by cloud region, so the import's id now also wins over the old hardcoded ids. Before, the a87 got 110 even with an EU import, and in the EU cloud 110 is the Zeo Lite washer (roborock.wm.a91). Without an import, the a87 now gets the EU id 103. /api/v1/appplugin answers the catalog records for the product ids that the cloud snapshot has no record for, like the built-in list before. It skips an id that the cloud import gives to another model than the catalog does, because that record would be the plugin of another model. --- scripts/refresh_device_plugin_catalog.py | 158 +++ .../https_server/endpoint_rules.py | 10 +- .../routes/api/product_service.py | 18 +- .../https_server/routes/api/v1/appplugin.py | 30 +- .../https_server/routes/plugin/common.py | 27 +- .../bundled_backend/shared/constants.py | 6 - .../shared/device_plugin_catalog.json | 971 ++++++++++++++++++ .../shared/device_plugin_catalog.py | 32 + tests/test_plugin_routes.py | 143 ++- tests/test_product_response.py | 114 ++ tests/test_refresh_device_plugin_catalog.py | 57 + 11 files changed, 1519 insertions(+), 47 deletions(-) create mode 100644 scripts/refresh_device_plugin_catalog.py create mode 100644 src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.json create mode 100644 src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py create mode 100644 tests/test_refresh_device_plugin_catalog.py diff --git a/scripts/refresh_device_plugin_catalog.py b/scripts/refresh_device_plugin_catalog.py new file mode 100644 index 00000000..fed37339 --- /dev/null +++ b/scripts/refresh_device_plugin_catalog.py @@ -0,0 +1,158 @@ +"""Rebuild the built-in device plugin catalog from the Roborock cloud. + +Without a cloud snapshot, the server answers /api/v5/product and +/api/v1/appplugin from this catalog. Any Roborock account 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. The script makes two +cloud requests and writes no login data. +""" + +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") +as_int = importlib.import_module("shared.data_helpers").as_int + +# Read by shared/device_plugin_catalog.py. +CATALOG_PATH = BACKEND_PATH / "shared" / "device_plugin_catalog.json" + +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) + return products, records + + +def build_catalog(products: Any, records: Any, *, base_url: 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, + "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, + 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) + + 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) + base_url = str(await api.base_url) + catalog = build_catalog( + products, + records, + base_url=base_url, + fetched_at_utc=datetime.now(UTC).isoformat(), + ) + args.output.write_text(json.dumps(catalog, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + 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 {args.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.") + 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( + "--output", + type=Path, + default=CATALOG_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..22b72a47 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,10 @@ 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.device_plugin_catalog import BUILTIN_PRODUCT_IDS from shared.http_helpers import wrap_response from shared.inventory_io import WEB_API_INVENTORY_FILE, load_inventory, write_inventory @@ -525,9 +526,10 @@ def _build_product_response(ctx: ServerContext, home_data: dict[str, Any]) -> di } 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_id = ( + as_int(raw_product_id, 0) + or BUILTIN_PRODUCT_IDS.get(model_key) + or stable_int(raw_product_id or category_name) % 1_000_000 ) product_entry = { "id": product_id, 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..efce2946 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,9 +2,9 @@ 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.device_plugin_catalog import BUILTIN_PRODUCT_IDS from ..plugin.common import snapshot_plugin_catalog_data @@ -37,12 +37,18 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]: } 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, + # The app requests the device plugin with this numeric id, so a hashed + # id gets it no plugin. Product ids differ by cloud region. So the id + # from the account's own cloud import wins, then a numeric id in home + # data, then the built-in id of the model. Newer models (e.g. a226) + # have a string id in home data. The built-in ids come from the EU + # cloud. Without an import, they only need to match the built-in plugin + # records, because the app gets both answers from this server. + product_id = ( cloud_product_ids.get(model_key) - or as_int(raw_product_id, stable_int(raw_product_id or category_name) % 1_000_000), + or as_int(raw_product_id, 0) + or BUILTIN_PRODUCT_IDS.get(model_key) + or stable_int(raw_product_id or category_name) % 1_000_000 ) product_entry = { "id": product_id, 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..7d1b5ce0 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 @@ -4,10 +4,16 @@ from typing import Any from shared.context import ServerContext -from shared.data_helpers import as_int +from shared.data_helpers import as_int, model_product_ids +from shared.device_plugin_catalog import BUILTIN_MODELS_BY_PRODUCT_ID from ...auth.service import ok -from ...plugin.common import APPPLUGIN_LIST, proxied_plugin_records, snapshot_plugin_records +from ...plugin.common import ( + APPPLUGIN_LIST, + proxied_plugin_records, + snapshot_plugin_catalog_data, + snapshot_plugin_records, +) # Request "type" of the iOS app; Android sends 2. IOS_APP_TYPE = 1 @@ -59,6 +65,24 @@ 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]]: + # The built-in records are keyed by the product ids of the EU cloud, and + # the ids differ by cloud region. If the cloud import gives an id to + # another model, the built-in record of that id is the plugin of another + # model here. So that id gets no built-in record. + import_models = { + product_id: model + for model, product_id in model_product_ids(snapshot_plugin_catalog_data(ctx, "product")).items() + } + records = [] + for record in APPPLUGIN_LIST: + product_id = _product_id(record) + built_in_model = BUILTIN_MODELS_BY_PRODUCT_ID.get(product_id) + if product_id in product_ids and import_models.get(product_id, built_in_model) == built_in_model: + records.append(record) + return records + + def build( ctx: ServerContext, _query_params: dict[str, list[str]], @@ -84,5 +108,5 @@ def build( # 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] + 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..65d54807 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,7 @@ from fastapi.responses import Response from shared.context import ServerContext +from shared.device_plugin_catalog import BUILTIN_APPPLUGIN_RECORDS from ..auth.service import load_cloud_full_snapshot PLUGIN_PROXY_ALLOWED_HOSTS = { @@ -82,29 +83,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 from the Roborock EU cloud. /api/v1/appplugin +# answers them for the product ids that the cloud snapshot has no record for. +APPPLUGIN_LIST = BUILTIN_APPPLUGIN_RECORDS def plugin_proxy_url(ctx: ServerContext, source_url: str) -> str: 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/device_plugin_catalog.json b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.json new file mode 100644 index 00000000..454a4689 --- /dev/null +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.json @@ -0,0 +1,971 @@ +{ + "_comment": "Generated by scripts/refresh_device_plugin_catalog.py. Do not edit by hand.", + "source": { + "base_url": "https://euiot.roborock.com", + "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/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..5a16506a --- /dev/null +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py @@ -0,0 +1,32 @@ +"""Built-in numeric product ids and Android device plugin records. + +The data comes from the Roborock EU cloud: 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 +rebuilds device_plugin_catalog.json with any cloud login. + +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. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +DEVICE_PLUGIN_CATALOG_PATH = Path(__file__).with_name("device_plugin_catalog.json") + +_CATALOG: dict[str, Any] = json.loads(DEVICE_PLUGIN_CATALOG_PATH.read_text(encoding="utf-8")) + +# Model -> numeric product id. /api/v5/product answers it as the product "id", +# and the app requests the device plugin with it. +BUILTIN_PRODUCT_IDS: dict[str, int] = { + model: int(entry["id"]) for model, entry in _CATALOG["products"].items() +} + +# Numeric product id -> model. Each id belongs to one model. +BUILTIN_MODELS_BY_PRODUCT_ID: dict[int, str] = {product_id: model for model, product_id in BUILTIN_PRODUCT_IDS.items()} + +# Android (type 2) records in the shape of the /api/v1/appplugin answer. +BUILTIN_APPPLUGIN_RECORDS: list[dict[str, Any]] = [dict(record) for record in _CATALOG["appplugin"]] diff --git a/tests/test_plugin_routes.py b/tests/test_plugin_routes.py index 1c65e70b..9b6f12cb 100644 --- a/tests/test_plugin_routes.py +++ b/tests/test_plugin_routes.py @@ -253,6 +253,8 @@ 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]) @@ -262,16 +264,17 @@ def test_app_plugin_falls_back_to_built_in_list_for_ids_missing_from_snapshot(tm 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, @@ -290,7 +293,11 @@ def test_app_plugin_prefers_snapshot_record_over_built_in_record(tmp_path: Path) 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" @@ -529,3 +536,129 @@ 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( + ("product_id", "version", "source"), + [ + # roborock.vacuum.a307, Saros 20 Flow + (263, 7046, "https://app-files.roborock.com/iot/plugin/de0ceb1351854a819a0374fdcbf17831.zip"), + # roborock.vacuum.a226, Qrevo Curv 2 Pro + (199, 6846, "https://app-files.roborock.com/iot/plugin/69588500d2c54b0bb154a967646dd57b.zip"), + # roborock.wdv.a194, F25 Ultra + (180, 2674, "https://app-files.roborock.com/iot/plugin/6d5e1e8589e54a1e81351ee54b75eed7.zip"), + # roborock.mower.a222, RockNeo Q1 + (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, product_id: int, version: int, source: str +) -> None: + supervisor = _build_supervisor(tmp_path) + 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_no_built_in_record_of_another_model(tmp_path: Path, model: str, import_id: int) -> None: + # 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)]}, + }, + ) + client = TestClient(supervisor.app) + + response = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [import_id], "type": 2}) + + assert _app_plugin_sources(response.json()) == [] + + +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)]}, + }, + ) + 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 as catalog + + product_ids = list(catalog.BUILTIN_PRODUCT_IDS.values()) + record_ids = [record["productid"] for record in catalog.BUILTIN_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.BUILTIN_APPPLUGIN_RECORDS: + assert is_allowed_plugin_source(record["url"]) diff --git a/tests/test_product_response.py b/tests/test_product_response.py index 35c05ebb..6fff9393 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, @@ -141,3 +143,115 @@ 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]) -> None: + # The import stores the cloud's /api/v5/product answer in the snapshot. + product_list = [{"id": product_id, "model": model} for model, product_id in products.items()] + catalog = {"data": {"categoryDetailList": [{"category": {"id": 1}, "productList": product_list}]}} + snapshot = {"web_api_cache": {"plugin_catalogs": {"product": catalog}}} + (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(tmp_path: Path) -> None: + _write_cloud_products(tmp_path, {"roborock.vacuum.a226": 199}) + 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 + + +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"]] diff --git a/tests/test_refresh_device_plugin_catalog.py b/tests/test_refresh_device_plugin_catalog.py new file mode 100644 index 00000000..3aec4731 --- /dev/null +++ b/tests/test_refresh_device_plugin_catalog.py @@ -0,0 +1,57 @@ +import asyncio +from typing import Any + +from scripts.refresh_device_plugin_catalog import build_catalog, fetch_cloud_answers + +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", + 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"]["fetched_at_utc"] == "2026-11-21T00:00:00+00:00" From c66e0f5ac0954777a45f86c502eb00b40651e1ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Sat, 21 Nov 2026 23:05:43 +0100 Subject: [PATCH 02/12] fix(scripts): take the email as username for a stored raw user data login A raw user data file has no username, and the import helper needs one. The refresh script did not pass --email on, so --source-json with raw user data failed with "Username is missing". It now passes the email as the username override, and the help text says so. --- scripts/refresh_device_plugin_catalog.py | 11 ++++++--- tests/test_refresh_device_plugin_catalog.py | 25 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/scripts/refresh_device_plugin_catalog.py b/scripts/refresh_device_plugin_catalog.py index fed37339..afc47a5d 100644 --- a/scripts/refresh_device_plugin_catalog.py +++ b/scripts/refresh_device_plugin_catalog.py @@ -9,8 +9,9 @@ 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. The script makes two -cloud requests and writes no login data. +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. """ from __future__ import annotations @@ -99,6 +100,7 @@ async def _login(args: argparse.Namespace, session: aiohttp.ClientSession) -> tu 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) @@ -137,7 +139,10 @@ async def call(path: str, *, method: str = "get", json_body: dict[str, Any] | No def _parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--email", help="Roborock account email for a code login.") + 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( diff --git a/tests/test_refresh_device_plugin_catalog.py b/tests/test_refresh_device_plugin_catalog.py index 3aec4731..b602026d 100644 --- a/tests/test_refresh_device_plugin_catalog.py +++ b/tests/test_refresh_device_plugin_catalog.py @@ -1,6 +1,11 @@ +import argparse import asyncio +import json +import types +from pathlib import Path from typing import Any +import scripts.refresh_device_plugin_catalog as refresh from scripts.refresh_device_plugin_catalog import build_catalog, fetch_cloud_answers CLOUD_PRODUCTS = { @@ -55,3 +60,23 @@ async def fake_call(path: str, *, method: str = "get", json_body: dict[str, Any] assert [record["productid"] for record in catalog["appplugin"]] == [23, 263] assert catalog["source"]["base_url"] == "https://euiot.roborock.com" 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"} From 4e74554e28143e888fe9bd5c9358bc2913d5c8ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Sat, 21 Nov 2026 23:06:20 +0100 Subject: [PATCH 03/12] fix(import): fetch the device plugins by the product list id of each model The local /api/v5/product gives a model the id of the cloud's product list, but the import fetched the plugins by the numeric home data id. If the two ids differed, the snapshot had no record for the id that the app requests, and the app got the Android-only built-in record, also on iOS. The import now takes the product list id of each model first, then the numeric home data id, like /api/v5/product. --- .../import_web_inventory_from_cloud.py | 25 ++++++++--------- tests/test_cloud_plugin_catalogs.py | 28 +++++++++++++++++++ 2 files changed, 39 insertions(+), 14 deletions(-) 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/tests/test_cloud_plugin_catalogs.py b/tests/test_cloud_plugin_catalogs.py index 8f8a1699..26aa060e 100644 --- a/tests/test_cloud_plugin_catalogs.py +++ b/tests/test_cloud_plugin_catalogs.py @@ -51,3 +51,31 @@ 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]] From 522453985b5a3a4f7859f013ef7acb01eda23320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Sat, 21 Nov 2026 23:11:24 +0100 Subject: [PATCH 04/12] fix(plugin): look up the built-in plugin catalog by model Product ids differ by cloud region, so a built-in record looked up by its EU id could be the plugin of another model, like the washer record of 110 for an a87 with a US import. /api/v5/product now resolves the ids of all home data products in one helper: the import's id, then a numeric home data id, then the built-in id if no other model holds it, then the hashed id. For an id that the snapshot has no record for, /api/v1/appplugin answers the built-in record of the model that gets the id, with the requested id. An id that no device has, or that two models get, gets no record. --- .../https_server/endpoint_rules.py | 21 +-- .../routes/api/product_service.py | 46 +++-- .../https_server/routes/api/v1/appplugin.py | 49 +++--- .../https_server/routes/plugin/common.py | 4 +- .../shared/device_plugin_catalog.py | 58 +++++- tests/test_plugin_routes.py | 57 ++++-- tests/test_product_response.py | 165 +++++++++++++++++- 7 files changed, 318 insertions(+), 82 deletions(-) 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 22b72a47..634122ed 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 @@ -9,8 +9,8 @@ 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.device_plugin_catalog import BUILTIN_PRODUCT_IDS +from shared.data_helpers import as_bool, as_int, default_home_id, default_product_name, get_value, model_product_ids +from shared.device_plugin_catalog import product_fields, resolve_product_ids from shared.http_helpers import wrap_response from shared.inventory_io import WEB_API_INVENTORY_FILE, load_inventory, write_inventory @@ -94,6 +94,7 @@ from .routes.api.v1.user import match_logout as _match_logout_v1 from .routes.api.v1.user import match_user_info as _match_user_info_v1 from .routes.api.v1.user import match_user_roles as _match_user_roles_v1 +from .routes.plugin.common import snapshot_plugin_catalog_data from .routes.user.app.info import build as _build_post_app_info from .routes.user.app.info import match as _match_post_app_info from .routes.user.inbox.latest import build as _build_get_inbox_latest @@ -508,12 +509,11 @@ def _build_product_response(ctx: ServerContext, home_data: dict[str, Any]) -> di 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 [] + products = [product for product in products if isinstance(product, dict)] + cloud_product_ids = model_product_ids(snapshot_plugin_catalog_data(ctx, "product")) 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 zip(products, resolve_product_ids(products, cloud_product_ids)): + model, _, category_name = product_fields(product) if category_name not in categories: category_id = len(categories) + 1 categories[category_name] = { @@ -524,13 +524,6 @@ def _build_product_response(ctx: ServerContext, home_data: dict[str, Any]) -> di }, "productList": [], } - model = str(product.get("model") or "roborock.vacuum.a117") - model_key = model.strip().lower() - product_id = ( - as_int(raw_product_id, 0) - or BUILTIN_PRODUCT_IDS.get(model_key) - or 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/product_service.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py index efce2946..8cd872e4 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 @@ -3,25 +3,36 @@ from typing import Any from shared.context import ServerContext -from shared.data_helpers import as_int, default_product_name, model_product_ids, stable_int -from shared.device_plugin_catalog import BUILTIN_PRODUCT_IDS +from shared.data_helpers import default_product_name, model_product_ids +from shared.device_plugin_catalog import product_fields, resolve_product_ids from ..plugin.common import snapshot_plugin_catalog_data 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) -> 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")) + return list(zip(products, resolve_product_ids(products, cloud_product_ids))) + + +def served_models_by_product_id(ctx: ServerContext) -> 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): + 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): + model, raw_product_id, category_name = product_fields(product) if category_name not in categories: category_id = len(categories) + 1 categories[category_name] = { @@ -35,21 +46,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() - # The app requests the device plugin with this numeric id, so a hashed - # id gets it no plugin. Product ids differ by cloud region. So the id - # from the account's own cloud import wins, then a numeric id in home - # data, then the built-in id of the model. Newer models (e.g. a226) - # have a string id in home data. The built-in ids come from the EU - # cloud. Without an import, they only need to match the built-in plugin - # records, because the app gets both answers from this server. - product_id = ( - cloud_product_ids.get(model_key) - or as_int(raw_product_id, 0) - or BUILTIN_PRODUCT_IDS.get(model_key) - or 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 7d1b5ce0..66cf83cb 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 @@ -4,16 +4,16 @@ from typing import Any from shared.context import ServerContext -from shared.data_helpers import as_int, model_product_ids -from shared.device_plugin_catalog import BUILTIN_MODELS_BY_PRODUCT_ID +from shared.data_helpers import as_int +from shared.device_plugin_catalog import BUILTIN_APPPLUGIN_RECORDS_BY_MODEL from ...auth.service import ok from ...plugin.common import ( APPPLUGIN_LIST, proxied_plugin_records, - snapshot_plugin_catalog_data, 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 @@ -66,20 +66,25 @@ def _product_id(record: dict[str, Any]) -> int: def _built_in_records(ctx: ServerContext, product_ids: set[int]) -> list[dict[str, Any]]: - # The built-in records are keyed by the product ids of the EU cloud, and - # the ids differ by cloud region. If the cloud import gives an id to - # another model, the built-in record of that id is the plugin of another - # model here. So that id gets no built-in record. - import_models = { - product_id: model - for model, product_id in model_product_ids(snapshot_plugin_catalog_data(ctx, "product")).items() - } + # 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. + served_models = served_models_by_product_id(ctx) records = [] - for record in APPPLUGIN_LIST: - product_id = _product_id(record) - built_in_model = BUILTIN_MODELS_BY_PRODUCT_ID.get(product_id) - if product_id in product_ids and import_models.get(product_id, built_in_model) == built_in_model: - records.append(record) + for product_id in sorted(product_ids): + models = served_models.get(product_id, set()) + if len(models) != 1: + continue + [model] = models + record = BUILTIN_APPPLUGIN_RECORDS_BY_MODEL.get(model) + if record is None: + continue + # The built-in records come from the EU cloud. For another region, the + # device gets the EU record of the same model, with the id that the app + # requested. That record is not verified for the other region, but it + # is the plugin of the same model. Without it, the device would get no + # plugin. + records.append(dict(record, productid=product_id)) return records @@ -103,10 +108,12 @@ def build( # 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 += _built_in_records(ctx, 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 65d54807..b0a00fe2 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 @@ -84,7 +84,9 @@ ] # Android device plugin records from the Roborock EU cloud. /api/v1/appplugin -# answers them for the product ids that the cloud snapshot has no record for. +# answers all of them to a request without product ids. For a requested id +# that the cloud snapshot has no record for, it answers the record of the +# model that /api/v5/product gives the id to. APPPLUGIN_LIST = BUILTIN_APPPLUGIN_RECORDS 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 index 5a16506a..2af1566f 100644 --- a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py @@ -12,9 +12,12 @@ from __future__ import annotations import json +from collections.abc import Mapping, Sequence from pathlib import Path from typing import Any +from .data_helpers import as_int, stable_int + DEVICE_PLUGIN_CATALOG_PATH = Path(__file__).with_name("device_plugin_catalog.json") _CATALOG: dict[str, Any] = json.loads(DEVICE_PLUGIN_CATALOG_PATH.read_text(encoding="utf-8")) @@ -25,8 +28,57 @@ model: int(entry["id"]) for model, entry in _CATALOG["products"].items() } -# Numeric product id -> model. Each id belongs to one model. -BUILTIN_MODELS_BY_PRODUCT_ID: dict[int, str] = {product_id: model for model, product_id in BUILTIN_PRODUCT_IDS.items()} - # Android (type 2) records in the shape of the /api/v1/appplugin answer. BUILTIN_APPPLUGIN_RECORDS: list[dict[str, Any]] = [dict(record) for record in _CATALOG["appplugin"]] + +_RECORDS_BY_PRODUCT_ID = {as_int(record.get("productid"), 0): record for record in BUILTIN_APPPLUGIN_RECORDS} + +# Model -> its Android record. /api/v1/appplugin looks the record up by the +# model that /api/v5/product gives the requested id to. +BUILTIN_APPPLUGIN_RECORDS_BY_MODEL: dict[str, dict[str, Any]] = { + model: _RECORDS_BY_PRODUCT_ID[product_id] + for model, product_id in BUILTIN_PRODUCT_IDS.items() + if product_id in _RECORDS_BY_PRODUCT_ID +} + + +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]) -> 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. A snapshot record matches + only the id of the cloud import, and /api/v1/appplugin 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. + """ + fields = [product_fields(product) for product in products] + model_keys = [model.strip().lower() for model, _, _ in fields] + 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]] = {} + for key, product_id in [*import_ids.items(), *zip(model_keys, fixed_ids)]: + if product_id: + holders.setdefault(product_id, set()).add(key) + product_ids: list[int] = [] + for key, fixed_id, (_, raw_id, category) in zip(model_keys, fixed_ids, fields): + built_in_id = BUILTIN_PRODUCT_IDS.get(key) + if fixed_id: + product_ids.append(fixed_id) + # The built-in ids come from the EU cloud. Another model can hold the + # same id in the import or in home data, like the a199 holds 199 in + # the US 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/tests/test_plugin_routes.py b/tests/test_plugin_routes.py index 9b6f12cb..be2e0156 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"]}) @@ -258,6 +278,7 @@ def test_app_plugin_falls_back_to_built_in_list_for_ids_missing_from_snapshot(tm 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}) @@ -288,6 +309,7 @@ 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}) @@ -474,7 +496,8 @@ 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 built-in list also has 23, which + # the paired a15 gets. supervisor = _build_supervisor(tmp_path) _write_app_plugin_snapshot( supervisor, @@ -489,6 +512,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) @@ -539,22 +563,23 @@ def test_app_plugin_ios_answers_full_ios_catalog_without_product_ids(tmp_path: P @pytest.mark.parametrize( - ("product_id", "version", "source"), + ("model", "product_id", "version", "source"), [ - # roborock.vacuum.a307, Saros 20 Flow - (263, 7046, "https://app-files.roborock.com/iot/plugin/de0ceb1351854a819a0374fdcbf17831.zip"), - # roborock.vacuum.a226, Qrevo Curv 2 Pro - (199, 6846, "https://app-files.roborock.com/iot/plugin/69588500d2c54b0bb154a967646dd57b.zip"), - # roborock.wdv.a194, F25 Ultra - (180, 2674, "https://app-files.roborock.com/iot/plugin/6d5e1e8589e54a1e81351ee54b75eed7.zip"), - # roborock.mower.a222, RockNeo Q1 - (224, 856, "https://app-files.roborock.com/iot/plugin/9dbe90bcb3b343458086800d7f556ab2.zip"), + # 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, product_id: int, version: int, source: str + 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}) @@ -608,7 +633,11 @@ def _cloud_product_catalog(products: dict[str, int]) -> dict: ("roborock.vacuum.a87", 110), ], ) -def test_app_plugin_answers_no_built_in_record_of_another_model(tmp_path: Path, model: str, import_id: int) -> None: +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 BUILTIN_APPPLUGIN_RECORDS_BY_MODEL + # 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. @@ -620,11 +649,12 @@ def test_app_plugin_answers_no_built_in_record_of_another_model(tmp_path: Path, "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}) - assert _app_plugin_sources(response.json()) == [] + assert _app_plugin_sources(response.json()) == [(import_id, BUILTIN_APPPLUGIN_RECORDS_BY_MODEL[model]["url"])] def test_app_plugin_answers_built_in_record_if_import_ids_agree(tmp_path: Path) -> None: @@ -640,6 +670,7 @@ def test_app_plugin_answers_built_in_record_if_import_ids_agree(tmp_path: Path) "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] diff --git a/tests/test_product_response.py b/tests/test_product_response.py index 6fff9393..6bb8fbec 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -187,11 +187,18 @@ def test_numeric_inventory_product_id_wins_over_built_in_id(tmp_path: Path) -> N assert product["id"] == 4242 -def _write_cloud_products(tmp_path: Path, products: dict[str, int]) -> None: - # The import stores the cloud's /api/v5/product answer in the snapshot. +def _write_cloud_products( + tmp_path: Path, products: dict[str, int], app_plugin_records: list[dict[str, object]] | 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()] - catalog = {"data": {"categoryDetailList": [{"category": {"id": 1}, "productList": product_list}]}} - snapshot = {"web_api_cache": {"plugin_catalogs": {"product": catalog}}} + 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 = {"web_api_cache": {"plugin_catalogs": catalogs}} (tmp_path / "web_api_inventory_full_snapshot.json").write_text(json.dumps(snapshot), encoding="utf-8") @@ -220,7 +227,8 @@ def test_cloud_import_product_id_wins_over_built_in_id( assert product["id"] == import_id -def test_model_missing_from_cloud_import_gets_built_in_id(tmp_path: Path) -> None: +def test_model_missing_from_cloud_import_gets_built_in_id_and_record(tmp_path: Path) -> None: + # The import comes from the EU cloud, like the built-in list. _write_cloud_products(tmp_path, {"roborock.vacuum.a226": 199}) device = dict(_DEVICE, model="roborock.vacuum.a307", product_id="4J89YHjAc2uUG9W0HLxKPP") @@ -228,6 +236,7 @@ def test_model_missing_from_cloud_import_gets_built_in_id(tmp_path: Path) -> Non [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: @@ -255,3 +264,149 @@ def test_app_gets_a307_plugin_without_cloud_import(tmp_path: Path) -> None: 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 _legacy_product_list(tmp_path: Path, device: dict[str, object]) -> list[dict]: + from https_server.endpoint_rules import _build_product_response + + home_data = { + "devices": [{"duid": device["duid"], "productId": device["product_id"]}], + "products": [{"id": device["product_id"], "model": device["model"], "category": "robot.vacuum.cleaner"}], + } + return _build_product_response(_make_context(tmp_path), home_data)["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 BUILTIN_APPPLUGIN_RECORDS_BY_MODEL + + return BUILTIN_APPPLUGIN_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") + + +@pytest.mark.parametrize("product_list", [_v5_product_list, _legacy_product_list], ids=["api_v5", "legacy"]) +def test_built_in_id_that_the_import_gives_another_model_is_skipped(tmp_path: Path, product_list) -> 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] = 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}) + 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 built-in list, 110 is the roborock.wm.a91 washer. + _write_cloud_products(tmp_path, {"roborock.vacuum.a87": 110}) + [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 BUILTIN_APPPLUGIN_RECORDS_BY_MODEL + + # 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 BUILTIN_APPPLUGIN_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) == [] From 3ace120121617e604aeb21eee860f8c8a70dc68f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Sat, 21 Nov 2026 23:18:54 +0100 Subject: [PATCH 05/12] feat(plugin): pick the built-in plugin catalog by cloud region The built-in catalog is now one file per cloud region, shared/device_plugin_catalog_.json, and the current one is the EU catalog. The server takes the region of its cloud import: the region of meta.base_url, else the region in the user data. Without an import, or if the import's region is unknown, it takes network.region from the config. The id resolution and the plugin lookup by model use the catalog of that region. A region without its own catalog uses the EU catalog, so a device gets the EU record of its model. The refresh script writes the file of the region. It takes the region from the cloud host, or from --region for an unknown host. --- scripts/refresh_device_plugin_catalog.py | 53 ++++++++--- .../https_server/endpoint_rules.py | 5 +- .../routes/api/product_service.py | 14 +-- .../https_server/routes/api/v1/appplugin.py | 18 ++-- .../https_server/routes/plugin/common.py | 38 ++++++-- .../bundled_backend/shared/data_helpers.py | 18 ++++ .../shared/device_plugin_catalog.py | 90 +++++++++++++------ ...log.json => device_plugin_catalog_eu.json} | 1 + tests/test_plugin_routes.py | 34 ++++--- tests/test_product_response.py | 90 ++++++++++++++++--- tests/test_refresh_device_plugin_catalog.py | 44 ++++++++- 11 files changed, 313 insertions(+), 92 deletions(-) rename src/roborock_local_server/bundled_backend/shared/{device_plugin_catalog.json => device_plugin_catalog_eu.json} (99%) diff --git a/scripts/refresh_device_plugin_catalog.py b/scripts/refresh_device_plugin_catalog.py index afc47a5d..0312059f 100644 --- a/scripts/refresh_device_plugin_catalog.py +++ b/scripts/refresh_device_plugin_catalog.py @@ -1,8 +1,8 @@ -"""Rebuild the built-in device plugin catalog from the Roborock cloud. +"""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 this catalog. Any Roborock account works, also one -without devices: +/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 @@ -12,6 +12,10 @@ 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 @@ -37,10 +41,11 @@ sys.path.insert(0, str(BACKEND_PATH)) # Loaded after the path change above. importer = importlib.import_module("import_web_inventory_from_cloud") -as_int = importlib.import_module("shared.data_helpers").as_int +data_helpers = importlib.import_module("shared.data_helpers") +as_int = data_helpers.as_int -# Read by shared/device_plugin_catalog.py. -CATALOG_PATH = BACKEND_PATH / "shared" / "device_plugin_catalog.json" +# 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" @@ -81,12 +86,29 @@ async def fetch_cloud_answers(call: CloudCall) -> tuple[Any, Any]: return products, records -def build_catalog(products: Any, records: Any, *, base_url: str, fetched_at_utc: str) -> dict[str, Any]: +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 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}", @@ -116,23 +138,26 @@ 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) - base_url = str(await api.base_url) catalog = build_catalog( products, records, base_url=base_url, + region=region, fetched_at_utc=datetime.now(UTC).isoformat(), ) - args.output.write_text(json.dumps(catalog, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + output = args.output or catalog_path(region) + output.write_text(json.dumps(catalog, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") 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 {args.output}: {len(catalog['products'])} products, {len(catalog['appplugin'])} plugin records.") + 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)}") @@ -145,11 +170,15 @@ def _parse_args() -> argparse.Namespace: ) 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, - default=CATALOG_PATH, - help="Catalog to write (default: shared/device_plugin_catalog.json in the bundled backend).", + help="Catalog to write (default: shared/device_plugin_catalog_.json in the bundled backend).", ) return parser.parse_args() 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 634122ed..a68b18d0 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 @@ -94,7 +94,7 @@ from .routes.api.v1.user import match_logout as _match_logout_v1 from .routes.api.v1.user import match_user_info as _match_user_info_v1 from .routes.api.v1.user import match_user_roles as _match_user_roles_v1 -from .routes.plugin.common import snapshot_plugin_catalog_data +from .routes.plugin.common import built_in_catalog, snapshot_plugin_catalog_data from .routes.user.app.info import build as _build_post_app_info from .routes.user.app.info import match as _match_post_app_info from .routes.user.inbox.latest import build as _build_get_inbox_latest @@ -511,8 +511,9 @@ def _build_product_response(ctx: ServerContext, home_data: dict[str, Any]) -> di 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, built_in_catalog(ctx)) categories: dict[str, dict[str, Any]] = {} - for product, product_id in zip(products, resolve_product_ids(products, cloud_product_ids)): + for product, product_id in zip(products, product_ids): model, _, category_name = product_fields(product) if category_name not in categories: category_id = len(categories) + 1 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 8cd872e4..d8dbe8a7 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 @@ -4,26 +4,26 @@ from shared.context import ServerContext from shared.data_helpers import default_product_name, model_product_ids -from shared.device_plugin_catalog import product_fields, resolve_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 from ..user.homes.service import home_payload -def _served_products(ctx: ServerContext) -> list[tuple[dict[str, Any], int]]: +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")) - return list(zip(products, resolve_product_ids(products, cloud_product_ids))) + return list(zip(products, resolve_product_ids(products, cloud_product_ids, catalog))) -def served_models_by_product_id(ctx: ServerContext) -> dict[int, set[str]]: +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): + for product, product_id in _served_products(ctx, catalog): model, _, _ = product_fields(product) models.setdefault(product_id, set()).add(model.strip().lower()) return models @@ -31,7 +31,7 @@ def served_models_by_product_id(ctx: ServerContext) -> dict[int, set[str]]: def build_product_response(ctx: ServerContext) -> dict[str, Any]: categories: dict[str, dict[str, Any]] = {} - for product, product_id in _served_products(ctx): + 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 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 66cf83cb..30247907 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 @@ -5,11 +5,10 @@ from shared.context import ServerContext from shared.data_helpers import as_int -from shared.device_plugin_catalog import BUILTIN_APPPLUGIN_RECORDS_BY_MODEL from ...auth.service import ok from ...plugin.common import ( - APPPLUGIN_LIST, + built_in_catalog, proxied_plugin_records, snapshot_plugin_records, ) @@ -69,21 +68,20 @@ def _built_in_records(ctx: ServerContext, product_ids: set[int]) -> list[dict[st # 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. - served_models = served_models_by_product_id(ctx) + 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 = BUILTIN_APPPLUGIN_RECORDS_BY_MODEL.get(model) + record = catalog.records_by_model.get(model) if record is None: continue - # The built-in records come from the EU cloud. For another region, the - # device gets the EU record of the same model, with the id that the app - # requested. That record is not verified for the other region, but it - # is the plugin of the same model. Without it, the device would get no - # plugin. + # The answer carries the id that the app requested. For a region + # without its own catalog, the record comes from the EU catalog; see + # catalog_for_region. records.append(dict(record, productid=product_id)) return records @@ -101,7 +99,7 @@ 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 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 b0a00fe2..51e91773 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,7 +11,8 @@ from fastapi.responses import Response from shared.context import ServerContext -from shared.device_plugin_catalog import BUILTIN_APPPLUGIN_RECORDS +from shared.data_helpers import 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 = { @@ -83,11 +84,9 @@ }, ] -# Android device plugin records from the Roborock EU cloud. /api/v1/appplugin -# answers all of them to a request without product ids. For a requested id -# that the cloud snapshot has no record for, it answers the record of the -# model that /api/v5/product gives the id to. -APPPLUGIN_LIST = BUILTIN_APPPLUGIN_RECORDS +# 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: @@ -117,6 +116,33 @@ 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 _snapshot_plugin_catalogs(ctx: ServerContext) -> dict[str, Any]: snapshot = load_cloud_full_snapshot(ctx) or {} web_cache = snapshot.get("web_api_cache") 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 index 2af1566f..57efb556 100644 --- a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py @@ -1,9 +1,9 @@ -"""Built-in numeric product ids and Android device plugin records. +"""Built-in numeric product ids and Android device plugin records, per cloud region. -The data comes from the Roborock EU cloud: 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 -rebuilds device_plugin_catalog.json with any cloud login. +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. @@ -13,33 +13,66 @@ 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 -DEVICE_PLUGIN_CATALOG_PATH = Path(__file__).with_name("device_plugin_catalog.json") +CATALOG_DIR = Path(__file__).parent +CATALOG_FILE_PREFIX = "device_plugin_catalog_" +# Regions without their own catalog file use this one. +FALLBACK_REGION = "eu" + + +@dataclass(frozen=True) +class DevicePluginCatalog: + 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 + }, + ) + -_CATALOG: dict[str, Any] = json.loads(DEVICE_PLUGIN_CATALOG_PATH.read_text(encoding="utf-8")) +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 -# Model -> numeric product id. /api/v5/product answers it as the product "id", -# and the app requests the device plugin with it. -BUILTIN_PRODUCT_IDS: dict[str, int] = { - model: int(entry["id"]) for model, entry in _CATALOG["products"].items() -} -# Android (type 2) records in the shape of the /api/v1/appplugin answer. -BUILTIN_APPPLUGIN_RECORDS: list[dict[str, Any]] = [dict(record) for record in _CATALOG["appplugin"]] +# Region -> catalog, for each catalog file in this directory. +CATALOGS: dict[str, DevicePluginCatalog] = _load_catalogs() -_RECORDS_BY_PRODUCT_ID = {as_int(record.get("productid"), 0): record for record in BUILTIN_APPPLUGIN_RECORDS} -# Model -> its Android record. /api/v1/appplugin looks the record up by the -# model that /api/v5/product gives the requested id to. -BUILTIN_APPPLUGIN_RECORDS_BY_MODEL: dict[str, dict[str, Any]] = { - model: _RECORDS_BY_PRODUCT_ID[product_id] - for model, product_id in BUILTIN_PRODUCT_IDS.items() - if product_id in _RECORDS_BY_PRODUCT_ID -} +def catalog_for_region(region: str | None) -> DevicePluginCatalog: + """Return the catalog of a cloud region, or the EU catalog if the region has none.""" + # 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 region + # without its own catalog gets the EU record of the same model. That record + # is not verified for the region, but without the catalog the device would + # get no plugin. + return CATALOGS.get(str(region or "").strip().lower()) or CATALOGS[FALLBACK_REGION] def product_fields(product: Mapping[str, Any]) -> tuple[str, str, str]: @@ -51,7 +84,9 @@ def product_fields(product: Mapping[str, Any]) -> tuple[str, str, str]: ) -def resolve_product_ids(products: Sequence[Mapping[str, Any]], import_ids: Mapping[str, int]) -> list[int]: +def resolve_product_ids( + products: Sequence[Mapping[str, Any]], import_ids: Mapping[str, int], catalog: DevicePluginCatalog +) -> 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. A snapshot record matches @@ -71,12 +106,13 @@ def resolve_product_ids(products: Sequence[Mapping[str, Any]], import_ids: Mappi holders.setdefault(product_id, set()).add(key) product_ids: list[int] = [] for key, fixed_id, (_, raw_id, category) in zip(model_keys, fixed_ids, fields): - built_in_id = BUILTIN_PRODUCT_IDS.get(key) + built_in_id = catalog.product_ids.get(key) if fixed_id: product_ids.append(fixed_id) - # The built-in ids come from the EU cloud. Another model can hold the - # same id in the import or in home data, like the a199 holds 199 in - # the US cloud. Then the id would name two models. + # Product ids differ by cloud region. Another model can hold the + # built-in id in the import or in home data, 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: diff --git a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.json b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog_eu.json similarity index 99% rename from src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.json rename to src/roborock_local_server/bundled_backend/shared/device_plugin_catalog_eu.json index 454a4689..96c8e0f4 100644 --- a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.json +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog_eu.json @@ -2,6 +2,7 @@ "_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" diff --git a/tests/test_plugin_routes.py b/tests/test_plugin_routes.py index be2e0156..029329f9 100644 --- a/tests/test_plugin_routes.py +++ b/tests/test_plugin_routes.py @@ -636,7 +636,7 @@ def _cloud_product_catalog(products: dict[str, int]) -> dict: 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 BUILTIN_APPPLUGIN_RECORDS_BY_MODEL + 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 @@ -654,7 +654,9 @@ def test_app_plugin_answers_built_in_record_of_the_model_that_gets_the_id( response = client.post("/api/v1/appplugin", json={"apilevel": 10046, "productids": [import_id], "type": 2}) - assert _app_plugin_sources(response.json()) == [(import_id, BUILTIN_APPPLUGIN_RECORDS_BY_MODEL[model]["url"])] + # 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: @@ -681,15 +683,19 @@ def test_app_plugin_answers_built_in_record_if_import_ids_agree(tmp_path: Path) 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 as catalog - - product_ids = list(catalog.BUILTIN_PRODUCT_IDS.values()) - record_ids = [record["productid"] for record in catalog.BUILTIN_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.BUILTIN_APPPLUGIN_RECORDS: - assert is_allowed_plugin_source(record["url"]) + 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 6bb8fbec..bbce285f 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -20,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", @@ -188,7 +188,11 @@ def test_numeric_inventory_product_id_wins_over_built_in_id(tmp_path: Path) -> N def _write_cloud_products( - tmp_path: Path, products: dict[str, int], app_plugin_records: list[dict[str, object]] | None = None + 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. @@ -198,7 +202,9 @@ def _write_cloud_products( } if app_plugin_records is not None: catalogs["appplugin"] = {"data": app_plugin_records} - snapshot = {"web_api_cache": {"plugin_catalogs": catalogs}} + 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") @@ -228,8 +234,7 @@ def test_cloud_import_product_id_wins_over_built_in_id( def test_model_missing_from_cloud_import_gets_built_in_id_and_record(tmp_path: Path) -> None: - # The import comes from the EU cloud, like the built-in list. - _write_cloud_products(tmp_path, {"roborock.vacuum.a226": 199}) + _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]) @@ -302,9 +307,9 @@ def _product_ids_by_model(data: dict) -> dict[str, int]: def _built_in_source(model: str) -> str: - from shared.device_plugin_catalog import BUILTIN_APPPLUGIN_RECORDS_BY_MODEL + from shared.device_plugin_catalog import catalog_for_region - return BUILTIN_APPPLUGIN_RECORDS_BY_MODEL[model]["url"] + return catalog_for_region("eu").records_by_model[model]["url"] def _plugin_sources(tmp_path: Path, product_id: int) -> list[tuple[int, str]]: @@ -338,7 +343,7 @@ def test_built_in_id_that_the_import_gives_another_model_is_skipped(tmp_path: Pa 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}) + _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])) @@ -358,8 +363,8 @@ def test_snapshot_record_wins_over_the_built_in_record_of_the_model(tmp_path: Pa 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 built-in list, 110 is the roborock.wm.a91 washer. - _write_cloud_products(tmp_path, {"roborock.vacuum.a87": 110}) + # 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 @@ -367,7 +372,7 @@ def test_a87_with_the_us_import_id_110_gets_the_a87_record(tmp_path: Path) -> No def test_a87_with_the_numeric_inventory_id_110_gets_the_a87_record(tmp_path: Path) -> None: - from shared.device_plugin_catalog import BUILTIN_APPPLUGIN_RECORDS_BY_MODEL + 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. @@ -376,7 +381,7 @@ def test_a87_with_the_numeric_inventory_id_110_gets_the_a87_record(tmp_path: Pat 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 BUILTIN_APPPLUGIN_RECORDS_BY_MODEL["roborock.vacuum.a87"]["productid"] == 103 + 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: @@ -410,3 +415,62 @@ def test_app_gets_no_built_in_plugin_for_an_id_without_inventory_device(tmp_path 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) + # 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_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"))] diff --git a/tests/test_refresh_device_plugin_catalog.py b/tests/test_refresh_device_plugin_catalog.py index b602026d..a2771582 100644 --- a/tests/test_refresh_device_plugin_catalog.py +++ b/tests/test_refresh_device_plugin_catalog.py @@ -5,8 +5,15 @@ 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, fetch_cloud_answers +from scripts.refresh_device_plugin_catalog import ( + build_catalog, + catalog_path, + catalog_region, + fetch_cloud_answers, +) CLOUD_PRODUCTS = { "categoryDetailList": [ @@ -42,6 +49,7 @@ async def fake_call(path: str, *, method: str = "get", json_body: dict[str, Any] products, records, base_url="https://euiot.roborock.com", + region="eu", fetched_at_utc="2026-11-21T00:00:00+00:00", ) @@ -59,6 +67,10 @@ async def fake_call(path: str, *, method: str = "get", json_body: dict[str, Any] } 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" @@ -80,3 +92,33 @@ def __init__(self, *, username: str, base_url: str | None, session: Any) -> 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() From 65b244a7a9b4f192c28d7494fc31cbc7a9fbac2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Sat, 21 Nov 2026 23:39:18 +0100 Subject: [PATCH 06/12] test(plugin): cover devices of one model, shared devices and catalog errors Two devices of one model get one product id, and the id still gets the plugin record of the model. A shared device gets its built-in id and record from both inventory spellings of the shared device list. A failed product or appplugin request in the snapshot falls back to the built-in id and record. The import stores the error of a failed product list and fetches the plugins by the numeric home data id, if there is one. --- tests/test_cloud_plugin_catalogs.py | 46 +++++++++++++++ tests/test_product_response.py | 91 +++++++++++++++++++++++++++-- 2 files changed, 132 insertions(+), 5 deletions(-) diff --git a/tests/test_cloud_plugin_catalogs.py b/tests/test_cloud_plugin_catalogs.py index 26aa060e..b4337668 100644 --- a/tests/test_cloud_plugin_catalogs.py +++ b/tests/test_cloud_plugin_catalogs.py @@ -79,3 +79,49 @@ async def fake_request(_api, _user_data, path, *, method="get", params=None, jso 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_product_response.py b/tests/test_product_response.py index bbce285f..255a1d65 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -41,11 +41,12 @@ def _make_context(tmp_path: Path, region: str = "us") -> 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), @@ -474,3 +475,83 @@ def test_us_import_without_us_catalog_gets_the_eu_catalog_by_model(tmp_path: Pat assert product["id"] == 263 assert _plugin_sources(tmp_path, 263) == [(263, _built_in_source("roborock.vacuum.a307"))] + + +_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"))] From 046a0ed6b69a0d7d54719cece5285e791bc9f80a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Sun, 22 Nov 2026 00:51:53 +0100 Subject: [PATCH 07/12] feat(plugin): merge the built-in plugin catalogs of all regions per model A model that the catalog of the server's region lacks now takes its record from the EU catalog, then from the other catalogs by region name. Before, the server used one catalog only, so such a model got no plugin. The id comes from the same catalog as the record. If an earlier catalog gives that id to another model, the model gets a hashed id, and /api/v1/appplugin still finds its record by model. Only the EU catalog exists so far, so nothing changes yet. --- .../https_server/routes/api/v1/appplugin.py | 5 +- .../shared/device_plugin_catalog.py | 55 ++++++++++++-- tests/test_product_response.py | 71 +++++++++++++++++++ 3 files changed, 121 insertions(+), 10 deletions(-) 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 30247907..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 @@ -79,9 +79,8 @@ def _built_in_records(ctx: ServerContext, product_ids: set[int]) -> list[dict[st record = catalog.records_by_model.get(model) if record is None: continue - # The answer carries the id that the app requested. For a region - # without its own catalog, the record comes from the EU catalog; see - # catalog_for_region. + # 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 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 index 57efb556..c1ff8e02 100644 --- a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py @@ -7,6 +7,7 @@ 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 @@ -21,12 +22,15 @@ CATALOG_DIR = Path(__file__).parent CATALOG_FILE_PREFIX = "device_plugin_catalog_" -# Regions without their own catalog file use this one. +# 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. @@ -65,14 +69,51 @@ def _load_catalogs() -> dict[str, DevicePluginCatalog]: def catalog_for_region(region: str | None) -> DevicePluginCatalog: - """Return the catalog of a cloud region, or the EU catalog if the region has none.""" + """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. + """ # 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 region - # without its own catalog gets the EU record of the same model. That record - # is not verified for the region, but without the catalog the device would - # get no plugin. - return CATALOGS.get(str(region or "").strip().lower()) or CATALOGS[FALLBACK_REGION] + # 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 = [str(region or "").strip().lower(), 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]: diff --git a/tests/test_product_response.py b/tests/test_product_response.py index 255a1d65..cb00882d 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -477,6 +477,77 @@ def test_us_import_without_us_catalog_gets_the_eu_catalog_by_model(tmp_path: Pat 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) + + +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") From 57c3634ff8cea0a435ec66f44566ac4db49a3426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Tue, 24 Nov 2026 18:44:57 +0100 Subject: [PATCH 08/12] fix(plugin): let a snapshot plugin record hold its product id /api/v1/appplugin matches a snapshot plugin record by its product id alone. If the record's device has left the inventory or has not paired, no model holds that id. Another model then got the id as its built-in id, and the app installed the record's plugin for it. For example, a US import stored the a199 plugin at 199. The EU catalog gives 199 to the a226, so an a226 got 199 and the a199 plugin. This happens if the import has no product list. Imports before #224 stored none, and neither does an import whose product list request failed. Such an import fetched the records by the numeric home data ids. The record now holds its id for the model that the snapshot's home data names, else for an unknown model. A paired device of the named model keeps the id and the record. The iOS test fixture gets the product list of a current import, because a real import never writes records without home data. --- .../https_server/endpoint_rules.py | 6 +- .../routes/api/product_service.py | 5 +- .../https_server/routes/plugin/common.py | 31 +++++++--- .../shared/device_plugin_catalog.py | 36 ++++++++---- tests/test_plugin_routes.py | 6 +- tests/test_product_response.py | 57 +++++++++++++++++++ 6 files changed, 116 insertions(+), 25 deletions(-) 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 a68b18d0..d2a9991a 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 @@ -94,7 +94,7 @@ from .routes.api.v1.user import match_logout as _match_logout_v1 from .routes.api.v1.user import match_user_info as _match_user_info_v1 from .routes.api.v1.user import match_user_roles as _match_user_roles_v1 -from .routes.plugin.common import built_in_catalog, snapshot_plugin_catalog_data +from .routes.plugin.common import built_in_catalog, snapshot_plugin_catalog_data, snapshot_plugin_record_owners from .routes.user.app.info import build as _build_post_app_info from .routes.user.app.info import match as _match_post_app_info from .routes.user.inbox.latest import build as _build_get_inbox_latest @@ -511,7 +511,9 @@ def _build_product_response(ctx: ServerContext, home_data: dict[str, Any]) -> di 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, built_in_catalog(ctx)) + product_ids = resolve_product_ids( + products, cloud_product_ids, built_in_catalog(ctx), snapshot_plugin_record_owners(ctx) + ) categories: dict[str, dict[str, Any]] = {} for product, product_id in zip(products, product_ids): model, _, category_name = product_fields(product) 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 d8dbe8a7..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 @@ -6,7 +6,7 @@ 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 built_in_catalog, 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 @@ -17,7 +17,8 @@ def _served_products(ctx: ServerContext, catalog: DevicePluginCatalog) -> list[t 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")) - return list(zip(products, resolve_product_ids(products, cloud_product_ids, catalog))) + 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]]: 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 51e91773..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,7 +11,7 @@ from fastapi.responses import Response from shared.context import ServerContext -from shared.data_helpers import cloud_region_from_base_url, known_cloud_region +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 @@ -143,13 +143,12 @@ def built_in_catalog(ctx: ServerContext) -> DevicePluginCatalog: 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: @@ -169,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/shared/device_plugin_catalog.py b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py index c1ff8e02..fb4a5367 100644 --- a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py @@ -126,34 +126,46 @@ def product_fields(product: Mapping[str, Any]) -> tuple[str, str, str]: def resolve_product_ids( - products: Sequence[Mapping[str, Any]], import_ids: Mapping[str, int], catalog: DevicePluginCatalog + 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. A snapshot record matches - only the id of the cloud import, and /api/v1/appplugin 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. + 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] 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]] = {} + 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 or in home data, like the a199 holds 199 - # in the US cloud and the a226 in the EU cloud. Then the id would name - # two models. + # 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: diff --git a/tests/test_plugin_routes.py b/tests/test_plugin_routes.py index 029329f9..962c6de7 100644 --- a/tests/test_plugin_routes.py +++ b/tests/test_plugin_routes.py @@ -496,12 +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, which - # the paired a15 gets. + # 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), diff --git a/tests/test_product_response.py b/tests/test_product_response.py index cb00882d..64537aee 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -626,3 +626,60 @@ def test_snapshot_catalog_error_gets_the_built_in_id_and_record(tmp_path: Path, 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"]) +@pytest.mark.parametrize("product_list", [_v5_product_list, _legacy_product_list], ids=["api_v5", "legacy"]) +def test_built_in_id_of_a_snapshot_record_without_inventory_device_is_skipped( + tmp_path: Path, product_list, 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] = 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"])] From 4d1d8b85ce8b92ba6110ea6ab7bd292d43a649a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Thu, 26 Nov 2026 14:37:23 +0100 Subject: [PATCH 09/12] refactor(product): drop the unused copy of the product response Nothing called _build_product_response in endpoint_rules.py. /api/v4/product and /api/v5/product both use product_service.build_product_response. The two helpers of the copy have their used versions in routes/user/homes/service.py. So a later change of the product ids has one place to go. --- .../https_server/endpoint_rules.py | 95 +------------------ tests/test_product_response.py | 20 +--- 2 files changed, 5 insertions(+), 110 deletions(-) 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 d2a9991a..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 @@ -9,8 +9,7 @@ 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, model_product_ids -from shared.device_plugin_catalog import product_fields, resolve_product_ids +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 @@ -94,7 +93,6 @@ from .routes.api.v1.user import match_logout as _match_logout_v1 from .routes.api.v1.user import match_user_info as _match_user_info_v1 from .routes.api.v1.user import match_user_roles as _match_user_roles_v1 -from .routes.plugin.common import built_in_catalog, snapshot_plugin_catalog_data, snapshot_plugin_record_owners from .routes.user.app.info import build as _build_post_app_info from .routes.user.app.info import match as _match_post_app_info from .routes.user.inbox.latest import build as _build_get_inbox_latest @@ -453,97 +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 [] - 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, built_in_catalog(ctx), snapshot_plugin_record_owners(ctx) - ) - categories: dict[str, dict[str, Any]] = {} - for product, product_id in zip(products, product_ids): - model, _, category_name = product_fields(product) - if category_name not in categories: - category_id = len(categories) + 1 - categories[category_name] = { - "category": { - "id": category_id, - "displayName": category_name, - "iconUrl": "", - }, - "productList": [], - } - 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/tests/test_product_response.py b/tests/test_product_response.py index 64537aee..b77899e3 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -291,16 +291,6 @@ def _v5_product_list(tmp_path: Path, device: dict[str, object]) -> list[dict]: return _products_v5(tmp_path, [device])["categoryDetailList"][0]["productList"] -def _legacy_product_list(tmp_path: Path, device: dict[str, object]) -> list[dict]: - from https_server.endpoint_rules import _build_product_response - - home_data = { - "devices": [{"duid": device["duid"], "productId": device["product_id"]}], - "products": [{"id": device["product_id"], "model": device["model"], "category": "robot.vacuum.cleaner"}], - } - return _build_product_response(_make_context(tmp_path), home_data)["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"] @@ -328,15 +318,14 @@ def _plugin_sources(tmp_path: Path, product_id: int) -> list[tuple[int, str]]: _WASHER = dict(_DEVICE, duid="device-b", model="roborock.wm.a91", product_id="rriot-wm-a91") -@pytest.mark.parametrize("product_list", [_v5_product_list, _legacy_product_list], ids=["api_v5", "legacy"]) -def test_built_in_id_that_the_import_gives_another_model_is_skipped(tmp_path: Path, product_list) -> None: +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] = product_list(tmp_path, _A226) + [product] = _v5_product_list(tmp_path, _A226) assert product["id"] == stable_int(_A226["product_id"]) % 1_000_000 @@ -645,9 +634,8 @@ def _write_snapshot_without_product_list( "home_products", [[{"id": "199", "model": "roborock.vacuum.a199"}], []], ids=["named_model", "unknown_model"] ) @pytest.mark.parametrize("catalog_name", ["appplugin", "appplugin_ios"]) -@pytest.mark.parametrize("product_list", [_v5_product_list, _legacy_product_list], ids=["api_v5", "legacy"]) def test_built_in_id_of_a_snapshot_record_without_inventory_device_is_skipped( - tmp_path: Path, product_list, catalog_name: str, home_products: list[dict] + tmp_path: Path, catalog_name: str, home_products: list[dict] ) -> None: from shared.data_helpers import stable_int @@ -656,7 +644,7 @@ def test_built_in_id_of_a_snapshot_record_without_inventory_device_is_skipped( # comes from the EU cloud, and it is 199. _write_snapshot_without_product_list(tmp_path, catalog_name, [_A199_RECORD], home_products) - [product] = product_list(tmp_path, _A226) + [product] = _v5_product_list(tmp_path, _A226) assert product["id"] == stable_int(_A226["product_id"]) % 1_000_000 From ba13a5364dcf2ea5bcaa13c17a1570bf8318277d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Thu, 26 Nov 2026 14:38:31 +0100 Subject: [PATCH 10/12] fix(scripts): refuse a plugin answer without records and write the catalog atomically If /api/v1/appplugin answered something other than a list of records, refresh_device_plugin_catalog.py wrote a catalog without plugin records and reported no error. It also wrote the file in place, so a crash left a truncated file, and the server failed to start on it. The script now raises an error if the answer has no record. It writes a .tmp file first and replaces the catalog with it. A failed write removes the .tmp file, so a package build can't ship it. --- scripts/refresh_device_plugin_catalog.py | 22 ++++++++++++- tests/test_refresh_device_plugin_catalog.py | 36 +++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/scripts/refresh_device_plugin_catalog.py b/scripts/refresh_device_plugin_catalog.py index 0312059f..3a652f94 100644 --- a/scripts/refresh_device_plugin_catalog.py +++ b/scripts/refresh_device_plugin_catalog.py @@ -83,6 +83,10 @@ async def fetch_cloud_answers(call: CloudCall) -> tuple[Any, Any]: 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 @@ -102,6 +106,22 @@ 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 { @@ -153,7 +173,7 @@ async def call(path: str, *, method: str = "get", json_body: dict[str, Any] | No fetched_at_utc=datetime.now(UTC).isoformat(), ) output = args.output or catalog_path(region) - output.write_text(json.dumps(catalog, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + 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] diff --git a/tests/test_refresh_device_plugin_catalog.py b/tests/test_refresh_device_plugin_catalog.py index a2771582..fd46928b 100644 --- a/tests/test_refresh_device_plugin_catalog.py +++ b/tests/test_refresh_device_plugin_catalog.py @@ -13,6 +13,7 @@ catalog_path, catalog_region, fetch_cloud_answers, + write_catalog, ) CLOUD_PRODUCTS = { @@ -122,3 +123,38 @@ def test_catalog_path_is_the_file_that_the_server_loads() -> None: 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"] From a7b07e86c44633c9597b4367aabe92d017392eeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Thu, 26 Nov 2026 14:39:37 +0100 Subject: [PATCH 11/12] perf(plugin): build the merged built-in catalog once per region catalog_for_region merged the catalogs of all regions on each call, and /api/v1/appplugin and /api/v5/product call it on every request. The catalog files load at import time and do not change at runtime. So the merged catalog is now cached per region. Tests that swap a region catalog also swap the cache. --- .../shared/device_plugin_catalog.py | 14 +++++++++++++- tests/test_product_response.py | 8 ++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) 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 index fb4a5367..1ef45bae 100644 --- a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py @@ -68,6 +68,11 @@ def _load_catalogs() -> dict[str, DevicePluginCatalog]: 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. @@ -77,12 +82,19 @@ def catalog_for_region(region: str | None) -> DevicePluginCatalog: 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 = [str(region or "").strip().lower(), FALLBACK_REGION, *sorted(CATALOGS)] + 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: diff --git a/tests/test_product_response.py b/tests/test_product_response.py index b77899e3..3b46e26d 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -443,6 +443,7 @@ def test_us_server_takes_ids_and_records_from_the_us_catalog(tmp_path: Path, mon }, ) 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") @@ -452,6 +453,12 @@ def test_us_server_takes_ids_and_records_from_the_us_catalog(tmp_path: Path, mon 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 @@ -485,6 +492,7 @@ def _add_region_catalog(monkeypatch, region: str, product_ids: dict[str, int], w }, ) 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: From ca3df6286219df6226d9f29417e1f955365ead17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20R=2E=20H=C3=B6lzlwimmer?= Date: Thu, 26 Nov 2026 14:39:47 +0100 Subject: [PATCH 12/12] docs(plugin): say why a numeric home data id skips the holders check A numeric home data id can only be the import id of another model if the inventory and the import come from different regions. The comment says so, as the review asked. --- .../bundled_backend/shared/device_plugin_catalog.py | 4 ++++ 1 file changed, 4 insertions(+) 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 index 1ef45bae..88e2875b 100644 --- a/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py +++ b/src/roborock_local_server/bundled_backend/shared/device_plugin_catalog.py @@ -156,6 +156,10 @@ def resolve_product_ids( """ 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)]: