This commit is contained in:
1 parent
9a6ec940f7
commit
fd32419371
114 files changed
+21997
-96
No files matched your search
@@ -0,0 +1,541 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
maxSyncIdentifier = 128
|
||||
maxSyncSessions = 1000
|
||||
)
|
||||
|
||||
type syncPeer struct {
|
||||
conn *websocket.Conn
|
||||
writeMu sync.Mutex
|
||||
clientID string
|
||||
sessionID string
|
||||
userAgent string
|
||||
ipAddress string
|
||||
remoteControlEnabled bool
|
||||
uiView string
|
||||
uiMediaID any
|
||||
uiMediaIDSet bool
|
||||
}
|
||||
|
||||
type syncHub struct {
|
||||
mu sync.Mutex
|
||||
peers map[*syncPeer]struct{}
|
||||
states map[string]map[string]any
|
||||
playAt map[string]string
|
||||
playAtLocalMs map[string]int64
|
||||
capturedAtMs map[string]int64
|
||||
controlOwners map[string]string
|
||||
}
|
||||
|
||||
func newSyncHub() *syncHub {
|
||||
return &syncHub{
|
||||
peers: make(map[*syncPeer]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 *syncHub) add(peer *syncPeer) {
|
||||
h.mu.Lock()
|
||||
h.peers[peer] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *syncHub) remove(peer *syncPeer) string {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
delete(h.peers, peer)
|
||||
if peer.clientID != "" && !h.hasClientLocked(peer.clientID) {
|
||||
delete(h.controlOwners, peer.clientID)
|
||||
for targetID, ownerID := range h.controlOwners {
|
||||
if ownerID == peer.clientID {
|
||||
delete(h.controlOwners, targetID)
|
||||
}
|
||||
}
|
||||
}
|
||||
return peer.sessionID
|
||||
}
|
||||
|
||||
func (h *syncHub) hasClientLocked(clientID string) bool {
|
||||
for peer := range h.peers {
|
||||
if peer.clientID == clientID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *syncHub) updatePeer(peer *syncPeer, clientID, sessionID string) {
|
||||
h.mu.Lock()
|
||||
if clientID != "" {
|
||||
peer.clientID = clientID
|
||||
}
|
||||
if sessionID != "" {
|
||||
peer.sessionID = sessionID
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *syncHub) clientStatus(peer *syncPeer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if sessionID != "" {
|
||||
peer.sessionID = sessionID
|
||||
}
|
||||
if view != "" {
|
||||
peer.uiView = view
|
||||
}
|
||||
if mediaIDSet {
|
||||
peer.uiMediaID = mediaID
|
||||
peer.uiMediaIDSet = true
|
||||
}
|
||||
if remoteSet {
|
||||
peer.remoteControlEnabled = remote
|
||||
if !remote && h.controlOwners[peer.clientID] != "" {
|
||||
delete(h.controlOwners, peer.clientID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *syncHub) clientsLocked(sessionID string) []map[string]any {
|
||||
byID := make(map[string]map[string]any)
|
||||
for peer := range h.peers {
|
||||
if peer.sessionID != sessionID || peer.clientID == "" {
|
||||
continue
|
||||
}
|
||||
entry, exists := byID[peer.clientID]
|
||||
if !exists {
|
||||
entry = map[string]any{
|
||||
"clientId": peer.clientID,
|
||||
"userAgent": peer.userAgent,
|
||||
"ipAddress": peer.ipAddress,
|
||||
"remoteControlEnabled": peer.remoteControlEnabled,
|
||||
"controlOwnerClientId": nil,
|
||||
}
|
||||
byID[peer.clientID] = entry
|
||||
} else if peer.remoteControlEnabled {
|
||||
entry["remoteControlEnabled"] = true
|
||||
}
|
||||
if peer.uiView != "" {
|
||||
entry["uiView"] = peer.uiView
|
||||
}
|
||||
if peer.uiMediaIDSet {
|
||||
entry["uiMediaId"] = peer.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 *syncHub) 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)
|
||||
}
|
||||
|
||||
func (h *syncHub) httpState(sessionID string) map[string]any {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return h.timingLocked(sessionID, h.stateLocked(sessionID))
|
||||
}
|
||||
|
||||
func (h *syncHub) 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 *syncHub) 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
|
||||
}
|
||||
|
||||
func (h *syncHub) broadcast(sessionID string) {
|
||||
h.mu.Lock()
|
||||
state := h.timingLocked(sessionID, h.stateLocked(sessionID))
|
||||
clients := h.clientsLocked(sessionID)
|
||||
peers := make([]*syncPeer, 0)
|
||||
for peer := range h.peers {
|
||||
if peer.sessionID == sessionID {
|
||||
peers = append(peers, peer)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
|
||||
for _, peer := range peers {
|
||||
if err := peer.send(message); err != nil {
|
||||
_ = peer.conn.Close(websocket.StatusGoingAway, "write failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (peer *syncPeer) send(message any) error {
|
||||
data, err := json.Marshal(message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
peer.writeMu.Lock()
|
||||
defer peer.writeMu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
return peer.conn.Write(ctx, websocket.MessageText, data)
|
||||
}
|
||||
|
||||
func (s *Server) websocketAcceptOptions(r *http.Request) *websocket.AcceptOptions {
|
||||
options := &websocket.AcceptOptions{}
|
||||
if s.cfg.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(s.cfg.AllowedOrigin)
|
||||
scheme := "http"
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
addOrigin(scheme + "://" + r.Host)
|
||||
options.OriginPatterns = patterns
|
||||
return options
|
||||
}
|
||||
|
||||
func (s *Server) syncWebsocket(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := websocket.Accept(w, r, s.websocketAcceptOptions(r))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
peer := &syncPeer{
|
||||
conn: conn,
|
||||
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
|
||||
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
|
||||
}
|
||||
s.sync.add(peer)
|
||||
defer func() {
|
||||
sessionID := s.sync.remove(peer)
|
||||
_ = conn.Close(websocket.StatusNormalClosure, "")
|
||||
if sessionID != "" {
|
||||
s.sync.broadcast(sessionID)
|
||||
}
|
||||
}()
|
||||
|
||||
_ = peer.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
|
||||
}
|
||||
s.handleSyncMessage(peer, message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleSyncMessage(peer *syncPeer, message map[string]any) {
|
||||
typ, _ := message["type"].(string)
|
||||
switch typ {
|
||||
case "ws:ping":
|
||||
_ = peer.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
|
||||
}
|
||||
s.sync.updatePeer(peer, clientID, sessionID)
|
||||
s.sync.broadcast(sessionID)
|
||||
case "client:status":
|
||||
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
|
||||
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
|
||||
if clientID == "" {
|
||||
return
|
||||
}
|
||||
s.sync.updatePeer(peer, clientID, sessionID)
|
||||
mediaID, mediaIDSet := syncMediaID(message)
|
||||
remote, remoteSet := message["remoteControlEnabled"].(bool)
|
||||
s.sync.clientStatus(peer, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
|
||||
s.sync.broadcast(sessionID)
|
||||
case "control:claim", "control:release":
|
||||
s.handleControlMessage(peer, typ, message)
|
||||
case "sync:update":
|
||||
s.handleSyncUpdate(peer, message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleControlMessage(peer *syncPeer, typ string, message map[string]any) {
|
||||
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
|
||||
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
|
||||
targetID := boundedSyncString(syncString(message, "targetClientId"))
|
||||
if requesterID == "" || targetID == "" || requesterID != peer.clientID {
|
||||
return
|
||||
}
|
||||
|
||||
s.sync.mu.Lock()
|
||||
owner := s.sync.controlOwners[targetID]
|
||||
ok := false
|
||||
reason := ""
|
||||
if typ == "control:claim" {
|
||||
enabled := false
|
||||
for candidate := range s.sync.peers {
|
||||
if candidate.clientID == targetID && candidate.remoteControlEnabled {
|
||||
enabled = true
|
||||
break
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case !enabled:
|
||||
reason = "disabled"
|
||||
case owner != "" && owner != requesterID:
|
||||
reason = "busy"
|
||||
default:
|
||||
s.sync.controlOwners[targetID] = requesterID
|
||||
owner = requesterID
|
||||
ok = true
|
||||
}
|
||||
} else if owner != "" && owner != requesterID {
|
||||
reason = "not-owner"
|
||||
} else {
|
||||
delete(s.sync.controlOwners, targetID)
|
||||
owner = ""
|
||||
ok = true
|
||||
}
|
||||
s.sync.mu.Unlock()
|
||||
|
||||
_ = peer.send(map[string]any{
|
||||
"type": "control:ack",
|
||||
"ok": ok,
|
||||
"action": strings.TrimPrefix(typ, "control:"),
|
||||
"targetClientId": targetID,
|
||||
"ownerClientId": nullableString(owner),
|
||||
"reason": nullableString(reason),
|
||||
})
|
||||
s.sync.broadcast(sessionID)
|
||||
}
|
||||
|
||||
func (s *Server) handleSyncUpdate(peer *syncPeer, message map[string]any) {
|
||||
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
|
||||
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
|
||||
if clientID == "" || clientID != peer.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"]
|
||||
|
||||
s.sync.mu.Lock()
|
||||
if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" {
|
||||
delete(s.sync.playAt, sessionID)
|
||||
delete(s.sync.playAtLocalMs, sessionID)
|
||||
} else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil {
|
||||
s.sync.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano)
|
||||
if local := syncInt(message, "playAtLocalMs", 0); local > 0 {
|
||||
s.sync.playAtLocalMs[sessionID] = local
|
||||
} else {
|
||||
delete(s.sync.playAtLocalMs, sessionID)
|
||||
}
|
||||
}
|
||||
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
|
||||
s.sync.capturedAtMs[sessionID] = captured
|
||||
}
|
||||
if toClientID == "" {
|
||||
s.sync.states[sessionID] = cloneMap(state)
|
||||
if len(s.sync.states) > maxSyncSessions {
|
||||
for key := range s.sync.states {
|
||||
delete(s.sync.states, key)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
state = s.sync.timingLocked(sessionID, state)
|
||||
clients := s.sync.clientsLocked(sessionID)
|
||||
peers := make([]*syncPeer, 0)
|
||||
if toClientID != "" {
|
||||
for candidate := range s.sync.peers {
|
||||
if candidate.sessionID == sessionID && candidate.clientID == toClientID {
|
||||
peers = append(peers, candidate)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.sync.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
|
||||
}
|
||||
s.sync.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
|
||||
}
|
||||
Reference in new issue
Block a user