agentmux_srv/server/
file_icons.rs1use axum::{
10 extract::Query,
11 http::{header, StatusCode},
12 response::{IntoResponse, Json, Response},
13};
14use serde_json::json;
15
16use crate::backend::file_icons::{self, request::IconRequest, IconError};
17
18#[derive(serde::Deserialize)]
19pub(super) struct IconQuery {
20 kind: Option<String>,
21 ext: Option<String>,
22 px: Option<String>,
23}
24
25const MAX_AGE: &str = "private, max-age=86400";
28
29fn refusal(status: StatusCode, why: &str) -> Response {
30 (status, Json(json!({ "error": why }))).into_response()
31}
32
33pub(super) async fn handle_file_icon(Query(q): Query<IconQuery>) -> Response {
34 let req = match IconRequest::parse(q.kind.as_deref(), q.ext.as_deref(), q.px.as_deref()) {
35 Ok(r) => r,
36 Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
37 };
38 match file_icons::icon_png(&req).await {
39 Ok(png) => (
40 [(header::CONTENT_TYPE, "image/png"), (header::CACHE_CONTROL, MAX_AGE)],
41 png.as_ref().clone(),
42 )
43 .into_response(),
44 Err(IconError::Unsupported) => refusal(StatusCode::NOT_IMPLEMENTED, "no system icons on this computer yet"),
45 Err(IconError::NoIcon) => refusal(StatusCode::NOT_FOUND, "no icon for this type"),
46 Err(IconError::Timeout) => refusal(StatusCode::GATEWAY_TIMEOUT, "the icon took too long"),
47 Err(IconError::Busy) => refusal(StatusCode::SERVICE_UNAVAILABLE, "too many icon requests"),
48 Err(IconError::Failed) => refusal(StatusCode::INTERNAL_SERVER_ERROR, "the icon could not be made"),
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55 use axum::{body::Body, http::Request, routing::get, Router};
56 use tower::ServiceExt;
57
58 async fn status(uri: &str) -> StatusCode {
59 let app = Router::new().route("/agentmux/file-icon", get(handle_file_icon));
60 app.oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()).await.unwrap().status()
61 }
62
63 #[tokio::test]
64 async fn a_request_that_is_not_a_type_and_a_listed_size_is_a_400_before_anything_runs() {
65 for bad in [
66 "/agentmux/file-icon",
67 "/agentmux/file-icon?kind=file&ext=rs",
68 "/agentmux/file-icon?kind=file&ext=rs&px=17",
69 "/agentmux/file-icon?kind=file&ext=..%2F..%2Fx&px=16",
70 "/agentmux/file-icon?kind=file&ext=C%3A%5Cwindows%5Cnotepad.exe&px=16",
71 "/agentmux/file-icon?kind=dir&ext=rs&px=16",
72 "/agentmux/file-icon?kind=path&ext=rs&px=16",
73 ] {
74 assert_eq!(status(bad).await, StatusCode::BAD_REQUEST, "{bad}");
75 }
76 }
77
78 #[cfg(not(windows))]
79 #[tokio::test]
80 async fn without_a_system_source_the_answer_is_501_so_the_page_keeps_its_own_icons() {
81 assert_eq!(status("/agentmux/file-icon?kind=file&ext=rs&px=16").await, StatusCode::NOT_IMPLEMENTED);
82 }
83}