Extract shared media backend library; remove dead multi-flavor app/binary

Adds mediaauth/mediacore/carriernodeclient/syncsocket packages under
backend/, extracting everything genuinely cross-service (auth, shared
media/tags/playlists/sync/profile routes, the CarrierNode HTTP client,
the playback-sync websocket hub) out of the old media-backend monolith.

The 7 media-family services (CarrierNode, ContentScanner, CraftStudio,
MediaViewer, MediaKiosk, ModerationHub, ProjectConfigurator) each now
have their own independent frontend and backend built on this library,
instead of sharing one generic multi-flavor webui/media-backend
selected by a MEDIA_SERVICE/VITE_MEDIA_APP flag. That generic app and
binary (webui/, media-backend/) are now dead and removed here, along
with their dedicated CI workflows. sync-consumers.ps1 and README.md
updated to describe the new architecture.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-09-07 15:06:06 +02:00
1 parent 2e6baaa70c
commit d1a02a8c4d
80 files changed
+1139 -16583

No files matched your search

@@ -0,0 +1,381 @@
// Package carriernodeclient is the HTTP client the 6 non-CarrierNode
// media-family services (MediaViewer, CraftStudio, ContentScanner,
// ModerationHub, ProjectConfigurator, MediaKiosk) use to store and serve
// media by calling CarrierNode's API, instead of touching a local
// MediaRoots/ThumbnailRoot/OutputRoot/DownloadsRoot/InputRoot/CopyRoot
// filesystem directly. CarrierNode's own backend keeps resolving and
// serving those roots itself - this client is never used from CarrierNode's
// own code path.
//
// Promoted unchanged (aside from being detached from a shared *Server type)
// from each service's own internal carriernode_client.go into this shared
// library, so all 6 callers use one copy instead of duplicating it.
package carriernodeclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// httpClient has no blanket timeout since it streams large media files;
// callers bound individual calls with a context deadline instead.
var httpClient = &http.Client{}
var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// Client calls CarrierNode's HTTP API on behalf of one of the other 6
// media-family services.
type Client struct {
// InternalServiceSecret is sent as the X-Internal-Auth header on every
// request, so CarrierNode can distinguish trusted service-to-service
// calls from public traffic. Empty means no header is sent.
InternalServiceSecret string
// BaseURL resolves CarrierNode's current base URL for a request. It is a
// function rather than a fixed string because CarrierNode's URL is
// configured live through ProjectConfigurator's Projects workspace
// (stored in the shared `settings` table under the "carriernode_url"
// key) - a change there takes effect on this client's very next call
// with no restart needed. Callers typically wire this as a closure over
// their own settings lookup, falling back to a static CARRIERNODE_URL
// env var default when no setting has been saved yet.
BaseURL func(ctx context.Context) string
}
// New returns a Client. baseURL is called fresh on every request (see
// Client.BaseURL's doc comment for why).
func New(internalServiceSecret string, baseURL func(ctx context.Context) string) *Client {
return &Client{InternalServiceSecret: internalServiceSecret, BaseURL: baseURL}
}
func (c *Client) newRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(c.BaseURL(ctx), "/")+path, body)
if err != nil {
return nil, err
}
if c.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", c.InternalServiceSecret)
}
return request, nil
}
// Proxy streams a CarrierNode response straight through to the original
// client, preserving range/conditional-request semantics so video scrubbing
// keeps working without reimplementing http.ServeContent on this side.
func (c *Client) Proxy(w http.ResponseWriter, r *http.Request, carrierNodePath string) {
request, err := c.newRequest(r.Context(), r.Method, carrierNodePath, nil)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
for _, header := range forwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := httpClient.Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
defer response.Body.Close()
for _, header := range forwardResponseHeaders {
if value := response.Header.Get(header); value != "" {
w.Header().Set(header, value)
}
}
w.WriteHeader(response.StatusCode)
if r.Method != http.MethodHead {
_, _ = io.Copy(w, response.Body)
}
}
// Probe checks whether a CarrierNode-served path exists without fetching its
// bytes. A 404 is reported as exists=false with a nil error, not a failure -
// only transport/5xx problems are surfaced as errors.
func (c *Client) Probe(ctx context.Context, carrierNodePath string) (exists bool, size int64, modTime time.Time, err error) {
request, err := c.newRequest(ctx, http.MethodHead, carrierNodePath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := httpClient.Do(request)
if err != nil {
return false, 0, time.Time{}, err
}
defer response.Body.Close()
if response.StatusCode == http.StatusNotFound {
return false, 0, time.Time{}, nil
}
if response.StatusCode >= 400 {
return false, 0, time.Time{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
}
size, _ = strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64)
modTime, _ = http.ParseTime(response.Header.Get("Last-Modified"))
return true, size, modTime, nil
}
// FetchToScratch downloads a CarrierNode-served path into an ephemeral temp
// file for local processing (ffmpeg/ffprobe/yt-dlp all need a real file
// handle). Callers must invoke the returned cleanup once done; it removes
// the scratch file unconditionally.
func (c *Client) FetchToScratch(ctx context.Context, carrierNodePath, suffix string) (path string, cleanup func(), err error) {
request, err := c.newRequest(ctx, http.MethodGet, carrierNodePath, nil)
if err != nil {
return "", nil, err
}
response, err := httpClient.Do(request)
if err != nil {
return "", nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("carriernode fetch failed: %s", response.Status)
}
scratch, err := os.CreateTemp("", "carriernode-src-*"+suffix)
if err != nil {
return "", nil, err
}
cleanup = func() { _ = os.Remove(scratch.Name()) }
if _, err := io.Copy(scratch, response.Body); err != nil {
scratch.Close()
cleanup()
return "", nil, err
}
if err := scratch.Close(); err != nil {
cleanup()
return "", nil, err
}
return scratch.Name(), cleanup, nil
}
// push streams a local file as the request body without buffering it in
// memory.
func (c *Client) push(ctx context.Context, method, carrierNodePath, localPath string) (*http.Response, error) {
file, err := os.Open(localPath)
if err != nil {
return nil, err
}
defer file.Close()
request, err := c.newRequest(ctx, method, carrierNodePath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := httpClient.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
response.Body.Close()
return nil, fmt.Errorf("carriernode push failed: %s: %s", response.Status, string(body))
}
return response, nil
}
func pushedSize(response *http.Response) int64 {
defer response.Body.Close()
var payload struct {
Size int64 `json:"size"`
}
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload.Size
}
// PushThumbnail uploads a locally-generated thumbnail to CarrierNode.
func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return pushedSize(response), nil
}
// DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as
// already-deleted, not an error.
func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
request, err := c.newRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := httpClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
return fmt.Errorf("carriernode delete thumbnail failed: %s", response.Status)
}
return nil
}
// PushOutput uploads a locally-produced output file (e.g. a converted or
// generated media file) to CarrierNode's OutputRoot.
func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return pushedSize(response), nil
}
// PushInput uploads a local file to CarrierNode's InputRoot.
func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return pushedSize(response), nil
}
// PushCopy uploads a local file to CarrierNode's CopyRoot.
func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return pushedSize(response), nil
}
// UploadDownload streams a locally-produced file (e.g. a completed yt-dlp
// download staged in a scratch dir) into CarrierNode's DownloadsRoot via its
// raw-upload endpoint.
func (c *Client) UploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := c.push(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath)
if err != nil {
return nil, err
}
defer response.Body.Close()
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// StoreDownload catalogs an already-uploaded file into CarrierNode's
// media/downloaded_media tables via its /api/store endpoint.
func (c *Client) StoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) {
body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status})
if err != nil {
return nil, err
}
request, err := c.newRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := httpClient.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode >= 400 {
errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
return nil, fmt.Errorf("carriernode store failed: %s: %s", response.Status, string(errorBody))
}
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// FileEntry describes one file CarrierNode reports via /api/files(/recent).
type FileEntry struct {
Rel string `json:"rel"`
Path string `json:"path"`
Type string `json:"type"`
Size int64 `json:"size"`
Mtime int64 `json:"mtime"`
}
// ListFiles lists files under CarrierNode's MediaRoots via its /api/files
// (recent=false) or /api/files/recent (recent=true) endpoints - the
// replacement for a local filepath.WalkDir over MediaRoots.
func (c *Client) ListFiles(ctx context.Context, relative string, recent bool, limit int) ([]FileEntry, error) {
endpoint := "/api/files"
if recent {
endpoint = "/api/files/recent"
}
query := url.Values{}
if relative != "" {
query.Set("path", relative)
}
if limit > 0 {
query.Set("limit", strconv.Itoa(limit))
}
if encoded := query.Encode(); encoded != "" {
endpoint += "?" + encoded
}
request, err := c.newRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := httpClient.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("carriernode file listing failed: %s", response.Status)
}
var payload struct {
Files []FileEntry `json:"files"`
}
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
return nil, err
}
return payload.Files, nil
}
// ProbeResult is the ffprobe-derived metadata CarrierNode's /api/probe
// endpoint reports for a media file.
type ProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
}
// ProbeMedia runs ffprobe on CarrierNode against a MediaRoots-relative path
// and returns just the metadata fields - bytes never leave CarrierNode,
// unlike every other method on Client.
func (c *Client) ProbeMedia(ctx context.Context, relative string) (ProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := c.newRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return ProbeResult{}, err
}
response, err := httpClient.Do(request)
if err != nil {
return ProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return ProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
}
var result ProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return ProbeResult{}, err
}
return result, nil
}
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})
}
+2
View File
@@ -3,6 +3,8 @@ module repos.gfranz.ch/Gabriel20xx/shared/backend
go 1.25.7
require (
github.com/coder/websocket v1.8.15
github.com/go-chi/chi/v5 v5.3.1
github.com/jackc/pgx/v5 v5.10.0
github.com/pressly/goose/v3 v3.27.3
golang.org/x/crypto v0.54.0
+4
View File
@@ -1,8 +1,12 @@
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
package mediaauth
import "testing"
func TestNormalizeCredentials(t *testing.T) {
email, username, password, err := normalizeCredentials(" User@Example.com ", "user", "correct horse battery staple")
if err != nil {
t.Fatal(err)
}
if email != "user@example.com" || username != "user" || password == "" {
t.Fatalf("normalized credentials = %q, %q, %q", email, username, password)
}
}
func TestNormalizeCredentialsAllowsAdminEmailOnly(t *testing.T) {
if _, _, _, err := normalizeCredentials("admin@example.com", "", "correct horse battery staple"); err != nil {
t.Fatalf("empty optional username rejected: %v", err)
}
}
func TestNormalizeRole(t *testing.T) {
if normalizeRole("MODERATOR") != "moderator" {
t.Fatal("moderator role was not normalized")
}
if normalizeRole("unknown") != "user" {
t.Fatal("unknown role was not reduced to user")
}
}
File diff suppressed because it is too large. Load diff
+181
View File
@@ -0,0 +1,181 @@
package mediacore
import "context"
// Migrate creates every table (and its indexes) mediacore's shared routes
// read or write, using CREATE TABLE/INDEX IF NOT EXISTS so whichever
// media-family service starts first against a fresh database creates them
// and every other service's own startup is a no-op. Statements are copied
// verbatim from the pre-split monolith's
// internal/database/migrations/001_initial.sql, limited to the tables
// mediacore itself owns (media, media_stats, media_view_sessions,
// media_tags, media_tag_votes, settings, playlists, playlist_items,
// workflow_jobs, thumbnails) plus `users`, which several of those
// reference via foreign key even though identity itself now lives in
// AuthGuard (see mediaauth's package doc comment) - the column is kept for
// FK integrity, not queried by mediacore.
//
// Each per-service backend additionally runs its own migration for tables
// it exclusively owns (e.g. ContentScanner's media_worker_jobs/
// media_analysis_tasks, CraftStudio's generated_media/downloaded_media,
// ProjectConfigurator's mount_paths) - those are NOT run here.
func (c *Core) Migrate(ctx context.Context) error {
for _, statement := range migrationStatements {
if _, err := c.db.Exec(ctx, statement); err != nil {
return err
}
}
return nil
}
var migrationStatements = []string{
`CREATE EXTENSION IF NOT EXISTS pgcrypto`,
`CREATE EXTENSION IF NOT EXISTS pg_trgm`,
`CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
username TEXT,
password_hash TEXT NOT NULL,
avatar_url TEXT,
bio TEXT,
role TEXT NOT NULL DEFAULT 'user',
permissions JSONB NOT NULL DEFAULT '{}'::jsonb,
disabled BOOLEAN NOT NULL DEFAULT FALSE,
totp_secret TEXT,
mfa_enabled BOOLEAN NOT NULL DEFAULT FALSE,
mfa_backup_codes JSONB,
password_reset_token TEXT,
password_reset_expires TIMESTAMPTZ,
last_login_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS users_username_unique ON users (LOWER(username)) WHERE username IS NOT NULL`,
`CREATE INDEX IF NOT EXISTS users_email_idx ON users (LOWER(email))`,
`CREATE TABLE IF NOT EXISTS media (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
media_key TEXT NOT NULL UNIQUE,
media_type TEXT NOT NULL DEFAULT 'unknown',
app TEXT,
source TEXT NOT NULL DEFAULT 'Filesystem',
title TEXT,
description TEXT,
category TEXT,
file_path TEXT,
original_filename TEXT,
active BOOLEAN NOT NULL DEFAULT TRUE,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
width INT,
height INT,
duration_ms BIGINT,
size_bytes BIGINT,
is_vr BOOLEAN NOT NULL DEFAULT FALSE,
has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
speed REAL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`,
`CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`,
`CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, '')))`,
`CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`,
`CREATE TABLE IF NOT EXISTS media_stats (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
stat_type TEXT NOT NULL,
app TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS media_stats_like_unique ON media_stats (user_id, media_key) WHERE stat_type = 'like' AND user_id IS NOT NULL`,
`CREATE INDEX IF NOT EXISTS media_stats_key_idx ON media_stats (media_key, stat_type)`,
`CREATE TABLE IF NOT EXISTS media_view_sessions (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
duration_ms BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE TABLE IF NOT EXISTS media_tags (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
tag TEXT NOT NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (media_key, tag, user_id)
)`,
`CREATE INDEX IF NOT EXISTS media_tags_tag_idx ON media_tags (LOWER(tag))`,
`CREATE INDEX IF NOT EXISTS media_tags_media_idx ON media_tags (media_key)`,
// AI-attributed tags are inserted with user_id NULL; a plain UNIQUE(media_key, tag, user_id)
// constraint does not dedupe NULLs against each other, so a dedicated partial index is
// required to make repeated analysis runs idempotent instead of piling up duplicate tag rows.
`CREATE UNIQUE INDEX IF NOT EXISTS media_tags_ai_tag_unique ON media_tags (media_key, tag) WHERE user_id IS NULL`,
`CREATE TABLE IF NOT EXISTS media_tag_votes (
id BIGSERIAL PRIMARY KEY,
media_key TEXT NOT NULL,
tag TEXT NOT NULL,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
vote SMALLINT NOT NULL CHECK (vote IN (-1, 1)),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (media_key, tag, user_id)
)`,
`CREATE TABLE IF NOT EXISTS playlists (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (user_id, name)
)`,
`CREATE TABLE IF NOT EXISTS playlist_items (
id BIGSERIAL PRIMARY KEY,
playlist_id BIGINT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
media_key TEXT NOT NULL,
position INT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (playlist_id, media_key)
)`,
`CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`INSERT INTO settings (key, value) VALUES ('auth_required', 'true') ON CONFLICT (key) DO NOTHING`,
`CREATE TABLE IF NOT EXISTS workflow_jobs (
id TEXT PRIMARY KEY,
service TEXT NOT NULL,
tool TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
progress INT NOT NULL DEFAULT 0,
request JSONB NOT NULL DEFAULT '{}'::jsonb,
result JSONB NOT NULL DEFAULT '{}'::jsonb,
error_message TEXT,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ
)`,
`CREATE INDEX IF NOT EXISTS workflow_jobs_service_idx ON workflow_jobs (service, created_at DESC)`,
`CREATE TABLE IF NOT EXISTS thumbnails (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
source_path TEXT UNIQUE,
width INT,
height INT,
file_size_bytes BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
}
+581
View File
@@ -0,0 +1,581 @@
// 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 ""
}