// Package syncsocket is the media-backend family's cross-device playback-sync // websocket hub: multiple clients viewing the same media session (identified // by a caller-chosen sessionId) see each other's play/pause/seek/remote-control // state live. Promoted unchanged from each service's own internal sync.go into // this shared library so the 6 media-family backends that mount it (every one // except MediaKiosk) use one copy instead of duplicating it. // // A service wires this up as: // // hub := syncsocket.NewHub() // router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { // hub.ServeWebSocket(w, r, cfg.AllowedOrigin) // }) // // and mediacore's shared GET/PUT /sync HTTP routes call hub.HTTPState/ // SetHTTPState/Broadcast to read and mutate the same session state the // websocket peers see. package syncsocket import ( "context" "encoding/json" "math" "net/http" "net/url" "strings" "sync" "time" "github.com/coder/websocket" ) const ( maxSyncIdentifier = 128 maxSyncSessions = 1000 ) type peer struct { conn *websocket.Conn writeMu sync.Mutex clientID string sessionID string userAgent string ipAddress string remoteControlEnabled bool uiView string uiMediaID any uiMediaIDSet bool } // Hub tracks every connected sync websocket peer and the last-known playback // state per session, broadcasting updates to every peer sharing a session. type Hub struct { mu sync.Mutex peers map[*peer]struct{} states map[string]map[string]any playAt map[string]string playAtLocalMs map[string]int64 capturedAtMs map[string]int64 controlOwners map[string]string } // NewHub returns an empty Hub ready to accept websocket connections and // serve/mutate HTTP sync state. func NewHub() *Hub { return &Hub{ peers: make(map[*peer]struct{}), states: make(map[string]map[string]any), playAt: make(map[string]string), playAtLocalMs: make(map[string]int64), capturedAtMs: make(map[string]int64), controlOwners: make(map[string]string), } } func (h *Hub) add(p *peer) { h.mu.Lock() h.peers[p] = struct{}{} h.mu.Unlock() } func (h *Hub) remove(p *peer) string { h.mu.Lock() defer h.mu.Unlock() delete(h.peers, p) if p.clientID != "" && !h.hasClientLocked(p.clientID) { delete(h.controlOwners, p.clientID) for targetID, ownerID := range h.controlOwners { if ownerID == p.clientID { delete(h.controlOwners, targetID) } } } return p.sessionID } func (h *Hub) hasClientLocked(clientID string) bool { for p := range h.peers { if p.clientID == clientID { return true } } return false } func (h *Hub) updatePeer(p *peer, clientID, sessionID string) { h.mu.Lock() if clientID != "" { p.clientID = clientID } if sessionID != "" { p.sessionID = sessionID } h.mu.Unlock() } func (h *Hub) clientStatus(p *peer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) { h.mu.Lock() defer h.mu.Unlock() if sessionID != "" { p.sessionID = sessionID } if view != "" { p.uiView = view } if mediaIDSet { p.uiMediaID = mediaID p.uiMediaIDSet = true } if remoteSet { p.remoteControlEnabled = remote if !remote && h.controlOwners[p.clientID] != "" { delete(h.controlOwners, p.clientID) } } } func (h *Hub) clientsLocked(sessionID string) []map[string]any { byID := make(map[string]map[string]any) for p := range h.peers { if p.sessionID != sessionID || p.clientID == "" { continue } entry, exists := byID[p.clientID] if !exists { entry = map[string]any{ "clientId": p.clientID, "userAgent": p.userAgent, "ipAddress": p.ipAddress, "remoteControlEnabled": p.remoteControlEnabled, "controlOwnerClientId": nil, } byID[p.clientID] = entry } else if p.remoteControlEnabled { entry["remoteControlEnabled"] = true } if p.uiView != "" { entry["uiView"] = p.uiView } if p.uiMediaIDSet { entry["uiMediaId"] = p.uiMediaID } } for clientID, entry := range byID { if owner := h.controlOwners[clientID]; owner != "" { entry["controlOwnerClientId"] = owner } } clients := make([]map[string]any, 0, len(byID)) for _, entry := range byID { clients = append(clients, entry) } return clients } func (h *Hub) stateLocked(sessionID string) map[string]any { state, ok := h.states[sessionID] if !ok { return map[string]any{ "sessionId": sessionID, "mediaId": nil, "timeMs": int64(0), "paused": true, "fps": 30, "frame": int64(0), "fromClientId": "", "updatedAt": time.Unix(0, 0).UTC().Format(time.RFC3339Nano), } } return cloneMap(state) } // HTTPState returns the current playback state for a session, as seen by the // GET /sync HTTP endpoint (mounted by mediacore). func (h *Hub) HTTPState(sessionID string) map[string]any { h.mu.Lock() defer h.mu.Unlock() return h.timingLocked(sessionID, h.stateLocked(sessionID)) } // SetHTTPState overwrites a session's playback state, as driven by the // PUT /sync HTTP endpoint (mounted by mediacore) - callers should follow this // with Broadcast to notify connected websocket peers. func (h *Hub) SetHTTPState(sessionID string, state map[string]any) { h.mu.Lock() defer h.mu.Unlock() h.states[sessionID] = cloneMap(state) if len(h.states) > maxSyncSessions { for key := range h.states { delete(h.states, key) break } } } func (h *Hub) timingLocked(sessionID string, state map[string]any) map[string]any { paused, _ := state["paused"].(bool) if !paused { if value := h.playAt[sessionID]; value != "" { state["playAt"] = value } } if value, ok := h.playAtLocalMs[sessionID]; ok { state["playAtLocalMs"] = value } if value, ok := h.capturedAtMs[sessionID]; ok { state["capturedAtLocalMs"] = value } return state } // Broadcast pushes the current state of sessionID to every connected // websocket peer sharing that session. func (h *Hub) Broadcast(sessionID string) { h.mu.Lock() state := h.timingLocked(sessionID, h.stateLocked(sessionID)) clients := h.clientsLocked(sessionID) peers := make([]*peer, 0) for p := range h.peers { if p.sessionID == sessionID { peers = append(peers, p) } } h.mu.Unlock() message := map[string]any{"type": "sync:state", "state": state, "clients": clients} for _, p := range peers { if err := p.send(message); err != nil { _ = p.conn.Close(websocket.StatusGoingAway, "write failed") } } } func (p *peer) send(message any) error { data, err := json.Marshal(message) if err != nil { return err } p.writeMu.Lock() defer p.writeMu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() return p.conn.Write(ctx, websocket.MessageText, data) } func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions { options := &websocket.AcceptOptions{} if allowedOrigin == "*" { options.InsecureSkipVerify = true return options } patterns := make([]string, 0, 2) addOrigin := func(value string) { parsed, err := url.Parse(strings.TrimSpace(value)) if err == nil && parsed.Scheme != "" && parsed.Host != "" { patterns = append(patterns, parsed.Scheme+"://"+parsed.Host) } } addOrigin(allowedOrigin) scheme := "http" if r.TLS != nil { scheme = "https" } addOrigin(scheme + "://" + r.Host) options.OriginPatterns = patterns return options } // ServeWebSocket upgrades the request to a websocket connection and services // it until the client disconnects. allowedOrigin should be the service's own // CORS_ORIGIN config value (or "*" to accept any origin). func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) { conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin)) if err != nil { return } p := &peer{ conn: conn, userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"), ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"), } h.add(p) defer func() { sessionID := h.remove(p) _ = conn.Close(websocket.StatusNormalClosure, "") if sessionID != "" { h.Broadcast(sessionID) } }() _ = p.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()}) for { messageType, payload, readErr := conn.Read(r.Context()) if readErr != nil { return } if messageType != websocket.MessageText { continue } var message map[string]any if json.Unmarshal(payload, &message) != nil { continue } h.handleMessage(p, message) } } func (h *Hub) handleMessage(p *peer, message map[string]any) { typ, _ := message["type"].(string) switch typ { case "ws:ping": _ = p.send(map[string]any{ "type": "ws:pong", "nonce": syncString(message, "nonce"), "clientSentAt": syncNumberValue(message, "clientSentAt"), "serverReceivedAt": time.Now().UnixMilli(), }) case "sync:hello": clientID := boundedSyncString(syncString(message, "clientId")) sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default")) if clientID == "" || sessionID == "" { return } h.updatePeer(p, clientID, sessionID) h.Broadcast(sessionID) case "client:status": clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) if clientID == "" { return } h.updatePeer(p, clientID, sessionID) mediaID, mediaIDSet := syncMediaID(message) remote, remoteSet := message["remoteControlEnabled"].(bool) h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote) h.Broadcast(sessionID) case "control:claim", "control:release": h.handleControlMessage(p, typ, message) case "sync:update": h.handleSyncUpdate(p, message) } } func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) { requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) targetID := boundedSyncString(syncString(message, "targetClientId")) if requesterID == "" || targetID == "" || requesterID != p.clientID { return } h.mu.Lock() owner := h.controlOwners[targetID] ok := false reason := "" if typ == "control:claim" { enabled := false for candidate := range h.peers { if candidate.clientID == targetID && candidate.remoteControlEnabled { enabled = true break } } switch { case !enabled: reason = "disabled" case owner != "" && owner != requesterID: reason = "busy" default: h.controlOwners[targetID] = requesterID owner = requesterID ok = true } } else if owner != "" && owner != requesterID { reason = "not-owner" } else { delete(h.controlOwners, targetID) owner = "" ok = true } h.mu.Unlock() _ = p.send(map[string]any{ "type": "control:ack", "ok": ok, "action": strings.TrimPrefix(typ, "control:"), "targetClientId": targetID, "ownerClientId": nullableString(owner), "reason": nullableString(reason), }) h.Broadcast(sessionID) } func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) { clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) if clientID == "" || clientID != p.clientID { return } mediaID, _ := syncMediaID(message) paused := syncBool(message, "paused") state := map[string]any{ "sessionId": sessionID, "mediaId": mediaID, "timeMs": syncInt(message, "timeMs", 0), "paused": paused, "fps": syncFPS(message), "frame": syncInt(message, "frame", 0), "fromClientId": clientID, "updatedAt": time.Now().UTC().Format(time.RFC3339Nano), } for _, key := range []string{"openInUi", "seekToken", "seekPhase", "seekWantPlay", "seekTargetClientId", "fullscreen", "goToGrid"} { if value, ok := message[key]; ok { state[key] = value } } toClientID := boundedSyncString(syncString(message, "toClientId")) playAtRaw, hasPlayAt := message["playAt"] h.mu.Lock() if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" { delete(h.playAt, sessionID) delete(h.playAtLocalMs, sessionID) } else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil { h.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano) if local := syncInt(message, "playAtLocalMs", 0); local > 0 { h.playAtLocalMs[sessionID] = local } else { delete(h.playAtLocalMs, sessionID) } } if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 { h.capturedAtMs[sessionID] = captured } if toClientID == "" { h.states[sessionID] = cloneMap(state) if len(h.states) > maxSyncSessions { for key := range h.states { delete(h.states, key) break } } } state = h.timingLocked(sessionID, state) clients := h.clientsLocked(sessionID) peers := make([]*peer, 0) if toClientID != "" { for candidate := range h.peers { if candidate.sessionID == sessionID && candidate.clientID == toClientID { peers = append(peers, candidate) } } } h.mu.Unlock() messageOut := map[string]any{"type": "sync:state", "state": state, "clients": clients} if toClientID != "" { for _, target := range peers { if err := target.send(messageOut); err != nil { _ = target.conn.Close(websocket.StatusGoingAway, "write failed") } } return } h.Broadcast(sessionID) } func syncMediaID(message map[string]any) (any, bool) { value, ok := message["mediaId"] if !ok { return nil, false } if value == nil { return nil, true } return boundedSyncString(syncStringValue(value)), true } func syncString(message map[string]any, key string) string { return syncStringValue(message[key]) } func syncStringValue(value any) string { if value == nil { return "" } if text, ok := value.(string); ok { return strings.TrimSpace(text) } return "" } func boundedSyncString(value string) string { value = strings.TrimSpace(value) if len(value) > maxSyncIdentifier { return value[:maxSyncIdentifier] } return value } func syncBool(message map[string]any, key string) bool { value, _ := message[key].(bool) return value } func syncNumberValue(message map[string]any, key string) any { if value, ok := message[key]; ok { return value } return nil } func syncInt(message map[string]any, key string, fallback int64) int64 { value, ok := message[key].(float64) if !ok || math.IsNaN(value) || math.IsInf(value, 0) { return fallback } if value < 0 { return 0 } if value > float64(^uint64(0)>>1) { return int64(^uint64(0) >> 1) } return int64(math.Round(value)) } func syncFPS(message map[string]any) int64 { fps := syncInt(message, "fps", 30) if fps < 1 { return 1 } if fps > 240 { return 240 } return fps } func nullableString(value string) any { if value == "" { return nil } return value } func cloneMap(value map[string]any) map[string]any { result := make(map[string]any, len(value)) for key, item := range value { result[key] = item } return result } func firstNonEmpty(values ...string) string { for _, value := range values { if strings.TrimSpace(value) != "" { return value } } return "" }