Fold MediaEngine (media-backend, media-webui) into this repo

Per owner decision: MediaEngine (the Media product family's Go backend
and SvelteKit frontend, previously its own repo referenced by 7 thin
service repos via git submodule) is folded directly into shared/ as
media-backend/ and media-webui/, rather than staying separate.

media-backend/go.mod's replace directive now points at ../backend (a
true sibling within this repo) instead of a vendored ../shared/backend
copy, since there's no more nested vendoring - it's the real thing.

Also moved MediaEngine's own CI (media-backend-lint.yml,
media-backend-tests.yml) and dev tooling scripts (scripts/media/*,
audit/lint/enforce scripts for the media-backend+media-webui content),
fixing their path assumptions for the new layout, and dropped
scripts/media/sync-shared.mjs (confirmed dead code, and now doubly
obsolete since there's no more vendored shared/ subfolder for it to
check). Added media:* script aliases to package.json for the moved
tooling, namespaced to avoid colliding with this repo's own scripts.

Also fixed sync-consumers.ps1's workspace-root resolution to walk up
until it finds a directory containing both Original/ and Forks/,
instead of assuming shared/ is always a direct child of the workspace
root - it broke when shared/ moved from Web/shared to Web/Central/shared
earlier in this same restructuring. Removed the now-obsolete
Original/MediaEngine entry from its consumer list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-08-31 22:06:29 +02:00
1 parent 79d9461769
commit acde180086
99 files changed
+20488 -1

No files matched your search

+956
View File
@@ -0,0 +1,956 @@
package auth
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
)
type User struct {
ID int64 `json:"id"`
Email string `json:"email"`
Username string `json:"username,omitempty"`
Role string `json:"role,omitempty"`
CanManageUsers bool `json:"canManageUsers"`
Bio string `json:"bio,omitempty"`
Avatar string `json:"avatarUrl,omitempty"`
MFAEnabled bool `json:"mfaEnabled"`
}
type storedUser struct {
User
PasswordHash string
Disabled bool
TOTPSecret string
}
type contextKey struct{}
var userContextKey contextKey
var (
ErrUnauthorized = errors.New("authentication required")
ErrForbidden = errors.New("administrator access required")
ErrInvalidLogin = errors.New("Invalid username or password.")
)
const loginRequiredSettingKey = "auth_required"
type Service struct {
db *pgxpool.Pool
cookieName string
secureCookies bool
sessionTTL time.Duration
resetManager *sharedauth.ResetManager
}
func New(db *pgxpool.Pool, cookieName string, secureCookies bool) *Service {
return &Service{
db: db,
cookieName: cookieName,
secureCookies: secureCookies,
sessionTTL: 7 * 24 * time.Hour,
resetManager: sharedauth.NewResetManager(),
}
}
func UserFromContext(ctx context.Context) *User {
value, _ := ctx.Value(userContextKey).(*User)
return value
}
func (s *Service) CurrentUser(r *http.Request) (*User, error) {
cookie, err := r.Cookie(s.cookieName)
if errors.Is(err, http.ErrNoCookie) || cookie.Value == "" {
return nil, nil
}
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
var user User
var disabled bool
err = s.db.QueryRow(ctx, `
SELECT u.id, u.email, COALESCE(u.username, ''), COALESCE(u.role, 'user'),
COALESCE(u.bio, ''), COALESCE(u.avatar_url, ''), u.disabled, COALESCE(u.mfa_enabled, false)
FROM go_sessions session
JOIN users u ON u.id = session.user_id
WHERE session.token_hash = $1 AND session.expires_at > NOW()
`, tokenHash(cookie.Value)).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &disabled, &user.MFAEnabled)
if errors.Is(err, pgx.ErrNoRows) || disabled {
return nil, nil
}
if err != nil {
return nil, err
}
user.CanManageUsers = sharedauth.CanManageUsers(user.Role)
return &user, nil
}
func (s *Service) Optional(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := s.CurrentUser(r)
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication lookup failed")
return
}
if user != nil {
r = r.WithContext(context.WithValue(r.Context(), userContextKey, user))
}
next.ServeHTTP(w, r)
})
}
func (s *Service) Require(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if UserFromContext(r.Context()) == nil {
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
next.ServeHTTP(w, r)
}))
}
// RequireIfLoginRequired protects actions when the application has login
// enabled, while allowing explicitly public installations to use actions that
// do not need a user identity.
func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if UserFromContext(r.Context()) != nil {
next.ServeHTTP(w, r)
return
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
next.ServeHTTP(w, r)
return
}
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
}))
}
func (s *Service) RequireAdmin(next http.Handler) http.Handler {
return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if !IsAdmin(user) {
writeError(w, http.StatusForbidden, ErrForbidden.Error())
return
}
next.ServeHTTP(w, r)
}))
}
// RequireAdminIfLoginRequired keeps administrative actions protected for
// authenticated users, while allowing explicitly public installations to use
// configuration endpoints that do not require a user identity.
func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
next.ServeHTTP(w, r)
return
}
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if !IsAdmin(user) {
writeError(w, http.StatusForbidden, ErrForbidden.Error())
return
}
next.ServeHTTP(w, r)
}))
}
func IsAdmin(user *User) bool {
if user == nil {
return false
}
switch strings.ToLower(strings.TrimSpace(user.Role)) {
case "admin", "superadmin", "moderator":
return true
default:
return false
}
}
func (s *Service) Me(w http.ResponseWriter, r *http.Request) {
user, err := s.CurrentUser(r)
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication lookup failed")
return
}
count, err := s.CountUsers(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"user": user,
"authRequired": loginRequired,
"setupRequired": count == 0,
})
}
func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
email := strings.ToLower(strings.TrimSpace(input.Email))
username := strings.TrimSpace(input.Username)
if !strings.Contains(email, "@") || len(email) > 254 {
writeError(w, http.StatusBadRequest, "a valid email is required")
return
}
if username == "" || len([]rune(username)) > 64 {
writeError(w, http.StatusBadRequest, "a username is required")
return
}
passwordHash := ""
if input.Password != "" {
if err := validatePassword(input.Password); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil {
writeError(w, http.StatusInternalServerError, "password could not be updated")
return
}
passwordHash = string(hash)
}
if _, err := s.db.Exec(r.Context(), `
UPDATE users
SET email = $1, username = $2, password_hash = COALESCE(NULLIF($3, ''), password_hash)
WHERE id = $4
`, email, username, passwordHash, user.ID); err != nil {
writeError(w, http.StatusBadRequest, "profile could not be updated")
return
}
updated, err := s.CurrentUser(r)
if err != nil || updated == nil {
writeError(w, http.StatusInternalServerError, "profile could not be loaded")
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": updated})
}
func (s *Service) RequireUserManager(next http.Handler) http.Handler {
return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if !sharedauth.CanManageUsers(user.Role) {
writeError(w, http.StatusForbidden, ErrForbidden.Error())
return
}
next.ServeHTTP(w, r)
}))
}
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
count, err := s.CountUsers(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": count == 0})
}
func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
var value string
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, loginRequiredSettingKey).Scan(&value)
if errors.Is(err, pgx.ErrNoRows) {
return true, nil
}
if err != nil {
return true, err
}
switch strings.ToLower(strings.TrimSpace(value)) {
case "false", "0", "no", "off":
return false, nil
default:
return true, nil
}
}
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "access settings unavailable")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": loginRequired})
}
func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
var input struct {
LoginRequired *bool `json:"loginRequired"`
}
if err := decodeJSON(r, &input); err != nil || input.LoginRequired == nil {
writeError(w, http.StatusBadRequest, "loginRequired must be a boolean")
return
}
if _, err := s.db.Exec(r.Context(), `
INSERT INTO settings (key, value, updated_at)
VALUES ($1, $2, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
`, loginRequiredSettingKey, strconv.FormatBool(*input.LoginRequired)); err != nil {
writeError(w, http.StatusInternalServerError, "access setting could not be saved")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired})
}
func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
count, err := s.CountUsers(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
user, _ := s.CurrentUser(r)
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"setupRequired": count == 0,
"authenticated": user != nil,
"authRequired": loginRequired,
"user": user,
})
}
type managedAccount struct {
ID int64
Email string
Username string
Role string
Disabled bool
CreatedAt time.Time
}
func (s *Service) managedAccount(ctx context.Context, id int64) (*managedAccount, error) {
var user managedAccount
err := s.db.QueryRow(ctx, `
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at
FROM users WHERE id = $1
`, id).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &user, nil
}
func managedAccountPayload(user *managedAccount) map[string]any {
return map[string]any{
"id": user.ID,
"username": user.Username,
"email": user.Email,
"role": string(sharedauth.NormalizeRole(user.Role)),
"createdAt": user.CreatedAt,
}
}
func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) {
rows, err := s.db.Query(r.Context(), `
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at
FROM users ORDER BY created_at, id
`)
if err != nil {
writeError(w, http.StatusInternalServerError, "users unavailable")
return
}
defer rows.Close()
users := make([]map[string]any, 0)
for rows.Next() {
var user managedAccount
if err := rows.Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt); err != nil {
writeError(w, http.StatusInternalServerError, "users unavailable")
return
}
users = append(users, managedAccountPayload(&user))
}
if err := rows.Err(); err != nil {
writeError(w, http.StatusInternalServerError, "users unavailable")
return
}
writeJSON(w, http.StatusOK, users)
}
func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) {
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
Role string `json:"role"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
actor := UserFromContext(r.Context())
role := sharedauth.NormalizeRole(input.Role)
if role == sharedauth.RoleSuperAdmin {
writeError(w, http.StatusBadRequest, "a new user cannot be a superadmin")
return
}
if actor == nil || sharedauth.NormalizeRole(actor.Role) != sharedauth.RoleSuperAdmin {
role = sharedauth.RoleUser
}
user, err := s.CreateUser(r.Context(), input.Email, input.Username, input.Password, string(role))
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
created, err := s.managedAccount(r.Context(), user.ID)
if err != nil || created == nil {
writeError(w, http.StatusInternalServerError, "user could not be loaded")
return
}
writeJSON(w, http.StatusCreated, managedAccountPayload(created))
}
func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid user id")
return
}
target, err := s.managedAccount(r.Context(), id)
if err != nil {
writeError(w, http.StatusInternalServerError, "user could not be loaded")
return
}
if target == nil {
writeError(w, http.StatusNotFound, "user not found")
return
}
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
Role *string `json:"role"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
actor := UserFromContext(r.Context())
targetRole := sharedauth.NormalizeRole(target.Role)
role := targetRole
if targetRole != sharedauth.RoleSuperAdmin && actor != nil && sharedauth.NormalizeRole(actor.Role) == sharedauth.RoleSuperAdmin && input.Role != nil {
requested := sharedauth.NormalizeRole(*input.Role)
if requested == sharedauth.RoleSuperAdmin {
writeError(w, http.StatusBadRequest, "the superadmin role is protected")
return
}
role = requested
}
if err := s.UpdateUser(r.Context(), id, input.Email, input.Username, string(role), nil); err != nil {
writeError(w, http.StatusBadRequest, "user could not be updated")
return
}
if strings.TrimSpace(input.Password) != "" {
if err := s.SetPassword(r.Context(), id, input.Password); err != nil {
writeError(w, http.StatusBadRequest, "password could not be updated")
return
}
}
updated, err := s.managedAccount(r.Context(), id)
if err != nil || updated == nil {
writeError(w, http.StatusInternalServerError, "user could not be loaded")
return
}
writeJSON(w, http.StatusOK, managedAccountPayload(updated))
}
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid user id")
return
}
target, err := s.managedAccount(r.Context(), id)
if err != nil {
writeError(w, http.StatusInternalServerError, "user could not be loaded")
return
}
if target == nil {
writeError(w, http.StatusNotFound, "user not found")
return
}
actor := UserFromContext(r.Context())
if actor == nil || actor.ID == target.ID || sharedauth.NormalizeRole(target.Role) == sharedauth.RoleSuperAdmin {
writeError(w, http.StatusForbidden, "the current or first account cannot be removed")
return
}
if err := s.DeleteUser(r.Context(), id); err != nil {
writeError(w, http.StatusNotFound, "user not found")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
email, username, password, err := normalizeCredentials(input.Email, input.Username, input.Password)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if username == "" {
writeError(w, http.StatusBadRequest, "a username is required")
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not secure password")
return
}
var user User
err = s.db.QueryRow(r.Context(), `
INSERT INTO users (email, username, password_hash, role)
SELECT $1, $2, $3, 'superadmin'
WHERE NOT EXISTS (SELECT 1 FROM users)
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'superadmin')
`, email, username, string(hash)).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusConflict, "Setup has already been completed.")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create account")
return
}
user.CanManageUsers = sharedauth.CanManageUsers(user.Role)
if err := s.startSession(w, r.Context(), user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "could not start session")
return
}
writeJSON(w, http.StatusCreated, map[string]any{"user": user})
}
func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
var input struct {
Identifier string `json:"identifier"`
Email string `json:"email"`
Password string `json:"password"`
TOTPToken string `json:"totpToken"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
identifier := strings.TrimSpace(input.Identifier)
if identifier == "" {
identifier = strings.TrimSpace(input.Email)
}
var user storedUser
err := s.db.QueryRow(r.Context(), `
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), COALESCE(bio, ''),
COALESCE(avatar_url, ''), password_hash, disabled, COALESCE(mfa_enabled, false), COALESCE(totp_secret, '')
FROM users WHERE LOWER(email) = LOWER($1) OR LOWER(COALESCE(username, '')) = LOWER($1)
LIMIT 1
`, identifier).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &user.PasswordHash, &user.Disabled, &user.MFAEnabled, &user.TOTPSecret)
if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "could not authenticate")
return
}
user.User.CanManageUsers = sharedauth.CanManageUsers(user.Role)
if user.Disabled || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(input.Password)) != nil {
writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
return
}
if user.MFAEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, strings.TrimSpace(input.TOTPToken), time.Now()) {
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Two-factor authentication code required.", "mfaRequired": true})
return
}
_, _ = s.db.Exec(r.Context(), `UPDATE users SET last_login_at = NOW() WHERE id = $1`, user.ID)
if err := s.startSession(w, r.Context(), user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "could not start session")
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": user.User})
}
func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"enabled": user.MFAEnabled, "mfaEnabled": user.MFAEnabled})
}
func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if user.MFAEnabled {
writeError(w, http.StatusConflict, "multi-factor authentication is already enabled")
return
}
secret, err := sharedauth.GenerateTOTPSecret()
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create authenticator secret")
return
}
if _, err := s.db.Exec(r.Context(), `UPDATE users SET totp_secret = $1, mfa_enabled = false WHERE id = $2`, secret, user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "could not save authenticator secret")
return
}
account := user.Username
if account == "" {
account = user.Email
}
uri := sharedauth.TOTPProvisioningURI("MediaCollection", account, secret)
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"secret": secret, "otpauth": uri, "otpauthUrl": uri, "enabled": false}})
}
func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
var input struct {
Token string `json:"token"`
TOTPToken string `json:"totpToken"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
var secret string
if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, '') FROM users WHERE id = $1`, user.ID).Scan(&secret); err != nil {
writeError(w, http.StatusInternalServerError, "could not load authenticator secret")
return
}
token := strings.TrimSpace(input.TOTPToken)
if token == "" {
token = strings.TrimSpace(input.Token)
}
if !sharedauth.VerifyTOTP(secret, token, time.Now()) {
writeError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return
}
if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = true WHERE id = $1 AND totp_secret <> ''`, user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "could not enable multi-factor authentication")
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": true, "enabled": true, "backupCodes": []string{}}})
}
func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
var input struct {
Token string `json:"token"`
TOTPToken string `json:"totpToken"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
var secret string
var enabled bool
if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, ''), COALESCE(mfa_enabled, false) FROM users WHERE id = $1`, user.ID).Scan(&secret, &enabled); err != nil {
writeError(w, http.StatusInternalServerError, "could not load authenticator state")
return
}
token := strings.TrimSpace(input.TOTPToken)
if token == "" {
token = strings.TrimSpace(input.Token)
}
if !enabled || !sharedauth.VerifyTOTP(secret, token, time.Now()) {
writeError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return
}
if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = false, totp_secret = NULL WHERE id = $1`, user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "could not disable multi-factor authentication")
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}})
}
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie(s.cookieName); err == nil && cookie.Value != "" {
_, _ = s.db.Exec(r.Context(), `DELETE FROM go_sessions WHERE token_hash = $1`, tokenHash(cookie.Value))
}
http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: "", Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1})
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Service) RequestAdminReset(w http.ResponseWriter, _ *http.Request) {
if _, err := s.resetManager.Request(); err != nil {
writeError(w, http.StatusInternalServerError, "could not create reset code")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Service) ConfirmAdminReset(w http.ResponseWriter, r *http.Request) {
var input struct {
Code string `json:"code"`
}
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
if !s.resetManager.Confirm(input.Code) {
writeError(w, http.StatusUnauthorized, "Invalid or expired reset code.")
return
}
if _, err := s.db.Exec(r.Context(), `DELETE FROM users`); err != nil {
writeError(w, http.StatusInternalServerError, "could not reset administrator accounts")
return
}
http.SetCookie(w, &http.Cookie{
Name: s.cookieName,
Value: "",
Path: "/",
HttpOnly: true,
Secure: s.secureCookies,
SameSite: http.SameSiteLaxMode,
MaxAge: -1,
})
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Service) CountUsers(ctx context.Context) (int64, error) {
var count int64
err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users`).Scan(&count)
return count, err
}
func (s *Service) CreateUser(ctx context.Context, email, username, password, role string) (*User, error) {
email, username, password, err := normalizeCredentials(email, username, password)
if err != nil {
return nil, err
}
role = normalizeRole(role)
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
var user User
err = s.db.QueryRow(ctx, `
INSERT INTO users (email, username, password_hash, role)
VALUES ($1, $2, $3, $4)
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user')
`, email, username, string(hash), role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
if err != nil {
return nil, err
}
return &user, nil
}
func (s *Service) ListUsers(ctx context.Context, search string, limit, offset int) ([]map[string]any, int64, error) {
search = strings.TrimSpace(search)
if limit <= 0 || limit > 200 {
limit = 50
}
if offset < 0 {
offset = 0
}
pattern := "%" + search + "%"
rows, err := s.db.Query(ctx, `
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at, last_login_at
FROM users
WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)
ORDER BY id DESC LIMIT $3 OFFSET $4
`, search, pattern, limit, offset)
if err != nil {
return nil, 0, err
}
defer rows.Close()
users := make([]map[string]any, 0)
for rows.Next() {
var id int64
var email, username, role string
var disabled bool
var created time.Time
var lastLogin *time.Time
if err := rows.Scan(&id, &email, &username, &role, &disabled, &created, &lastLogin); err != nil {
return nil, 0, err
}
users = append(users, map[string]any{"id": id, "email": email, "username": username, "role": role, "disabled": disabled, "createdAt": created, "lastLoginAt": lastLogin})
}
var total int64
err = s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)`, search, pattern).Scan(&total)
return users, total, err
}
func (s *Service) DeleteUser(ctx context.Context, id int64) error {
_, err := s.db.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
return err
}
func (s *Service) UpdateUser(ctx context.Context, id int64, email, username, role string, disabled *bool) error {
role = strings.ToLower(strings.TrimSpace(role))
if role != "" {
role = normalizeRole(role)
}
_, err := s.db.Exec(ctx, `
UPDATE users SET email = COALESCE(NULLIF($2, ''), email), username = COALESCE(NULLIF($3, ''), username),
role = COALESCE(NULLIF($4, ''), role), disabled = COALESCE($5, disabled) WHERE id = $1
`, id, strings.TrimSpace(email), strings.TrimSpace(username), role, disabled)
return err
}
func (s *Service) SetPassword(ctx context.Context, id int64, password string) error {
if err := validatePassword(password); err != nil {
return err
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, string(hash))
return err
}
func validatePassword(password string) error {
if len([]rune(password)) < 8 || len([]rune(password)) > 1024 {
return fmt.Errorf("Password must be at least 8 characters.")
}
return nil
}
func (s *Service) startSession(w http.ResponseWriter, ctx context.Context, userID int64) error {
token, err := randomToken()
if err != nil {
return err
}
expires := time.Now().Add(s.sessionTTL)
if _, err := s.db.Exec(ctx, `INSERT INTO go_sessions (token_hash, user_id, expires_at) VALUES ($1, $2, $3)`, tokenHash(token), userID, expires); err != nil {
return err
}
_, _ = s.db.Exec(ctx, `DELETE FROM go_sessions WHERE expires_at <= NOW()`)
http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: token, Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, Expires: expires, MaxAge: int(s.sessionTTL.Seconds())})
return nil
}
func normalizeCredentials(email, username, password string) (string, string, string, error) {
email = strings.ToLower(strings.TrimSpace(email))
username = strings.TrimSpace(username)
if !strings.Contains(email, "@") || len(email) > 254 {
return "", "", "", fmt.Errorf("a valid email is required")
}
if len([]rune(username)) > 64 {
return "", "", "", fmt.Errorf("username is too long")
}
if len([]rune(password)) < 8 || len([]rune(password)) > 1024 {
return "", "", "", fmt.Errorf("Password must be at least 8 characters.")
}
return email, username, password, nil
}
func normalizeRole(role string) string {
switch strings.ToLower(strings.TrimSpace(role)) {
case "admin", "superadmin", "moderator":
return strings.ToLower(strings.TrimSpace(role))
default:
return "user"
}
}
func randomToken() (string, error) {
data := make([]byte, 32)
if _, err := rand.Read(data); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(data), nil
}
func tokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func decodeJSON(r *http.Request, target any) error {
defer r.Body.Close()
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
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})
}
func (u User) String() string { return strconv.FormatInt(u.ID, 10) }
+28
View File
@@ -0,0 +1,28 @@
package auth
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")
}
}
+237
View File
@@ -0,0 +1,237 @@
package config
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
type Service string
const (
Viewer Service = "viewer"
Tools Service = "tools"
Analyzer Service = "analyzer"
ConfigService Service = "config"
Moderator Service = "moderator"
Kiosk Service = "kiosk"
Servant Service = "servant"
Desktop Service = "desktop"
)
type Config struct {
Port string
DatabaseURL string
Service Service
ServiceName string
WebRoot string
MediaRoots []string
InputRoot string
CopyRoot string
WorkflowsRoot string
ThumbnailRoot string
OutputRoot string
DownloadsRoot string
ModelsRoot string
AllowedOrigin string
PublicURL string
SessionCookie string
SecureCookies bool
InternalServiceSecret string
FFmpeg string
FFprobe string
YTDLP string
ComfyURL string
AnalyzerModelsURL string
ServantURL string
MaxUploadBytes int64
TLSCertFile string
TLSKeyFile string
}
func Load() (*Config, error) {
service := normalizeService(os.Getenv("MEDIA_SERVICE"))
if service == "" {
service = normalizeService(os.Getenv("SERVICE"))
}
if service == "" {
service = Viewer
}
name := serviceName(service)
port := envOr("PORT", defaultPort(service))
root := envOr("MEDIA_ROOT", envOr("MEDIA_PATH", "./media"))
roots := splitPaths(os.Getenv("MEDIA_ROOTS"))
if len(roots) == 0 {
roots = []string{root}
}
for i := range roots {
roots[i] = filepath.Clean(roots[i])
}
maxUpload, err := parseBytes(envOr("MAX_UPLOAD_BYTES", "53687091200"))
if err != nil {
return nil, fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
}
cfg := &Config{
Port: port,
DatabaseURL: strings.TrimSpace(os.Getenv("DATABASE_URL")),
Service: service,
ServiceName: name,
WebRoot: resolveWebRoot(service),
MediaRoots: roots,
InputRoot: filepath.Clean(envOr("INPUT_DIR", "./input")),
CopyRoot: filepath.Clean(envOr("UPLOAD_COPY_DIR", "./copy")),
WorkflowsRoot: filepath.Clean(envOr("WORKFLOWS_DIR", filepath.Join("..", "Forge", "public", "workflows"))),
ThumbnailRoot: filepath.Clean(envOr("THUMBNAIL_DIR", "./thumbnails")),
OutputRoot: filepath.Clean(envOr("OUTPUT_DIR", "./output")),
DownloadsRoot: filepath.Clean(envOr("DOWNLOADS_DIR", "./downloads")),
ModelsRoot: filepath.Clean(envOr("MODEL_CACHE_DIR", "./models")),
AllowedOrigin: envOr("CORS_ORIGIN", "http://localhost:5173"),
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"),
SessionCookie: envOr("SESSION_COOKIE", "mediacollection_session"),
SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""),
InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")),
FFmpeg: envOr("FFMPEG_PATH", "ffmpeg"),
FFprobe: envOr("FFPROBE_PATH", "ffprobe"),
YTDLP: envOr("YT_DLP_PATH", "yt-dlp"),
ComfyURL: strings.TrimRight(envOr("COMFYUI_URL", "http://127.0.0.1:8188"), "/"),
AnalyzerModelsURL: strings.TrimRight(envOr("ANALYZER_MODELS_URL", "http://127.0.0.1:8801"), "/"),
ServantURL: strings.TrimRight(envOr("SERVANT_URL", "http://127.0.0.1:3003"), "/"),
MaxUploadBytes: maxUpload,
TLSCertFile: strings.TrimSpace(os.Getenv("TLS_CERT_FILE")),
TLSKeyFile: strings.TrimSpace(os.Getenv("TLS_KEY_FILE")),
}
if cfg.DatabaseURL == "" {
return nil, fmt.Errorf("DATABASE_URL is required")
}
if (cfg.TLSCertFile == "") != (cfg.TLSKeyFile == "") {
return nil, fmt.Errorf("TLS_CERT_FILE and TLS_KEY_FILE must be set together")
}
return cfg, nil
}
func normalizeService(value string) Service {
switch strings.ToLower(strings.TrimSpace(value)) {
case "viewer", "mediaviewer":
return Viewer
case "tools", "mediatools":
return Tools
case "analyzer", "mediaanalyzer":
return Analyzer
case "config", "mediaconfig":
return ConfigService
case "moderator", "mediamoderator":
return Moderator
case "kiosk", "mediakiosk":
return Kiosk
case "servant", "mediaservant":
return Servant
case "desktop", "mediadesktop":
return Desktop
default:
return ""
}
}
func serviceName(service Service) string {
switch service {
case Viewer:
return "MediaViewer"
case Tools:
return "MediaTools"
case Analyzer:
return "MediaAnalyzer"
case ConfigService:
return "MediaConfig"
case Moderator:
return "MediaModerator"
case Kiosk:
return "MediaKiosk"
case Servant:
return "MediaServant"
case Desktop:
return "MediaDesktop"
default:
return "MediaCollection"
}
}
func defaultPort(service Service) string {
switch service {
case ConfigService:
return "3005"
case Moderator:
return "8090"
case Servant:
return "3003"
default:
return "3000"
}
}
func resolveWebRoot(_ Service) string {
if value := strings.TrimSpace(os.Getenv("WEB_ROOT")); value != "" {
return filepath.Clean(value)
}
return filepath.Join("..", "WebUI", "build")
}
func splitPaths(value string) []string {
parts := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ';' })
result := make([]string, 0, len(parts))
for _, part := range parts {
if trimmed := strings.TrimSpace(part); trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
func parseBytes(value string) (int64, error) {
value = strings.TrimSpace(strings.ToLower(value))
if value == "" {
return 0, nil
}
multiplier := int64(1)
suffixes := []struct {
suffix string
factor int64
}{
{"gb", 1 << 30},
{"mb", 1 << 20},
{"kb", 1 << 10},
{"b", 1},
}
for _, s := range suffixes {
if strings.HasSuffix(value, s.suffix) {
value = strings.TrimSpace(strings.TrimSuffix(value, s.suffix))
multiplier = s.factor
break
}
}
n, err := strconv.ParseInt(value, 10, 64)
if err != nil || n < 0 {
return 0, fmt.Errorf("must be a non-negative byte count")
}
return n * multiplier, nil
}
func envOr(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envBool(key string, fallback bool) bool {
value := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
if value == "" {
return fallback
}
return value == "1" || value == "true" || value == "yes" || value == "on"
}
@@ -0,0 +1,43 @@
package config
import (
"testing"
)
func TestLoadDefaultsAndServiceSelection(t *testing.T) {
t.Setenv("DATABASE_URL", "postgres://media:media@localhost/mediadb")
t.Setenv("MEDIA_SERVICE", "MediaKiosk")
t.Setenv("SERVICE", "viewer")
t.Setenv("MEDIA_ROOTS", `./media;./other-media`)
t.Setenv("MAX_UPLOAD_BYTES", "2mb")
t.Setenv("WEB_ROOT", "./webui")
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if cfg.Service != Kiosk {
t.Fatalf("service = %q, want %q", cfg.Service, Kiosk)
}
if len(cfg.MediaRoots) != 2 {
t.Fatalf("media roots = %#v, want two roots", cfg.MediaRoots)
}
if cfg.MaxUploadBytes != 2*1024*1024 {
t.Fatalf("max upload bytes = %d", cfg.MaxUploadBytes)
}
}
func TestLoadRequiresDatabase(t *testing.T) {
t.Setenv("DATABASE_URL", "")
if _, err := Load(); err == nil {
t.Fatal("Load() succeeded without DATABASE_URL")
}
}
func TestParseBytesRejectsInvalidValues(t *testing.T) {
for _, value := range []string{"-1", "nope", "1tb"} {
if _, err := parseBytes(value); err == nil {
t.Errorf("parseBytes(%q) succeeded", value)
}
}
}
@@ -0,0 +1,55 @@
package database
import (
"context"
"embed"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed migrations/001_initial.sql
var migrations embed.FS
func Open(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
return nil, fmt.Errorf("parse database URL: %w", err)
}
cfg.MaxConns = 20
cfg.MinConns = 1
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return pool, nil
}
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
data, err := migrations.ReadFile("migrations/001_initial.sql")
if err != nil {
return fmt.Errorf("read migration: %w", err)
}
lockCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
conn, err := pool.Acquire(lockCtx)
if err != nil {
return fmt.Errorf("acquire migration connection: %w", err)
}
defer conn.Release()
if _, err := conn.Exec(lockCtx, `SELECT pg_advisory_lock(42424242)`); err != nil {
return fmt.Errorf("acquire migration lock: %w", err)
}
defer func() { _, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(42424242)`) }()
if _, err := conn.Exec(lockCtx, string(data)); err != nil {
return fmt.Errorf("run migration: %w", err)
}
return nil
}
@@ -0,0 +1,321 @@
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()
);
ALTER TABLE users ADD COLUMN IF NOT EXISTS username TEXT;
ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
UPDATE users SET role = 'superadmin'
WHERE id = (SELECT id FROM users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM users WHERE role = 'superadmin');
ALTER TABLE users ADD COLUMN IF NOT EXISTS permissions JSONB NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE users ADD COLUMN IF NOT EXISTS disabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
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 go_sessions (
token_hash TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS go_sessions_expiry_idx ON go_sessions (expires_at);
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()
);
ALTER TABLE media ADD COLUMN IF NOT EXISTS file_path TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS source TEXT NOT NULL DEFAULT 'Filesystem';
ALTER TABLE media ADD COLUMN IF NOT EXISTS title TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS description TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS category TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS original_filename TEXT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS active BOOLEAN NOT NULL DEFAULT TRUE;
ALTER TABLE media ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE media ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
ALTER TABLE media ADD COLUMN IF NOT EXISTS media_type TEXT NOT NULL DEFAULT 'unknown';
ALTER TABLE media ADD COLUMN IF NOT EXISTS width INT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS height INT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS duration_ms BIGINT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS size_bytes BIGINT;
ALTER TABLE media ADD COLUMN IF NOT EXISTS is_vr BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE media ADD COLUMN IF NOT EXISTS has_funscript BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE media ADD COLUMN IF NOT EXISTS speed REAL;
ALTER TABLE media ADD COLUMN IF NOT EXISTS 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 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()
);
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS media_id BIGINT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS media_key TEXT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS user_id BIGINT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS stat_type TEXT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS app TEXT;
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS 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_metrics (
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,
elapsed_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);
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 media_worker_jobs (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
media_key TEXT,
file_path TEXT NOT NULL,
file_name TEXT NOT NULL DEFAULT '',
media_type TEXT NOT NULL DEFAULT 'unknown',
status TEXT NOT NULL DEFAULT 'queued',
progress INT NOT NULL DEFAULT 0,
queued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
duration_ms INT,
error_message TEXT,
extracted_data JSONB,
file_size_bytes BIGINT,
scan_batch_id TEXT,
tags TEXT[],
title TEXT,
description TEXT,
has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
is_vr BOOLEAN NOT NULL DEFAULT FALSE,
vr_fov INT,
vr_stereo TEXT,
data_outcome TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS media_worker_jobs_status_idx ON media_worker_jobs (status, queued_at DESC);
CREATE UNIQUE INDEX IF NOT EXISTS media_worker_jobs_file_path_unique ON media_worker_jobs (file_path);
CREATE TABLE IF NOT EXISTS generated_media (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
workflow TEXT,
prompt TEXT,
parameters JSONB,
output_filename TEXT,
output_path TEXT,
elapsed_ms INT,
status TEXT NOT NULL DEFAULT 'completed',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS downloaded_media (
id BIGSERIAL PRIMARY KEY,
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
job_id BIGINT,
source_url TEXT NOT NULL,
tool TEXT,
file_path TEXT,
file_name TEXT,
file_size_bytes BIGINT,
status TEXT NOT NULL DEFAULT 'completed',
error_message TEXT,
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
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 workflow_schedules (
id TEXT PRIMARY KEY,
service TEXT NOT NULL,
tool TEXT NOT NULL,
name TEXT NOT NULL,
interval_minutes INT NOT NULL DEFAULT 60,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
settings JSONB NOT NULL DEFAULT '{}'::jsonb,
last_run_at TIMESTAMPTZ,
last_status TEXT,
next_run_at TIMESTAMPTZ,
user_id BIGINT REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
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()
);
CREATE TABLE IF NOT EXISTS mount_paths (
project TEXT NOT NULL,
function_name TEXT NOT NULL,
path TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (project, function_name)
);
-- Per-step status tracking for metadata extraction and thumbnail generation, independent of the
-- legacy `status`/`error_message` columns above (which track the overall discovery row).
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS metadata_status TEXT NOT NULL DEFAULT 'queued';
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS metadata_error TEXT;
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS thumbnail_status TEXT NOT NULL DEFAULT 'queued';
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS thumbnail_error TEXT;
CREATE INDEX IF NOT EXISTS media_worker_jobs_metadata_status_idx ON media_worker_jobs (media_type, metadata_status);
CREATE INDEX IF NOT EXISTS media_worker_jobs_thumbnail_status_idx ON media_worker_jobs (media_type, thumbnail_status);
-- One row per (file, AI task) since a single image can have up to six independently toggleable
-- AI tasks (tags/title/description/age/gender/nsfw), which doesn't fit the one-row-per-file shape
-- of media_worker_jobs.
CREATE TABLE IF NOT EXISTS media_analysis_tasks (
id BIGSERIAL PRIMARY KEY,
media_key TEXT NOT NULL,
media_type TEXT NOT NULL,
task TEXT NOT NULL,
model TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
result JSONB,
error_message TEXT,
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (media_key, task)
);
CREATE INDEX IF NOT EXISTS media_analysis_tasks_status_idx ON media_analysis_tasks (media_type, status);
-- 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;
-- Speeds up the Lookout dashboard/pipelines/history/live-status queries: analyzerStats and
-- analyzerPipelineBreakdown group active media by type (and join it against thumbnails), and
-- analyzerHistory sorts media_worker_jobs by queued_at with no status filter, none of which the
-- existing media/media_worker_jobs indexes above actually cover.
CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type);
CREATE INDEX IF NOT EXISTS media_worker_jobs_queued_at_idx ON media_worker_jobs (queued_at DESC);
CREATE INDEX IF NOT EXISTS media_worker_jobs_media_type_status_idx ON media_worker_jobs (media_type, status);
CREATE INDEX IF NOT EXISTS media_worker_jobs_funscript_status_idx ON media_worker_jobs (status) WHERE has_funscript = TRUE;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,710 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// analysisState tracks the currently-running AI analysis pass, mirroring thumbnailGenerationState.
type analysisState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// analyzerTasksByMediaType mirrors WebUI/src/lib/features/MediaTypePipeline.svelte's stagesForType -
// the set of AI tasks that exist for each media type.
var analyzerTasksByMediaType = map[string][]string{
"image": {"tags", "title", "description", "age", "gender", "nsfw"},
"video": {"tags"},
"audio": {"tags"},
"funscript": {},
}
func (s *Server) analyzerAnalyzeStatus(w http.ResponseWriter, r *http.Request) {
s.analysisMu.Lock()
state := s.analysis
s.analysisMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"status": map[string]any{
"running": state.Running,
"state": firstNonEmpty(state.State, "idle"),
"total": state.Total,
"completed": state.Completed,
"failed": state.Failed,
"current": state.Current,
"startedAt": state.StartedAt,
"finishedAt": state.FinishedAt,
"lastError": state.LastError,
},
})
}
func (s *Server) analyzerAnalyzeStart(w http.ResponseWriter, r *http.Request) {
selected := parseMediaTypesPayload(r, false)
s.analysisMu.Lock()
if s.analysis.Running {
s.analysisMu.Unlock()
writeError(w, http.StatusConflict, "AI analysis is already running")
return
}
ctx, cancel := context.WithCancel(context.Background())
now := time.Now().UTC()
s.analysis = analysisState{Running: true, State: "running", StartedAt: &now}
s.analysisCancel = cancel
s.analysisMu.Unlock()
go s.runAiAnalysis(ctx, mediaTypesList(selected))
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "running"})
}
func (s *Server) analyzerAnalyzeStop(w http.ResponseWriter, r *http.Request) {
s.analysisMu.Lock()
cancel := s.analysisCancel
running := s.analysis.Running
s.analysisMu.Unlock()
if !running || cancel == nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"})
return
}
log.Printf("analyzer: AI analysis stop requested")
cancel()
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"})
}
// runAiAnalysis queues any AI task that isn't already completed under the currently-configured
// model, then works through everything queued. mediaTypeFilters scopes both stages to a subset of
// media types (empty means every type) - used both by the dashboard's media-type selector and by
// the per-media-type retry-errors action (which passes a single-element list) so a scoped run
// never kicks off a full-library pass.
func (s *Server) runAiAnalysis(ctx context.Context, mediaTypeFilters []string) {
if err := s.syncAnalysisTasks(ctx, mediaTypeFilters); err != nil && ctx.Err() == nil {
log.Printf("analyzer: AI analysis: failed to sync tasks: %v", err)
s.finishAnalysis(err)
return
}
s.processAnalysisTasks(ctx, mediaTypeFilters)
}
type modelStageConfig struct {
Primary string
Enabled bool
}
// parseModelStageConfig mirrors MediaTypePipeline.svelte's own leniency: older saves stored the
// model as a bare string rather than {primary, fallback, enabled}.
func parseModelStageConfig(raw json.RawMessage) modelStageConfig {
var asString string
if json.Unmarshal(raw, &asString) == nil {
if asString == "" || asString == "disabled" {
return modelStageConfig{}
}
return modelStageConfig{Primary: asString, Enabled: true}
}
var asObject struct {
Primary string `json:"primary"`
Enabled bool `json:"enabled"`
}
if json.Unmarshal(raw, &asObject) == nil {
return modelStageConfig{Primary: asObject.Primary, Enabled: asObject.Enabled}
}
return modelStageConfig{}
}
// enabledAnalysisTasks reads the analyzer_model_config setting (the same one the model-config
// endpoints already read/write) and returns, per media type, the task->model pairs the user has
// actually turned on.
func (s *Server) enabledAnalysisTasks(ctx context.Context, mediaTypeFilters []string) map[string]map[string]string {
value := s.settingValue(ctx, "analyzer_model_config", "{}")
var wrapper struct {
Config map[string]map[string]json.RawMessage `json:"config"`
}
if json.Unmarshal([]byte(value), &wrapper) != nil {
return nil
}
filterSet := make(map[string]bool, len(mediaTypeFilters))
for _, mediaType := range mediaTypeFilters {
filterSet[mediaType] = true
}
result := make(map[string]map[string]string)
for mediaType, tasks := range analyzerTasksByMediaType {
if len(filterSet) > 0 && !filterSet[mediaType] {
continue
}
section, ok := wrapper.Config[mediaType]
if !ok {
continue
}
enabled := make(map[string]string)
for _, task := range tasks {
raw, ok := section[task]
if !ok {
continue
}
stage := parseModelStageConfig(raw)
if stage.Enabled && stage.Primary != "" && stage.Primary != "disabled" {
enabled[task] = stage.Primary
}
}
if len(enabled) > 0 {
result[mediaType] = enabled
}
}
return result
}
// syncAnalysisTasks upserts one media_analysis_tasks row per (active media file, enabled task).
// A file whose task previously errored, or whose configured model has since changed, is put back
// on the queue - mirroring how thumbnails/metadata already retry automatically on every run
// rather than requiring the dedicated retry-errors action.
func (s *Server) syncAnalysisTasks(ctx context.Context, mediaTypeFilters []string) error {
tasksByType := s.enabledAnalysisTasks(ctx, mediaTypeFilters)
if len(tasksByType) == 0 {
return nil
}
query := `SELECT media_key, LOWER(COALESCE(media_type, '')) FROM media WHERE active = TRUE`
args := []any{}
if len(mediaTypeFilters) > 0 {
query += ` AND LOWER(COALESCE(media_type, '')) = ANY($1)`
args = append(args, mediaTypeFilters)
}
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
return err
}
type mediaItem struct{ key, mediaType string }
items := make([]mediaItem, 0)
for rows.Next() {
var item mediaItem
if rows.Scan(&item.key, &item.mediaType) == nil {
items = append(items, item)
}
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, item := range items {
tasks, ok := tasksByType[item.mediaType]
if !ok {
continue
}
for task, model := range tasks {
if ctx.Err() != nil {
return nil
}
_, _ = s.db.Exec(ctx, `
INSERT INTO media_analysis_tasks (media_key, media_type, task, model, status)
VALUES ($1,$2,$3,$4,'queued')
ON CONFLICT (media_key, task) DO UPDATE SET
model = EXCLUDED.model,
status = 'queued',
error_message = NULL,
updated_at = NOW()
WHERE media_analysis_tasks.status = 'error'
OR (media_analysis_tasks.status = 'completed' AND media_analysis_tasks.model <> EXCLUDED.model)`,
item.key, item.mediaType, task, model)
}
}
return nil
}
type pendingAnalysisTask struct {
id int64
mediaKey, mediaType string
task, model, filePath string
}
func (s *Server) processAnalysisTasks(ctx context.Context, mediaTypeFilters []string) {
query := `
SELECT t.id, t.media_key, t.media_type, t.task, t.model, COALESCE(NULLIF(m.file_path, ''), m.media_key)
FROM media_analysis_tasks t
JOIN media m ON m.media_key = t.media_key
WHERE t.status = 'queued' AND m.active = TRUE`
args := []any{}
if len(mediaTypeFilters) > 0 {
query += ` AND t.media_type = ANY($1)`
args = append(args, mediaTypeFilters)
}
query += ` ORDER BY t.id ASC`
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
if ctx.Err() != nil {
s.finishAnalysis(nil)
} else {
log.Printf("analyzer: AI analysis: failed to load queued tasks: %v", err)
s.finishAnalysis(err)
}
return
}
items := make([]pendingAnalysisTask, 0)
for rows.Next() {
var item pendingAnalysisTask
if rows.Scan(&item.id, &item.mediaKey, &item.mediaType, &item.task, &item.model, &item.filePath) == nil {
items = append(items, item)
}
}
rows.Close()
log.Printf("analyzer: AI analysis started: %d tasks queued", len(items))
s.analysisMu.Lock()
s.analysis.Total = len(items)
s.analysisMu.Unlock()
for _, item := range items {
if ctx.Err() != nil {
s.finishAnalysis(nil)
return
}
s.analysisMu.Lock()
s.analysis.Current = item.filePath
s.analysis.CurrentType = item.mediaType
s.analysisMu.Unlock()
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='processing', started_at=NOW() WHERE id=$1`, item.id)
result, runErr := s.runAnalysisTask(ctx, item)
s.analysisMu.Lock()
if runErr != nil {
s.analysis.Failed++
s.analysis.LastError = runErr.Error()
} else {
s.analysis.Completed++
}
s.analysisMu.Unlock()
if runErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='error', error_message=$2, finished_at=NOW() WHERE id=$1`, item.id, runErr.Error())
continue
}
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='completed', error_message=NULL, result=$2, finished_at=NOW() WHERE id=$1`, item.id, mustJSON(result))
s.applyAnalysisResult(ctx, item.mediaKey, result)
}
s.finishAnalysis(nil)
}
func (s *Server) finishAnalysis(runErr error) {
now := time.Now().UTC()
s.analysisMu.Lock()
defer s.analysisMu.Unlock()
s.analysis.Running = false
s.analysisCancel = nil
s.analysis.Current = ""
s.analysis.CurrentType = ""
s.analysis.FinishedAt = &now
if runErr != nil {
s.analysis.State = "error"
s.analysis.LastError = runErr.Error()
} else if s.analysis.Completed+s.analysis.Failed < s.analysis.Total {
s.analysis.State = "stopped"
} else if s.analysis.Failed > 0 {
s.analysis.State = "completed_with_errors"
} else {
s.analysis.State = "completed"
s.analysis.LastError = ""
}
log.Printf("analyzer: AI analysis finished: %d/%d done, %d failed, state=%s", s.analysis.Completed, s.analysis.Total, s.analysis.Failed, s.analysis.State)
if s.analysis.LastError != "" {
log.Printf("analyzer: AI analysis last error: %s", s.analysis.LastError)
}
}
// runAnalysisTask dispatches one (file, task, model) unit of work. Every model produces a fixed
// output shape regardless of which task slot it was assigned to in the UI (the model dropdown
// isn't filtered per task), so storage in applyAnalysisResult is driven by what a model actually
// returns, not by the task key it ran under.
func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask) (map[string]any, error) {
sourcePath := filepath.ToSlash(item.filePath)
// Video frames come from an existing thumbnail when possible (see videoAnalysisFrame) rather
// than always fetching the whole video across the wire to Servant just to grab one frame.
if item.mediaType == "video" && item.model != "laplacian" {
framePath, cleanup, err := s.videoAnalysisFrame(ctx, sourcePath)
if err != nil {
return nil, err
}
if cleanup != nil {
defer cleanup()
}
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, framePath)
}
scratchPath, cleanup, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return nil, fmt.Errorf("fetch %s: %w", item.filePath, err)
}
defer cleanup()
if item.model == "laplacian" {
if item.mediaType != "image" {
return nil, fmt.Errorf("laplacian quality scoring only supports images")
}
variance, err := computeLaplacianVariance(scratchPath)
if err != nil {
return nil, err
}
return map[string]any{"quality": map[string]any{"laplacianVariance": variance}}, nil
}
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, scratchPath)
}
// videoAnalysisFrame reuses an already-generated thumbnail as the representative frame for
// image-shaped models when one exists, fetching the source video and extracting a temporary
// frame otherwise so AI analysis doesn't depend on the thumbnails stage being enabled. Both paths
// return a scratch file the AnalyzerModels sidecar (co-located in this container - see
// callAnalyzerModelsService) can read directly.
func (s *Server) videoAnalysisFrame(ctx context.Context, sourcePath string) (string, func(), error) {
var thumbnailID string
if err := s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, sourcePath).Scan(&thumbnailID); err == nil {
if scratchPath, cleanup, fetchErr := s.fetchServantToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil {
return scratchPath, cleanup, nil
}
}
videoScratch, cleanupVideo, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return "", nil, fmt.Errorf("fetch %s: %w", sourcePath, err)
}
defer cleanupVideo()
temporary, err := os.CreateTemp("", "analysis-frame-*.jpg")
if err != nil {
return "", nil, fmt.Errorf("create temporary frame: %w", err)
}
temporaryPath := temporary.Name()
if err := temporary.Close(); err != nil {
_ = os.Remove(temporaryPath)
return "", nil, err
}
frameCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
args := []string{"-hide_banner", "-loglevel", "error", "-y", "-ss", "0", "-i", videoScratch, "-vf", "scale=320:-2:force_original_aspect_ratio=decrease", "-frames:v", "1", "-q:v", "3", temporaryPath}
command := exec.CommandContext(frameCtx, s.cfg.FFmpeg, args...)
var stderr bytes.Buffer
command.Stderr = &stderr
if err := command.Run(); err != nil {
_ = os.Remove(temporaryPath)
detail := strings.TrimSpace(stderr.String())
if len(detail) > 300 {
detail = detail[len(detail)-300:]
}
if detail != "" {
return "", nil, fmt.Errorf("ffmpeg: %s", detail)
}
return "", nil, err
}
return temporaryPath, func() { _ = os.Remove(temporaryPath) }, nil
}
type analysisSidecarRequest struct {
Task string `json:"task"`
Model string `json:"model"`
Path string `json:"path"`
}
// callAnalyzerModelsService calls the AnalyzerModels sidecar (a separate process in the same
// container, not baked into this binary - see ANALYZER_MODELS_URL and Lookout/Dockerfile),
// the same way executeGeneration already calls out to ComfyUI for image generation. Video frames
// are analyzed through the image endpoint since by the time this runs the video has already been
// reduced to a still frame.
func (s *Server) callAnalyzerModelsService(ctx context.Context, mediaType, task, model, path string) (map[string]any, error) {
endpoint, ok := map[string]string{"image": "/analyze/image", "video": "/analyze/image", "audio": "/analyze/audio"}[mediaType]
if !ok {
return nil, fmt.Errorf("unsupported media type for AI analysis: %s", mediaType)
}
body, err := json.Marshal(analysisSidecarRequest{Task: task, Model: model, Path: path})
if err != nil {
return nil, err
}
// Some models (florence2 especially) run several seconds per file on CPU - generous timeout
// so a slow model doesn't get mistaken for a hung one.
requestCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, s.cfg.AnalyzerModelsURL+endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, fmt.Errorf("analyzer models service request failed: %w", err)
}
defer response.Body.Close()
var payload struct {
Result map[string]any `json:"result"`
// FastAPI's HTTPException serializes as {"detail": "..."} , not {"error": "..."}.
Detail string `json:"detail"`
}
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&payload); err != nil {
return nil, fmt.Errorf("invalid analyzer models response: %w", err)
}
if response.StatusCode >= 300 {
if payload.Detail == "" {
payload.Detail = response.Status
}
return nil, fmt.Errorf("analyzer models service: %s", payload.Detail)
}
return payload.Result, nil
}
// applyAnalysisResult writes a completed task's output into the tables the rest of the app
// actually reads, not just the analyzer's own history - tags into media_tags (user_id NULL marks
// them as AI-attributed), title/description onto media (never overwriting a value that's already
// set, whether user-edited or from an earlier analysis run), everything else into media.metadata.
func (s *Server) applyAnalysisResult(ctx context.Context, mediaKey string, result map[string]any) {
if result == nil {
return
}
if tagsRaw, ok := result["tags"].([]any); ok {
for _, tagValue := range tagsRaw {
tag, ok := tagValue.(string)
tag = strings.ToLower(strings.TrimSpace(tag))
if !ok || tag == "" {
continue
}
_, _ = s.db.Exec(ctx, `
INSERT INTO media_tags (media_key, tag, user_id) VALUES ($1, $2, NULL)
ON CONFLICT (media_key, tag) WHERE user_id IS NULL DO NOTHING`, mediaKey, tag)
}
}
title, _ := result["title"].(string)
description, _ := result["description"].(string)
if strings.TrimSpace(title) != "" || strings.TrimSpace(description) != "" {
_, _ = s.db.Exec(ctx, `
UPDATE media SET
title = COALESCE(NULLIF(media.title, ''), NULLIF($2, '')),
description = COALESCE(NULLIF(media.description, ''), NULLIF($3, ''))
WHERE media_key = $1`, mediaKey, title, description)
}
extra := map[string]any{}
for _, key := range []string{"age", "gender", "nsfwLabel", "nsfwScore", "quality"} {
if value, ok := result[key]; ok {
extra[key] = value
}
}
if len(extra) > 0 {
_, _ = s.db.Exec(ctx, `UPDATE media SET metadata = metadata || $2::jsonb WHERE media_key = $1`, mediaKey, mustJSON(extra))
}
}
// computeLaplacianVariance measures image sharpness/blur without any external model: convert to
// grayscale, convolve with the standard 4-neighbor Laplacian kernel, and take the variance of the
// result - a low variance means a flat/blurry image, a high variance means a lot of sharp edges.
// Only the image formats Go's standard library can decode (JPEG/PNG/GIF) are supported; anything
// else surfaces as a normal per-file error rather than silently skipping.
func computeLaplacianVariance(fullPath string) (float64, error) {
file, err := os.Open(fullPath)
if err != nil {
return 0, err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return 0, fmt.Errorf("decode image: %w", err)
}
bounds := img.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width < 3 || height < 3 {
return 0, fmt.Errorf("image too small for quality analysis")
}
gray := make([]float64, width*height)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
r, g, b, _ := img.At(bounds.Min.X+x, bounds.Min.Y+y).RGBA()
gray[y*width+x] = 0.299*float64(r>>8) + 0.587*float64(g>>8) + 0.114*float64(b>>8)
}
}
at := func(x, y int) float64 {
if x < 0 {
x = 0
} else if x >= width {
x = width - 1
}
if y < 0 {
y = 0
} else if y >= height {
y = height - 1
}
return gray[y*width+x]
}
var sum, sumSquares float64
count := float64(width * height)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
laplacian := at(x-1, y) + at(x+1, y) + at(x, y-1) + at(x, y+1) - 4*at(x, y)
sum += laplacian
sumSquares += laplacian * laplacian
}
}
mean := sum / count
return sumSquares/count - mean*mean, nil
}
// retryPipelineErrors resets one media type's failed items for one stage back onto the queue and
// immediately re-runs that stage for just that type, rather than requiring a full "Run pipeline".
func (s *Server) retryPipelineErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) {
ctx := r.Context()
log.Printf("analyzer: retry errors requested (mediaType=%s, stage=%s)", mediaType, stage)
switch stage {
case "metadata":
go s.retryMetadataErrors(mediaType)
case "thumbnails":
go s.retryThumbnailErrors(mediaType)
case "analyze":
go s.runAiAnalysis(context.Background(), []string{mediaType})
default:
writeError(w, http.StatusBadRequest, "unknown pipeline stage")
return
}
_ = ctx
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "started": true})
}
// mediaTypeErrorCondition returns a media_worker_jobs WHERE fragment for one media type, and the
// single arg it needs (if any) - the same "funscript" special-case analyzerHistory and
// parseMediaTypesPayload use, since it isn't a real media_type value on that table, just the
// has_funscript flag on a video/audio row.
func mediaTypeErrorCondition(mediaType string) (string, []any) {
if mediaType == "funscript" {
return "has_funscript = TRUE", nil
}
return "LOWER(COALESCE(media_type, '')) = $1", []any{mediaType}
}
type pipelineStageError struct {
FilePath string `json:"filePath"`
Error string `json:"error"`
}
// pipelineStageErrors returns the most recent error messages recorded for one media type's one
// pipeline stage, so the "Show errors" button next to Retry (see PipelineFlowDiagram.svelte) can
// display what's actually failing instead of just the count already shown in the breakdown.
func (s *Server) pipelineStageErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) {
ctx := r.Context()
limit := optionalInt(r.URL.Query().Get("limit"), 20, 1, 100)
items := make([]pipelineStageError, 0)
var query string
var args []any
switch stage {
case "metadata":
condition, condArgs := mediaTypeErrorCondition(mediaType)
query = fmt.Sprintf(`SELECT file_path, COALESCE(metadata_error, '') FROM media_worker_jobs
WHERE metadata_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1)
args = append(condArgs, limit)
case "thumbnails":
condition, condArgs := mediaTypeErrorCondition(mediaType)
query = fmt.Sprintf(`SELECT file_path, COALESCE(thumbnail_error, '') FROM media_worker_jobs
WHERE thumbnail_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1)
args = append(condArgs, limit)
case "analyze":
query = `SELECT media_key, COALESCE(error_message, '') FROM media_analysis_tasks
WHERE status = 'error' AND LOWER(media_type) = $1 ORDER BY finished_at DESC NULLS LAST LIMIT $2`
args = []any{mediaType, limit}
default:
writeError(w, http.StatusBadRequest, "unknown pipeline stage")
return
}
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
writeError(w, http.StatusInternalServerError, "pipeline errors unavailable")
return
}
defer rows.Close()
for rows.Next() {
var item pipelineStageError
if rows.Scan(&item.FilePath, &item.Error) == nil && item.Error != "" {
items = append(items, item)
}
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "errors": items})
}
func (s *Server) retryMetadataErrors(mediaType string) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
rows, err := s.db.Query(ctx, `
SELECT file_path FROM media_worker_jobs
WHERE LOWER(COALESCE(media_type, '')) = $1 AND metadata_status = 'error'`, mediaType)
if err != nil {
return
}
filePaths := make([]string, 0)
for rows.Next() {
var filePath string
if rows.Scan(&filePath) == nil {
filePaths = append(filePaths, filePath)
}
}
rows.Close()
for _, filePath := range filePaths {
if ctx.Err() != nil {
return
}
if probe, probeErr := s.servantProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, filePath, probeErr.Error())
} else {
duration := nullableInt64(probe.DurationMs)
width, height := probe.Width, probe.Height
_, _ = s.db.Exec(ctx, `UPDATE media SET duration_ms = COALESCE($2, duration_ms), width = COALESCE($3, width), height = COALESCE($4, height) WHERE file_path = $1`, filePath, duration, nullableInt(width), nullableInt(height))
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='completed', metadata_error=NULL WHERE file_path=$1`, filePath)
}
}
}
func (s *Server) retryThumbnailErrors(mediaType string) {
s.thumbnailMu.Lock()
if s.thumbnail.Running {
s.thumbnailMu.Unlock()
return
}
ctx, cancel := context.WithCancel(context.Background())
now := time.Now().UTC()
s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now}
s.thumbnailCancel = cancel
s.thumbnailMu.Unlock()
candidates, err := s.thumbnailCandidatesWithErrors(ctx, mediaType)
if err != nil {
s.finishThumbnailGeneration(err)
return
}
s.runThumbnailCandidates(ctx, candidates)
}
@@ -0,0 +1,139 @@
package server
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
)
// runAnalyzerScheduler polls due, enabled workflow_schedules for this service and runs them. It's
// deliberately a simple poll loop rather than a precise cron: schedules only ever run on
// minute-scale intervals, so "checked every 30s, run when due" is accurate enough and far simpler
// than tracking individual timers per schedule.
func (s *Server) runAnalyzerScheduler(ctx context.Context) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.runDueAnalyzerSchedules(ctx)
}
}
}
func (s *Server) runDueAnalyzerSchedules(ctx context.Context) {
rows, err := s.db.Query(ctx, `
SELECT id, tool, settings
FROM workflow_schedules
WHERE service = $1 AND enabled = TRUE AND (next_run_at IS NULL OR next_run_at <= NOW())`, s.cfg.ServiceName)
if err != nil {
log.Printf("analyzer: schedule poll: failed to load due schedules: %v", err)
return
}
type due struct {
id, tool string
settings []byte
}
items := make([]due, 0)
for rows.Next() {
var item due
if rows.Scan(&item.id, &item.tool, &item.settings) == nil {
items = append(items, item)
}
}
rows.Close()
for _, item := range items {
if ctx.Err() != nil {
return
}
var parsed struct {
Types []string `json:"types"`
}
_ = json.Unmarshal(item.settings, &parsed)
types := normalizeMediaTypes(parsed.Types, true)
status := "started"
started, err := s.startAnalyzerScheduledRun(item.tool, types)
switch {
case err != nil:
status = "error: " + err.Error()
case !started:
status = "skipped: busy"
}
log.Printf("analyzer: automation schedule %s fired (tool=%s): %s", item.id, item.tool, status)
// Always advance next_run_at, even on skip/error, so a busy or misconfigured schedule
// doesn't get retried on every single tick - it just waits for its normal interval instead.
_, _ = s.db.Exec(ctx, `
UPDATE workflow_schedules
SET last_run_at = NOW(), last_status = $2, next_run_at = NOW() + make_interval(mins => interval_minutes), updated_at = NOW()
WHERE id = $1`, item.id, status)
}
}
// startAnalyzerScheduledRun dispatches one schedule's action exactly the way its corresponding
// manual-trigger HTTP handler does: guard the relevant busy-state slot, then hand off to the same
// background worker function used everywhere else. "started" is false (not an error) when that
// slot was already busy - the schedule just waits for its next tick rather than queuing up or
// failing loudly, mirroring how the dashboard's own buttons behave under the same condition.
func (s *Server) startAnalyzerScheduledRun(tool string, types map[string]bool) (bool, error) {
now := time.Now().UTC()
switch tool {
case "discover":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now}
s.scanMu.Unlock()
go s.scanMediaFiles(types)
case "metadata":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "metadata", StartedAt: &now}
s.scanMu.Unlock()
go s.refreshMetadataForTypes(types)
case "cleanup":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "cleanup", StartedAt: &now}
s.scanMu.Unlock()
go s.cleanupStaleMedia()
case "thumbnails":
s.thumbnailMu.Lock()
if s.thumbnail.Running {
s.thumbnailMu.Unlock()
return false, nil
}
runCtx, cancel := context.WithCancel(context.Background())
s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now}
s.thumbnailCancel = cancel
s.thumbnailMu.Unlock()
go s.generateThumbnails(runCtx, types)
case "analyze":
s.analysisMu.Lock()
if s.analysis.Running {
s.analysisMu.Unlock()
return false, nil
}
runCtx, cancel := context.WithCancel(context.Background())
s.analysis = analysisState{Running: true, State: "running", StartedAt: &now}
s.analysisCancel = cancel
s.analysisMu.Unlock()
go s.runAiAnalysis(runCtx, mediaTypesList(types))
default:
return false, fmt.Errorf("unsupported schedule action: %s", tool)
}
return true, nil
}
+195
View File
@@ -0,0 +1,195 @@
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
"mediacollection/internal/config"
)
type kioskMessage struct {
Type string `json:"type"`
QueueMode string `json:"queueMode,omitempty"`
DisplayDuration int64 `json:"displayDuration,omitempty"`
}
func (s *Server) kioskWebsocket(w http.ResponseWriter, r *http.Request) {
options := s.websocketAcceptOptions(r)
conn, err := websocket.Accept(w, r, options)
if err != nil {
return
}
defer conn.Close(websocket.StatusNormalClosure, "")
updates := make(chan []byte, 16)
s.kioskMu.Lock()
s.kioskClients[updates] = struct{}{}
latest := s.kioskLatest
s.kioskMu.Unlock()
defer func() {
s.kioskMu.Lock()
delete(s.kioskClients, updates)
s.kioskMu.Unlock()
}()
if latest != "" {
s.kioskSend(updates, map[string]any{"type": "new-image", "path": latest})
}
s.kioskSend(updates, map[string]any{
"type": "settings-updated",
"queueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"),
"serverDisplayDuration": kioskDuration(s.settingValue(r.Context(), "server_display_duration", "5000")),
})
ctx := r.Context()
writeCtx, cancelWrite := context.WithCancel(ctx)
defer cancelWrite()
go func() {
for {
select {
case <-writeCtx.Done():
return
case data := <-updates:
if err := conn.Write(writeCtx, websocket.MessageText, data); err != nil {
return
}
}
}
}()
s.startKioskPoll()
for {
messageType, payload, readErr := conn.Read(ctx)
if readErr != nil {
return
}
if messageType != websocket.MessageText {
continue
}
var message kioskMessage
if json.Unmarshal(payload, &message) != nil || message.Type != "update-settings" {
continue
}
if message.QueueMode != "" && (message.QueueMode == "client" || message.QueueMode == "server") {
_ = s.saveSetting(ctx, "kiosk_queue_mode", message.QueueMode)
}
if message.DisplayDuration >= 0 && message.DisplayDuration <= 24*60*60*1000 {
_ = s.saveSetting(ctx, "server_display_duration", formatInt(message.DisplayDuration))
}
s.kioskBroadcast(map[string]any{
"type": "settings-updated",
"queueMode": s.settingValue(ctx, "kiosk_queue_mode", "client"),
"serverDisplayDuration": kioskDuration(s.settingValue(ctx, "server_display_duration", "5000")),
})
}
}
func (s *Server) startKioskPoll() {
s.kioskMu.Lock()
if s.kioskPolling {
s.kioskMu.Unlock()
return
}
s.kioskPolling = true
s.kioskMu.Unlock()
go s.kioskPoll(context.Background())
}
func (s *Server) kioskPoll(ctx context.Context) {
if s.cfg.Service != config.Kiosk {
return
}
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for {
s.kioskPollOnce(ctx)
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
func (s *Server) kioskPollOnce(ctx context.Context) {
files, err := s.servantListFiles(ctx, "", false, 0)
if err != nil {
return
}
images := make([]fileEntry, 0, len(files))
for _, file := range files {
if file.Type == "image" {
images = append(images, file)
}
}
if len(images) == 0 {
return
}
sort.Slice(images, func(i, j int) bool { return images[i].Mtime > images[j].Mtime })
latest := images[0].Rel
s.kioskMu.Lock()
changed := latest != s.kioskLatest
s.kioskLatest = latest
s.kioskMu.Unlock()
if changed {
s.kioskBroadcast(map[string]any{"type": "new-image", "path": latest})
}
}
func (s *Server) kioskBroadcast(message any) {
data, err := json.Marshal(message)
if err != nil {
return
}
s.kioskMu.Lock()
defer s.kioskMu.Unlock()
for client := range s.kioskClients {
select {
case client <- data:
default:
}
}
}
func (s *Server) kioskSend(client chan []byte, message any) {
data, err := json.Marshal(message)
if err != nil {
return
}
select {
case client <- data:
default:
}
}
func (s *Server) kioskImage(w http.ResponseWriter, r *http.Request) {
relative := chi.URLParam(r, "*")
if relative == "" {
relative = strings.TrimPrefix(r.URL.Path, "/api/images/")
}
if !safeRelative(relative) || !isImagePath(relative) {
writeError(w, http.StatusNotFound, "image not found")
return
}
s.proxyServant(w, r, "/media/"+urlPath(relative))
}
func kioskDuration(value string) int64 {
var duration int64
if _, err := fmt.Sscanf(value, "%d", &duration); err != nil || duration < 0 {
return 5000
}
return duration
}
func formatInt(value int64) string {
return strconv.FormatInt(value, 10)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,83 @@
package server
import (
"net"
"os"
"path/filepath"
"strings"
"testing"
)
func TestSafeRelativeRejectsTraversal(t *testing.T) {
for _, value := range []string{"", ".", "..", "../secret", `..\secret`, `/etc/passwd`, "a/../../b"} {
if safeRelative(value) {
t.Errorf("safeRelative(%q) = true", value)
}
}
for _, value := range []string{"video.mp4", "nested/image.webp", "funscript.json"} {
if !safeRelative(value) {
t.Errorf("safeRelative(%q) = false", value)
}
}
}
func TestSameRealRootRejectsSymlinkEscape(t *testing.T) {
root := t.TempDir()
inside := filepath.Join(root, "inside.txt")
if err := os.WriteFile(inside, []byte("ok"), 0o600); err != nil {
t.Fatal(err)
}
if !sameRealRoot(root, inside) {
t.Fatal("sameRealRoot rejected a file inside the root")
}
outside := t.TempDir()
outsideFile := filepath.Join(outside, "outside.txt")
if err := os.WriteFile(outsideFile, []byte("secret"), 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "link.txt")
if err := os.Symlink(outsideFile, link); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
if sameRealRoot(root, link) {
t.Fatal("sameRealRoot accepted a symlink outside the root")
}
}
func TestConversionArgsDoNotAcceptArbitraryEncoderFlags(t *testing.T) {
args := strings.Join(conversionArgs("input.mp4", "output.mp4", "mp4", "-filter_complex malicious"), " ")
if strings.Contains(args, "malicious") || !strings.Contains(args, "libx264") {
t.Fatalf("conversion args = %q", args)
}
}
func TestHasFunscriptSidecar(t *testing.T) {
root := t.TempDir()
mediaPath := filepath.Join(root, "clip.mp4")
if os.WriteFile(mediaPath, []byte("media"), 0o600) != nil {
t.Fatal("could not create media fixture")
}
if hasFunscriptSidecar(mediaPath) {
t.Fatal("media without a sidecar was marked as having a funscript")
}
if os.WriteFile(filepath.Join(root, "clip.funscript"), []byte("{}"), 0o600) != nil {
t.Fatal("could not create funscript fixture")
}
if !hasFunscriptSidecar(mediaPath) {
t.Fatal("funscript sidecar was not detected")
}
}
func TestDownloadURLValidation(t *testing.T) {
for _, value := range []string{"file:///etc/passwd", "http://127.0.0.1/x", "http://169.254.169.254/", "https://user:pass@example.com/x"} {
if err := validateDownloadURL(value); err == nil {
t.Errorf("validateDownloadURL(%q) succeeded", value)
}
}
if err := validateDownloadURL("https://example.com/video"); err != nil {
t.Fatalf("public URL rejected: %v", err)
}
if !isPrivateIP(net.ParseIP("127.0.0.1")) {
t.Fatal("loopback was not classified as private")
}
}
@@ -0,0 +1,331 @@
package server
// Servant client: every non-Servant service serves and stores media by calling Porter's
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. Servant's own handlers keep using those
// roots directly (see media.go, admin_storage.go) - this file is never called from Servant's
// own code path.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// servantHTTPClient has no blanket timeout since it streams large media files; callers bound
// individual calls with a context deadline instead.
var servantHTTPClient = &http.Client{}
func (s *Server) servantClient() *http.Client {
return servantHTTPClient
}
// servantBaseURL is configured in MediaConfig and stored in the settings table (key
// "mediaservant_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
// every project's connection URL) - not a static env var, so a change in MediaConfig takes
// effect on every service's very next request without a restart. SERVANT_URL is only the
// bootstrap fallback before that setting has ever been saved.
func (s *Server) servantBaseURL(ctx context.Context) string {
return strings.TrimRight(s.settingValue(ctx, "mediaservant_url", s.cfg.ServantURL), "/")
}
func (s *Server) newServantRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, s.servantBaseURL(ctx)+path, body)
if err != nil {
return nil, err
}
if s.cfg.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
}
return request, nil
}
var servantForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var servantForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// proxyServant streams a Servant 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 (s *Server) proxyServant(w http.ResponseWriter, r *http.Request, servantPath string) {
request, err := s.newServantRequest(r.Context(), r.Method, servantPath, nil)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
for _, header := range servantForwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := s.servantClient().Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
defer response.Body.Close()
for _, header := range servantForwardResponseHeaders {
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)
}
}
// probeServant checks whether a Servant-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 (s *Server) probeServant(ctx context.Context, servantPath string) (bool, int64, time.Time, error) {
request, err := s.newServantRequest(ctx, http.MethodHead, servantPath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := s.servantClient().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("servant 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
}
// fetchServantToScratch downloads a Servant-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 (s *Server) fetchServantToScratch(ctx context.Context, servantPath, suffix string) (string, func(), error) {
request, err := s.newServantRequest(ctx, http.MethodGet, servantPath, nil)
if err != nil {
return "", nil, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return "", nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("servant fetch failed: %s", response.Status)
}
scratch, err := os.CreateTemp("", "servant-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
}
// pushToServant streams a local file as the request body without buffering it in memory.
func (s *Server) pushToServant(ctx context.Context, method, servantPath, localPath string) (*http.Response, error) {
file, err := os.Open(localPath)
if err != nil {
return nil, err
}
defer file.Close()
request, err := s.newServantRequest(ctx, method, servantPath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := s.servantClient().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("servant push failed: %s: %s", response.Status, string(body))
}
return response, nil
}
func servantPushedSize(response *http.Response) int64 {
defer response.Body.Close()
var payload struct {
Size int64 `json:"size"`
}
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload.Size
}
func (s *Server) servantPushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantDeleteThumbnail(ctx context.Context, id string) error {
request, err := s.newServantRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := s.servantClient().Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
return fmt.Errorf("servant delete thumbnail failed: %s", response.Status)
}
return nil
}
func (s *Server) servantPushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantPushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantPushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
// servantUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
// staged in a scratch dir) into Servant's DownloadsRoot via its existing raw-upload endpoint.
func (s *Server) servantUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := s.pushToServant(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
}
// servantStoreDownload catalogs an already-uploaded file into Servant's media/downloaded_media
// tables via its existing /api/store endpoint - callers should stop duplicating that DB write
// locally once they migrate to this.
func (s *Server) servantStoreDownload(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 := s.newServantRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := s.servantClient().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("servant store failed: %s: %s", response.Status, string(errorBody))
}
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// servantListFiles lists files under Servant's MediaRoots via its existing /api/files(/recent)
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
func (s *Server) servantListFiles(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 := s.newServantRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("servant 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
}
type servantProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
}
// servantProbe runs ffprobe on Servant against a MediaRoots-relative path and returns just the
// metadata fields - bytes never leave Servant, unlike every other helper in this file.
func (s *Server) servantProbe(ctx context.Context, relative string) (servantProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := s.newServantRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return servantProbeResult{}, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return servantProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return servantProbeResult{}, fmt.Errorf("servant probe failed: %s", response.Status)
}
var result servantProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return servantProbeResult{}, err
}
return result, nil
}
+433
View File
@@ -0,0 +1,433 @@
package server
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path"
"runtime"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/auth"
"mediacollection/internal/config"
)
type Server struct {
cfg *config.Config
db *pgxpool.Pool
auth *auth.Service
startedAt time.Time
mediaMu sync.RWMutex
media map[string]MediaRecord
jobsMu sync.RWMutex
jobs map[string]*WorkflowJob
workflowSem chan struct{}
sync *syncHub
thumbnailMu sync.Mutex
thumbnail thumbnailGenerationState
thumbnailCancel context.CancelFunc
clearMu sync.Mutex
clear databaseClearState
scanMu sync.Mutex
scan scanState
scanCancel context.CancelFunc
analysisMu sync.Mutex
analysis analysisState
analysisCancel context.CancelFunc
kioskMu sync.Mutex
kioskClients map[chan []byte]struct{}
kioskLatest string
kioskPolling bool
}
type MediaRecord struct {
ID int64
MediaKey string
MediaType string
Title *string
Description *string
FilePath string
OriginalName string
Source string
Width *int
Height *int
DurationMs *int64
SizeBytes *int64
IsVR bool
HasFunscript bool
Speed *float32
ModifiedAt time.Time
}
type WorkflowJob struct {
ID string `json:"id"`
Service string `json:"service"`
Tool string `json:"tool"`
Status string `json:"status"`
Progress int `json:"progress"`
Request map[string]any `json:"request,omitempty"`
Result map[string]any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"createdAt"`
StartedAt *time.Time `json:"startedAt,omitempty"`
FinishedAt *time.Time `json:"finishedAt,omitempty"`
}
type thumbnailGenerationState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// databaseClearState tracks a dashboard/per-media-type reset so it can be reported through the
// same live status endpoint as the analyzer workers. The reset itself is deliberately kept
// synchronous from the HTTP caller's perspective, but large libraries still need an honest state
// while their thumbnail files and database rows are being removed.
type databaseClearState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// scanState tracks the currently-running discover/metadata walk so the analyzer UI can show
// which media type is actively being indexed right now - scanMediaFiles has no separate queue,
// it indexes (and, per pipelineStageEnabled, extracts metadata for) each file synchronously as
// it's found, so "active" here is the closest honest signal to a live "processing" state.
type scanState struct {
Running bool
Mode string // "discover" (filesystem walk), "metadata" (refresh), or "cleanup" (stale sweep)
CurrentType string
CurrentFile string
FilesIndexed int64
// Total is only known upfront for metadata/cleanup - both pre-fetch their full row list before
// looping. discover has no total (a live filesystem walk doesn't know its own size in advance)
// and leaves this at zero, which the UI treats as "not available".
Total int64
StartedAt *time.Time
// LastError survives the end-of-run reset (unlike every other field here) so a run that
// failed fast - e.g. Porter unreachable - doesn't just look like it silently reverted
// to idle; analyzerStatus reports it until the next run overwrites or clears it.
LastError string
}
func New(cfg *config.Config, db *pgxpool.Pool) *Server {
return &Server{
cfg: cfg,
db: db,
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies),
startedAt: time.Now(),
media: make(map[string]MediaRecord),
jobs: make(map[string]*WorkflowJob),
workflowSem: make(chan struct{}, 2),
sync: newSyncHub(),
thumbnail: thumbnailGenerationState{State: "idle"},
analysis: analysisState{State: "idle"},
kioskClients: make(map[chan []byte]struct{}),
}
}
func (s *Server) Handler() http.Handler {
router := chi.NewRouter()
router.Use(chimiddleware.RequestID)
router.Use(chimiddleware.Recoverer)
router.Use(s.securityHeadersMiddleware)
router.Use(s.cors)
router.Get("/healthz", s.health)
router.Get("/health", s.health)
router.Get("/ready", s.ready)
router.With(s.auth.RequireIfLoginRequired).Get("/api/tech-stack", s.techStack)
router.Get("/__cache-policy", s.cachePolicy)
router.Route("/auth", func(r chi.Router) {
r.Post("/signup", s.auth.Signup)
r.Post("/login", s.auth.Login)
r.Post("/logout", s.auth.Logout)
r.Post("/reset/request", s.auth.RequestAdminReset)
r.Post("/reset/confirm", s.auth.ConfirmAdminReset)
r.Get("/me", s.auth.Me)
r.With(s.auth.Require).Put("/me", s.auth.UpdateMe)
r.Get("/status", s.auth.Status)
r.Get("/bootstrap/admin-needed", s.auth.AdminNeeded)
})
router.Route("/api/auth", func(r chi.Router) {
manager := r.With(s.auth.RequireUserManager)
manager.Get("/access", s.auth.AccessSettings)
manager.Put("/access", s.auth.UpdateAccessSettings)
manager.Get("/users", s.auth.ManagedUsers)
manager.Post("/users", s.auth.ManagedCreateUser)
manager.Put("/users/{id}", s.auth.ManagedUpdateUser)
manager.Patch("/users/{id}", s.auth.ManagedUpdateUser)
manager.Delete("/users/{id}", s.auth.ManagedDeleteUser)
})
router.Route("/api", func(r chi.Router) {
s.mountServiceRoutes(r)
})
if s.cfg.Service == config.Kiosk {
s.mountKioskSocket(router)
}
if s.cfg.Service != config.Kiosk {
router.HandleFunc("/ws", s.syncWebsocket)
}
if s.cfg.Service == config.Servant {
internal := s.internalServiceAuth
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.servantDownloadMedia)))
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.servantGeneratedMedia)))
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.servantInputMedia)))
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.servantCopyMedia)))
router.Handle("/media/*", internal(http.HandlerFunc(s.servantMedia)))
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.servantThumbnail)))
}
router.NotFound(s.staticHandler)
return router
}
func (s *Server) mountServiceRoutes(r chi.Router) {
s.mountSharedRoutes(r)
switch s.cfg.Service {
case config.Viewer:
s.mountViewerRoutes(r)
case config.Tools:
s.mountToolsRoutes(r)
case config.Analyzer:
s.mountAnalyzerRoutes(r)
case config.ConfigService:
s.mountConfigRoutes(r)
case config.Moderator:
s.mountModeratorRoutes(r)
case config.Kiosk:
s.mountKioskRoutes(r)
case config.Servant:
s.mountServantRoutes(r)
case config.Desktop:
s.mountDesktopRoutes(r)
}
}
func (s *Server) securityHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:")
next.ServeHTTP(w, r)
})
}
func (s *Server) cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" && (s.cfg.AllowedOrigin == "*" || origin == s.cfg.AllowedOrigin) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Add("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Internal-Auth")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) health(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName, "uptimeSeconds": int(time.Since(s.startedAt).Seconds())})
}
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
if s.db == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.db.Ping(ctx); err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName})
}
func (s *Server) techStack(w http.ResponseWriter, _ *http.Request) {
appVersion := os.Getenv("APP_VERSION")
if appVersion == "" {
appVersion = "go-rewrite"
}
writeJSON(w, http.StatusOK, map[string]any{
"appVersion": appVersion,
"stack": []map[string]string{
{"label": "Runtime", "value": runtime.Version()},
{"label": "HTTP", "value": "net/http + chi"},
{"label": "Database", "value": "PostgreSQL + pgx"},
{"label": "Authentication", "value": "bcrypt + PostgreSQL sessions"},
},
})
}
func (s *Server) cachePolicy(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"service": s.cfg.ServiceName, "policies": map[string]string{"static": "public, max-age=3600", "media": "private, max-age=0, must-revalidate"}})
}
func (s *Server) staticHandler(w http.ResponseWriter, r *http.Request) {
root := os.DirFS(s.cfg.WebRoot)
if _, err := fs.Stat(root, "."); err != nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "frontend build not found"})
return
}
requested := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
if requested == "." || requested == "" {
requested = "index.html"
}
if info, err := fs.Stat(root, requested); err == nil && !info.IsDir() {
http.FileServer(http.FS(root)).ServeHTTP(w, r)
return
}
if path.Ext(requested) != "" {
http.NotFound(w, r)
return
}
index, err := fs.ReadFile(root, "index.html")
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(index)
}
func (s *Server) listenAndServe(ctx context.Context) error {
server := &http.Server{Addr: ":" + s.cfg.Port, Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 0, IdleTimeout: 60 * time.Second}
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = server.Shutdown(shutdownCtx)
}()
log.Printf("%s listening on http://:%s (Go)", s.cfg.ServiceName, s.cfg.Port)
if s.cfg.TLSCertFile != "" {
return server.ListenAndServeTLS(s.cfg.TLSCertFile, s.cfg.TLSKeyFile)
}
return server.ListenAndServe()
}
func (s *Server) Run(ctx context.Context) error {
go s.resumeWorkflowJobs(ctx)
if s.cfg.Service == config.Analyzer {
go s.runAnalyzerScheduler(ctx)
}
return s.listenAndServe(ctx)
}
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})
}
func stringValue(value *string) string {
if value == nil {
return ""
}
return *value
}
func intValue(value *int) any {
if value == nil {
return nil
}
return *value
}
func int64Value(value *int64) any {
if value == nil {
return nil
}
return *value
}
func floatValue(value *float32) any {
if value == nil {
return nil
}
return *value
}
func boolQuery(value string) *bool {
switch strings.ToLower(strings.TrimSpace(value)) {
case "1", "true", "yes", "on":
result := true
return &result
case "0", "false", "no", "off":
result := false
return &result
default:
return nil
}
}
func (s *Server) internalServiceAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s.cfg.InternalServiceSecret == "" || r.Header.Get("X-Internal-Auth") != s.cfg.InternalServiceSecret {
writeError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) requireAdminOrInternal(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.IsAdmin(auth.UserFromContext(r.Context())) || (s.cfg.InternalServiceSecret != "" && r.Header.Get("X-Internal-Auth") == s.cfg.InternalServiceSecret) {
next.ServeHTTP(w, r)
return
}
writeError(w, http.StatusUnauthorized, "administrator or internal service authentication required")
})
}
func optionalInt(value string, fallback, minimum, maximum int) int {
var parsed int
if _, err := fmt.Sscanf(strings.TrimSpace(value), "%d", &parsed); err != nil {
return fallback
}
if parsed < minimum {
return minimum
}
if parsed > maximum {
return maximum
}
return parsed
}
+541
View File
@@ -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
}
File diff suppressed because it is too large. Load diff