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
1 change: 1 addition & 0 deletions apps/admin_console/core/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def __init__(self):
self._wake_event: asyncio.Event | None = None
self._shutdown_event: asyncio.Event | None = None
self.worker_task: asyncio.Task | None = None
self.automation_scheduler_task: asyncio.Task | None = None

@property
def wake_event(self) -> asyncio.Event:
Expand Down
149 changes: 149 additions & 0 deletions apps/admin_console/routers/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Installed-app inventory for the automation app picker.

Android does not expose an app's display name over adb: ``dumpsys package`` and
``pm dump`` only return a ``labelRes`` resource id (and MIUI strips even that).
So the picker gets the third-party package list from the device and resolves
display names from two sources instead:

- built-in dictionaries in the frontend (i18n / APP_REGISTRY), and
- user-supplied labels persisted here under ``app_label.<package>``.
"""

from __future__ import annotations

import asyncio
import subprocess
import time
from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from artemis.runtime.adb_endpoint import adb_command
from artemis.runtime.app_launcher import launch_package
from artemis.runtime.device_pool import device_pool

try:
from admin_console.services.settings_service import settings_service
except ImportError: # pragma: no cover - import path differs when run as a package
from apps.admin_console.services.settings_service import settings_service


router = APIRouter(prefix="/api/apps", tags=["apps"])

_LABEL_PREFIX = "app_label."
_CACHE_TTL_SECONDS = 300.0
_ADB_TIMEOUT_SECONDS = 20.0
# System packages that still show up under "third-party" on some ROMs.
_SYSTEM_PREFIXES = (
"com.miui.",
"com.mediatek.",
"com.android.internal.",
"com.android.cts.",
"com.google.android.syncadapters.",
)
_package_cache: dict[str, tuple[float, list[str]]] = {}


class AppLabelPayload(BaseModel):
label: str = ""


def _pick_serial() -> str | None:
try:
devices = device_pool.get_ready_devices()
except Exception:
return None
return devices[0].serial if devices else None


def _run_pm_list(serial: str, *extra: str) -> list[str]:
try:
completed = subprocess.run(
adb_command(["-s", serial, "shell", "pm", "list", "packages", *extra]),
capture_output=True,
text=True,
timeout=_ADB_TIMEOUT_SECONDS,
)
except Exception:
return []
return [
line.split("package:", 1)[1].strip()
for line in (completed.stdout or "").splitlines()
if line.startswith("package:") and line.split("package:", 1)[1].strip()
]


def _packages(serial: str | None, refresh: bool = False) -> dict[str, list[str]]:
"""Every installed package plus the third-party subset.

The picker needs the full list: some ROMs ship the messaging apps the user
cares about as system packages, so restricting to ``-3`` hides them.
"""
empty = {"apps": [], "third_party": []}
if not serial:
return empty
cached = _package_cache.get(serial)
if cached and not refresh and time.time() - cached[0] < _CACHE_TTL_SECONDS:
return cached[1]
apps = _run_pm_list(serial)
third = _run_pm_list(serial, "-3")
# Some ROMs report system components under "-3"; drop them from the
# "third-party" hint but keep them in the full list.
third = [p for p in third if not p.startswith(_SYSTEM_PREFIXES)]
payload = {"apps": apps, "third_party": third}
_package_cache[serial] = (time.time(), payload)
return payload


@router.get("")
async def list_apps(refresh: bool = False):
"""Every installed package, the third-party subset, and user labels."""
serial = await asyncio.to_thread(_pick_serial)
packages = await asyncio.to_thread(_packages, serial, refresh)
settings: dict[str, Any] = await asyncio.to_thread(settings_service.get_all)
labels = {
key[len(_LABEL_PREFIX) :]: value
for key, value in settings.items()
if key.startswith(_LABEL_PREFIX) and isinstance(value, str) and value.strip()
}
return {
"device_serial": serial,
"apps": packages["apps"],
"third_party": packages["third_party"],
"labels": labels,
}


@router.put("/labels/{package}")
async def set_app_label(package: str, payload: AppLabelPayload):
"""Save a display name for a package; an empty label clears the override."""
label = payload.label.strip()
await asyncio.to_thread(settings_service.update, {f"{_LABEL_PREFIX}{package}": label})
return {"package": package, "label": label}


@router.post("/{package}/launch")
async def launch_app(package: str):
"""Open an installed app on the phone so the user can confirm what it is."""
serial = await asyncio.to_thread(_pick_serial)
if not serial:
raise HTTPException(status_code=400, detail="No device is connected.")
launched = await asyncio.to_thread(launch_package, serial, package)
if not launched:
raise HTTPException(status_code=400, detail=f"Could not launch {package}.")
return {"package": package, "launched": True}
234 changes: 234 additions & 0 deletions apps/admin_console/routers/automations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Automation (scheduled / device-watch) management API."""

