diff --git a/cmd/dwelling-radio/main.go b/cmd/dwelling-radio/main.go index 6d78962..cdcf37a 100644 --- a/cmd/dwelling-radio/main.go +++ b/cmd/dwelling-radio/main.go @@ -68,13 +68,14 @@ func main() { djh := ihttp.NewDJHandlers(lstnrs, plylst, songList, &mostListenedSong, *fallbackSong) - s := r.Sub("/api/listener") - s.Handler(http.MethodGet, "/", djh.ListenersGet) - s.Handler(http.MethodPost, "/", djh.ListenersInc) - s.Handler(http.MethodDelete, "/", djh.ListenersDec) + // s := r.Sub("/api/listener") + // s.Handler(http.MethodGet, "/", djh.ListenersGet) + // s.Handler(http.MethodPost, "/", djh.ListenersInc) + // s.Handler(http.MethodDelete, "/", djh.ListenersDec) - s = r.Sub("/api") + s := r.Sub("/api") + s.Handler(http.MethodPost, "/listener/icecast", djh.ListenersUpdate) s.Handler(http.MethodGet, "/playlist", djh.PlaylistNext) s.Handler(http.MethodGet, "/status", djh.Status) // s.Handler(http.MethodGet, "/song", djh.Song) diff --git a/configs/icecast.xml b/configs/icecast.xml index 158ce56..f1aa722 100644 --- a/configs/icecast.xml +++ b/configs/icecast.xml @@ -40,8 +40,11 @@ /stream.ogg UTF8 1 - /usr/bin/dwelling-radio-listener-connect - /usr/bin/dwelling-radio-listener-disconnect + + diff --git a/configs/nginx.conf b/configs/nginx.conf index 57a7f38..82761aa 100644 --- a/configs/nginx.conf +++ b/configs/nginx.conf @@ -36,10 +36,12 @@ server { } location /api/listener { + allow 192.168.144.2; deny all; } location /api/playlist { + allow 192.168.144.2; deny all; } } diff --git a/internal/http/dj_handlers.go b/internal/http/dj_handlers.go index 3686130..fc76826 100644 --- a/internal/http/dj_handlers.go +++ b/internal/http/dj_handlers.go @@ -25,6 +25,41 @@ func NewDJHandlers(l *radio.ListenerCounter, p *radio.Playlist, mostLSong: mls, fallbackSong: fS} } +func (dj *DJHandlers) ListenersUpdate(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + log.Println("DJHandlers.ListenersUpdate panic:", err) + } + }() + + if err := r.ParseForm(); err != nil { + log.Println("DJHandlers.ListenersUpdate:", err) + http.Error(w, "cannot parse form", http.StatusBadRequest) + return + } + + fmt.Println(r.Method, r.Form) + + switch r.FormValue("action") { + case "listener_add": + l := dj.listeners.Inc() + go dj.songList.UpdateCurrentMaxListeners(l) + case "listener_remove": + if _, err := dj.listeners.Dec(); err != nil { + log.Println("DJHandlers.ListenersUpdate:", err) + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + default: + w.WriteHeader(http.StatusNotAcceptable) + return + } + + w.Header().Add("Content-Type", "text/plain") + w.Header().Add("Icecast-Auth-User", "1") + w.WriteHeader(http.StatusOK) +} + func (dj *DJHandlers) ListenersGet(w http.ResponseWriter, _ *http.Request) { w.Header().Add("Content-Type", "application/json") json.NewEncoder(w).Encode(dj.listeners)