Skip to content
Merged
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
23 changes: 22 additions & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("/api/peers", s.handlePeers)
mux.HandleFunc("/api/players", s.handlePlayers)
mux.HandleFunc("/api/nowplaying", s.handleNowPlaying)
mux.HandleFunc("/api/events", s.handleEvents)
mux.HandleFunc("/api/overlay/config", s.handleOverlayConfig)
mux.HandleFunc("/api/history", s.handleHistory)
mux.HandleFunc("/api/tracks", s.handleTracks)
Expand Down Expand Up @@ -383,7 +384,27 @@ func (s *Server) Handler() http.Handler {
if s.Web {
RegisterWebUI(mux)
}
return mux
return corsMiddleware(mux)
}

// corsMiddleware adds permissive CORS to every response and answers preflight
// OPTIONS requests uniformly, so a frontend served from another origin or
// device can call the API. Vynull is a trusted-LAN tool with no auth; this just
// makes the already-open posture consistent across every endpoint instead of
// the former per-handler patchwork (those handlers set the same header, so they
// remain correct — this just guarantees it everywhere, preflight included).
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Access-Control-Allow-Origin", "*")
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD, OPTIONS")
h.Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}

func (s *Server) Start(ctx context.Context) error {
Expand Down
69 changes: 69 additions & 0 deletions api/events.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: GPL-3.0-or-later

package api

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)

// handleEvents streams live deck + now-playing state as Server-Sent Events, so
// a frontend gets push updates instead of polling /api/players. Each event is:
//
// event: state
// data: {"players":[...],"nowplaying":{...}}
//
// A snapshot is sent on change — effectively ~4 Hz while a deck is active (the
// playhead's beat_age_ms keeps changing) and nothing while idle, with a
// heartbeat comment to hold the connection open. beat_age_ms lets the client
// interpolate the playhead between events, so a few per second render smoothly.
func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache")
h.Set("Connection", "keep-alive")
// CORS is applied by the mux middleware.

ctx := r.Context()
tick := time.NewTicker(250 * time.Millisecond)
defer tick.Stop()
heartbeat := time.NewTicker(15 * time.Second)
defer heartbeat.Stop()

var last []byte
send := func() {
players := s.getPlayers()
snap := struct {
Players []PlayerInfo `json:"players"`
NowPlaying NowPlaying `json:"nowplaying"`
}{Players: players, NowPlaying: nowPlayingFrom(players)}
data, err := json.Marshal(snap)
if err != nil || bytes.Equal(data, last) {
return // marshal failed, or nothing changed since the last event
}
last = data
fmt.Fprintf(w, "event: state\ndata: %s\n\n", data)
flusher.Flush()
}

send() // prime the client immediately on connect
for {
select {
case <-ctx.Done():
return
case <-tick.C:
send()
case <-heartbeat.C:
fmt.Fprint(w, ": ping\n\n")
flusher.Flush()
}
}
}
Loading