Skip to content
Merged
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 @@ -638,7 +638,7 @@ async def _fetch_cloud_home_data_with_api(api: RoborockApiClient, user_data: Use
# The library applies request rate-limits per method family.
# Back off a bit before trying legacy endpoint variants.
await asyncio.sleep(1.2)
raise RuntimeError(f"Failed to fetch cloud home_data: {last_error}")
raise RuntimeError(f"Failed to fetch cloud home_data: {last_error}") from last_error


async def _fetch_cloud_home_data_from_dict(
Expand Down
143 changes: 142 additions & 1 deletion src/roborock_local_server/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,22 @@
from typing import Any, Literal

import aiohttp
from roborock.data import UserData
from roborock.exceptions import (
RoborockAccountDoesNotExist,
RoborockConnectionException,
RoborockInvalidCredentials,
RoborockNoResponseFromBaseURL,
RoborockRateLimit,
RoborockTimeout,
)
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 +40,29 @@
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 catalog.get("fetched_at_utc"):
entry["fetched_at_utc"] = catalog["fetched_at_utc"]
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 All @@ -47,6 +80,43 @@ def _to_jsonable(value: Any) -> Any:
return str(value)


def _merge_plugin_catalogs(stored: dict[str, Any], fresh: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
"""Catalog by catalog: a fresh entry with an error never replaces a stored one that has none."""
merged = dict(stored)
kept: list[str] = []
for name, entry in fresh.items():
previous = stored.get(name)
failed = isinstance(entry, dict) and "error" in entry
if failed and isinstance(previous, dict) and "error" not in previous:
kept.append(name)
# Stamp the kept entry with its real age so the new top-level stamp does not make it look fresh.
merged[name] = {"fetched_at_utc": stored.get("fetched_at_utc"), **previous}
continue
merged[name] = entry
return merged, kept


def _describe_refresh_error(exc: BaseException) -> str:
"""Only a rejected login says to sign in again; other failures get their own advice."""
chain: list[BaseException] = []
current: BaseException | None = exc
while current is not None and current not in chain:
chain.append(current)
current = current.__cause__ or current.__context__
if any(isinstance(item, RoborockRateLimit) for item in chain):
return f"The cloud is rate limiting requests ({exc}). Wait a few minutes and refresh again."
if any(isinstance(item, (RoborockInvalidCredentials, RoborockAccountDoesNotExist)) for item in chain):
return f"The cloud rejected the stored login ({exc}). Request a code and sign in again."
if any(isinstance(item, (TimeoutError, RoborockTimeout)) for item in chain):
return "The cloud did not answer in time. Try the refresh again."
if any(
isinstance(item, (aiohttp.ClientError, OSError, RoborockConnectionException, RoborockNoResponseFromBaseURL))
for item in chain
):
return f"The cloud could not be reached ({exc}). Check the network and try again."
return f"The cloud request failed ({exc}). The stored catalogs were kept."


@dataclass
class PendingCloudSession:
session_id: str
Expand All @@ -68,6 +138,7 @@ def __init__(self, *, inventory_path: Path, snapshot_path: Path, ttl_seconds: in
self.ttl_seconds = ttl_seconds
self._sessions: dict[str, PendingCloudSession] = {}
self._lock = threading.Lock()
self._snapshot_lock = threading.Lock()

def _cleanup_locked(self) -> None:
now = time.time()
Expand Down Expand Up @@ -127,6 +198,74 @@ 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(_describe_refresh_error(exc)) 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}). The stored catalogs were kept.")

fresh = _to_jsonable(catalogs)
# The cloud wait is over; re-read under the lock so a sign-in that finished meanwhile is not reverted.
with self._snapshot_lock:
snapshot = self._read_snapshot()
current = snapshot.get("user_data")
if not isinstance(current, dict) or not current.get("token"):
raise ValueError("The stored cloud login is missing or unreadable. Request a code and sign in again.")
if current.get("token") != user_data.token:
raise ValueError("A new sign-in finished while the refresh ran. Run the refresh again.")
web_cache = snapshot.get("web_api_cache")
if not isinstance(web_cache, dict):
web_cache = {}
snapshot["web_api_cache"] = web_cache
stored = web_cache.get("plugin_catalogs")
stored = stored if isinstance(stored, dict) else {}
merged, kept = _merge_plugin_catalogs(stored, fresh)
web_cache["plugin_catalogs"] = merged
atomic_write_inventory(self.snapshot_path, snapshot)
result = {"success": True, "step": "plugins_refreshed", **summarize_plugin_catalogs(merged)}
if kept:
result["kept_previous"] = kept
return result

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 +319,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 All @@ -196,7 +336,8 @@ async def submit_code(self, *, session_id: str, code: str) -> dict[str, Any]:
)

atomic_write_inventory(self.inventory_path, normalized_inventory)
self.snapshot_path.write_text(json.dumps(normalized_snapshot, indent=2) + "\n", encoding="utf-8")
with self._snapshot_lock:
atomic_write_inventory(self.snapshot_path, normalized_snapshot)

with self._lock:
self._sessions.pop(normalized_session_id, None)
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 @@ -492,3 +492,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 @@ -1635,3 +1635,37 @@ def test_create_room_with_new_capitalization_updates_existing_room(tmp_path: Pat
stored_inventory = json.loads(paths.inventory_path.read_text(encoding="utf-8"))
for stored_rooms in (stored_inventory["home"]["rooms"], stored_inventory["rooms"]):
assert stored_rooms == [{"id": 11100, "name": "Master Bedroom"}, {"id": 11101, "name": "Hallway"}]


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