Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 212 additions & 0 deletions scripts/refresh_device_plugin_catalog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
"""Rebuild the built-in device plugin catalog of a region from the Roborock cloud.

Without a cloud snapshot, the server answers /api/v5/product and
/api/v1/appplugin from the catalog of its cloud region. Any Roborock account
of the region works, also one without devices:

uv run python scripts/refresh_device_plugin_catalog.py --email you@example.com
uv run python scripts/refresh_device_plugin_catalog.py --source-json login.json

The first form asks Roborock for a login code and reads it from the terminal.
The second form reuses a stored login, in the formats that
import_web_inventory_from_cloud.py --source-json accepts. A raw user data file
has no username, so it needs --email too. The script makes two cloud requests
and writes no login data.

The region comes from the cloud host, for example eu for euiot.roborock.com.
The script writes shared/device_plugin_catalog_<region>.json. For an unknown
host, pass --region.
"""

from __future__ import annotations

import argparse
import asyncio
import importlib
import json
import sys
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import aiohttp
from roborock.data import UserData
from roborock.web_api import RoborockApiClient

# The script edits the catalog in this checkout. It does not import the server,
# because the server needs the catalog to start.
BACKEND_PATH = Path(__file__).resolve().parents[1] / "src" / "roborock_local_server" / "bundled_backend"
if str(BACKEND_PATH) not in sys.path:
sys.path.insert(0, str(BACKEND_PATH))
# Loaded after the path change above.
importer = importlib.import_module("import_web_inventory_from_cloud")
data_helpers = importlib.import_module("shared.data_helpers")
as_int = data_helpers.as_int

# shared/device_plugin_catalog.py reads each device_plugin_catalog_<region>.json here.
CATALOG_DIR = BACKEND_PATH / "shared"

PRODUCTS_PATH = "/api/v5/product"
APPPLUGIN_PATH = "/api/v1/appplugin"
# The Android app 4.60.06 sends type 2 and apilevel 10046. The cloud answers
# the newest plugin that this app can load.
APP_TYPE_ANDROID = 2
APP_API_LEVEL = 10046

CloudCall = Callable[..., Awaitable[Any]]


def _product_entries(products: Any) -> list[tuple[str, dict[str, Any]]]:
entries: list[tuple[str, dict[str, Any]]] = []
category_details = products.get("categoryDetailList") if isinstance(products, dict) else None
for category_detail in category_details or []:
category = (category_detail or {}).get("category") or {}
for product in (category_detail or {}).get("productList") or []:
model = str(product.get("model") or "").strip().lower()
product_id = as_int(product.get("id"), 0)
if model and product_id > 0:
entry = {
"id": product_id,
"name": str(product.get("name") or ""),
"category": str(category.get("code") or ""),
}
entries.append((model, entry))
return entries


async def fetch_cloud_answers(call: CloudCall) -> tuple[Any, Any]:
"""Fetch the product list, then the Android plugin records of all its products in one request."""
products = await call(PRODUCTS_PATH)
product_ids = sorted({entry["id"] for _, entry in _product_entries(products)})
if not product_ids:
raise RuntimeError(f"{PRODUCTS_PATH} listed no product with a numeric id")
body = {"type": APP_TYPE_ANDROID, "apilevel": APP_API_LEVEL, "productids": product_ids}
records = await call(APPPLUGIN_PATH, method="post", json_body=body)
# An answer that is not a list of records would give a catalog without
# plugin records.
if not isinstance(records, list) or not any(isinstance(record, dict) for record in records):
raise RuntimeError(f"{APPPLUGIN_PATH} answered no plugin record")
return products, records


def catalog_region(base_url: str, region: str | None = None) -> str:
"""Return the region of the catalog: --region if given, else the region of the cloud host."""
host_region = data_helpers.cloud_region_from_base_url(base_url)
if region:
if host_region and host_region != region:
raise RuntimeError(f"--region {region} does not match the {host_region} cloud at {base_url}")
return region
if host_region is None:
raise RuntimeError(f"The region of {base_url} is unknown. Pass --region.")
return host_region


def catalog_path(region: str) -> Path:
return CATALOG_DIR / f"device_plugin_catalog_{region}.json"