from __future__ import annotations

from datetime import datetime
import re
from typing import Any

from fastapi import APIRouter, HTTPException

try:
from admin_console.services.automation_scheduler import (
build_probe_argv,
compute_next_run,
)
from admin_console.services.automation_store import TRIGGER_TYPES, automation_store
from admin_console.services.task_queue_service import task_queue_service
except ImportError: # pragma: no cover
from apps.admin_console.services.automation_scheduler import (
build_probe_argv,
compute_next_run,
)
from apps.admin_console.services.automation_store import TRIGGER_TYPES, automation_store
from apps.admin_console.services.task_queue_service import task_queue_service


router = APIRouter(prefix="/api/automations", tags=["automations"])

_TIME_RE = re.compile(r"^(\d{1,2}):(\d{2})$")
_PACKAGE_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$")


def _is_valid_time(value: Any) -> bool:
"""True for a 'HH:MM' clock time within 00:00-23:59."""
match = _TIME_RE.match(str(value).strip())
if not match:
return False
hour, minute = int(match.group(1)), int(match.group(2))
return 0 <= hour <= 23 and 0 <= minute <= 59


def _validate_payload(payload: dict[str, Any], *, partial: dict[str, Any] | None = None) -> None:
"""Validate a create/update payload, merging over an existing record for updates."""
merged = {**(partial or {}), **payload}
trigger_type = merged.get("trigger_type")
if trigger_type not in TRIGGER_TYPES:
raise HTTPException(
status_code=400,
detail=f"trigger_type must be one of {', '.join(TRIGGER_TYPES)}.",
)
goal = (merged.get("goal") or "").strip()
if not goal:
raise HTTPException(status_code=400, detail="goal must not be empty.")
if merged.get("profile") not in (None, "flash", "pro"):
raise HTTPException(status_code=400, detail="profile must be 'flash' or 'pro'.")

