manualops

package
v0.6.19-dev.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: AGPL-3.0 Imports: 28 Imported by: 0

Documentation

Overview

Package manualops implements the business logic for manual subtitle search and download operations. The HTTP handler glue remains in the parent server package; this package owns validation, query parsing, result building, and the background download pipeline.

Index

Constants

View Source
const (
	NoticeGated = "gated"
	NoticeError = "error"
)

Manual provider notice kinds.

View Source
const DownloadTimeout = 5 * time.Minute

DownloadTimeout bounds a single manual download's run.

View Source
const MaxResults = 50

MaxResults caps the number of results a manual search returns.

Variables

View Source
var (
	ErrMissingRequired = errors.New("provider, subtitle_id, media_id, and language are required")
	// ErrInvalidLangCode gates on subflux's internal language-code space
	// (ISO 639-1 plus "pb") rather than a list of characters to bar, because
	// the code becomes a dot segment of the subtitle filename written next
	// to the media file, and a vocabulary cannot be widened by an input.
	ErrInvalidLangCode  = errors.New("invalid language code")
	ErrInvalidMediaType = errors.New("invalid media_type")
	ErrMissingEpisode   = errors.New("season and episode are required for episode downloads")
)

Validation errors returned by ValidateDownloadRequest.

Functions

func LookupEpisodeMediaID

func LookupEpisodeMediaID(ctx context.Context, ls *LiveState, seriesID, season, episode int) string

LookupEpisodeMediaID resolves a Sonarr episode's stable media ID by series ID, season, and episode.

func LookupMediaTitle

func LookupMediaTitle(ctx context.Context, ls *LiveState, mediaType subflux.MediaType, arrID int) string

LookupMediaTitle resolves a media item's title by arr ID.

func LookupMovieMediaID

func LookupMovieMediaID(ctx context.Context, ls *LiveState, arrID int) string

LookupMovieMediaID resolves a Radarr movie's stable media ID by arr ID.

func NotifyError

func NotifyError(deps *SearchDeps, n ErrorNotice)

NotifyError records an error notice to both the operator alert log and the user notify bus.

func ParseSearchQuery

func ParseSearchQuery(r *http.Request) (req subflux.SearchRequest, lang string, mediaType subflux.MediaType, arrID int)

ParseSearchQuery extracts search parameters from the request URL. The optional media_id parameter is the ARR internal ID (Radarr movie ID / Sonarr series ID): with season/episode it forms the MediaRef the handler resolves server-side for hash computation.

func PostDownloadUpdate

func PostDownloadUpdate(ctx context.Context, ls *LiveState, db DownloadStore,
	req *DownloadRequest, mediaType subflux.MediaType, coverageMediaID, subPath string, variant subflux.Variant,
)

PostDownloadUpdate records the coverage file and triggers an arr rescan after a manual download.

func QueryInt

func QueryInt(q interface{ Get(string) string }, key string) int

QueryInt parses a non-negative integer query parameter, returning 0 when absent or invalid.

func ResolveMediaIDs

func ResolveMediaIDs(ctx context.Context, ls *LiveState,
	mediaType subflux.MediaType, arrID, season, episode int,
) (coverageID, historyID string)

ResolveMediaIDs resolves the coverage and history media IDs for a manual download.

func RunDownload

func RunDownload(ctx context.Context, deps *SearchDeps, ls *LiveState, db DownloadStore,
	media MediaWriter, req *DownloadRequest, actID string,
) bool

RunDownload performs the download, post-processing, and the save through media. actID is the download's activity entry: on success its detail is updated with the saved subtitle path, which is how the remote CLI's poll loop learns where the file landed. Returns true on success.

func TryComputeHash

func TryComputeHash(ctx context.Context, ls *LiveState, req *subflux.SearchRequest, filePath string)

TryComputeHash computes and sets the request's video hash, best-effort, when a file path is available.

func ValidateDownloadRequest

func ValidateDownloadRequest(req *DownloadRequest) error

ValidateDownloadRequest checks that the download request has all required fields and valid values, normalising MediaType to "movie" when empty.

Types

type ActivityTracker

type ActivityTracker interface {
	Start(action, detail string, source activity.Source) string
	End(id string)
	Fail(id string)
	Progress(id string, current, total int, detail string)
}

ActivityTracker manages activity lifecycle. Progress also mutates the entry detail: download completion writes the saved subtitle path there so the remote CLI's poll loop can report it.

