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
16 changes: 16 additions & 0 deletions docs/roborock_app.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,22 @@ During `JNI_OnLoad`, `librrcodec.so` calls a verification function that retrieve

---

## Refreshing the Plugin List

The official app downloads each device's screens as plugins, and the server hands it the list it saved from the cloud when you signed in. Newer robots can need newer plugins than that saved list holds. Refresh it without signing in again:

```sh
curl -c jar -X POST https://your-server/admin/api/login -H 'Content-Type: application/json' -d '{"password": "..."}'
curl -b jar -X POST https://your-server/admin/api/cloud/refresh-plugins
curl -b jar https://your-server/admin/api/cloud/plugins
```

The refresh reuses the login stored by the email-code sign-in and only replaces the plugin catalogs, with the product ids of every device on the account. The reply lists each plugin's version, API level and download URL. `GET /admin/api/cloud/plugins` shows what is stored now without asking the cloud.

If the cloud rejects the stored login, or the snapshot predates this feature and has none, sign in again with the email code; that stores a login the refresh can use.

---

## LocalRock (Third-Party App)

[LocalRock](https://github.com/DonSidro/LocalRock) is an open-source app created by **Sidon Kodraliu** ([@DonSidro](https://github.com/DonSidro)) that connects directly to the local Roborock server.
Expand Down
2 changes: 2 additions & 0 deletions src/roborock_local_server/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def _resolve_backend_path() -> Path:
_build_inventory,
_fetch_additional_web_cache,
_fetch_cloud_home_data_with_api,
_fetch_plugin_catalogs,
_flatten_device_scenes,
_load_existing_inventory_for_merge,
_merge_existing_inventory_mutations,
Expand Down Expand Up @@ -52,6 +53,7 @@ def _resolve_backend_path() -> Path:
"_extract_inventory_vacuums",
"_fetch_additional_web_cache",
"_fetch_cloud_home_data_with_api",
"_fetch_plugin_catalogs",
"_flatten_device_scenes",
"_load_existing_inventory_for_merge",
"_load_inventory",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

from shared.constants import MODEL_PRODUCT_ID_OVERRIDES
from shared.context import ServerContext
from shared.data_helpers import as_int, default_product_name, stable_int
from shared.data_helpers import as_int, default_product_name, model_product_ids, stable_int

from ..plugin.common import snapshot_plugin_catalog_data

from ..user.homes.service import home_payload

Expand All @@ -13,6 +15,7 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]:
home_data = home_payload(ctx)
products_value = home_data.get("products")
products = products_value if isinstance(products_value, list) else []
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):
Expand All @@ -34,9 +37,12 @@ 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,
as_int(raw_product_id, stable_int(raw_product_id or category_name) % 1_000_000),
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,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,44 @@
from __future__ import annotations

import json
from typing import Any

from shared.context import ServerContext

from ...auth.service import ok
from ...plugin.common import APPPLUGIN_LIST, plugin_records_with_snapshot_fallback, proxied_plugin_records

# Request "type" of the iOS app; Android sends 2.
IOS_APP_TYPE = 1


def match(path: str) -> bool:
return path.rstrip("/") == "/api/v1/appplugin"


def _request_app_type(body_params: dict[str, list[str]]) -> int | None:
for raw in body_params.get("__json") or []:
try:
body = json.loads(raw)
except (TypeError, json.JSONDecodeError):
continue
if isinstance(body, dict):
try:
return int(body.get("type"))
except (TypeError, ValueError):
return None
return None