def write_catalog(path: Path, catalog: dict[str, Any]) -> None:
"""Write the catalog through a temporary file, so a crash keeps the old file.

The server loads every device_plugin_catalog_*.json at import time, and a
truncated file would stop it from starting. Its glob skips the .tmp file.
"""
tmp_path = path.with_name(f"{path.name}.tmp")
try:
tmp_path.write_text(json.dumps(catalog, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
tmp_path.replace(path)
except BaseException:
# The package build would ship a leftover .tmp file.
tmp_path.unlink(missing_ok=True)
raise


def build_catalog(products: Any, records: Any, *, base_url: str, region: str, fetched_at_utc: str) -> dict[str, Any]:
plugin_records = [dict(record) for record in records or [] if isinstance(record, dict)]
return {
"_comment": "Generated by scripts/refresh_device_plugin_catalog.py. Do not edit by hand.",
"source": {
"base_url": base_url,
"region": region,
"fetched_at_utc": fetched_at_utc,
"products": f"GET {PRODUCTS_PATH}",
"appplugin": f"POST {APPPLUGIN_PATH} with type {APP_TYPE_ANDROID} and apilevel {APP_API_LEVEL}",
},
"products": dict(sorted(_product_entries(products), key=lambda item: item[0])),
"appplugin": sorted(plugin_records, key=lambda record: as_int(record.get("productid"), 0)),
}


async def _login(args: argparse.Namespace, session: aiohttp.ClientSession) -> tuple[RoborockApiClient, UserData]:
if args.source_json:
username, base_url, user_data = importer._load_source_from_json_file(
source_file=args.source_json,
username_override=args.email,
base_url_override=args.base_url,
)
api = RoborockApiClient(username=username, base_url=base_url, session=session)
return api, UserData.from_dict(user_data)
email = (args.email or input("Roborock account email: ")).strip()
api = RoborockApiClient(username=email, base_url=args.base_url, session=session)
await api.request_code_v4()
code = input("Login code from the Roborock email: ").strip()
return api, await api.code_login_v4(code)


async def _main_async(args: argparse.Namespace) -> None:
timeout = aiohttp.ClientTimeout(total=120)
async with aiohttp.ClientSession(timeout=timeout) as session:
api, user_data = await _login(args, session)
base_url = str(await api.base_url)
region = catalog_region(base_url, args.region)

async def call(path: str, *, method: str = "get", json_body: dict[str, Any] | None = None) -> Any:
return await importer._request_cloud_api_data(api, user_data, path, method=method, json_body=json_body)

products, records = await fetch_cloud_answers(call)
catalog = build_catalog(
products,
records,
base_url=base_url,
region=region,
fetched_at_utc=datetime.now(UTC).isoformat(),
)
output = args.output or catalog_path(region)
write_catalog(output, catalog)

ids_with_record = {as_int(record.get("productid"), 0) for record in catalog["appplugin"]}
without_record = [model for model, entry in catalog["products"].items() if entry["id"] not in ids_with_record]
print(f"Wrote {output}: {len(catalog['products'])} products, {len(catalog['appplugin'])} plugin records.")
if without_record:
print(f"No Android plugin record: {', '.join(without_record)}")


def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--email",
help="Roborock account email for a code login. With --source-json, it replaces the stored username.",
)
parser.add_argument("--source-json", type=Path, help="Stored login, as for import_web_inventory_from_cloud.py.")
parser.add_argument("--base-url", help="Cloud API base URL, for example https://euiot.roborock.com.")
parser.add_argument(
"--region",
type=lambda value: value.strip().lower(),
help="Region of the catalog, for example eu. Needed only for an unknown cloud host.",
)
parser.add_argument(
"--output",
type=Path,
help="Catalog to write (default: shared/device_plugin_catalog_<region>.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())
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import time
from typing import Any, Callable, Sequence

from shared.constants import DEFAULT_HOME_NAME, DEFAULT_PRODUCT_SCHEMA, DEFAULT_TIMEZONE, MODEL_PRODUCT_ID_OVERRIDES
from shared.constants import DEFAULT_HOME_NAME, DEFAULT_PRODUCT_SCHEMA, DEFAULT_TIMEZONE
from shared.context import ServerContext
from shared.data_helpers import as_bool, as_int, default_home_id, default_product_name, get_value, stable_int
from shared.data_helpers import as_bool, as_int, default_home_id, default_product_name, get_value
from shared.http_helpers import wrap_response
from shared.inventory_io import WEB_API_INVENTORY_FILE, load_inventory, write_inventory

Expand Down Expand Up @@ -451,101 +451,6 @@ def _build_web_state(ctx: ServerContext) -> dict[str, Any]:
}


def _device_has_runtime_did(ctx: ServerContext, duid: str) -> bool:
runtime_credentials = getattr(ctx, "runtime_credentials", None)
if runtime_credentials is None:
return False
try:
credential_device = runtime_credentials.resolve_device(duid=duid)
except Exception:
return False
if credential_device is None:
return False
did = str(credential_device.get("did") or "").strip()
mqtt_user = str(credential_device.get("device_mqtt_usr") or "").strip()
return bool(did or mqtt_user)


def _filter_home_data_to_runtime_devices(ctx: ServerContext, home_data: dict[str, Any]) -> dict[str, Any]:
filtered_home = dict(home_data)
allowed_product_ids: set[str] = set()

for collection_key in ("devices", "receivedDevices", "received_devices"):
devices_value = home_data.get(collection_key)
if not isinstance(devices_value, list):
filtered_home.pop(collection_key, None)
continue
devices = devices_value
filtered_devices: list[dict[str, Any]] = []
for device in devices:
if not isinstance(device, dict):
continue
duid = str(get_value(device, "duid", "did", default="")).strip()
if not duid or not _device_has_runtime_did(ctx, duid):
continue
filtered_devices.append(dict(device))
product_id = str(get_value(device, "productId", "product_id", default="")).strip()
if product_id:
allowed_product_ids.add(product_id)
filtered_home[collection_key] = filtered_devices

products_value = home_data.get("products")
products = products_value if isinstance(products_value, list) else []
filtered_products: list[dict[str, Any]] = []
for product in products:
if not isinstance(product, dict):
continue
product_id = str(get_value(product, "id", "productId", "product_id", default="")).strip()
if not product_id or product_id not in allowed_product_ids:
continue
filtered_products.append(dict(product))
filtered_home["products"] = filtered_products
return filtered_home


def _build_product_response(ctx: ServerContext, home_data: dict[str, Any]) -> dict[str, Any]:
filtered_home_data = _filter_home_data_to_runtime_devices(ctx, home_data)
products_value = filtered_home_data.get("products")
products = products_value if isinstance(products_value, list) else []
categories: dict[str, dict[str, Any]] = {}
for product in products:
if not isinstance(product, dict):
continue
raw_product_id = str(product.get("id") or "")
category_name = str(product.get("category") or "robot.vacuum.cleaner")
if category_name not in categories:
category_id = len(categories) + 1
categories[category_name] = {
"category": {
"id": category_id,
"displayName": category_name,
"iconUrl": "",
},
"productList": [],
}
model = str(product.get("model") or "roborock.vacuum.a117")
model_key = model.strip().lower()
product_id = MODEL_PRODUCT_ID_OVERRIDES.get(
model_key,
as_int(raw_product_id, stable_int(raw_product_id or category_name) % 1_000_000),
)
product_entry = {
"id": product_id,
"name": str(product.get("name") or default_product_name(model)),
"model": model,
"packagename": f"com.roborock.{model.split('.')[-1]}",
"ncMode": "global",
"status": 10,
}
icon_url = product.get("iconUrl")
if isinstance(icon_url, str) and icon_url:
product_entry["picurl"] = icon_url
product_entry["cardPicUrl"] = icon_url
product_entry["pluginPicUrl"] = icon_url
categories[category_name]["productList"].append(product_entry)
return {"categoryDetailList": list(categories.values())}


@dataclass(frozen=True)
class EndpointRule:
"""Describes when a path matches and how to build its response."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,38 @@

from typing import Any

from shared.constants import MODEL_PRODUCT_ID_OVERRIDES
from shared.context import ServerContext
from shared.data_helpers import as_int, default_product_name, model_product_ids, stable_int
from shared.data_helpers import default_product_name, model_product_ids
from shared.device_plugin_catalog import DevicePluginCatalog, product_fields, resolve_product_ids

from ..plugin.common import snapshot_plugin_catalog_data
from ..plugin.common import built_in_catalog, snapshot_plugin_catalog_data, snapshot_plugin_record_owners

from ..user.homes.service import home_payload


def build_product_response(ctx: ServerContext) -> dict[str, Any]:
home_data = home_payload(ctx)
products_value = home_data.get("products")
def _served_products(ctx: ServerContext, catalog: DevicePluginCatalog) -> list[tuple[dict[str, Any], int]]:
"""Pair each home data product with the numeric product id of /api/v5/product."""
products_value = home_payload(ctx).get("products")
products = products_value if isinstance(products_value, list) else []
products = [product for product in products if isinstance(product, dict)]
cloud_product_ids = model_product_ids(snapshot_plugin_catalog_data(ctx, "product"))
product_ids = resolve_product_ids(products, cloud_product_ids, catalog, snapshot_plugin_record_owners(ctx))
return list(zip(products, product_ids))


def served_models_by_product_id(ctx: ServerContext, catalog: DevicePluginCatalog) -> dict[int, set[str]]:
"""Map each product id that /api/v5/product answers to the models that get it."""
models: dict[int, set[str]] = {}
for product, product_id in _served_products(ctx, catalog):
model, _, _ = product_fields(product)
models.setdefault(product_id, set()).add(model.strip().lower())
return models


def build_product_response(ctx: ServerContext) -> dict[str, Any]:
categories: dict[str, dict[str, Any]] = {}
for product in products:
if not isinstance(product, dict):
continue
raw_product_id = str(product.get("id") or "")
category_name = str(product.get("category") or "robot.vacuum.cleaner")
for product, product_id in _served_products(ctx, built_in_catalog(ctx)):
model, raw_product_id, category_name = product_fields(product)
if category_name not in categories:
category_id = len(categories) + 1
categories[category_name] = {
Expand All @@ -35,15 +47,6 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]:
},
"productList": [],
}
model = str(product.get("model") or "roborock.vacuum.a117")
model_key = model.strip().lower()
# String product ids (e.g. a226) take the cloud's numeric id for the model;
# plugins are keyed by it, so a hashed id gets the app no device plugin.
product_id = MODEL_PRODUCT_ID_OVERRIDES.get(
model_key,
cloud_product_ids.get(model_key)
or as_int(raw_product_id, stable_int(raw_product_id or category_name) % 1_000_000),
)
product_entry = {
"id": product_id,
"name": str(product.get("name") or default_product_name(model)),
Expand Down
Loading