type BGTracker

type BGTracker interface {
	Go(f func())
}

BGTracker registers a background goroutine with the server's WaitGroup for graceful-shutdown tracking. One method, mirroring sync.WaitGroup.Go (launch and count in one call), so an Add/Done pair can never leak a counter via an early return or panic before the defer is installed.

type DownloadAccepted added in v0.1.148

type DownloadAccepted struct {
	ActivityID string `json:"activity_id"`
	Status     string `json:"status"`
}

DownloadAccepted is the 202 response body for an accepted manual download.

type DownloadRequest

type DownloadRequest struct {
	Provider    subflux.ProviderID `json:"provider"`
	SubtitleID  string             `json:"subtitle_id"`
	Language    string             `json:"language"`
	ReleaseName string             `json:"release_name,omitempty"`
	MediaType   subflux.MediaType  `json:"media_type,omitempty"`

	Score      int  `json:"score,omitempty"`
	Season     int  `json:"season,omitempty"`
	Episode    int  `json:"episode,omitempty"`
	ArrID      int  `json:"media_id,omitempty"`
	TopPick    bool `json:"top_pick,omitempty"`
	HearingImp bool `json:"hearing_impaired,omitempty"`
	Forced     bool `json:"forced,omitempty"`
	// contains filtered or unexported fields
}

DownloadRequest holds the parsed fields for a manual download. The video is addressed by MediaRef only (media_type + media_id [arr ID] + season/episode); the server resolves the video file path from the arr, so the wire carries no file path. videoPath is the server-resolved value, set by the handler after resolution, never decoded from JSON.

func (*DownloadRequest) SetVideoPath added in v0.1.148

func (req *DownloadRequest) SetVideoPath(path string)

SetVideoPath records the server-resolved video path on the request, called by the HTTP handler after MediaRef resolution.

func (*DownloadRequest) VideoPath added in v0.1.148

func (req *DownloadRequest) VideoPath() string

VideoPath returns the server-resolved video path.

type DownloadStore

type DownloadStore interface {
	Store
	NextManualNumber(ctx context.Context, key subflux.ManualLockKey) int
	UpsertSubtitleFile(ctx context.Context, mediaType subflux.MediaType, mediaID string, sf *subflux.SubtitleFile) error
	SetSyncOffset(ctx context.Context, path string, offsetMs int64) error
	SaveDownload(ctx context.Context, rec *subflux.DownloadRecord) error
}

DownloadStore is what saving a manual download writes: the next ordinal for the numbered file, the coverage row, the timing offset, and the download record — plus Store, embedded so the search and download legs cannot disagree about the read half.

type ErrorNotice added in v0.4.0

type ErrorNotice struct {
	// Source attributes the alert to a subsystem.
	Source string
	// Alert is the operator-facing text; it lands in the alert log.
	Alert string
	// UI is the user-facing text; it lands on the notify bus.
	UI string
}

ErrorNotice is one error's two audiences: the operator reading the alert log and the user watching the UI. Named fields rather than positional, because Alert and UI are both human-readable strings and a transposition would compile and read plausibly at most call sites.

type EventPublisher

type EventPublisher interface {
	PublishNotify(level events.NotifyLevel, text string)
	PublishCoverageUpdate(ev *events.CoverageEvent)
}

EventPublisher publishes events to SSE clients. Satisfied structurally by *events.EventBus.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler serves the manual search/download HTTP endpoints.

func NewHandler

func NewHandler(deps HandlerDeps) *Handler

NewHandler constructs a Handler from its dependencies.

func (*Handler) HandleClearLock

func (h *Handler) HandleClearLock(w http.ResponseWriter, r *http.Request)

HandleClearLock handles POST /api/search/clear-lock.

func (*Handler) HandleManualDownload

func (h *Handler) HandleManualDownload(w http.ResponseWriter, r *http.Request)

HandleManualDownload handles POST /api/search/download.

func (*Handler) HandleManualSearch

func (h *Handler) HandleManualSearch(w http.ResponseWriter, r *http.Request)

HandleManualSearch handles GET /api/search?imdb=tt1234567&lang=fr&type=movie

func (*Handler) HandleSearchResolve added in v0.1.148

func (h *Handler) HandleSearchResolve(w http.ResponseWriter, r *http.Request)

HandleSearchResolve handles GET /api/search/resolve.