config = merged.get("trigger_config") or {}
if trigger_type == "daily":
raw_times = config.get("times") or []
invalid = [t for t in raw_times if not _is_valid_time(t)]
if invalid:
raise HTTPException(
status_code=400,
detail=f"Invalid time(s) {invalid!r}: expected 'HH:MM' between 00:00 and 23:59.",
)
if not raw_times:
raise HTTPException(
status_code=400, detail="daily trigger needs at least one 'HH:MM' time."
)
elif trigger_type == "interval":
try:
if int(config.get("minutes", 0)) < 1:
raise ValueError
except (TypeError, ValueError):
raise HTTPException(
status_code=400, detail="interval trigger needs 'minutes' >= 1."
) from None
elif trigger_type == "watch":
try:
build_probe_argv(str(config.get("probe") or ""), config.get("params") or {})
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
pattern = config.get("pattern")
if not pattern:
raise HTTPException(status_code=400, detail="watch trigger needs a 'pattern' regex.")
try:
re.compile(str(pattern))
except re.error as exc:
raise HTTPException(status_code=400, detail=f"Invalid pattern regex: {exc}") from exc
elif trigger_type == "notification":
packages = config.get("packages") or []
if not isinstance(packages, list):
raise HTTPException(
status_code=400, detail="notification trigger 'packages' must be a list."
)
invalid = [p for p in packages if not _PACKAGE_RE.match(str(p))]
if invalid:
raise HTTPException(
status_code=400,
detail=f"Invalid package name(s) {invalid!r}: expected e.g. 'com.tencent.mm'.",
)
pattern = config.get("pattern")
if pattern:
try:
re.compile(str(pattern))
except re.error as exc:
raise HTTPException(
status_code=400, detail=f"Invalid pattern regex: {exc}"
) from exc
try:
if float(config.get("cooldown_seconds", 60)) < 0:
raise ValueError
except (TypeError, ValueError):
raise HTTPException(
status_code=400, detail="notification trigger 'cooldown_seconds' must be >= 0."
) from None
if config.get("keep_alive"):
try:
if int(config.get("keep_alive_interval_seconds", 60)) < 30:
raise ValueError
except (TypeError, ValueError):
raise HTTPException(
status_code=400,
detail="notification trigger 'keep_alive_interval_seconds' must be >= 30.",
) from None
elif trigger_type == "app_alive":
packages = config.get("packages") or []
if not isinstance(packages, list) or not packages:
raise HTTPException(
status_code=400,
detail="app_alive trigger needs a non-empty 'packages' list.",
)
invalid = [p for p in packages if not _PACKAGE_RE.match(str(p))]
if invalid:
raise HTTPException(
status_code=400,
detail=f"Invalid package name(s) {invalid!r}: expected e.g. 'com.tencent.mm'.",
)
try:
if int(config.get("interval_seconds", 60)) < 30:
raise ValueError
except (TypeError, ValueError):
raise HTTPException(
status_code=400,
detail="app_alive trigger 'interval_seconds' must be >= 30.",
) from None
if str(config.get("on_dead") or "restart") not in ("restart", "alert"):
raise HTTPException(
status_code=400, detail="app_alive trigger 'on_dead' must be 'restart' or 'alert'."
)


def _prepare(payload: dict[str, Any], *, is_new: bool) -> dict[str, Any]:
cleaned = {
"name": (payload.get("name") or "").strip(),
"enabled": bool(payload.get("enabled", True)),
"trigger_type": payload["trigger_type"],
"trigger_config": payload.get("trigger_config") or {},
"goal": payload["goal"].strip(),
"profile": payload.get("profile") or "flash",
"device_serial": payload.get("device_serial") or None,
}
if is_new or "trigger_type" in payload or "trigger_config" in payload:
cleaned["next_run_at"] = compute_next_run(
cleaned["trigger_type"], cleaned["trigger_config"], datetime.now()
)
return cleaned


@router.get("")
async def list_automations():
return {"automations": automation_store.list()}


@router.post("")
async def create_automation(payload: dict):
_validate_payload(payload)
return automation_store.create(_prepare(payload, is_new=True))


@router.get("/{automation_id}")
async def get_automation(automation_id: str):
automation = automation_store.get(automation_id)
if automation is None:
raise HTTPException(status_code=404, detail="Automation not found.")
return automation


@router.put("/{automation_id}")
async def update_automation(automation_id: str, payload: dict):
current = automation_store.get(automation_id)
if current is None:
raise HTTPException(status_code=404, detail="Automation not found.")
_validate_payload(payload, partial=current)
updated = automation_store.update(automation_id, _prepare({**current, **payload}, is_new=False))
return updated


@router.delete("/{automation_id}")
async def delete_automation(automation_id: str):
if not automation_store.delete(automation_id):
raise HTTPException(status_code=404, detail="Automation not found.")
return {"status": "deleted", "automation_id": automation_id}


@router.post("/{automation_id}/run-now")
async def run_automation_now(automation_id: str):
"""Submit the automation's goal immediately, bypassing its schedule."""
automation = automation_store.get(automation_id)
if automation is None:
raise HTTPException(status_code=404, detail="Automation not found.")
result = await task_queue_service.enqueue_tasks(
[automation["goal"]],
profile=automation.get("profile") or "flash",
device_serial=automation.get("device_serial"),
ingress="automation",
)
tasks = result.get("tasks") or []
session_id = str(tasks[0].get("session_id") or "") if tasks else ""
return {"status": "queued", "session_id": session_id, "automation_id": automation_id}
Loading