def build(
ctx: ServerContext,
_query_params: dict[str, list[str]],
_body_params: dict[str, list[str]],
body_params: dict[str, list[str]],
_clean_path: str,
) -> dict[str, Any]:
records = plugin_records_with_snapshot_fallback(ctx, "appplugin", APPPLUGIN_LIST)
if _request_app_type(body_params) == IOS_APP_TYPE:
# Same plugin version, different zip: the iOS app cannot load the Android
# one. Imports from before the iOS catalog existed fall back to Android.
records = plugin_records_with_snapshot_fallback(ctx, "appplugin_ios", records)
return ok(proxied_plugin_records(ctx, records))

Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,10 @@ def _dict_records(value: Any) -> list[dict[str, Any]]:
return [dict(item) for item in value if isinstance(item, dict)]


def snapshot_plugin_catalog_data(ctx: ServerContext, catalog_name: str) -> Any:
return _catalog_data(_snapshot_plugin_catalogs(ctx), catalog_name)


def snapshot_plugin_records(
ctx: ServerContext,
catalog_name: str,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
from roborock.exceptions import RoborockRateLimit
from roborock.web_api import PreparedRequest, RoborockApiClient, _get_hawk_authentication

from shared.data_helpers import model_product_ids


def _find_repo_root() -> Path:
current = Path(__file__).resolve().parent
Expand Down Expand Up @@ -376,13 +378,18 @@ async def _request_cloud_api_data(
return response.get("data")


def _plugin_product_ids(home_data: HomeData) -> list[int]:
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.
ids_by_model = model_product_ids(cloud_products)
product_ids: set[int] = set()
for product in home_data.products or []:
try:
product_ids.add(int(product.id))
except (TypeError, ValueError):
continue
model_id = ids_by_model.get(str(product.model or "").strip().lower())
if model_id:
product_ids.add(model_id)
for device in _all_home_devices(home_data):
try:
product_ids.add(int(getattr(device, "product_id", 0) or 0))
Expand Down Expand Up @@ -442,21 +449,21 @@ async def fetch_catalog(
"/api/v1/plugins",
params={"type": 2, "apiLevel": 10043},
)
product_ids = _plugin_product_ids(home_data)
if product_ids:
await fetch_catalog(
"appplugin",
"/api/v1/appplugin",
method="post",
json_body={"type": 2, "apilevel": 10043, "productids": product_ids},
)
else:
catalogs["appplugin"] = {
"path": "/api/v1/appplugin",
"method": "POST",
"json": {"type": 2, "apilevel": 10043, "productids": []},
"error": "no product ids available",
}
await fetch_catalog("product", "/api/v5/product")
product_ids = _plugin_product_ids(home_data, catalogs["product"].get("data"))
# The cloud serves a separate zip per platform for the same plugin version:
# type 2 is Android, type 1 is iOS.
for name, app_type in (("appplugin", 2), ("appplugin_ios", 1)):
json_body = {"type": app_type, "apilevel": 10043, "productids": product_ids}
if product_ids:
await fetch_catalog(name, "/api/v1/appplugin", method="post", json_body=json_body)
else:
catalogs[name] = {
"path": "/api/v1/appplugin",
"method": "POST",
"json": json_body,
"error": "no product ids available",
}
return catalogs


Expand Down
13 changes: 13 additions & 0 deletions src/roborock_local_server/bundled_backend/shared/data_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ def stable_int(seed: str) -> int:
return int(hashlib.sha256(seed.encode("utf-8")).hexdigest()[:12], 16)


def model_product_ids(cloud_products: Any) -> dict[str, int]:
"""Map model -> numeric product id from a cloud /api/v5/product payload."""
ids: dict[str, int] = {}
category_details = cloud_products.get("categoryDetailList") if isinstance(cloud_products, dict) else None
for category_detail in category_details 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:
ids[model] = product_id
return ids


def default_home_id(ctx: ServerContext) -> int:
return stable_int(f"{ctx.duid}:home")

Expand Down
79 changes: 79 additions & 0 deletions src/roborock_local_server/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
from typing import Any, Literal

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

from .backend import (
_build_inventory,
_fetch_additional_web_cache,
_fetch_cloud_home_data_with_api,
_fetch_plugin_catalogs,
_flatten_device_scenes,
_load_existing_inventory_for_merge,
_merge_existing_inventory_mutations,
Expand All @@ -30,6 +32,27 @@
from shared.inventory_io import atomic_write_inventory, inventory_transaction


def summarize_plugin_catalogs(catalogs: dict[str, Any]) -> dict[str, Any]:
"""The plugin catalogs reduced to what picks a plugin: versions, levels and download URLs."""
keep = ("version", "apiLevel", "apilevel", "pluginLevel", "productid", "categoryId", "category", "moduleType", "url", "id", "model")
summary: dict[str, Any] = {"fetched_at_utc": catalogs.get("fetched_at_utc")}
for name, catalog in catalogs.items():
if not isinstance(catalog, dict):
continue
entry: dict[str, Any] = {"params": catalog.get("params") or catalog.get("json") or {}}
if "error" in catalog:
entry["error"] = catalog["error"]
data = catalog.get("data")
if isinstance(data, dict):
data = data.get("categoryPluginList")
records = data if isinstance(data, list) else []
entry["plugins"] = [
{key: record[key] for key in keep if key in record} for record in records if isinstance(record, dict)
]
summary[name] = entry
return summary


def _to_jsonable(value: Any) -> Any:
if value is None or isinstance(value, (str, int, float, bool)):
return value
Expand Down Expand Up @@ -127,6 +150,61 @@ async def request_code(self, *, email: str, base_url: str = "") -> dict[str, Any
"expires_at": datetime.fromtimestamp(expires_at_ts, tz=timezone.utc).isoformat(),
}

def _read_snapshot(self) -> dict[str, Any]:
try:
parsed = json.loads(self.snapshot_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
return parsed if isinstance(parsed, dict) else {}

def plugin_catalogs(self) -> dict[str, Any]:
"""The stored plugin catalogs, summarized, without any cloud request."""
web_cache = self._read_snapshot().get("web_api_cache")
catalogs = web_cache.get("plugin_catalogs") if isinstance(web_cache, dict) else None
return summarize_plugin_catalogs(catalogs) if isinstance(catalogs, dict) else {}

async def refresh_plugin_catalogs(self) -> dict[str, Any]:
"""Re-reads the plugin catalogs from the cloud with the login the snapshot already holds.

Only the plugin catalogs in the snapshot change; the inventory is left alone. A rejected
login needs the email-code sign-in again, which stores a fresh one.
"""
snapshot = self._read_snapshot()
meta = snapshot.get("meta") if isinstance(snapshot.get("meta"), dict) else {}
try:
user_data = UserData.from_dict(snapshot.get("user_data"))
except (TypeError, ValueError, KeyError):
user_data = None
email = str(meta.get("username") or "")
if user_data is None or not user_data.token or not email:
raise ValueError("No cloud login is stored. Request a code and sign in first.")

timeout = aiohttp.ClientTimeout(total=120)
async with aiohttp.ClientSession(timeout=timeout) as session:
api = RoborockApiClient(username=email, base_url=str(meta.get("base_url") or "") or None, session=session)
if meta.get("device_identifier"):
setattr(api, "_device_identifier", str(meta["device_identifier"]))
try:
home_data = await _fetch_cloud_home_data_with_api(api, user_data)
catalogs = await _fetch_plugin_catalogs(api, user_data, home_data)
except Exception as exc: # noqa: BLE001
raise ValueError(
f"The cloud rejected the stored login ({exc}). Request a code and sign in again."
) from exc

failed = [name for name, item in catalogs.items() if isinstance(item, dict) and "error" in item]
if failed and len(failed) == sum(1 for item in catalogs.values() if isinstance(item, dict)):
errors = "; ".join(str(catalogs[name]["error"]) for name in failed)
raise ValueError(f"The cloud returned no plugin catalogs ({errors}). Request a code and sign in again.")

web_cache = snapshot.get("web_api_cache")
if not isinstance(web_cache, dict):
web_cache = {}
snapshot["web_api_cache"] = web_cache
web_cache["plugin_catalogs"] = _to_jsonable(catalogs)
self.snapshot_path.write_text(json.dumps(snapshot, indent=2) + "\n", encoding="utf-8")
return {"success": True, "step": "plugins_refreshed", **summarize_plugin_catalogs(catalogs)}

async def submit_code(self, *, session_id: str, code: str) -> dict[str, Any]:
normalized_session_id = session_id.strip()
normalized_code = code.strip()
Expand Down Expand Up @@ -180,6 +258,7 @@ async def submit_code(self, *, session_id: str, code: str) -> dict[str, Any]:
"generated_at_utc": datetime.now(timezone.utc).isoformat(),
"username": session_data.email,
"base_url": session_data.base_url,
"device_identifier": session_data.device_identifier,
"source": "admin_email_code_login",
},
"user_data": _to_jsonable(user_data),
Expand Down
15 changes: 15 additions & 0 deletions src/roborock_local_server/standalone_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,3 +478,18 @@ async def admin_cloud_submit_code(request: Request) -> JSONResponse:
result = {"success": False, "step": "code_submit_failed", "error": str(exc)}
supervisor.runtime_state.record_cloud_request(result)
return JSONResponse(result, status_code=200 if result.get("success") else 400)

@app.get("/admin/api/cloud/plugins")
async def admin_cloud_plugins(request: Request) -> JSONResponse:
supervisor._require_admin(request)
return JSONResponse({"success": True, **supervisor.cloud_manager.plugin_catalogs()})

@app.post("/admin/api/cloud/refresh-plugins")
async def admin_cloud_refresh_plugins(request: Request) -> JSONResponse:
supervisor._require_admin(request)
try:
result = await supervisor.cloud_manager.refresh_plugin_catalogs()
except Exception as exc: # noqa: BLE001
result = {"success": False, "step": "plugin_refresh_failed", "error": str(exc)}
supervisor.runtime_state.record_cloud_request(result)
return JSONResponse(result, status_code=200 if result.get("success") else 400)
34 changes: 34 additions & 0 deletions tests/test_admin_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1602,3 +1602,37 @@ def test_create_room_returns_bare_id_in_result_and_object_in_data(tmp_path: Path
assert body["data"]["id"] == body["result"]
assert body["data"]["name"] == "Study"
assert body["data"]["created"] is True


def test_admin_plugin_catalog_endpoints_require_auth_and_report_the_snapshot(tmp_path: Path) -> None:
config_file = write_release_config(tmp_path)
config = load_config(config_file)
paths = resolve_paths(config_file, config)
supervisor = ReleaseSupervisor(config=config, paths=paths)
client = TestClient(supervisor.app)

assert client.get("/admin/api/cloud/plugins").status_code == 401
assert client.post("/admin/api/cloud/refresh-plugins", json={}).status_code == 401

assert client.post("/admin/api/login", json={"password": "correct horse battery staple"}).status_code == 200
assert client.get("/admin/api/cloud/plugins").json() == {"success": True}

paths.cloud_snapshot_path.write_text(
json.dumps(
{
"web_api_cache": {
"plugin_catalogs": {
"appplugin": {"json": {"type": 2}, "data": [{"productid": 110, "version": 7006, "url": "https://files.roborock.com/a.zip"}]},
}
}
}
),
encoding="utf-8",
)
stored = client.get("/admin/api/cloud/plugins").json()
assert stored["appplugin"]["plugins"] == [{"productid": 110, "version": 7006, "url": "https://files.roborock.com/a.zip"}]

refused = client.post("/admin/api/cloud/refresh-plugins", json={})
assert refused.status_code == 400
assert refused.json()["step"] == "plugin_refresh_failed"
assert "No cloud login" in refused.json()["error"]
Loading
Loading