type HandlerDeps

type HandlerDeps struct {
	DBFunc     func() DownloadStore
	Activity   ActivityTracker
	Alerts     WarnRecorder
	Events     EventPublisher
	Media      MediaWriter
	StateFunc  func() *LiveState
	BGTracker  BGTracker
	ServerCtx  func() context.Context
	Resolve    *resolve.Resolver
	DecodeJSON func(w http.ResponseWriter, r *http.Request, v any, maxSize int64) bool
}

HandlerDeps holds the dependencies for the manual search/download HTTP handlers. Resolve is the typed-reference resolver: the download verb and the manual-search hash computation address the video by MediaRef and the server resolves the file path from the arr — no client-supplied paths.

type LiveState

type LiveState struct {
	Cfg       pathValidator
	Engine    manualEngine
	Scorer    tierLabeller
	Sonarr    ManualSonarrClient
	Radarr    ManualRadarrClient
	SonarrLib ResolveSonarrClient
	RadarrLib ResolveRadarrClient
	Providers []provider.Provider
}

LiveState holds the runtime state needed for a manual search pass. Sonarr/Radarr are the narrow by-ID surfaces manual downloads use; SonarrLib/RadarrLib are the library-listing surfaces the resolve endpoint uses (all nil when the corresponding arr is not configured).

type ManualProviderNotice added in v0.6.6

type ManualProviderNotice struct {
	Provider subflux.ProviderID `json:"provider"`
	// Kind is "gated" when the provider gate skipped the provider and
	// "error" when its search failed.
	Kind    string `json:"kind"`
	Message string `json:"message"`
}

ManualProviderNotice says why one provider contributed no results.

type ManualRadarrClient added in v0.1.106

type ManualRadarrClient interface {
	MovieByID(ctx context.Context, movieID int) (arrapi.Movie, error)
	RescanMovie(ctx context.Context, movieID int) error
}

ManualRadarrClient is the Radarr surface manual downloads use.

type ManualSearchResponse

type ManualSearchResponse struct {
	Results   []SearchResult         `json:"results"`
	Providers []ManualProviderNotice `json:"providers,omitempty"`
}

ManualSearchResponse is the typed response from RunSearch. It deliberately carries no lock state: manual locks are invisible infrastructure, not a user-facing concept, so the popup has nothing to display about them. Providers lists each provider that returned nothing because it was skipped or failed.

func RunSearch

func RunSearch(ctx context.Context, deps *SearchDeps, ls *LiveState,
	req *subflux.SearchRequest, lang string, mediaType subflux.MediaType, filePath string,
) ManualSearchResponse

RunSearch queries every configured provider through the engine and returns the scored manual-search response.

type ManualSonarrClient added in v0.1.106

type ManualSonarrClient interface {
	SeriesByID(ctx context.Context, seriesID int) (arrapi.Series, error)
	RescanSeries(ctx context.Context, seriesID int) error
}

ManualSonarrClient is the Sonarr surface manual downloads use.

type MediaWriter added in v0.6.6

type MediaWriter interface {
	WriteFile(ctx context.Context, path string, data []byte) error
	Preflight(ctx context.Context, req mediawrite.PreflightRequest) error
}

MediaWriter saves a manual subtitle and write-tests its folder before the download is accepted; *mediawrite.Writer satisfies it.

type ResolveCandidate added in v0.1.148

type ResolveCandidate struct {
	MediaType subflux.MediaType `json:"media_type"`
	Title     string            `json:"title"`
	MediaID   int               `json:"media_id"`
	Year      int               `json:"year,omitempty"`
}

ResolveCandidate is one ambiguous match in a resolve response's candidate list.

type ResolveQueryParams added in v0.1.148

type ResolveQueryParams struct {
	Season  *int
	Episode *int
	Title   string
	Imdb    string
	Type    string // "", "series", or "movie"
	Tmdb    int
}

ResolveQueryParams is the validated query surface of the resolve endpoint. Season and Episode carry PRESENCE, not just value: nil means the parameter was absent, while a non-nil zero is an explicit season=0 (specials) or episode=0 — an explicit zero narrows the expansion and marks the query episodic exactly like any other supplied value.

type ResolveRadarrClient added in v0.1.148

type ResolveRadarrClient interface {
	Movies(ctx context.Context) ([]arrapi.Movie, error)
}

