87 lines
3.0 KiB
Go
87 lines
3.0 KiB
Go
package syncsocket
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"io"
|
||
|
|
"net/http"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/go-chi/chi/v5"
|
||
|
|
)
|
||
|
|
|
||
|
|
// MountRoutes wires the cross-device sync HTTP routes onto r. GET /sync returns a session's
|
||
|
|
// current state and PUT /sync replaces it and broadcasts the change to that session's websocket
|
||
|
|
// peers. optional and required are the caller's auth middleware (an auth.Service's Optional and
|
||
|
|
// Require): GET runs with optional and PUT with required.
|
||
|
|
func MountRoutes(r chi.Router, hub *Hub, optional, required func(http.Handler) http.Handler) {
|
||
|
|
r.With(optional).Get("/sync", func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
getState(hub, w, r)
|
||
|
|
})
|
||
|
|
r.With(required).Put("/sync", func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
putState(hub, w, r)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
func getState(hub *Hub, w http.ResponseWriter, r *http.Request) {
|
||
|
|
sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default"))
|
||
|
|
writeJSON(w, http.StatusOK, hub.HTTPState(sessionID))
|
||
|
|
}
|
||
|
|
|
||
|
|
func putState(hub *Hub, w http.ResponseWriter, r *http.Request) {
|
||
|
|
var input map[string]any
|
||
|
|
if err := decodeRequestJSON(r, &input); err != nil {
|
||
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
clientID := boundedSyncString(syncString(input, "clientId"))
|
||
|
|
if clientID == "" {
|
||
|
|
writeError(w, http.StatusBadRequest, "clientId is required")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
mediaID, ok := syncScalar(input["mediaId"])
|
||
|
|
if !ok {
|
||
|
|
writeError(w, http.StatusBadRequest, "mediaId must be a string, a number or null")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
|
||
|
|
state := map[string]any{
|
||
|
|
"sessionId": sessionID,
|
||
|
|
"mediaId": mediaID,
|
||
|
|
"timeMs": syncInt(input, "timeMs", 0),
|
||
|
|
"paused": syncBool(input, "paused"),
|
||
|
|
"fps": syncFPS(input),
|
||
|
|
"frame": syncInt(input, "frame", 0),
|
||
|
|
"fromClientId": clientID,
|
||
|
|
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
|
||
|
|
}
|
||
|
|
if value, ok := input["playAt"]; ok {
|
||
|
|
playAt, valid := syncScalar(value)
|
||
|
|
if !valid {
|
||
|
|
writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
state["playAt"] = playAt
|
||
|
|
}
|
||
|
|
hub.SetHTTPState(sessionID, state)
|
||
|
|
// Broadcast queues immutable messages without waiting for network writes, so a slow
|
||
|
|
// websocket peer does not hold this response or create one goroutine per request.
|
||
|
|
hub.Broadcast(sessionID)
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state})
|
||
|
|
}
|
||
|
|
|
||
|
|
func decodeRequestJSON(r *http.Request, target any) error {
|
||
|
|
defer r.Body.Close()
|
||
|
|
decoder := json.NewDecoder(io.LimitReader(r.Body, 512*1024))
|
||
|
|
decoder.DisallowUnknownFields()
|
||
|
|
return decoder.Decode(target)
|
||
|
|
}
|
||
|
|
|
||
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||
|
|
w.WriteHeader(status)
|
||
|
|
_ = json.NewEncoder(w).Encode(value)
|
||
|
|
}
|
||
|
|
|
||
|
|
func writeError(w http.ResponseWriter, status int, message string) {
|
||
|
|
writeJSON(w, status, map[string]string{"error": message, "message": message})
|
||
|
|
}
|