From 5b15f5d70e06b6ba5a9aa1aaca24389bf20432a5 Mon Sep 17 00:00:00 2001 From: Piotr Tabor Date: Mon, 25 Nov 2024 21:13:31 +0100 Subject: [PATCH] Added support for: GET /statuses (#198) --- http/handlers.go | 54 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/http/handlers.go b/http/handlers.go index 528ee89..9c132d1 100644 --- a/http/handlers.go +++ b/http/handlers.go @@ -60,7 +60,8 @@ func (h *Handler) registerHandlers() { POST /connect-all?wait=...&iface=... POST /disconnect?uuid= POST /disconnect-all - POST /status?uuid= + GET /status?uuid= + GET /statuses POST /pause?uuid= POST /unpause?uuid= POST /skipad?uuid= @@ -81,6 +82,7 @@ func (h *Handler) registerHandlers() { h.mux.HandleFunc("/disconnect", h.disconnect) h.mux.HandleFunc("/disconnect-all", h.disconnectAll) h.mux.HandleFunc("/status", h.status) + h.mux.HandleFunc("/statuses", h.statuses) h.mux.HandleFunc("/pause", h.pause) h.mux.HandleFunc("/unpause", h.unpause) h.mux.HandleFunc("/skipad", h.skipad) @@ -164,6 +166,17 @@ func (h *Handler) app(uuid string) (application.App, bool) { return app, ok } +func (h *Handler) ConnectedDeviceUUIDs() []string { + h.mu.Lock() + defer h.mu.Unlock() + + var uuids []string + for k, _ := range h.apps { + uuids = append(uuids, k) + } + return uuids +} + func (h *Handler) connect(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() @@ -258,11 +271,9 @@ func (h *Handler) connectAll(w http.ResponseWriter, r *http.Request) { } var resp []connectResponse - h.mu.Lock() - for deviceUUID, _ := range h.apps { + for _, deviceUUID := range h.ConnectedDeviceUUIDs() { resp = append(resp, connectResponse{DeviceUUID: deviceUUID}) } - h.mu.Unlock() w.Header().Add("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(resp); err != nil { @@ -351,6 +362,41 @@ func (h *Handler) status(w http.ResponseWriter, r *http.Request) { } } +func (h *Handler) statuses(w http.ResponseWriter, r *http.Request) { + h.log("statuses for devices") + uuids := h.ConnectedDeviceUUIDs() + mapUUID2Ch := map[string]chan statusResponse{} + + for _, deviceUUID := range uuids { + app, ok := h.app(deviceUUID) + if ok { + ch := make(chan statusResponse, 1) + mapUUID2Ch[deviceUUID] = ch + go func() { + castApplication, castMedia, castVolume := app.Status() + ch <- fromApplicationStatus( + castApplication, + castMedia, + castVolume, + ) + }() + } + } + + statusResponses := map[string]statusResponse{} + for deviceUUID, ch := range mapUUID2Ch { + statusResponse := <-ch + statusResponses[deviceUUID] = statusResponse + } + + w.Header().Add("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(statusResponses); err != nil { + h.log("error encoding json: %v", err) + httpError(w, fmt.Errorf("unable to json encode statuses: %v", err)) + return + } +} + func (h *Handler) pause(w http.ResponseWriter, r *http.Request) { app, found := h.appForRequest(w, r) if !found {