ResolveRadarrClient is the Radarr surface query resolution uses.

type ResolveResponse added in v0.1.148

type ResolveResponse struct {
	Items      []ResolvedItem     `json:"items,omitempty"`
	Candidates []ResolveCandidate `json:"candidates,omitempty"`
	Resolved   bool               `json:"resolved"`
}

ResolveResponse is the typed result of GET /api/search/resolve. Exactly one holds: Resolved with Items (success), Candidates (ambiguous), or all empty (no match).

func ResolveQuery added in v0.1.148

func ResolveQuery(ctx context.Context, ls *LiveState, p *ResolveQueryParams) (ResolveResponse, error)

ResolveQuery maps the validated query onto arr media items. With an explicit type only that arm runs (an unconfigured arr is then an error); with no type, series runs first and movies only when the series arm found nothing and no season/episode narrowing was requested — EXCEPT when a TMDB id was supplied, which resolves the movie identity first since a supplied stable ID always outranks a title match. A conflict short-circuits; an arm failure surfaces only when the healthy arm could not satisfy the query (partial-arr rule).

type ResolveSearchIDs added in v0.1.148

type ResolveSearchIDs struct {
	Imdb string `json:"imdb,omitempty"`
	Tvdb int    `json:"tvdb,omitempty"`
	Tmdb int    `json:"tmdb,omitempty"`
}

ResolveSearchIDs carries the stable search identifiers a resolved item forwards to the search leg.

type ResolveSonarrClient added in v0.1.148

type ResolveSonarrClient interface {
	Series(ctx context.Context) ([]arrapi.Series, error)
	Episodes(ctx context.Context, seriesID int) ([]arrapi.Episode, error)
}

ResolveSonarrClient is the Sonarr surface query resolution uses: the full series list for matching and per-series episodes for expansion.

type ResolvedItem added in v0.1.148

type ResolvedItem struct {
	MediaType subflux.MediaType `json:"media_type"`
	Title     string            `json:"title"`
	SearchIDs ResolveSearchIDs  `json:"search_ids"`
	MediaID   int               `json:"media_id"`
	Year      int               `json:"year,omitempty"`
	Season    int               `json:"season,omitempty"`
	Episode   int               `json:"episode,omitempty"`
}

ResolvedItem is one searchable media item: an episode of the matched series (file-bearing only) or the matched movie. MediaID is the arr ID, the same identity the search and download endpoints consume.

type SearchDeps

type SearchDeps struct {
	DB       Store
	Activity ActivityTracker
	Alerts   WarnRecorder
	Events   EventPublisher
}

SearchDeps holds the dependencies a manual search or download pass needs.

type SearchResult

type SearchResult struct {
	Matches     map[string]int     `json:"matches,omitempty"`
	Provider    subflux.ProviderID `json:"provider"`
	Language    string             `json:"language"`
	ReleaseName string             `json:"release_name"`
	MatchedBy   string             `json:"matched_by"`
	SubtitleID  string             `json:"subtitle_id"`
	// Tier is the score's quality-tier label, computed server-side by the
	// scorer (same table as /api/score): the remote CLI renders it and has
	// no scorer of its own.
	Tier       subflux.ScoreTier `json:"tier"`
	Score      int               `json:"score"`
	HearingImp bool              `json:"hearing_impaired"`
	Forced     bool              `json:"forced"`
	OnDisk     bool              `json:"on_disk"`
}

SearchResult is one scored manual-search candidate in the API response.

func BuildSearchResults

func BuildSearchResults(scored []subflux.ScoredResult, refs []subflux.DownloadedRef, sc tierLabeller) []SearchResult

BuildSearchResults converts scored results to API response format. sc supplies the server-computed tier label per score; a nil scorer leaves tiers empty.

type Store added in v0.4.0

type Store interface {
	DownloadedRefs(ctx context.Context, mediaType subflux.MediaType, mediaID, language string) ([]subflux.DownloadedRef, error)
	ClearManualLock(ctx context.Context, key subflux.ManualLockKey) error
}

Store is the two rows a manual search touches: what is already on disk for the language and releasing a lock. The lock key's empty variant means "all variants of the language" (see subflux.ManualLockKey).

type WarnRecorder added in v0.4.0

type WarnRecorder interface {
	RecordWarn(source, msg string)
}

WarnRecorder records an actionable warning for the UI's alert list. Satisfied structurally by activity.AlertLog.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL