Documentation
¶
Overview ¶
Package subflux is the application's wire and domain type vocabulary.
It is named for the app because that is what it holds: the nouns every other package speaks in. Read at a use site, the qualifier says which vocabulary a type belongs to — subflux.Subtitle, subflux.SearchRequest, subflux.MediaType, subflux.ProviderID.
Every declaration is a type, a constant, or a method on one of this package's own types. There are no interfaces, no free functions, and no behaviour over the world. A consumer that needs a contract declares it at its own site, sized to what it calls; behaviour lives in the package named for the job it does.
The package imports no subflux package at all — only errors, fmt and time, plus cplieger/auth for the user and session types the auth response bodies carry. Implementation packages import it, never the reverse, and that acyclicity is what the package is for.
Two of its contents are a published contract rather than an internal detail. The constants of the enums wirespec registers (ErrorCode, JobOutcome) and every json-tagged struct here are discovered by internal/wirespec and emitted as TypeScript, so a type that leaves or a field that is renamed changes a cross-language contract. SchemaFunc is a func type, and the one contract-shaped declaration still here.
Index ¶
- Constants
- Variables
- type AdaptiveConfig
- type AdminUserCreatedResponse
- type ArrConfig
- type AudioRuleJSON
- type AuthError
- type BackoffEntry
- type BackoffParams
- type CleanupResult
- type ConfigDrift
- type DownloadMeta
- type DownloadRecord
- type DownloadedRef
- type EmbeddedPolicy
- type EmbeddedTrack
- type ErrorCode
- type JobOutcome
- type KeyGenerated
- type LangOutcome
- type LangOutcomeKind
- type LanguageRulesJSON
- type LogFormat
- type LogLevel
- type LoginSuccess
- type ManualLockEntry
- type ManualLockKey
- type MatchMethod
- type MatchSet
- type MeResponse
- type MediaType
- type PasskeyRegistered
- type PollKey
- type PostProcessConfig
- type ProviderAuthRecord
- type ProviderCfg
- type ProviderID
- type ProviderSchema
- type ProviderSchemaField
- type ProviderStatus
- type ProvidersResponse
- type RateLimitError
- type ReconcileResult
- type ScanOutcome
- type ScanRecord
- type ScanStateRow
- type ScanStats
- type SchemaField
- type SchemaFunc
- type SchemaOption
- type SchemaSection
- type ScorePreview
- type ScoreResult
- type ScoreTier
- type ScoredResult
- type Scores
- type SearchConfig
- type SearchRequest
- type SearchResult
- type SearchTarget
- type SearchTargets
- type SetupStatus
- type ShowSubtitleQuery
- type StateEntry
- type StatePage
- type StateQuery
- type Stats
- type StatusResponse
- type Subtitle
- type SubtitleCue
- type SubtitleEntry
- type SubtitleFile
- type SubtitleInfo
- type SubtitleSource
- type SubtitleTargJSON
- type SubtitleTarget
- type SyncConfig
- type Variant
- type VideoInfo
- type WebAuthnAvailability
- type WebAuthnUnavailableReason
- type WebAuthnUnknownCredentialResponse
Constants ¶
const ( VariantStandard Variant = "standard" DefaultVariant = VariantStandard VariantHI Variant = "hi" VariantForced Variant = "forced" // VariantAliasSDH is the alternative name for HI subtitles used in external // subtitle filenames and provider metadata. VariantAliasSDH = "sdh" // VariantAliasForeign is the alternative name for forced subtitles used in // external subtitle filenames and provider metadata. VariantAliasForeign = "foreign" )
Subtitle variant identifiers. Shared across api, search, server, and cli so the auto and manual download paths agree on a single vocabulary.
const DefaultDownloadMaxAttempts = 3
DefaultDownloadMaxAttempts is the fallback number of download attempts per search when the config value is zero.
const DefaultManualProviderTimeout = 30 * time.Second
DefaultManualProviderTimeout is the per-provider search timeout for manual searches (the /api/search path, which also serves the remote CLI's search subcommand).
const DefaultProviderConcurrency = 4
DefaultProviderConcurrency is the default maximum number of parallel provider searches when the config value is zero.
const DefaultProviderPriority = 99
DefaultProviderPriority is used when no priority is configured for a provider.
const DefaultSyncMinConfidence = 0.6
DefaultSyncMinConfidence is the default minimum confidence for auto-sync to be applied. Used by config and syncing packages.
const KeyStatus = "status"
KeyStatus is the canonical JSON key for operation result status responses (StatusResponse is the typed carrier). Used by server, scanning, and confighandlers for the handful of status bodies still built as a map.
const MaxSafeFileBytes = 10 << 20
MaxSafeFileBytes is the maximum file size (10 MB) for config files, subtitle files, and other user-supplied payloads. Prevents OOM from oversized or malicious inputs. Shared across config, subsync, and provider packages.
Variables ¶
var DefaultScores = Scores{
Hash: 100,
Source: 28,
ReleaseGroup: 23,
StreamingService: 14,
VideoCodec: 10,
HDR: 8,
Edition: 15,
SeasonPack: 15,
}
DefaultScores for release attribute matching.
Movie (98): source=28, release_group=23, streaming_service=14, edition=15, video_codec=10, hdr=8. Episode (98): source=28, release_group=23, streaming_service=14, season_pack=15, video_codec=10, hdr=8.
Hash match = 100 directly, bypasses attribute scoring.
var ErrSubtitleAbsent = errors.New("subtitle absent upstream")
ErrSubtitleAbsent reports that the upstream no longer holds the subtitle a search result named: the file the ID points at is gone (an expired listing, a withdrawn upload, a retired mirror path). It is a normal outcome of a download, not a fault of the provider or of subflux, and it is the one download failure an operator should read as "search again later", not as "this provider is broken".
It exists because absence used to be reported as a successful download of zero bytes, which the callers then rejected as an empty or invalid payload — so a withdrawn upload and a provider serving corrupt data produced the same operator-visible message. Providers return it wrapped with their own name.
Functions ¶
This section is empty.
Types ¶
type AdaptiveConfig ¶
type AdaptiveConfig struct {
InitialDelay time.Duration
MaxDelay time.Duration
BackoffMultiplier float64
MaxAttempts int
Enabled bool
}
AdaptiveConfig controls adaptive search backoff.
type AdminUserCreatedResponse ¶
type AdminUserCreatedResponse struct {
Username string `json:"username"`
Email string `json:"email"`
Role auth.Role `json:"role"`
ID int64 `json:"id"`
}
AdminUserCreatedResponse is the JSON response after admin creates a user.
type AudioRuleJSON ¶
type AudioRuleJSON struct {
Audio string `json:"audio"`
Subtitles []SubtitleTargJSON `json:"subtitles"`
}
AudioRuleJSON is a JSON-friendly audio rule.
type AuthError ¶
type AuthError struct{ Msg string }
AuthError indicates invalid or expired credentials.
type BackoffEntry ¶
type BackoffEntry struct {
LastTried time.Time `json:"last_tried"`
NextRetry time.Time `json:"next_retry"`
MediaType MediaType `json:"media_type"`
MediaID string `json:"media_id"`
Language string `json:"language"`
Provider ProviderID `json:"provider"`
Failures int `json:"failures"`
}
BackoffEntry represents an item in adaptive search backoff.
type BackoffParams ¶
BackoffParams groups adaptive backoff configuration for RecordNoResult.
type CleanupResult ¶
type CleanupResult struct {
// Paths are subtitle file paths whose DB entries were removed.
// The caller is responsible for validating and deleting files from disk.
Paths []string
}
CleanupResult holds the outcome of a media cleanup operation. Used by both DeleteStateByPaths and ReconcileState.
type ConfigDrift ¶
type ConfigDrift struct {
// RemovedLanguages are language codes that were in the old config
// but not in the new one. Their search_attempts should be cleared.
RemovedLanguages []string
// RemovedProviders are provider names that were enabled in the old
// config but disabled or removed in the new one. Their
// search_attempts should be cleared.
RemovedProviders []ProviderID
// AdaptiveDisabled is true when adaptive search was enabled in the
// old config but disabled in the new one. All search_attempts
// should be cleared.
AdaptiveDisabled bool
}
ConfigDrift describes DB cleanup actions needed after a config change.
func (*ConfigDrift) Empty ¶
func (d *ConfigDrift) Empty() bool
Empty returns true if no cleanup is needed.
type DownloadMeta ¶
type DownloadMeta struct {
Title string
ImdbID string
VideoPath string // Path to the video file (for reconciliation and upgrades).
Season int
Episode int
Manual bool // True if user manually selected this subtitle.
}
DownloadMeta holds optional metadata for a subtitle state record.
type DownloadRecord ¶
type DownloadRecord struct {
Meta *DownloadMeta
MediaType MediaType
MediaID string
Language string
Variant Variant // subtitle variant (standard/hi/forced); empty is normalized to standard
ProviderName ProviderID
ReleaseName string
Path string
Score int
}
DownloadRecord groups the parameters for Store.SaveDownload. Using a named struct (rather than positional string arguments) makes call sites self-documenting and prevents silent swaps of same-typed fields like Language/ProviderName.
type DownloadedRef ¶
type DownloadedRef struct {
ReleaseName string
Provider ProviderID
}
DownloadedRef identifies a previously-downloaded subtitle by its release name and provider. Returned by Store.DownloadedRefs to mark matching entries in the manual search popup as already on disk.
type EmbeddedPolicy ¶
type EmbeddedPolicy struct {
// IgnorePGS excludes PGS bitmap subs (Blu-ray) from target satisfaction.
IgnorePGS bool
// IgnoreVobSub excludes VobSub bitmap subs (DVD) from target satisfaction.
IgnoreVobSub bool
// IgnoreASS excludes ASS/SSA styled subs (anime) from target satisfaction.
IgnoreASS bool
}
EmbeddedPolicy is the typed search policy for embedded subtitle codecs, resolved from the top-level embedded_subtitles config section. The detector always returns every normalized track; this policy decides which codecs count as "present but not usable" for target satisfaction (they stay visible in coverage but trigger external search).
type EmbeddedTrack ¶
EmbeddedTrack represents a subtitle track detected inside a video container.
type ErrorCode ¶
type ErrorCode string
ErrorCode is the machine-readable code carried in the JSON error envelope. A defined type (not an alias) so the wire generator discovers the catalog as a TS string-union; one-off codes still pass as string literals (untyped constants convert).
const ( CodeBadRequest ErrorCode = "bad_request" CodeForbidden ErrorCode = "forbidden" CodeNotFound ErrorCode = "not_found" CodeMethodNotAllowed ErrorCode = "method_not_allowed" CodeConflict ErrorCode = "conflict" CodeRateLimited ErrorCode = "rate_limited" CodeBadGateway ErrorCode = "bad_gateway" CodeInternalError ErrorCode = "internal_error" )
Generic codes (status mapped 1:1).
const ( CodeAuthInvalidCredentials ErrorCode = "auth_invalid_credentials" CodeAuthAccountDisabled ErrorCode = "auth_account_disabled" CodeAuthSessionInvalid ErrorCode = "auth_session_invalid" CodeAuthSessionRequired ErrorCode = "auth_session_required" CodeAuthRoleRequired ErrorCode = "auth_role_required" )
Auth codes.
const ( CodeWebAuthnSessionInvalid ErrorCode = "webauthn_session_invalid" CodeWebAuthnRegisterFailed ErrorCode = "webauthn_register_failed" CodeWebAuthnNotDiscoverable ErrorCode = "webauthn_not_discoverable" CodeWebAuthnAssertionFailed ErrorCode = "webauthn_assertion_failed" CodeWebAuthnUnsupportedOrigin ErrorCode = "webauthn_unsupported_origin" CodeWebAuthnUnconfigured ErrorCode = "webauthn_unconfigured" )
WebAuthn codes.
const ( CodeOIDCStateInvalid ErrorCode = "oidc_state_invalid" CodeOIDCExchangeFailed ErrorCode = "oidc_exchange_failed" )
OIDC codes.
const ( CodeConfigInvalid ErrorCode = "config_invalid" CodeConfigUnreachableArr ErrorCode = "config_unreachable_arr" CodeConfigTooLarge ErrorCode = "config_too_large" CodeConfigReloadFailed ErrorCode = "config_reload_failed" )
Config codes.
const ( CodeScanInProgress ErrorCode = "scan_in_progress" CodeSearchProviderDisabled ErrorCode = "search_provider_disabled" // CodeMediaUnwritable: a media folder the work would write into failed // its write test, so nothing was started. CodeMediaUnwritable ErrorCode = "media_unwritable" )
Scan / search / manual ops codes.
const ( CodePathNotAllowed ErrorCode = "path_not_allowed" CodeMediaNotFound ErrorCode = "media_not_found" CodeSubtitleNotFound ErrorCode = "subtitle_not_found" CodeSyncUnsupportedFormat ErrorCode = "sync_unsupported_format" // CodeSubtitleExtensionNotAllowed is the 409 a delete answers when the // target's extension lacks the delete capability in the subtitle // extension authority (a server-derived stored-state disagreement, not // caller authorization — hence 409, not 403). CodeSubtitleExtensionNotAllowed ErrorCode = "subtitle_extension_not_allowed" )
File / preview / sync codes.
const (
CodeArrUnreachable ErrorCode = "arr_unreachable"
)
Provider / arr action codes.
const (
CodeQueryInvalidFilter ErrorCode = "query_invalid_filter"
)
Query codes.
const (
CodeSetupAlreadyComplete ErrorCode = "setup_already_complete"
)
Setup codes.
type JobOutcome ¶ added in v0.5.0
type JobOutcome string
JobOutcome names how a done sync job ended, mirroring the typed core's vocabulary. It lives here rather than beside the dispatcher because it crosses a one-way seam: syncjobs.Job serves it on GET /api/sync/jobs and events.SyncDoneEvent carries it on sync:done, and syncjobs imports events (the publish seam), so neither of those two can own it.
const ( JobResult JobOutcome = "result" JobTimeout JobOutcome = "timeout" JobCancelled JobOutcome = "cancelled" JobCrash JobOutcome = "crash" )
Sync job outcomes (meaningful only in the done state).
type KeyGenerated ¶
type KeyGenerated struct {
CreatedAt time.Time `json:"created_at"`
Key string `json:"key"`
KeyPrefix string `json:"key_prefix"`
KeySuffix string `json:"key_suffix"`
Label string `json:"label"`
ID int64 `json:"id"`
}
KeyGenerated is the JSON response after generating an API key.
type LangOutcome ¶
type LangOutcome struct {
Lang string // ISO 639-1 language code
Kind LangOutcomeKind // what happened for this language group
Paths []string // subtitle files downloaded for this language
Searched int // variant targets processed against provider results
// Queried counts the provider queries the group's single sweep actually
// issued (successful or erroring; providers skipped by the health
// timeout never sent a request and don't count). Zero for skipped and
// backed-off groups. Distinct from Searched, which counts VARIANT
// targets processed against results and stays positive even when the
// sweep issued no query (every eligible provider timed out).
Queried int
// Answered counts the providers that answered the sweep without error.
// Zero on a searched group means the sweep observed nothing.
Answered int
// Failed counts variant targets that had candidates and saved none.
Failed int
// WriteBlocked counts variant targets skipped or stopped because their
// folder refuses writes. Not a failure of the item: no evidence, no
// backoff and no resume stamp.
WriteBlocked int
}
LangOutcome is the typed per-language result of a SearchTargets call. It replaces the former parallel FoundLangs/SearchedLangs slices and aggregate counters: each language carries its own classification and evidence, so consumers (season tracker, scan stats, coverage events) read one structure instead of reconstructing sets from slice pairs.
func (*LangOutcome) Found ¶
func (o *LangOutcome) Found() bool
Found reports whether at least one subtitle was downloaded for the language.
type LangOutcomeKind ¶
type LangOutcomeKind string
LangOutcomeKind classifies what happened for one language group in a SearchTargets call. Exactly one kind applies per language.
const ( // LangSearched: providers were actually queried for this language. LangSearched LangOutcomeKind = "searched" // LangSkipped: nothing needed a search (covered on disk, manually // locked, or not eligible for upgrade). LangSkipped LangOutcomeKind = "skipped" // LangBackedOff: the language needed a search but every provider was in // adaptive backoff, so no query ran. Distinct from both other kinds; it // must never feed no-result evidence into the season tracker. LangBackedOff LangOutcomeKind = "backed_off" // LangWriteBlocked: the language needed a search but the item's folder // refuses writes, so no query ran. LangWriteBlocked LangOutcomeKind = "write_blocked" )
Language-group outcome kinds.
type LanguageRulesJSON ¶
type LanguageRulesJSON struct {
Rules []AudioRuleJSON `json:"rules,omitempty"`
Default []SubtitleTargJSON `json:"default,omitempty"`
}
LanguageRulesJSON is the language rules in a JSON-serializable format for the settings UI.
type LoginSuccess ¶
type LoginSuccess struct {
Redirect string `json:"redirect"`
User MeResponse `json:"user"`
}
LoginSuccess is the JSON response after successful login.
type ManualLockEntry ¶
type ManualLockEntry struct {
// The key is embedded untagged, so encoding/json promotes its four fields
// and the entry marshals FLAT — the wire shape stays the five fields it
// has always been (wiregen applies the same promotion rules).
ManualLockKey
Count int `json:"count"`
}
ManualLockEntry represents a manually locked media+language+variant quad: the quad the lock lives on plus that quad's manual-row count.
type ManualLockKey ¶
type ManualLockKey struct {
MediaType MediaType `json:"media_type"`
MediaID string `json:"media_id"`
Language string `json:"language"`
Variant Variant `json:"variant"`
}
ManualLockKey addresses one manual-override lock: the (media_type, media_id, language, variant) quad the lock lives on. Passing the quad as a named struct rather than four positional arguments keeps MediaID and Language — two adjacent strings — from being silently transposed at a call site, which would compile and address the wrong lock.
An empty Variant is a WILDCARD, and what it means is per method, not per type: IsManuallyLocked, ClearManualLock and ManualSubtitlePaths read it as "any/all variants of the language", while ManualDownloadCount and NextManualNumber require an exact variant (a lock count and an ordinal sequence are both per variant). Each method's doc on Store states which it is.
The json tags serve ManualLockEntry, which embeds this type and must keep marshalling the quad flat under its established wire names.
type MatchMethod ¶
type MatchMethod string
MatchMethod is a typed string identifying how a subtitle was matched to the requested media. Use the exported constants rather than raw string literals. Follows the same pattern as MediaType and AuthMethod.
const ( MatchByHash MatchMethod = "hash" MatchByIMDB MatchMethod = "imdb" MatchByTitle MatchMethod = "title" MatchByTVDB MatchMethod = "tvdb" MatchByTMDB MatchMethod = "tmdb" )
Match method constants. Canonical source for all packages.
type MatchSet ¶
type MatchSet struct {
Hash bool
Source bool
ReleaseGroup bool
StreamingService bool
VideoCodec bool
HDR bool
Edition bool
SeasonPack bool
SeriesIMDB bool
IMDB bool
}
MatchSet tracks which attributes matched between a subtitle and a video. Each field corresponds to a release attribute; struct fields make invalid keys impossible at compile time.
type MeResponse ¶
type MeResponse struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Role auth.Role `json:"role"`
ID int64 `json:"id"`
HasPasskeys bool `json:"has_passkeys"`
OIDCLinked bool `json:"oidc_linked"`
HasPassword bool `json:"has_password"`
CanLinkOIDC bool `json:"can_link_oidc"`
}
MeResponse is the JSON response for GET /api/auth/me.
type MediaType ¶
type MediaType string
MediaType is a typed string identifying the kind of media being searched. Use the exported constants rather than raw string literals.
Media type constants used by SearchRequest.MediaType and related helpers. Canonical source for all packages; import from here instead of declaring local unexported copies.
type PasskeyRegistered ¶
type PasskeyRegistered struct {
CreatedAt time.Time `json:"created_at"`
Name string `json:"name"`
Transport string `json:"transport"`
ID int64 `json:"id"`
}
PasskeyRegistered is the JSON response after successful passkey registration.
type PollKey ¶
type PollKey string
PollKey identifies an arr-source poll-timestamp row in the store. Using a typed string instead of bare string prevents typo-induced silent failures (e.g. "Sonarr" capitalization or "sonar" typo would silently insert a new row and force history re-fetch).
Canonical poll-key values. New arr sources should add a constant here.
type PostProcessConfig ¶
type PostProcessConfig struct {
StripHI bool `json:"strip_hi"`
StripTags bool `json:"strip_tags"`
NormalizeUTF8 bool `json:"normalize_utf8"`
CleanWhitespace bool `json:"clean_whitespace"`
NormalizeEndings bool `json:"normalize_endings"`
RemoveEmpty bool `json:"remove_empty"`
}
PostProcessConfig controls subtitle post-processing.
type ProviderAuthRecord ¶ added in v0.6.6
type ProviderAuthRecord struct {
LastFailureAt time.Time `json:"last_failure_at"`
NextAttemptAt time.Time `json:"next_attempt_at"`
DisabledAt time.Time `json:"disabled_at"`
Provider ProviderID `json:"provider"`
Fingerprint string `json:"fingerprint"`
LastError string `json:"last_error"`
FailedOps []string `json:"failed_ops"`
Failures int `json:"failures"`
}
ProviderAuthRecord is one provider's persisted credential-failure state, the provider_auth bucket value. Fingerprint is an Argon2id PHC hash of the provider's canonical settings, never the settings themselves; LastError is provider error text that was already redacted and sanitized. A zero DisabledAt means the provider is not disabled.
type ProviderCfg ¶
type ProviderCfg struct {
Settings map[string]any
Priority int // Lower = higher trust. 0 means unset (defaults to 99).
Enabled bool
}
ProviderCfg is a generic provider configuration block.
type ProviderID ¶
type ProviderID string
ProviderID is a typed string identifying a subtitle provider. Use this instead of raw strings when passing provider names to metrics, backoff, and other subsystems that key on provider identity.
const ( ProviderNameSynthetic ProviderID = "synthetic" ProviderNameHDBits ProviderID = "hdbits" ProviderNameOpenSubtitles ProviderID = "opensubtitles" ProviderNameSubSource ProviderID = "subsource" ProviderNameAnimeTosho ProviderID = "animetosho" ProviderNameYifySubtitles ProviderID = "yifysubtitles" ProviderNameSubDL ProviderID = "subdl" ProviderNameBetaSeries ProviderID = "betaseries" ProviderNameGestdown ProviderID = "gestdown" )
Provider name constants (canonical SSOT). All packages MUST reference these instead of declaring local string literals.
type ProviderSchema ¶
type ProviderSchema struct {
Name string `json:"name"`
Label string `json:"label"`
Settings []SchemaField `json:"settings,omitempty"`
// ConnTest marks a provider whose implementation can validate its
// credentials without searching, so the settings dialog and the setup
// wizard render a test control on its card. The provider-section twin of
// SchemaSection.ConnTest, keyed by Name the way that one is keyed by Key.
ConnTest bool `json:"conn_test,omitempty"`
}
ProviderSchema describes a single provider's settings fields.
type ProviderSchemaField ¶
type ProviderSchemaField struct {
Key string `json:"key"`
Label string `json:"label"`
Type string `json:"type"` // text, secret, bool
Default string `json:"default,omitempty"`
Help string `json:"help,omitempty"`
Secret bool `json:"secret,omitempty"`
}
ProviderSchemaField describes a single provider setting for the UI schema.
type ProviderStatus ¶
type ProviderStatus struct {
LastError string `json:"last_error,omitempty"`
DisabledReason string `json:"disabled_reason,omitempty"`
RejectedSettings []string `json:"rejected_settings,omitempty"`
CooldownRemaining time.Duration `json:"cooldown_remaining,omitempty"`
PausedFor time.Duration `json:"paused_for,omitempty"`
RecentFailures int `json:"recent_failures"`
Threshold int `json:"threshold"`
AuthFailures int `json:"auth_failures,omitempty"`
TimedOut bool `json:"timed_out"`
Disabled bool `json:"disabled"`
}
ProviderStatus is one provider's callability: the health tracker's timeout (TimedOut, CooldownRemaining, RecentFailures, Threshold, LastError) and the credential gate's disable, rate-limit pause and rejected optional settings.
type ProvidersResponse ¶
type ProvidersResponse struct {
Providers map[ProviderID]ProviderStatus `json:"providers"`
Enabled bool `json:"enabled"`
}
ProvidersResponse is the JSON response for GET /api/providers/timeout.
type RateLimitError ¶
RateLimitError indicates the provider's rate limit was exceeded. RetryAfter, when non-zero, is the hint from the upstream's Retry-After header (delta-seconds or HTTP-date resolved to a positive duration). Consumers may use it to schedule the next attempt; a zero value means no hint was provided.
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
type ReconcileResult ¶
type ReconcileResult struct {
// Deleted contains subtitle paths removed because the video is gone.
Deleted CleanupResult
// ResetCount is the number of entries reset for re-search because
// the subtitle file was missing but the video still exists.
ResetCount int64
}
ReconcileResult holds the outcome of a state reconciliation pass.
type ScanOutcome ¶
type ScanOutcome string
ScanOutcome is a typed string for scan result classification. Canonical source; scanning/ and server/ should import from here.
const ( ScanFound ScanOutcome = "found" ScanSkipped ScanOutcome = "skipped" ScanNoResult ScanOutcome = "none" // ScanBackedOff means every language target that needed a search had all // of its providers in adaptive backoff, so no provider was queried at // all. Distinct from ScanNoResult ("we looked, nothing found") and // ScanSkipped ("nothing needed a search"): "we already know there is // probably nothing, so we didn't look". Never recorded in the season // early-termination tracker and counted in its own stats bucket. ScanBackedOff ScanOutcome = "backed_off" // ScanDownloadFailed means candidates were found and none was saved. // Neither a found nor a no-result: it never feeds the season tracker. ScanDownloadFailed ScanOutcome = "download_failed" // ScanWriteBlocked means nothing was saved because the item's folder // refuses writes. A fact about the folder, so nothing is recorded // against the item. ScanWriteBlocked ScanOutcome = "write_blocked" )
Scan outcome constants.
type ScanRecord ¶
type ScanRecord struct {
MediaType MediaType
MediaID string
Title string
AudioLang string
Season int
Episode int
// Searched records whether provider work actually ran to completion for
// this stamp. False for inventory-only visits (scan skip paths record
// coverage without searching); the resume set and staleness displays can
// distinguish "we looked at the disk" from "we searched providers".
Searched bool
}
ScanRecord groups the parameters for CoverageStore.RecordScanState.
type ScanStateRow ¶
type ScanStateRow struct {
ScannedAt string `json:"scanned_at"`
MediaID string `json:"media_id"`
Title string `json:"title"`
AudioLang string `json:"audio_lang"`
Season int `json:"season,omitempty"`
Episode int `json:"episode,omitempty"`
// Searched is false for inventory-only stamps (scan skip paths that
// recorded coverage without provider work).
Searched bool `json:"searched"`
}
ScanStateRow records when a media item was last scanned.
type ScanStats ¶
type ScanStats struct {
// Post-scan outcomes for episodes. EpisodesSearched counts every episode
// the scan loop processed (it drives progress reporting); the other
// fields are its per-outcome buckets.
EpisodesSearched int // Episodes processed by the scan loop.
EpisodesSkipped int // Episodes with existing subs (no search needed).
EpisodesFound int // Episodes where a subtitle was downloaded.
EpisodesNoResult int // Episodes searched but no subtitle found.
EpisodesBackedOff int // Episodes where every needed provider was in adaptive backoff (no query ran).
// Episodes with candidates of which none was saved.
EpisodesDownloadFailed int
// Episodes skipped or stopped because their folder refuses writes.
EpisodesWriteBlocked int
SeriesSkipped int // Series skipped by show-level pre-check.
// Post-scan outcomes for movies.
MoviesSearched int
MoviesSkipped int
MoviesFound int
MoviesNoResult int
MoviesBackedOff int
MoviesDownloadFailed int
MoviesWriteBlocked int
}
ScanStats tracks scan progress and outcomes for logging.
type SchemaField ¶
type SchemaField struct {
Key string `json:"key"`
Label string `json:"label"`
Type string `json:"type"`
Default string `json:"default,omitempty"`
Help string `json:"help,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Min string `json:"min,omitempty"`
Max string `json:"max,omitempty"`
ShowWhen string `json:"show_when,omitempty"`
Requires string `json:"requires,omitempty"`
Group string `json:"group,omitempty"`
Fields []SchemaField `json:"fields,omitempty"`
Options []SchemaOption `json:"options,omitempty"`
Secret bool `json:"secret,omitempty"`
Required bool `json:"required,omitempty"`
}
SchemaField describes a single configuration field for the UI.
type SchemaFunc ¶
type SchemaFunc func(providers []ProviderSchema) []SchemaSection
SchemaFunc returns the full configuration schema for the UI.
type SchemaOption ¶
SchemaOption is a value+label pair for select fields.
type SchemaSection ¶
type SchemaSection struct {
Key string `json:"key"`
Title string `json:"title"`
Type string `json:"type"`
Help string `json:"help,omitempty"`
RequiredGroup string `json:"required_group,omitempty"`
EnableKey string `json:"enable_key,omitempty"`
Fields []SchemaField `json:"fields,omitempty"`
Providers []ProviderSchema `json:"providers,omitempty"`
// ConnTest marks a section that reaches a remote service and can be
// tested before saving: the settings dialog and the setup wizard render a
// "Test connection" control for it, keyed by the section's own Key. It is
// schema data for the same reason EnableKey is — which sections get which
// controls is the schema's job, not a key comparison inside a renderer.
ConnTest bool `json:"conn_test,omitempty"`
}
SchemaSection describes a top-level config section.
type ScorePreview ¶
type ScorePreview struct {
Tier ScoreTier `json:"tier"`
Score int `json:"score"`
ScoreNoHash int `json:"score_no_hash"`
}
ScorePreview is the JSON response for POST /api/score/preview.
type ScoreResult ¶
type ScoreResult struct {
Tier ScoreTier // Quality tier label (excellent/good/acceptable/minimal/none).
Score int // Final score including hash match bonus.
ScoreNoHash int // Score from release attributes only, excluding hash match.
}
ScoreResult holds the output of a score simulation.
type ScoredResult ¶
type ScoredResult struct {
Matches map[string]int // Per-category score contributions.
Sub Subtitle
Score int
}
ScoredResult is a scored subtitle for use by the manual search and CLI APIs.
type Scores ¶
type Scores struct {
Hash int `json:"hash" yaml:"hash"`
Source int `json:"source" yaml:"source"`
ReleaseGroup int `json:"release_group" yaml:"release_group"`
StreamingService int `json:"streaming_service" yaml:"streaming_service"`
VideoCodec int `json:"video_codec" yaml:"video_codec"`
HDR int `json:"hdr" yaml:"hdr"`
Edition int `json:"edition" yaml:"edition"` // movies only
SeasonPack int `json:"season_pack" yaml:"season_pack"` // episodes only
}
Scores defines the weight for each release attribute match type.
Identity fields (series, season, episode, title, year) are not scored here; they are enforced by the provider query (identity gate). Resolution is excluded; its signal is captured by source + release_group.
Movie-only: Edition. For episodes, edition=0 and season_pack takes its place. Applicable non-hash weights sum to 98 for each media type. Hash match bypasses attribute scoring entirely (score = 100).
type SearchConfig ¶
type SearchConfig struct {
ExcludeArrTags []string
ScanInterval time.Duration
ProviderTimeout time.Duration
ScanDelay time.Duration
MinScore int
UpgradeWindowDays int
DownloadMaxAttempts int // Max download attempts per search (0 = default DefaultDownloadMaxAttempts)
MaxProviderConcurrency int // Max parallel provider searches (0 = default DefaultProviderConcurrency)
MaxSSEClients int // Max concurrent SSE connections (0 = default 32)
UpgradeEnabled bool
}
SearchConfig controls search behavior.
type SearchRequest ¶
type SearchRequest struct {
MediaType MediaType // "episode" or "movie"
ImdbID string // IMDB ID; fallback for providers without TMDB/TVDB support
Title string
AlternativeTitles []string // from Sonarr/Radarr alternateTitles
EpisodeTitle string // Episode title from Sonarr (for identity validation across numbering schemes)
ReleaseName string
VideoPath string // Absolute path to the video file (for embedded track detection and sync)
VideoHash string // OpenSubtitles hash
AudioLang string // resolved audio language (for coverage tracking)
Languages []string // ISO 639-1 codes to search for
TmdbID int // Movie TMDB ID from Radarr; 0 for episodes
Year int
Season int // 0 for movies
Episode int // 0 for movies
TvdbID int // Series TVDB ID from Sonarr; 0 for movies
MaxResults int // 0 = provider default (typically one page)
// Alternate episode numbering from Sonarr (0 = not available).
// Scene numbers come from TheXEM; absolute numbers from TVDB.
SceneSeason int
SceneEpisode int
AbsoluteEpisode int
// ForceUpgrade makes the search engine treat all external subtitles
// as eligible for upgrade, regardless of the upgrade_enabled config.
// Set by manual scan triggers (series/season search buttons).
ForceUpgrade bool
}
SearchRequest holds the parameters for a subtitle search across providers.
func (*SearchRequest) MediaLabel ¶
func (r *SearchRequest) MediaLabel() string
MediaLabel returns a human-readable label for log messages. Movies: "Inception (2010)", episodes: "Bleach (2004) - S09E15".
type SearchResult ¶
type SearchResult struct {
// WriteFailure is the first folder fault a save in this call learned (a
// *mediawrite.UnwritableError; read it with errors.As). Nil when targets
// were only skipped for an already-known fault.
WriteFailure error
Langs []LangOutcome // one entry per language group, in target order
CoverageChanged bool // true if RecordSubtitleFiles detected changes on disk
}
SearchResult holds the outcome of a SearchTargets call: one typed entry per language group plus the coverage-inventory flag.
func (*SearchResult) Paths ¶
func (r *SearchResult) Paths() []string
Paths returns every subtitle file downloaded across all language groups.
func (*SearchResult) ProviderQueried ¶
func (r *SearchResult) ProviderQueried() bool
ProviderQueried reports whether at least one provider query was actually issued during the call, across all language groups. This is the inter-item pacing signal: the scan delay exists to space real provider traffic, so an item that touched no provider (fully covered, locked, in adaptive backoff, or with every eligible provider health-timed-out) must not pay it. Deliberately not keyed on TargetsSearched(): that counts variant targets and stays positive even when the sweep sent zero requests.
func (*SearchResult) TargetsBackedOff ¶
func (r *SearchResult) TargetsBackedOff() int
TargetsBackedOff returns the number of language groups that needed a search but had every provider in adaptive backoff.
func (*SearchResult) TargetsFailed ¶ added in v0.6.6
func (r *SearchResult) TargetsFailed() int
TargetsFailed returns the number of variant targets that had candidates and saved none, across all language groups.
func (*SearchResult) TargetsSearched ¶
func (r *SearchResult) TargetsSearched() int
TargetsSearched returns the number of variant targets that ran against provider results across all language groups.
func (*SearchResult) WriteBlocked ¶ added in v0.6.6
func (r *SearchResult) WriteBlocked() int
WriteBlocked returns the number of variant targets skipped or stopped for an unwritable folder, across all language groups.
type SearchTarget ¶
type SearchTarget struct {
MinScore *int `json:"min_score,omitempty"`
Code string `json:"code"`
Variant string `json:"variant"`
Providers []string `json:"providers,omitempty"`
Exclude []string `json:"exclude,omitempty"`
}
SearchTarget describes a single subtitle search target in the API response.
type SearchTargets ¶
type SearchTargets struct {
OrigLang string `json:"orig_lang"`
AudioLangs []string `json:"audio_langs"`
Targets []SearchTarget `json:"targets"`
}
SearchTargets is the JSON response for GET /api/search/targets.
type SetupStatus ¶
type SetupStatus struct {
SetupRequired bool `json:"setup_required"`
ConfigValid bool `json:"config_valid"`
// PasskeyLoginAvailable reports whether a passkey login could succeed on
// this server: a relying party is configured AND at least one stored
// credential could answer a discoverable login. It says nothing about the
// calling page's origin, which a GET cannot know; that half is the
// availability probe's, which takes the origin explicitly.
PasskeyLoginAvailable bool `json:"passkey_login_available"`
}
SetupStatus is the JSON response for GET /api/auth/setup.
type ShowSubtitleQuery ¶
type ShowSubtitleQuery struct {
// ImdbID is the show's IMDb identifier ("tt0903747").
ImdbID string
// Language is the subtitle language, in subflux's internal code space.
Language string
}
ShowSubtitleQuery names the two values a show-level count is taken over. They are both free-form strings that no call site can tell apart by shape, so they are named rather than positional: a transposed pair would query a language as if it were a show and answer zero, which the caller reads as a legitimate "this show has almost no subtitles" and acts on by skipping the whole series.
type StateEntry ¶
type StateEntry struct {
MediaImported time.Time `json:"media_imported"`
Title string `json:"title"`
MediaID string `json:"media_id"`
Language string `json:"language"`
Variant Variant `json:"variant"`
Provider ProviderID `json:"provider"`
Path string `json:"path"`
ReleaseName string `json:"release_name"`
ImdbID string `json:"imdb_id,omitempty"`
MediaType MediaType `json:"media_type"`
ID int64 `json:"id"`
Score int `json:"score"`
Season int `json:"season,omitempty"`
Episode int `json:"episode,omitempty"`
Manual bool `json:"manual"`
}
StateEntry represents a subtitle state record for API responses.
type StatePage ¶ added in v0.6.0
type StatePage struct {
Entries []StateEntry `json:"entries"`
UnfilteredTotal int `json:"unfiltered_total"`
}
StatePage is the GET /api/state response: one page of history rows plus the number of rows the store holds with NO filter applied. The second field is what lets a client tell "nothing matched this filter" from "nothing was ever downloaded"; the rows alone cannot, because the query filters server-side.
type StateQuery ¶
type StateQuery struct {
MediaType MediaType
Language string
Provider ProviderID
Search string
Limit int
Offset int
}
StateQuery groups the filter parameters for Store.State. Using a named struct (rather than positional string/int arguments) makes call sites self-documenting and prevents silent swaps of same-typed fields like Language/Provider/Search.
type Stats ¶
type Stats struct {
LastScan string `json:"last_scan"`
Downloads int `json:"downloads"`
Attempts int64 `json:"attempts"`
ScanIntervalSeconds int `json:"scan_interval_seconds"`
TotalSubs int `json:"total_subs"`
TotalSeries int `json:"total_series"`
TotalMovies int `json:"total_movies"`
MissingSubs int `json:"missing_subs"`
Partial bool `json:"partial"`
}
Stats is the JSON response for GET /api/stats.
type StatusResponse ¶
type StatusResponse struct {
Status string `json:"status"`
}
StatusResponse is the canonical {"status": "..."} operation-result body used by action endpoints (scan triggers, resets, logout).
type Subtitle ¶
type Subtitle struct {
Provider ProviderID
ID string // provider-specific identifier
Language string // ISO 639-1 code
ReleaseName string
DownloadURL string
MatchedBy MatchMethod // how this subtitle was matched (hash, title, imdb, etc.)
Title string // show/movie title from provider (for identity validation)
Season int // season from provider (0 if unknown or movie)
Episode int // episode from provider (0 if unknown or movie)
HearingImp bool
Forced bool
}
Subtitle is a search result returned by a provider.
type SubtitleCue ¶
SubtitleCue represents a single subtitle entry with timing.
type SubtitleEntry ¶
type SubtitleEntry struct {
MediaID string `json:"media_id"`
Language string `json:"language"`
Variant string `json:"variant"`
Source string `json:"source"`
Codec string `json:"codec,omitempty"`
Path string `json:"-"`
VideoPath string `json:"-"`
Score int `json:"score,omitempty"`
Ordinal int `json:"ordinal,omitempty"`
OffsetMs int64 `json:"offset_ms,omitempty"`
}
SubtitleEntry is a subtitle-file row from coverage queries. On the wire it carries NO filesystem paths (S7: clients address files by typed reference, never by path); Path and VideoPath stay populated for in-process consumers (file listing size stat, deletion, reconciliation) but are json-omitted. Ordinal is the manual-sibling number parsed from the row's filename (subtitlefile.ManualOrdinal) — together with (media_type, media_id, language, variant, source) it forms the wire FileRef the client echoes back to address this exact file.
type SubtitleFile ¶
type SubtitleFile struct {
Language string // ISO 639-1
Variant Variant // "standard", "hi", "forced"
Source SubtitleSource // SourceEmbedded or SourceExternal
Codec string // e.g. "subrip", "ass"; empty for external
Path string // file path for external; empty for embedded
}
SubtitleFile represents a discovered subtitle (embedded or external) for a media file.
type SubtitleInfo ¶
type SubtitleInfo struct {
HashVerifiable bool
}
SubtitleInfo describes a subtitle result for scoring purposes.
type SubtitleSource ¶
type SubtitleSource string
SubtitleSource identifies where a subtitle was found.
const ( // SourceEmbedded indicates a subtitle embedded in the video container. SourceEmbedded SubtitleSource = "embedded" // SourceExternal indicates a subtitle in a separate file on disk. SourceExternal SubtitleSource = "external" )
type SubtitleTargJSON ¶
type SubtitleTargJSON struct {
MinScore *int `json:"min_score,omitempty"`
Code string `json:"code"`
Variant string `json:"variant,omitempty"`
Variants []string `json:"variants,omitempty"`
Providers []string `json:"providers,omitempty"`
Exclude []string `json:"exclude,omitempty"`
}
SubtitleTargJSON is a JSON-friendly subtitle target.
type SubtitleTarget ¶
type SubtitleTarget struct {
MinScore *int
Code string
Variant Variant
Variants []string
Providers []ProviderID
Exclude []ProviderID
}
SubtitleTarget defines a single subtitle to search for.
func (*SubtitleTarget) EffectiveVariant ¶
func (t *SubtitleTarget) EffectiveVariant() Variant
EffectiveVariant returns the variant, defaulting to DefaultVariant.
type SyncConfig ¶
type SyncConfig struct {
// SyncSubtitles enables automatic timing sync against embedded
// reference subtitles when a new subtitle is downloaded.
SyncSubtitles bool `json:"sync_subtitles"`
// AudioSyncFallback enables audio-based sync as a fallback when
// no embedded reference subtitle is available or sync fails.
AudioSyncFallback bool `json:"audio_sync_fallback"`
// SyncMinConfidence is the minimum confidence threshold (0.0–1.0) for
// accepting an automatic sync result. Defaults to DefaultSyncMinConfidence when zero.
SyncMinConfidence float64 `json:"sync_min_confidence,omitempty"`
}
SyncConfig controls subtitle synchronization on import.
type Variant ¶
type Variant string
Variant is a typed string enum for subtitle variant identifiers. Valid variants: standard (default), hi (hearing impaired), forced.
type VideoInfo ¶
type VideoInfo struct {
ReleaseGroup string // Full release name for parsing.
MediaType MediaType // "episode" or "movie"
}
VideoInfo describes the video file for scoring purposes. Only MediaType and ReleaseGroup are used by the match builder.
type WebAuthnAvailability ¶ added in v0.6.0
type WebAuthnAvailability struct {
Reason WebAuthnUnavailableReason `json:"reason,omitempty"`
RPID string `json:"rp_id,omitempty"`
SuggestedRPID string `json:"suggested_rp_id,omitempty"`
Available bool `json:"available"`
}
WebAuthnAvailability is the JSON response for GET /api/auth/webauthn/availability. Reason names the condition and the client owns the sentence; RPID and SuggestedRPID are what make a refusal actionable, and neither is a secret (the RP ID rides every assertion challenge, the suggestion derives from the caller's own origin).
type WebAuthnUnavailableReason ¶ added in v0.6.0
type WebAuthnUnavailableReason string
WebAuthnUnavailableReason names why a passkey ceremony cannot be conducted.
const ( )
The wire reasons, one per condition, so the client's sentence per reason is total: a parse-stage refusal of the probed origin is address_unusable, an IP host is unconfigurable, and only host_not_covered is origin_not_accepted.
type WebAuthnUnknownCredentialResponse ¶
type WebAuthnUnknownCredentialResponse struct {
Error string `json:"error"`
Signal string `json:"signal"`
}
WebAuthnUnknownCredentialResponse signals an unknown credential to the client.