use adk_kernel::pairing::DeviceScope;
use axum::extract::{Path, State};
use axum::http::Method;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Extension, Json, Router};
use super::phone::{AnswerRequest, StopRequest};
use super::{Context, Unauthenticated, caller, device_of, failed, paths, unauthenticated};
use crate::engine::{Command, CommandOutcome, SurfaceEngine};
use crate::error::SurfaceError;
use crate::origin::SurfaceKind;
#[derive(Clone)]
pub(crate) struct DeviceEnds(pub(crate) adk_kernel::pairing::Pairing);
pub fn router_with_devices(engine: SurfaceEngine, pairing: adk_kernel::pairing::Pairing) -> Router {
super::router(engine).layer(Extension(DeviceEnds(pairing)))
}
pub fn devices_router(engine: SurfaceEngine) -> Router {
Router::new()
.route(paths::ANSWER, post(answer))
.route(paths::STOP, post(stop))
.with_state(engine)
}
async fn answer(
State(engine): State<SurfaceEngine>,
context: Context,
Path(id): Path<String>,
Json(request): Json<AnswerRequest>,
) -> Response {
let caller = match caller(context, SurfaceKind::Web, None) {
Ok(caller) => caller,
Err(Unauthenticated) => return unauthenticated(),
};
let command = Command::Decide {
decision_id: id,
version: request.version,
answer: request.answer,
edited_args: request.edited_args,
reason: request.reason,
expanded: request.expanded,
evidence: request.evidence,
};
match engine.execute(&caller, command).await {
Ok(outcome) => Json::<CommandOutcome>(outcome).into_response(),
Err(error) => failed(error),
}
}
async fn stop(
State(engine): State<SurfaceEngine>,
context: Context,
Json(request): Json<StopRequest>,
) -> Response {
if let Some(Extension(Some(context))) = &context
&& device_of(context).is_none()
{
return failed(SurfaceError::NotHere(
"this route is a paired device's Stop all; the home and the terminal stop with a \
stopAll command"
.into(),
));
}
let caller = match caller(context, SurfaceKind::Web, None) {
Ok(caller) => caller,
Err(Unauthenticated) => return unauthenticated(),
};
match engine.execute(&caller, Command::StopAll { reason: request.reason }).await {
Ok(outcome) => Json::<CommandOutcome>(outcome).into_response(),
Err(error) => failed(error),
}
}
pub fn device_scope_for(method: &Method, path: &str) -> Option<DeviceScope> {
let path = path.split(['?', '#']).next().unwrap_or_default();
let path = path.strip_prefix("/api").unwrap_or(path);
let segments: Vec<&str> = path.split('/').filter(|segment| !segment.is_empty()).collect();
match (method.as_str(), segments.as_slice()) {
("GET", ["surface", "phone", "devices"] | ["surface", "phone", "push", "deliveries"])
| (_, ["surface", "phone", "qr"] | ["surface", "commands"]) => None,
("GET", ["surface", "phone"])
| ("PUT" | "DELETE", ["surface", "phone", "push"])
| ("POST", ["surface", "phone", "push", "received"]) => Some(DeviceScope::Read),
("POST", ["surface", "phone", "passkey"] | ["surface", "phone", "passkey", "options"])
| (
"POST",
["surface", "decisions", _, "answer" | "confirm" | "take-over"]
| ["surface", "decisions", _, "confirm", "options"],
) => Some(DeviceScope::Decide),
("POST", ["surface", "stop"]) => Some(DeviceScope::Stop),
("POST", ["surface", "cameras", _, "off" | "stop"]) => Some(DeviceScope::Stop),
("POST", ["surface", "cameras", _, "on" | "frames" | "retry" | "freeze" | "cards"]) => {
Some(DeviceScope::Decide)
}
("GET", ["surface", ..]) => Some(DeviceScope::Read),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_surface_route_has_its_device_scope() {
let cases: &[(Method, &str, Option<DeviceScope>)] = &[
(Method::GET, "/api/surface/decisions?surface=phone", Some(DeviceScope::Read)),
(Method::GET, "/api/surface/decisions/apr_1", Some(DeviceScope::Read)),
(Method::GET, "/api/surface/sessions/s1/feed", Some(DeviceScope::Read)),
(Method::GET, "/api/surface/status", Some(DeviceScope::Read)),
(Method::GET, "/api/surface/phone", Some(DeviceScope::Read)),
(Method::PUT, "/api/surface/phone/push", Some(DeviceScope::Read)),
(Method::DELETE, "/api/surface/phone/push", Some(DeviceScope::Read)),
(Method::POST, "/api/surface/phone/push/received", Some(DeviceScope::Read)),
(Method::POST, "/api/surface/phone/passkey/options", Some(DeviceScope::Decide)),
(Method::POST, "/api/surface/phone/passkey", Some(DeviceScope::Decide)),
(Method::POST, "/api/surface/decisions/apr_1/answer", Some(DeviceScope::Decide)),
(
Method::POST,
"/api/surface/decisions/apr_1/confirm/options",
Some(DeviceScope::Decide),
),
(Method::POST, "/api/surface/decisions/apr_1/confirm", Some(DeviceScope::Decide)),
(Method::POST, "/api/surface/decisions/apr_1/take-over", Some(DeviceScope::Decide)),
(Method::POST, "/api/surface/stop", Some(DeviceScope::Stop)),
(
Method::GET,
"/api/surface/vision/s1/images/sha256%3Aab/view",
Some(DeviceScope::Read),
),
(Method::GET, "/api/surface/vision/s1/images/sha256%3Aab", Some(DeviceScope::Read)),
(Method::POST, "/api/surface/vision/s1/examples", None),
(Method::GET, "/api/surface/cameras", Some(DeviceScope::Read)),
(Method::GET, "/api/surface/cameras/line-2", Some(DeviceScope::Read)),
(
Method::GET,
"/api/surface/cameras/line-2/frames/sha256%3Aab",
Some(DeviceScope::Read),
),
(Method::GET, "/api/surface/cameras/line-2/feed", Some(DeviceScope::Read)),
(Method::POST, "/api/surface/cameras/line-2/off", Some(DeviceScope::Stop)),
(Method::POST, "/api/surface/cameras/line-2/stop", Some(DeviceScope::Stop)),
(Method::POST, "/api/surface/cameras/line-2/on", Some(DeviceScope::Decide)),
(Method::POST, "/api/surface/cameras/this-computer/frames", Some(DeviceScope::Decide)),
(Method::POST, "/api/surface/cameras/line-2/retry", Some(DeviceScope::Decide)),
(Method::POST, "/api/surface/cameras/line-2/freeze", Some(DeviceScope::Decide)),
(Method::POST, "/api/surface/cameras/line-2/cards", Some(DeviceScope::Decide)),
(Method::PUT, "/api/surface/cameras/line-2/zones/inspection-window", None),
(Method::POST, "/api/surface/commands", None),
(Method::POST, "/api/surface/phone/qr", None),
(Method::GET, "/api/surface/phone/devices", None),
(Method::GET, "/api/surface/phone/push/deliveries", None),
(Method::DELETE, "/api/surface/phone/passkey/abc", None),
(Method::POST, "/api/surface/decisions/apr_1", None),
(Method::POST, "/api/kernel/unfreeze", None),
(Method::GET, "/api/kernel/health", None),
];
for (method, path, scope) in cases {
assert_eq!(device_scope_for(method, path), *scope, "{method} {path}");
}
}
}