* feat(nodeconfig): harden config watcher for integrated-mode use - RequestReload(): non-blocking, coalescing reload nudge that runs on the poll goroutine, so concurrent requests can never swap a stale snapshot over a newer one (unlike ForceReload from request handlers) - Skip OnChange callbacks when the reloaded config is deep-equal to the previous one, so the 60s poll doesn't fire rebuild/log callbacks on no-op reloads - Add RedisURL to BootstrapOverrides; previously a reload clobbered an env-provided Redis URL in the live config - Split reload into fetchSettings/applySettings and add unit tests Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(config): hot-reload config watcher in integrated mode Start nodeconfig.Watcher in integrated/api mode (previously only proxy/ transcode worker modes hot-reloaded). Expose the live config to the API and jellycompat routers via func-typed LiveConfig/OnConfigChange fields with nil fallbacks to the startup snapshot, and wire the admin settings update hook to RequestReload so same-process changes apply immediately even without Redis. No consumer reads the live config yet — conversions land separately. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(admin): truthful restart-required banner for settings saves The settings UI showed 'restart required' after every save regardless of the key. The backend now classifies each key via a central registry (internal/config/restart_keys.go) and PUT /admin/settings/{key} reports restart_required per key; useSettingsForm only raises the banner when a saved key actually needs a restart (and keeps it raised until restart). The registry is conservative: every currently startup-frozen key is marked restart-required; subsequent hot-reload conversions shrink it. Settings read live from the settings repo (branding, overlays, markers, download.*, ...) default to no-restart. DownloadSettings/OverlaySettings drop their hardcoded restartRequired={false} special-casing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(logging): hot-reload server.log_level and server.log_quiet Share one slog.LevelVar across the handler chain and make logfilter.Handler's quiet-prefix list an atomic pointer shared with WithAttrs/WithGroup clones (New previously returned the inner handler unwrapped when the quiet list was empty, leaving nothing to update). The integrated-mode config watcher now applies both settings live; their keys leave the restart-required registry. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(auth): hot-reload access/refresh token expiries JWTService stores expiries as atomics with a SetExpiries hook; all three instances (main API, ABS compat, jellycompat) re-apply them on config reload. Applies to newly issued tokens; outstanding tokens keep their original expiry. The JWT secret stays fixed for the process lifetime. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(playback): read transcode config live at session start The playback and stream handlers pull ffmpeg path / hwaccel / transcode dir from the live config when starting a transcode or extracting subtitles, instead of values frozen at router construction. Each session snapshots the config once so its output dir and binary stay consistent. Also fixes a real bug: playback.hw_device was parsed into the config but never wired into the integrated-mode handler, so local transcodes always ran with an empty HWDevice while transcode nodes honored it. playback.transcode_dir leaves the restart-required registry (the handler is its only consumer); ffmpeg_path/hw_accel stay restart-required until scanner/chapterthumbs/audiobook consumers convert. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(jellycompat): read compat identity settings live per request System/Auth handlers take a config provider instead of the startup snapshot, so jellyfin_compat.public_url, .server_name, and .emulated_server_version apply without restart. server_id stays restart-required (generate-once, baked into the resource mapper), as do the session-store TTLs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(scanner,metadata,mdblist): hot-reload worker pools and API key scanner.workers, matcher.workers/batch_size, metadata.cache_images, and mdblist.api_key convert to atomic fields with setters wired to the config watcher. Worker counts apply on the next scan/match cycle (the loops read them per cycle); the MDBList key applies to the next request. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(ai): hot-reload AI connection, models, toggles, and quotas The shared llm.Client holds its config behind an atomic pointer (UpdateConfig; each request snapshots once), and the subtitle/metadata AI services gain UpdateConfig plus setters on the translator (batching) and Whisper transcriber (ffmpeg path, chunk seconds). The router derives their configs from shared helpers used both at construction and in OnConfigChange callbacks, re-evaluating the chat-only-gateway transcribe guard on each reload and warning only when it newly fires. Everything on the AI Services page now applies without restart except ai.max_concurrent_jobs (fixed-capacity dispatch semaphore). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(playback): wire transcode_enabled; remove dead playback/scanner knobs playback.transcode_enabled was parsed into the config but the resolver always received a hardcoded true — the admin toggle did nothing. It now reads the live config per playback start, so disabling transcodes applies without restart. Remove settings that were wired to nothing so 'save + restart' stops pretending: playback.allow_hevc_encoding (resolver field never assigned), playback.transcode_ahead_segments and playback.segment_duration (parsed, never consumed — segment duration is per-session from the client), scanner.file_removal_grace (DeleteMissing is never called). UI fields removed and the config struct fields pruned so they don't resurrect; YAML import still tolerates the legacy keys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
306 lines
12 KiB
Go
306 lines
12 KiB
Go
package jellycompat
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/Silo-Server/silo-server/internal/clientip"
|
|
"github.com/Silo-Server/silo-server/internal/config"
|
|
)
|
|
|
|
type authenticateByNameRequest struct {
|
|
Username string `json:"Username"`
|
|
Pw string `json:"Pw"`
|
|
Password string `json:"Password"`
|
|
}
|
|
|
|
type userPolicyResponse struct {
|
|
IsAdministrator bool `json:"IsAdministrator"`
|
|
IsHidden bool `json:"IsHidden"`
|
|
EnableCollectionManagement bool `json:"EnableCollectionManagement"`
|
|
EnableSubtitleManagement bool `json:"EnableSubtitleManagement"`
|
|
EnableLyricManagement bool `json:"EnableLyricManagement"`
|
|
IsDisabled bool `json:"IsDisabled"`
|
|
EnableUserPreferenceAccess bool `json:"EnableUserPreferenceAccess"`
|
|
EnableRemoteControlOfOtherUsers bool `json:"EnableRemoteControlOfOtherUsers"`
|
|
EnableSharedDeviceControl bool `json:"EnableSharedDeviceControl"`
|
|
EnableRemoteAccess bool `json:"EnableRemoteAccess"`
|
|
EnableLiveTVManagement bool `json:"EnableLiveTvManagement"`
|
|
EnableLiveTVAccess bool `json:"EnableLiveTvAccess"`
|
|
EnableMediaPlayback bool `json:"EnableMediaPlayback"`
|
|
EnableAudioPlaybackTranscoding bool `json:"EnableAudioPlaybackTranscoding"`
|
|
EnableVideoPlaybackTranscoding bool `json:"EnableVideoPlaybackTranscoding"`
|
|
EnablePlaybackRemuxing bool `json:"EnablePlaybackRemuxing"`
|
|
ForceRemoteSourceTranscoding bool `json:"ForceRemoteSourceTranscoding"`
|
|
EnableContentDeletion bool `json:"EnableContentDeletion"`
|
|
EnableContentDownloading bool `json:"EnableContentDownloading"`
|
|
EnableSyncTranscoding bool `json:"EnableSyncTranscoding"`
|
|
EnableMediaConversion bool `json:"EnableMediaConversion"`
|
|
EnableAllDevices bool `json:"EnableAllDevices"`
|
|
EnableAllChannels bool `json:"EnableAllChannels"`
|
|
EnableAllFolders bool `json:"EnableAllFolders"`
|
|
InvalidLoginAttemptCount int `json:"InvalidLoginAttemptCount"`
|
|
LoginAttemptsBeforeLockout int `json:"LoginAttemptsBeforeLockout"`
|
|
MaxActiveSessions int `json:"MaxActiveSessions"`
|
|
EnablePublicSharing bool `json:"EnablePublicSharing"`
|
|
RemoteClientBitrateLimit int `json:"RemoteClientBitrateLimit"`
|
|
AuthenticationProviderID string `json:"AuthenticationProviderId"`
|
|
PasswordResetProviderID string `json:"PasswordResetProviderId"`
|
|
SyncPlayAccess string `json:"SyncPlayAccess"`
|
|
BlockedTags []string `json:"BlockedTags,omitempty"`
|
|
AllowedTags []string `json:"AllowedTags,omitempty"`
|
|
EnableContentDeletionFromFolders []string `json:"EnableContentDeletionFromFolders,omitempty"`
|
|
EnabledDevices []string `json:"EnabledDevices,omitempty"`
|
|
EnabledChannels []string `json:"EnabledChannels,omitempty"`
|
|
EnabledFolders []string `json:"EnabledFolders,omitempty"`
|
|
BlockedMediaFolders []string `json:"BlockedMediaFolders,omitempty"`
|
|
BlockedChannels []string `json:"BlockedChannels,omitempty"`
|
|
}
|
|
|
|
type userDTOResponse struct {
|
|
ID string `json:"Id"`
|
|
Name string `json:"Name"`
|
|
ServerID string `json:"ServerId"`
|
|
HasPassword bool `json:"HasPassword"`
|
|
HasConfiguredPassword bool `json:"HasConfiguredPassword"`
|
|
HasConfiguredEasyPassword bool `json:"HasConfiguredEasyPassword"`
|
|
Policy userPolicyResponse `json:"Policy"`
|
|
Configuration userConfigurationResponse `json:"Configuration"`
|
|
}
|
|
|
|
type userConfigurationResponse struct {
|
|
PlayDefaultAudioTrack bool `json:"PlayDefaultAudioTrack"`
|
|
DisplayMissingEpisodes bool `json:"DisplayMissingEpisodes"`
|
|
GroupedFolders []string `json:"GroupedFolders"`
|
|
SubtitleMode string `json:"SubtitleMode"`
|
|
DisplayCollectionsView bool `json:"DisplayCollectionsView"`
|
|
EnableLocalPassword bool `json:"EnableLocalPassword"`
|
|
OrderedViews []string `json:"OrderedViews"`
|
|
LatestItemsExcludes []string `json:"LatestItemsExcludes"`
|
|
MyMediaExcludes []string `json:"MyMediaExcludes"`
|
|
HidePlayedInLatest bool `json:"HidePlayedInLatest"`
|
|
RememberAudioSelections bool `json:"RememberAudioSelections"`
|
|
RememberSubtitleSelections bool `json:"RememberSubtitleSelections"`
|
|
EnableNextEpisodeAutoPlay bool `json:"EnableNextEpisodeAutoPlay"`
|
|
}
|
|
|
|
type authenticateByNameResponse struct {
|
|
AccessToken string `json:"AccessToken"`
|
|
ServerID string `json:"ServerId"`
|
|
User userDTOResponse `json:"User"`
|
|
SessionInfo *sessionInfoResponse `json:"SessionInfo,omitempty"`
|
|
}
|
|
|
|
type sessionInfoResponse struct {
|
|
PlayableMediaTypes []string `json:"PlayableMediaTypes"`
|
|
UserID string `json:"UserId"`
|
|
UserName string `json:"UserName"`
|
|
LastActivityDate string `json:"LastActivityDate"`
|
|
LastPlaybackCheckIn string `json:"LastPlaybackCheckIn"`
|
|
IsActive bool `json:"IsActive"`
|
|
SupportsMediaControl bool `json:"SupportsMediaControl"`
|
|
SupportsRemoteControl bool `json:"SupportsRemoteControl"`
|
|
HasCustomDeviceName bool `json:"HasCustomDeviceName"`
|
|
SupportedCommands []string `json:"SupportedCommands"`
|
|
ServerID string `json:"ServerId"`
|
|
}
|
|
|
|
type loginResolver interface {
|
|
Resolve(ctx context.Context, combinedUsername, password, userAgent, remoteIP string) (*Session, error)
|
|
}
|
|
|
|
// AuthHandler serves Jellyfin login/current-user routes.
|
|
type AuthHandler struct {
|
|
cfg func() *config.Config
|
|
loginResolver loginResolver
|
|
authenticator *Authenticator
|
|
}
|
|
|
|
// NewAuthHandler creates a new auth handler. The config provider is invoked
|
|
// per request so compat setting changes apply without restart.
|
|
func NewAuthHandler(cfg func() *config.Config, loginResolver loginResolver, authenticator *Authenticator) *AuthHandler {
|
|
return &AuthHandler{
|
|
cfg: cfg,
|
|
loginResolver: loginResolver,
|
|
authenticator: authenticator,
|
|
}
|
|
}
|
|
|
|
// HandlePublicUsers serves GET /Users/Public.
|
|
func (h *AuthHandler) HandlePublicUsers(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, []any{})
|
|
}
|
|
|
|
// HandleAuthenticateByName serves POST /Users/AuthenticateByName.
|
|
func (h *AuthHandler) HandleAuthenticateByName(w http.ResponseWriter, r *http.Request) {
|
|
var req authenticateByNameRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "BadRequest", "Invalid request body")
|
|
return
|
|
}
|
|
|
|
password := req.Pw
|
|
if password == "" {
|
|
password = req.Password
|
|
}
|
|
if req.Username == "" || password == "" {
|
|
writeError(w, http.StatusBadRequest, "BadRequest", "Username and password are required")
|
|
return
|
|
}
|
|
|
|
session, err := h.loginResolver.Resolve(r.Context(), req.Username, password, r.UserAgent(), clientip.FromContext(r.Context()))
|
|
if err != nil {
|
|
status, code, message := mapLoginError(err)
|
|
writeError(w, status, code, message)
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, authenticateByNameResponse{
|
|
AccessToken: session.Token,
|
|
ServerID: h.cfg().JellyfinCompat.ServerID,
|
|
User: h.userDTO(session),
|
|
SessionInfo: h.sessionInfo(session),
|
|
})
|
|
}
|
|
|
|
// HandleCurrentUser serves GET /Users/Me.
|
|
func (h *AuthHandler) HandleCurrentUser(w http.ResponseWriter, r *http.Request) {
|
|
session := SessionFromContext(r.Context())
|
|
if session == nil {
|
|
writeError(w, http.StatusUnauthorized, "Unauthorized", "Missing authentication token")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, h.userDTO(session))
|
|
}
|
|
|
|
// HandleUsers serves GET /Users.
|
|
//
|
|
// Jellyfin's user-list endpoint accepts any authenticated caller (including an
|
|
// API key) and is what Tunarr probes to verify an API-key connection (the key
|
|
// has no "me"). Silo separates login accounts from household profiles and is
|
|
// multi-account, so we return only the caller's own user as a single-element
|
|
// list rather than enumerating every account's profiles — listing all users
|
|
// would leak identities across households.
|
|
func (h *AuthHandler) HandleUsers(w http.ResponseWriter, r *http.Request) {
|
|
session := SessionFromContext(r.Context())
|
|
if session == nil {
|
|
writeError(w, http.StatusUnauthorized, "Unauthorized", "Missing authentication token")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, []userDTOResponse{h.userDTO(session)})
|
|
}
|
|
|
|
// HandleUserByID serves GET /Users/{id}.
|
|
func (h *AuthHandler) HandleUserByID(w http.ResponseWriter, r *http.Request) {
|
|
session := SessionFromContext(r.Context())
|
|
if session == nil {
|
|
writeError(w, http.StatusUnauthorized, "Unauthorized", "Missing authentication token")
|
|
return
|
|
}
|
|
|
|
if chi.URLParam(r, "id") != session.PseudoUserID.String() {
|
|
writeError(w, http.StatusNotFound, "NotFound", "User not found")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, h.userDTO(session))
|
|
}
|
|
|
|
// HandleLogout serves POST /Sessions/Logout.
|
|
func (h *AuthHandler) HandleLogout(w http.ResponseWriter, r *http.Request) {
|
|
token, ok := ExtractToken(r)
|
|
if !ok {
|
|
writeError(w, http.StatusUnauthorized, "Unauthorized", "Missing authentication token")
|
|
return
|
|
}
|
|
h.authenticator.sessions.Delete(token)
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *AuthHandler) userDTO(session *Session) userDTOResponse {
|
|
name := session.Username
|
|
|
|
return userDTOResponse{
|
|
ID: session.PseudoUserID.String(),
|
|
Name: name,
|
|
ServerID: h.cfg().JellyfinCompat.ServerID,
|
|
HasPassword: true,
|
|
HasConfiguredPassword: true,
|
|
HasConfiguredEasyPassword: false,
|
|
Policy: userPolicyResponse{
|
|
IsAdministrator: false,
|
|
IsHidden: false,
|
|
EnableCollectionManagement: false,
|
|
EnableSubtitleManagement: false,
|
|
EnableLyricManagement: false,
|
|
IsDisabled: false,
|
|
EnableUserPreferenceAccess: true,
|
|
EnableRemoteControlOfOtherUsers: false,
|
|
EnableSharedDeviceControl: false,
|
|
EnableRemoteAccess: true,
|
|
EnableLiveTVManagement: false,
|
|
EnableLiveTVAccess: false,
|
|
EnableMediaPlayback: true,
|
|
EnableAudioPlaybackTranscoding: true,
|
|
EnableVideoPlaybackTranscoding: true,
|
|
EnablePlaybackRemuxing: true,
|
|
ForceRemoteSourceTranscoding: false,
|
|
EnableContentDeletion: false,
|
|
EnableContentDownloading: true,
|
|
EnableSyncTranscoding: false,
|
|
EnableMediaConversion: false,
|
|
EnableAllDevices: true,
|
|
EnableAllChannels: false,
|
|
EnableAllFolders: true,
|
|
InvalidLoginAttemptCount: 0,
|
|
LoginAttemptsBeforeLockout: 0,
|
|
MaxActiveSessions: 0,
|
|
EnablePublicSharing: false,
|
|
RemoteClientBitrateLimit: 0,
|
|
AuthenticationProviderID: "silo-local",
|
|
PasswordResetProviderID: "silo-local",
|
|
SyncPlayAccess: "None",
|
|
},
|
|
Configuration: userConfigurationResponse{
|
|
PlayDefaultAudioTrack: true,
|
|
DisplayMissingEpisodes: false,
|
|
GroupedFolders: []string{},
|
|
SubtitleMode: "Smart",
|
|
DisplayCollectionsView: true,
|
|
EnableLocalPassword: false,
|
|
OrderedViews: []string{},
|
|
LatestItemsExcludes: []string{},
|
|
MyMediaExcludes: []string{},
|
|
HidePlayedInLatest: false,
|
|
RememberAudioSelections: true,
|
|
RememberSubtitleSelections: true,
|
|
EnableNextEpisodeAutoPlay: true,
|
|
},
|
|
}
|
|
}
|
|
|
|
func (h *AuthHandler) sessionInfo(session *Session) *sessionInfoResponse {
|
|
name := session.ProfileName
|
|
if name == "" {
|
|
name = session.Username
|
|
}
|
|
now := time.Now().UTC().Format(time.RFC3339Nano)
|
|
|
|
return &sessionInfoResponse{
|
|
PlayableMediaTypes: []string{},
|
|
UserID: session.PseudoUserID.String(),
|
|
UserName: name,
|
|
LastActivityDate: now,
|
|
LastPlaybackCheckIn: now,
|
|
IsActive: true,
|
|
SupportsMediaControl: true,
|
|
SupportsRemoteControl: true,
|
|
HasCustomDeviceName: false,
|
|
SupportedCommands: []string{},
|
|
ServerID: h.cfg().JellyfinCompat.ServerID,
|
|
}
|
|
}
|