Documentation
¶
Overview ¶
Package core holds the domain types and the interfaces between Ether's components. It has no dependencies on other Ether packages, so every component can import it. Changing a type here is a contract change: keep edits additive.
Index ¶
- Constants
- Variables
- func AudioFormat(codec string) string
- func BrowseScope(ctx context.Context) string
- func BrowseSeekable(q BrowseQuery) bool
- func CarrySearchCoverage(dst, src context.Context) context.Context
- func CatalogCandidates(ctx context.Context) bool
- func CatalogViewerID(ctx context.Context) int64
- func CatalogViewerRestricted(ctx context.Context) bool
- func CheckReleaseHealth(ctx context.Context, hc HealthChecker, releaseID string, nzb []byte) (bool, error)
- func ClassifyDevice(product, platform, device string) string
- func CodecFormat(codec string) string
- func ColdDetail(ctx context.Context, key RatingKey) bool
- func CountsTowardMinimum(id string) bool
- func DaypartAt(t time.Time) string
- func DetailBurst(userID int64, clientID string, key RatingKey) bool
- func EffectiveSortTitle(title, explicitSortTitle string) string
- func ExactPeopleOnly(ctx context.Context) bool
- func ExplicitSearch(ctx context.Context) bool
- func FacetID(kind, value string) string
- func FilterOutSurroundAudio(codecs []string) []string
- func FoldSortTitle(s string) string
- func FoldedSortTitleForRow(title, stored string) string
- func ForegroundReserve(ctx context.Context) int
- func HasWarmReadWindow(ctx context.Context) bool
- func IndexerPurpose(ctx context.Context) string
- func IndexerSkipped(ctx context.Context, id string) bool
- func InheritBackground(dst, src context.Context) context.Context
- func InheritIndexerPurpose(dst, src context.Context) context.Context
- func IsAutoVersionSelector(selector string) bool
- func IsBackgroundAnalysis(ctx context.Context) bool
- func IsBackgroundCheck(ctx context.Context) bool
- func IsBuiltinFormat(id string) bool
- func IsExplicitVersionSlotSelector(selector string) bool
- func IsFireTV(product, device string) bool
- func IsGrantCredential(s string) bool
- func IsLastViewedSort(raw string) bool
- func IsPlexPart(ctx context.Context) bool
- func IsPluginPersonID(id int64) bool
- func IsPluginRankingStep(step string) bool
- func IsProfileMedia(media string) bool
- func IsSpeculative(ctx context.Context) bool
- func IsSurroundAudioCodec(c string) bool
- func IsUnattendedSearch(ctx context.Context) bool
- func IsWeekend(t time.Time) bool
- func JobsBusyErrorBody(err error) []byte
- func JobsBusyFromPending(message string, retryInMS int64) error
- func JobsBusyMessage(err error) string
- func JobsBusyRetrySeconds(err error, fallback int) int
- func LiveApp(ctx context.Context) string
- func LocalResponse(ctx context.Context) bool
- func MediaApplies(scope, media string) bool
- func MediaTypeForApp(app string) string
- func NeedsGeneratedPoster(t *Title) bool
- func NormalizeCatalogueTabFacet(kind, facet string) (string, bool)
- func NormalizeReleasePoster(poster string) string
- func NormalizeRuleDocument(raw []byte) ([]byte, bool)
- func NormalizeRuleMediaType(s string) string
- func NoteSearchIncomplete(ctx context.Context)
- func OnDemandAllowedAt(ctx context.Context, r Release, rank int) bool
- func OnDemandCached(r Release) bool
- func OnDemandStreamsAllowed(ctx context.Context) bool
- func OnDemandWarmGranted(ctx context.Context, r Release) bool
- func ParseCatalogueAddedMonth(id string) (fromTS, toTS int64, ok bool)
- func ParseCatalogueRatingBand(id string) (minR, maxR float64, maxExclusive, ok bool)
- func ParseCatalogueRuntimeBand(id string) (minSec, maxSec int64, ok bool)
- func PlexSaferRating(ctx context.Context) bool
- func PluginLibraryKey(pluginID, kindKey string) string
- func PluginPersonID(name string) int64
- func PreFetchContentIDFor(size int64, poster string, uploadDate time.Time) string
- func PreparingFromPending(retryInMS int64) error
- func PreparingRetrySeconds(err error, fallback int) int
- func ProfileServesEveryMedia(profiles []QualityProfile, name string) bool
- func ProviderLeaseCancel(ctx context.Context) context.CancelFunc
- func PublishDescribeProgress(ctx context.Context, spec *CollectionSpec, items []Title)
- func QualityOrderError(order []QualityItem) string
- func ReleaseSizeBucket(size int64) int64
- func ReportDetailPending(ctx context.Context, key RatingKey, fields ...string)
- func ResolutionLabel(w, h int) string
- func ResolutionTier(w, h int) int
- func SameReleaseContent(a, b Release) bool
- func ScoresForMedia(scores map[string]int, media string) map[string]int
- func SearchCategories(category string) ([]int, error)
- func SearchClientFrom(ctx context.Context) string
- func SearchListFacts(ctx context.Context) bool
- func SearchSummaryFacts(ctx context.Context) bool
- func SessionActiveStream(ps *PlaySession) bool
- func SessionCountsForLimit(ps *PlaySession) bool
- func SessionPaused(ps *PlaySession) bool
- func SessionVisible(ps *PlaySession) bool
- func SourceFormat(s Source) string
- func SourceLabel(s Source) string
- func SourceRevision(s *PlaySession) string
- func SpeculativeIndexerWork(ctx context.Context) bool
- func SpendBackground(ctx context.Context, resource, source string, amount int64) error
- func StreamKey(ctx context.Context) any
- func StreamingFormatScores() map[string]int
- func TargetReleaseID(releaseID string, t ReleaseTarget) string
- func TitleSortKey(s string) string
- func TorrentOnlySearch(ctx context.Context) bool
- func TrickplayCacheKey(s *PlaySession) string
- func ValidArtworkPath(path string) bool
- func ValidCardShape(s string) bool
- func ValidDateDisplay(s string) bool
- func ValidExternalID(id string) bool
- func ValidMediaClass(s string) bool
- func ValidMediaRole(s string) bool
- func ValidTabLayout(s string) bool
- func WarmReadContext(ctx context.Context, end int64) (context.Context, context.CancelFunc)
- func WithBackgroundAnalysis(ctx context.Context) context.Context
- func WithBackgroundBudget(ctx context.Context, budget BackgroundBudget) context.Context
- func WithBrowseScope(ctx context.Context, scope string) context.Context
- func WithCatalogCandidates(ctx context.Context) context.Context
- func WithCatalogViewer(ctx context.Context, u *User) context.Context
- func WithColdDetail(ctx context.Context, key RatingKey) context.Context
- func WithDescribeProgress(ctx context.Context, publish func(*CollectionSpec, []Title)) context.Context
- func WithExactPeopleOnly(ctx context.Context) context.Context
- func WithExplicitSearch(ctx context.Context) context.Context
- func WithForegroundReserve(ctx context.Context, percent int) context.Context
- func WithIndexerPurpose(ctx context.Context, purpose string) context.Context
- func WithIndexerSkip(ctx context.Context, ids map[string]bool) context.Context
- func WithLiveApp(ctx context.Context, app string) context.Context
- func WithLocalResponse(ctx context.Context) context.Context
- func WithMediaCapWait(ctx context.Context, m *MediaCapWait) context.Context
- func WithOnDemandStreamsForAvailability(ctx context.Context) context.Context
- func WithOnDemandWarm(ctx context.Context, admit func(Release) bool) context.Context
- func WithPlexPart(ctx context.Context) context.Context
- func WithPlexSaferRating(ctx context.Context) context.Context
- func WithProviderLeaseCancel(ctx context.Context, cancel context.CancelFunc) context.Context
- func WithRangeResponse(ctx context.Context, policy RangeResponse) context.Context
- func WithRankingCandidates(ctx context.Context, c *SearchCandidates) context.Context
- func WithReadOrigin(ctx context.Context, component, reason string) context.Context
- func WithReadRetirement(ctx context.Context, tracker *ReadRetirement) context.Context
- func WithSearchAffinity(ctx context.Context, fn SearchAffinityFunc) context.Context
- func WithSearchCandidates(ctx context.Context, c *SearchCandidates) context.Context
- func WithSearchClient(ctx context.Context, clientID string) context.Context
- func WithSearchListFacts(ctx context.Context) context.Context
- func WithSearchMemo(ctx context.Context) context.Context
- func WithSearchSummaryFacts(ctx context.Context) context.Context
- func WithSearchTypes(ctx context.Context, types []MediaType) context.Context
- func WithSpeculative(ctx context.Context) (context.Context, func())
- func WithStreamKey(ctx context.Context, key any) context.Context
- func WithTorrentOnlySearch(ctx context.Context) context.Context
- func WithUnattendedSearch(ctx context.Context) context.Context
- func WithWarmReadWindow(ctx context.Context, w *WarmReadWindow) context.Context
- func WithoutCatalogViewer(ctx context.Context) context.Context
- func WithoutLocalResponse(ctx context.Context) context.Context
- func WithoutOnDemandStreams(ctx context.Context) context.Context
- type ActiveUserSource
- type ActivityDay
- type AiredEpisodeTally
- type AlignRequest
- type AnalysisReaderAt
- type AnalysisSourceStats
- type ArchiveVolumeSource
- type ArticleFetcher
- type ArticlePart
- type ArtworkAccessPolicy
- type ArtworkImageFile
- type ArtworkImages
- type AudioLimit
- type Auth
- type AuthoritativeTitleRefresher
- type AvailabilitySource
- type BackgroundBudget
- type BatchWatchState
- type Bedtime
- type BedtimeState
- type BitrateAccessPolicy
- type BrowseQuery
- type BufferedInputSwapper
- type BufferedSource
- type BugSettings
- type BuiltinFormat
- type BurstArticleFetcher
- type CacheCause
- type CachePlayRecorder
- type CacheProvenance
- type CacheProvenanceRecorder
- type CacheShelfDetail
- type CachedTitleSource
- type Catalog
- type CatalogFacetCollection
- type CatalogFacetCollectionsPage
- type CatalogFacetCollectionsQuery
- type CatalogFacetPeoplePage
- type CatalogFacetPeopleQuery
- type CatalogFacetPerson
- type CatalogSchedule
- type ChannelGraphics
- type ChannelPreparer
- type ChannelSegmentMetadata
- type Chapter
- type ClientCapabilityOverride
- type ClientCapabilityProfiles
- type ClientCaps
- type ClientCodecProfile
- type ClientContainerProfile
- type ClientDirectPlayProfile
- type ClientProfileCondition
- type ClientSubtitleProfile
- type ClientTranscodeProfile
- type ClipRef
- type ClipRequest
- type Collection
- type CollectionArtwork
- type CollectionArtworkSource
- type CollectionLayoutSource
- type CollectionPlaceholder
- type CollectionPreview
- type CollectionRotate
- type CollectionRow
- type CollectionRows
- type CollectionRule
- type CollectionSchedule
- type CollectionSource
- type CollectionSpec
- type CollectionSpecSource
- type CollectionTargets
- type CollectionTemplate
- type Collections
- type CompressedZipMemberSource
- type ConcurrentRangeReaderAt
- type ContainerRef
- type ContextReaderAt
- type ContextualRecommender
- type CopyTimeline
- type CourMapping
- type CreditFilter
- type CustomFormat
- type DASHSession
- type DamageReporter
- type DamagedSegmentSkipper
- type DateFilter
- type DebridServiceRef
- type DecideOptions
- type Decision
- type DecisionCandidate
- type DecisionKind
- type DecisionTrace
- type DecisionTraceSource
- type DelegationAuth
- type DeliveryPolicy
- type DescriptiveCatalog
- type DescriptiveResult
- type DescriptiveSearchController
- type DescriptiveSearcher
- type DetailPending
- type Device
- type DirectDeliverer
- type DirectPlayRetrier
- type DirectSourceLink
- type DirectURLSource
- type DownloadAccessPolicy
- type DownloadRemuxRequest
- type DownloadRemuxer
- type DurablePrefetcher
- type EncoderInputLease
- type EncoderRetirement
- type EncoderStatus
- type Engine
- type EpisodeIdentity
- type EpisodeLayout
- type EpisodeNamesake
- type EpisodeNumber
- type EpisodeTally
- type ErrBedtime
- type ExactVariantPlayback
- type FacetValue
- type FeedEvaluation
- type FeedVerdict
- type Filter
- type FilterGroup
- type FormatSpecification
- type FrontendHostPolicy
- type GoodputSession
- type HLSDiagnosticRecord
- type HLSDiagnosticSession
- type HLSIndependentSegments
- type HLSLadderSession
- type HLSPlaybackDiagnostics
- type HLSPreparationEvent
- type HLSRamp
- type HLSRequest
- type HLSResume
- type HLSRung
- type HLSSession
- type HTTPSession
- type HWAccel
- type HealthChecker
- type HistoryCount
- type HistoryEntry
- type HistoryQuery
- type HistoryStore
- type HistoryTopStore
- type HomeCandidateSource
- type HomeLayout
- type HomeLayoutSource
- type HomePreview
- type HomeRow
- type HomeSituation
- type Hub
- type HubContext
- type HubImpression
- type HubItemSource
- type IDs
- type Identity
- type ImageURLFunc
- type ImpressionSink
- type Indexer
- type InputSwapState
- type IntentTracker
- type ItemRef
- type ItemUnavailable
- type JobsBusyError
- type KeyKind
- type KeyframePoint
- type KindArtRef
- type KindBrowseRequest
- type KindChangePage
- type KindExpandRequest
- type KindExpandResponse
- type KindInput
- type KindItem
- type KindItemPart
- type KindMatchRequest
- type KindMatchResponse
- type KindMatchScore
- type KindPage
- type KindPlayback
- type KindResolveRequest
- type KindResolveResponse
- type LayoutPage
- type LayoutTuning
- type LayoutWhen
- type Library
- type LibraryExclusion
- type LibraryID
- type LibrarySource
- type LibraryTab
- type LikesState
- type ListRows
- type LiveChannel
- type LocalFileSource
- type LookupResult
- type MIMESource
- type MarkedPlaylists
- type MediaAccessTracker
- type MediaBrowserPresentation
- type MediaCapWait
- type MediaCapWaitSource
- type MediaClass
- type MediaCredit
- type MediaInfo
- type MediaRole
- type MediaSource
- type MediaType
- type MetadataProber
- type MetadataProvider
- type MetadataReaderAt
- type MetadataRequest
- type MicroReason
- type MicroReasoner
- type NeutralEntryRef
- type NeutralHomeLayoutSource
- type NeutralHomeRow
- type NeutralImpression
- type NeutralImpressionSink
- type OriginSource
- type OwnedCollectionLister
- type OwnedEncoderSession
- type OwnedSourcePlayback
- type OwnedTranscoder
- type Page
- type Person
- type PersonCredit
- type PersonCreditForm
- type PersonMetadata
- type PersonalPick
- type PersonalPicker
- type PersonalScorer
- type PlayExperience
- type PlayMetadataProber
- type PlaySession
- type PlayableSource
- type Playback
- type PlaybackAccessPolicy
- type PlaybackDecisionRecorder
- type PlaybackDurationSetter
- type PlaybackEncoderInputs
- type PlaybackPosition
- type PlaybackPrepareWithin
- type PlaybackPreparer
- type PlaybackRevisionPin
- type PlaybackSelectionFence
- type PlaybackSourceHistory
- type PlaybackSourceObservation
- type PlaybackSourceResource
- type PlaybackSourceSnapshot
- type PlaybackTimeline
- type Playlist
- type PlaylistEdit
- type PlaylistEditor
- type PlaylistMutation
- type PlaylistMutator
- type Playlists
- type PlexPresentation
- type PolicyHomeCandidateSource
- type PostPlayPick
- type PostPlayer
- type PreferenceFallbackObserver
- type PrefetchReaderAt
- type PreparingError
- type PrerollClip
- type PrerollPlay
- type PrerollRequest
- type Prerolls
- type PresentationOverrides
- type PresentationSource
- type Presentations
- type PrewarmOptions
- type Prewarmer
- type Priority
- type ProcessCPUTime
- type ProcessIdentity
- type ProcessPeakMemory
- type ProfileImport
- type Protocol
- type QualityItem
- type QualityLimitation
- type QualityProfile
- type QualityVariant
- type RangeRepresentation
- type RangeResponse
- type RankerFeature
- type RankerInsight
- type RatingKey
- func CollectionKey(id int64) RatingKey
- func EphemeralSmartKey(seq int64) RatingKey
- func EpisodeKey(show int64, season, episode int) RatingKey
- func ExtraKey(id int64) RatingKey
- func LocalKey(id int64) RatingKey
- func MovieKey(tmdb int64) RatingKey
- func ParseRatingKey(s string) (RatingKey, error)
- func PlaylistKey(id int64) RatingKey
- func PluginKey(seq int64) RatingKey
- func PluginPartKey(parent RatingKey, partIndex int) (RatingKey, bool)
- func PrerollKey(id int64) RatingKey
- func SeasonKey(show int64, season int) RatingKey
- func SectionCollectionKey(k RatingKey, t MediaType) RatingKey
- func ShowKey(tmdb int64) RatingKey
- func SmartKey(id int64) RatingKey
- func (k RatingKey) CollectionSection() (RatingKey, MediaType)
- func (k RatingKey) Episode() int
- func (k RatingKey) ExtraID() int64
- func (k RatingKey) IsEphemeral() bool
- func (k RatingKey) IsPluginItemKey() bool
- func (k RatingKey) IsPluginKey() bool
- func (k RatingKey) IsPluginPartKey() bool
- func (k RatingKey) IsPreroll() bool
- func (k RatingKey) IsTitleKey() bool
- func (k RatingKey) Kind() KeyKind
- func (k RatingKey) Parent() RatingKey
- func (k RatingKey) PluginPart() (parent RatingKey, partIndex int, ok bool)
- func (k RatingKey) PluginSeq() int64
- func (k RatingKey) PrerollID() int64
- func (k RatingKey) Season() int
- func (k RatingKey) String() string
- func (k RatingKey) TMDB() int64
- func (k RatingKey) Valid() bool
- type ReadOrigin
- type ReadRetirement
- type ReadingProgress
- type ReadingState
- type Recommender
- type RecoveryAACCursor
- type RecoveryBuffer
- type RecoveryBufferSource
- type RecoveryPacketClock
- type RecoverySourceReader
- type RecoveryStart
- type Release
- func (r Release) EffectiveContentID() string
- func (r Release) KnownFileCount() int
- func (r Release) OpensOnDemand() bool
- func (r Release) PreFetchContentID() string
- func (r Release) ProbeContentKeys() []string
- func (r Release) ReleaseContentKey() string
- func (r Release) ReportedTitleIDs() IDs
- func (r Release) ScopedContentID(base string) string
- type ReleaseBatchBlockChecker
- type ReleaseBlockChecker
- type ReleaseCondition
- type ReleaseFeed
- type ReleaseFile
- type ReleaseHealthChecker
- type ReleaseHint
- type ReleaseInfo
- type ReleaseMember
- type ReleaseNumbering
- type ReleaseRule
- type ReleaseSizeSource
- type ReleaseTarget
- type ReleaseVariant
- type RemuxRequirer
- type RepairEvent
- type RepairReporter
- type RepairWindow
- type ReplacementOutputWaiter
- type RescueIndexer
- type Resolution
- type ResolveRequest
- type ResolvedAppPresentation
- type ResolvedMemberSource
- type ResolvedPresentations
- type Resolver
- type RowDescriptor
- type RowInsight
- type RowPolicy
- type RowPurpose
- type SearchAffinityFunc
- type SearchCacheRefiller
- type SearchCandidates
- type SearchCoverage
- type SearchMemo
- type SearchRequest
- type SectionCandidateSource
- type SegmentCache
- type SegmentCacheLimit
- type SegmentPresence
- type SessionActivity
- type SessionLiveness
- type SessionLivenessInput
- type SessionLivenessState
- type SessionPolicy
- type ShowTrajectory
- type SiloPresentation
- type SmartPlaylists
- type SortOrder
- type SortSpec
- type Source
- type SourceCandidate
- type SourceDelivery
- type SourceDeliveryObserver
- type SourceDeliveryReporter
- type SourceQuery
- type SourceRetirement
- type State
- type StoredTitleLookup
- type StreamInfo
- type StreamingIndexer
- type StreamingRescueIndexer
- type StremioPresentation
- type StringFilter
- type SubtitleExtractor
- type SurfaceScopedPlayback
- type TabFilter
- type TasteDecade
- type TasteHabits
- type TasteLanguage
- type TasteOverride
- type TastePerson
- type TasteProfile
- type TasteWeight
- type TimelineAligner
- type Title
- type TitleFact
- type TitleFacts
- type TitleParent
- type TitleReading
- type TrackHint
- type TransactionalMarkedPlaylists
- type Transcoder
- type TrickplayCanceler
- type TrickplayLease
- type TrickplayLeaser
- type TrickplayProvider
- type TrickplaySource
- type UncachedError
- type UsenetCheckResult
- type User
- type UserPolicySource
- type UserTargets
- type VariantPlayback
- type VariantResolver
- type VelaPresentation
- type VersionAvailability
- type VersionHeaderProber
- type VersionProfile
- type VibeSearcher
- type VideoEnhancement
- type VideoEnhancementSupport
- type Viewer
- type ViewerActivity
- type ViewerChoiceSummary
- type ViewerInvalidator
- type ViewerLayout
- type ViewerStats
- type VolumeRef
- type WarmProbeWaiter
- type WarmProber
- type WarmReadWindow
- type WarmupSearchCacheRefiller
- type WatchPage
- type WatchStatus
- type XtreamPresentation
Constants ¶
const ( ProtocolUsenet = "" // the zero value: an NZB from a Newznab indexer ProtocolTorrent = "torrent" // a Torznab result streamed through a debrid service // ProtocolUnstated is a filename preview with no protocol fact. // Live releases keep the empty-string Usenet default; this value // exists so a preview cannot report that default as evidence. ProtocolUnstated = "unstated" // ProtocolHTTP is a stream URL a Stremio addon resolved itself (often // through the addon owner's own debrid account), read with HTTP range // requests. It needs no debrid account in Ether (additive). The same // name is Plex for Mac / Desktop's protocol=http conversion (a chunked // Matroska stream on /video/:/transcode/universal/start). ProtocolHTTP = "http" )
Release protocols (Release.Protocol).
const ( UsenetNone = "none" UsenetFailed = "failed" )
UncachedError.Usenet values.
const ( FormatKindRelease = "release" FormatKindStreaming = "streaming" )
Built-in format kinds.
const ( FamilySource = "source" FamilyCodec = "codec" FamilyAudio = "audio" )
Built-in format families: at most one format of a family matches a release (it has one release type, one video and one audio codec).
const ( FormatDolbyVision = "ether:dolby-vision" FormatHDR = "ether:hdr" FormatHDR10 = "ether:hdr10" FormatAtmos = "ether:atmos" FormatRepackProper = "ether:repack-proper" FormatLowBitrate = "ether:low-bitrate" FormatPreferredLanguage = "ether:preferred-language" FormatPreferredLanguageRegion = "ether:preferred-language-region" FormatOtherLanguage = "ether:other-language" FormatPreferredSubtitles = "ether:preferred-subtitles" FormatViewerLanguage = "ether:viewer-language" FormatSeriesYearDiffers = "ether:series-year-differs" FormatVideoTranscode = "ether:video-transcode" FormatAudioDirect = "ether:audio-direct" FormatAudioTranscode = "ether:audio-transcode" FormatAtmosPassthrough = "ether:atmos-passthrough" FormatToneMapping = "ether:tone-mapping" FormatPastRetention = "ether:past-retention" )
Built-in format ids that are not per source or codec.
const ( IndexerPurposeFeed = "feed" // release-feed polls IndexerPurposeAvailability = "availability" // background availability checks IndexerPurposePlayback = "playback" // a viewer pressed Play (incl. failover) IndexerPurposeDetail = "detail" // a viewer opened a playable detail page IndexerPurposeWarmup = "warmup" // warm-ups, prefetch, managed cache, watchlist IndexerPurposeRescue = "rescue" // second-pass rescue searches IndexerPurposeCaps = "caps" // capability (t=caps) fetches IndexerPurposeTest = "test" // the owner's "Test" button IndexerPurposeConsole = "console" // owner release searches and checks in the console IndexerPurposeOther = "other" // untagged callers )
Indexer purposes say why an indexer API request was made. The owner console breaks each indexer's real API hits and grabs down by purpose, so an owner comparing Ether with the indexer's own counter can see what spent the quota. Speculative work (SpeculativeIndexerWork: warm-ups, detail discovery, availability) searches narrowly. Unattended work and viewer detail discovery have separate small daily allowances, leaving the rest of each indexer's limit to playback.
const ( CardPoster = "poster" CardLandscape = "landscape" CardSquare = "square" )
Library card shapes.
const ( DateDisplayYear = "year" DateDisplayDate = "date" )
Library date display formats.
const ( TabLayoutGrid = "grid" TabLayoutList = "list" TabLayoutTimeline = "timeline" )
Library tab view layouts (used on kind: "view" tabs).
const ( TabRecommended = "recommended" TabLibrary = "library" TabCollections = "collections" TabPeople = "people" TabView = "view" TabLive = "live" )
Library tab kinds.
const ( VisibilityEverywhere = "everywhere" VisibilityDiscovery = "discovery" )
Visibility rule scopes.
const ( AffinityServer = 1 AffinityViewer = 2 )
Search affinity levels: someone on this server has a history with the title, or the searching viewer has.
const ( RankCast = 5 RankWriters = 3 RankCrew = 6 )
RankCast, RankWriters and RankCrew are how many of a title's cast, writers and crew a taste ranking reads (personalize's Taste.Fit), in credit order; it reads every director. A ranking window reads no more.
const ( DeviceTV = "tv" DeviceMobile = "mobile" DeviceWeb = "web" DeviceDesktop = "desktop" )
Device classes for HubContext.Device.
const ( DaypartMorning = "morning" // 05:00–11:59 DaypartAfternoon = "afternoon" // 12:00–16:59 DaypartEvening = "evening" // 17:00–21:59 DaypartLate = "late" // 22:00–04:59 )
Dayparts for HubContext.Daypart, in the server's local time.
const ( RowSourceEngine = "engine" // generated by the personalization engine RowSourceOwner = "owner" // an owner-designed collection RowSourcePlex = "plex" // built by the Plex front end (Continue Watching, playlists) )
Row sources for HomeRow.Source.
const ( ProtocolHLS = "hls" ProtocolDASH = "dash" )
Streaming protocols of HLSRequest.Protocol.
const ( PrerollBeforeTrailers = "before_trailers" PrerollAfterTrailers = "after_trailers" )
Pre-roll placement relative to Cinema Trailers.
const ( PrewarmDetail = "detail" // a detail page was opened PrewarmTrailer = "trailer" // a trailer or Cinema Trailer for the title is playing PrewarmPostPlay = "postplay" // the viewer is near the end of something and this is up next PrewarmBrowse = "browse" // a home/section row is on screen; open the debrid link only PrewarmNextEpisode = "nextepisode" // the viewer is nearing the end of an episode; warm the next one )
Reasons for PrewarmOptions.Reason.
const ( CacheCausePlaying = "playing" CacheCausePaused = "paused" CacheCauseUnfinished = "unfinished" CacheCauseOwnerPin = "owner-pin" CacheCauseShelf = "shelf" CacheCauseNextEpisode = "next-episode" CacheCausePostPlay = "post-play" CacheCauseResumeWarm = "resume-warm" CacheCauseDetailWarm = "detail-warm" CacheCauseTrailerWarm = "trailer-warm" CacheCauseBrowseWarm = "browse-warm" CacheCauseWatchlist = "watchlist" CacheCauseQualityCheck = "quality-check" CacheCauseFailover = "failover" CacheCauseRepair = "repair" CacheCauseUnrecorded = "unrecorded" )
Cache cause codes explain why a release's bytes were fetched or retained. The vocabulary is closed: readers ignore unknown codes and never guess one.
const ( PluginKeyBase int64 = 5_000_000_000_000 PluginKeyMaxSeq int64 = 2_000_000_000_000 // PluginKeyOffset is the base integer added to plugin_items.seq to produce // its RatingKey: RatingKey(PluginKeyOffset + seq) == PluginKey(seq). PluginKeyOffset int64 = int64(KindLocal)*keyBase + PluginKeyBase // PluginPartKeyBase carves out [PluginPartKeyBase+PluginPartStride, ...) // inside KindLocal for synthetic per-part RatingKeys of multi-part plugin // items (hints.parts / fields.parts), keeping every key strictly below 2^53. PluginPartKeyBase int64 = 7_000_000_000_000 PluginPartStride int64 = 10_000 PluginPartMaxSeq int64 = 19_900_000 )
PluginKeyBase and PluginKeyMaxSeq carve out the KindLocal payload range [PluginKeyBase+1, PluginKeyBase+PluginKeyMaxSeq) for plugin items while keeping every RatingKey below 2^53 (spec §2.2).
const ( PluginPersonIDBase int64 = 4_000_000_000_000 PluginPersonIDSpan int64 = 1_000_000_000_000 )
PluginPersonIDBase and PluginPersonIDSpan carve out deterministic positive person IDs in (PluginPersonIDBase, PluginPersonIDBase+PluginPersonIDSpan) for cast credited on plugin items. Values stay far above TMDB person IDs (< 10^9) and safely below 2^53 for JavaScript clients.
const ( EphemeralSmartBase int64 = 800_000_000_000_000 EphemeralSmartEnd int64 = 900_000_000_000_000 )
EphemeralSmartBase and EphemeralSmartEnd bound the KindSmart payloads reserved for ephemeral generated collections. The range stops where personalize's Year in Review collections begin (payload 9*10^14 and up), and database smart-collection ids stay far below it.
const ( MediaAny = "" MediaMovie = "movie" MediaTV = "tv" )
Media scopes a quality profile or rule. Every profile serves exactly one media; a client rule may leave it empty to apply to every media.
const ( ProfileLanguageOriginal = "original" // each title's original language ProfileLanguageAny = "any" // every language )
A quality profile's Language values beside a specific language.
const ( // PausedSessionRetention bounds a silent pause without treating it as an // abandoned stream. Explicit stop still closes immediately. PausedSessionRetention = 30 * time.Minute // AbandonedSessionTimeout is how long a session that never received a // playback position and never served media bytes is kept before expiring. AbandonedSessionTimeout = 2 * time.Minute // StartupGraceWindow is how long a freshly prepared/opened session holds a // stream-limit reservation while the client connects and starts fetching. StartupGraceWindow = 12 * time.Second // PlayingEvidenceWindowDirect is how recently a direct-play / range session // must have served media bytes or received a playing progress/timeline // report to count as playing when no range read is currently in flight. PlayingEvidenceWindowDirect = 45 * time.Second // PlayingEvidenceWindowHLS is how recently an HLS/DASH/transcode session // must have served a segment or received a playing progress/timeline report // to count as playing. HLS clients fetch segments in bursts between buffer // refills. PlayingEvidenceWindowHLS = 60 * time.Second // PlayingEvidenceWindowLive is how recently a Live TV viewer must have // consumed live media bytes/segments to count as playing. PlayingEvidenceWindowLive = 30 * time.Second )
Shared session liveness thresholds across playback, broker, live TV, Activity/Overview, restart/update gating, upload budget, and stream limits.
const BuiltinFormatPrefix = "ether:"
BuiltinFormatPrefix namespaces built-in format ids.
const EncoderInputScopeHeader = "X-Ether-Encoder-Input"
EncoderInputScopeHeader is reserved for a manager-issued input lease. It is never provider metadata, client authorization, a source lease or a URL token.
const GrantCredentialPrefix = "eg1_"
GrantCredentialPrefix reserves Ether-issued credentials from external providers.
const KindAutoVersionID = VersionSelectorPrefix + "eyJrIjoiYXV0byJ9"
KindAutoVersionID is the synthetic Auto slot identity of a plugin kind item's version menu (index 0). Its payload matches the canonical Auto selector ({"k":"auto"}), so Auto-slot checks recognize it uniformly across resolver, playback and frontends. Picked, Vela omits versionId.
const ( // MaxPrerollID is the largest pre-roll id a key can carry. MaxPrerollID int64 = 999_999_999 )
Pre-rolls are owner videos played before a feature (GitHub #298). They are served to clients as extras, so their rating keys are KindExtra keys with payloads in a range the extras registry never assigns.
const MaxTitleRuleKeys = 500
MaxTitleRuleKeys bounds the number of rating keys in one "title" visibility condition so compiled key IN (...) predicates stay bounded.
const MaxVariants = 7
MaxVariants caps both version-menu modes, including Auto. The resolver and Plex front end share this bound for tier/cut selection and balanced alternatives across resolutions.
const PreFetchContentIDPrefix = "pre:"
PreFetchContentIDPrefix namespaces Usenet pre-fetch content identities ("pre:<sizeBucket>|<poster>|<uploadDay>").
const PrivateTorrentReason = "private tracker torrent: only an existing debrid cache is used"
PrivateTorrentReason explains why an uncached private-tracker torrent is skipped rather than added to or downloaded by a debrid service.
const ProbeFactsVersion = 9
ProbeFactsVersion is the generation of facts a probe is expected to carry, including reference frames, descriptive audio handler titles, HEVC decoder- configuration completeness, AAC channels, scan and rotation facts. Persisted probes from an older generation are cache misses.
const RankPluginPrefix = "plugin:"
RankPluginPrefix namespaces plugin-contributed ranking steps: "plugin:<plugin id>/<key>". A profile lists the steps it uses in QualityProfile.PluginScores; each adds the number its plugin returns for a release to that release's custom format score.
const RowSourcePrecomposed = "precomposed"
RowSourcePrecomposed identifies utility rows already assembled by a host service. Their ordering and items are not generated by the recommendation engine. RowSourcePlex remains supported for existing data and clients.
const RuleFormatPrefix = "rule:"
RuleFormatPrefix keys a Prefer rule's score in CustomFormatScores: "rule:<rule id>".
const SetupOwnerID int64 = 1<<63 - 1
SetupOwnerID is the reserved source-ownership principal for an admitted LAN open-setup request. It is never persisted as a user or accepted as a login. Producers must stop using it immediately when any real owner exists.
const VersionSelectorPrefix = "ether-slot:v1:"
VersionSelectorPrefix identifies a configured menu choice rather than a concrete release. Only the resolver interprets or authorizes its payload.
const VisibilityFacts = FactGenres | FactStudios | FactCountries | FactKeywords | FactHomeRelease
VisibilityFacts is every fact a visibility decision can read.
Variables ¶
var ( FormatSources = []Source{SourceRemux, SourceBluRay, SourceWEBDL, SourceWEBRip, SourceHDTV, SourceDVD} FormatCodecs = []string{"hevc", "av1", "h264", "vp9", "vc1", "mpeg2", "xvid"} FormatAudioCodecs = []string{"truehd", "dtshd", "eac3", "dts", "ac3", "aac", "flac", "opus", "mp3"} )
FormatSources, FormatCodecs and FormatAudioCodecs are the release types, video codecs and audio formats with a built-in format, in the order the console lists them.
var ( ErrNotFound = errors.New("not found") ErrNotAvailable = errors.New("not available yet") // no acceptable release exists ErrMoreCandidates = errors.New("more candidates remain") // per-call validation budget hit with untried candidates left ErrPreparing = errors.New("item is still being prepared") ErrJobsBusy = errors.New("playback preparation jobs are all busy") ErrUnreleased = errors.New("title has not been released") ErrArticleMissing = errors.New("article missing on all providers") ErrArticleCorrupt = errors.New("corrupt article or media data") ErrReleaseRejected = errors.New("release cannot be streamed") // ErrNoUsableFile reports a structural verdict that a release contains no // file usable for the request (for example, no matching audio/book file or // no playable video), distinct from transient transport/article failures. ErrNoUsableFile = errors.New("release has no usable file for this request") ErrArchiveUnstreamable = errors.New("this archive format or compression method cannot be streamed") ErrBudgetExhausted = errors.New("indexer daily budget exhausted") ErrStreamLimit = errors.New("stream limit reached") // ErrPolicyUnconfirmed means the durable policy store could not be read. // Callers may keep an unrestricted cached decision. Restricted viewers fail closed. ErrPolicyUnconfirmed = errors.New("policy store unavailable") // filter; the caller pages by offset instead. ErrSeekUnavailable = errors.New("seek title unavailable") // ErrVideoTranscodingDisabled means delivery requires re-encoding video // while transcode.videoTranscoding is set to "off". ErrVideoTranscodingDisabled error = videoTranscodingDisabledError{} )
var ErrDebridAuth = errors.New("debrid: authentication failed")
ErrDebridAuth is a debrid service rejecting the configured API key (or an account that cannot use the API). A configuration problem, never a release failure.
var ErrDownloadBudget = errors.New("download: temporary disk budget exceeded")
ErrDownloadBudget is returned when a download would exceed the temporary disk budget for remuxed files.
var ErrDownloadLimit = fmt.Errorf("the debrid account is at its active-download limit: %w", ErrDownloadRefused)
ErrDownloadLimit is ErrDownloadRefused because the debrid account is at its active-download limit (Real-Debrid too_many_active_downloads, TorBox ACTIVE_LIMIT): no release of any title can start downloading for now.
var ErrDownloadNeedsTranscode = errors.New("download: source codecs cannot be copied to MP4")
ErrDownloadNeedsTranscode is returned by DownloadRemuxer when the resolved streams cannot be copied or converted into an MP4 the requesting client's download profile plays.
var ErrDownloadPaused = fmt.Errorf("torrent adds are temporarily paused after provider refusals: %w", ErrDownloadRefused)
ErrDownloadPaused means Ether temporarily stopped adding torrents after repeated provider refusals; no download was submitted during the pause.
var ErrDownloadQueued = fmt.Errorf("sent to the debrid service to download: %w", ErrNotCached)
ErrDownloadQueued reports that an uncached torrent was handed to a debrid account to download (cached-only off): not playable yet, but it will be.
var ErrDownloadRefused = fmt.Errorf("the debrid service did not take it to download: %w", ErrNotCached)
ErrDownloadRefused reports that an uncached torrent could not be sent to a debrid account to download (cached-only off): the service refused it (a blocked file, a refused add) or the add failed. Nothing is downloading.
var ErrEncoderExhausted = errors.New("encoder session exhausted")
ErrEncoderExhausted means the encoder session reached its per-session or per-segment failure cap or the client is gone; further failover swaps against this session cannot succeed.
var ErrEncoderInputPending = errors.New("encoder input producers are pending")
var ErrEncoderInputUnverified = errors.New("encoder input producer retirement is unverified")
var ErrEncoderPending = errors.New("encoder retirement is pending")
var ErrForegroundOnly = errors.New("background check cannot decide this source")
ErrForegroundOnly reports a speculative check that could not decide a source without work only a foreground attempt may do (adding a torrent to a debrid account, say). Like ErrBudgetExhausted it is never evidence of source absence: a foreground caller tries the source itself.
var ErrMetadataFiltered = errors.New("metadata is hidden by catalogue visibility rules")
var ErrMetadataIdentity = errors.New("metadata has no supported catalogue identity")
var ErrNoSources = fmt.Errorf("no indexers to search: %w", ErrNotAvailable)
ErrNoSources reports that there is nothing to search: no enabled indexer at all. A configuration problem, not proof a title has no release, so callers must not record the title as unavailable.
var ErrNoTorrentSources = fmt.Errorf("debrid has no torrent indexer to search: %w", ErrNoSources)
ErrNoTorrentSources reports that debrid is the only way to play (no Usenet provider) but no enabled indexer returns torrents (Torznab, a Stremio addon or a torrent built-in site).
var ErrNotCached = fmt.Errorf("not cached by any debrid provider: %w", ErrNotAvailable)
ErrNotCached reports that no debrid provider can serve a torrent release instantly. It is a per-release skip, never proof the release is broken, so it wraps ErrNotAvailable and is not a permanent failure.
var ErrPrepareSlow = errors.New("playback preparation is still running")
ErrPrepareSlow indicates that preparation continues after the caller's wait.
var ErrPrivateUncached error = privateUncachedError{}
ErrPrivateUncached reports that a private-tracker torrent is not already cached on any debrid provider and therefore was never added or queued.
var ErrReplacementSuperseded = errors.New("replacement output superseded")
ErrReplacementSuperseded means a seek or another input change abandoned the original handoff; its old source must not be used for rollback.
var ErrSourceChanged = errors.New("playback: source revision changed")
ErrSourceChanged signals an absent or different source revision.
var ErrWrongContent = fmt.Errorf("release contains different content: %w", ErrNotAvailable)
ErrWrongContent is a request-specific release mismatch, never an account failure or proof that the torrent is unusable for another title.
var ProfileMediaTypes = []string{MediaMovie, MediaTV}
ProfileMediaTypes lists the media a quality profile can serve, in the order the console shows them. It is the one list: validation, the upgrade split, shared-name resolution and the console's media options (PROFILE_MEDIA in web/src/lib/releases.ts) all follow it. Adding a media such as anime means adding its constant here and to PROFILE_MEDIA, plus classifying titles into it (titleMedia in the resolver); nothing else is restructured.
var TVOnlyFormats = []string{FormatSeriesYearDiffers}
TVOnlyFormats are built-in formats only TV episodes can match.
Functions ¶
func AudioFormat ¶
AudioFormat is the built-in format id of an audio format.
func BrowseScope ¶
func BrowseSeekable ¶
func BrowseSeekable(q BrowseQuery) bool
BrowseSeekable reports whether Browse continues a page after AfterKey in q's sort order: one media type and one sort over a stored column (or the key order). Other queries ignore AfterKey.
func CarrySearchCoverage ¶ added in v0.3.3
CarrySearchCoverage carries src's coverage record into dst, for a search that runs on a context detached from its caller.
func CatalogCandidates ¶
func CatalogViewerID ¶
func CatalogViewerRestricted ¶
CatalogViewerRestricted reports a catalogue viewer with a content rating cap or section limits: catalogue rules fail closed for them.
func CheckReleaseHealth ¶
func CheckReleaseHealth(ctx context.Context, hc HealthChecker, releaseID string, nzb []byte) (bool, error)
CheckReleaseHealth runs hc.CheckRelease when hc implements it, else hc.Check.
func ClassifyDevice ¶
ClassifyDevice maps a Plex client's X-Plex-Product, X-Plex-Platform and X-Plex-Device headers onto a hub form factor (DeviceTV, DeviceMobile, DeviceWeb, DeviceDesktop). Playback codecs, HDR and subtitle support are not decided here; those come from the client capability registry.
- TV: Apple TV, Android TV / Google TV / Fire TV / Shield, Roku, smart TVs (Samsung Tizen, LG webOS, Vizio, Hisense, Sony...), game consoles (Xbox, PlayStation) and set-top boxes.
- Desktop: Plex HTPC, Plex for Windows/Mac/Linux, Plex Media Player.
- Web: Plex Web in any browser.
- Mobile: Plex for iOS / Android phones and tablets.
Unknown clients fall back on their platform, then on DeviceWeb.
func CodecFormat ¶
CodecFormat is the built-in format id of a video codec.
func ColdDetail ¶
ColdDetail reports whether key is the exact page allowed a cold fill.
func CountsTowardMinimum ¶
CountsTowardMinimum reports whether a format's score counts toward a profile's minimum custom format score: only the owner's and imported formats do.
func DaypartAt ¶
DaypartAt returns the daypart of t in t's own location: morning 05:00–11:59, afternoon 12:00–16:59, evening 17:00–21:59, late 22:00–04:59.
func DetailBurst ¶
DetailBurst records a detail read of key by this client and reports whether the client is reading detail pages like a crawler. Repeat reads of the same title do not count.
func EffectiveSortTitle ¶
EffectiveSortTitle returns the collation key for a title: the folded explicit sortTitle when one is present, otherwise TitleSortKey(title).
func ExactPeopleOnly ¶
ExactPeopleOnly reports WithExactPeopleOnly.
func ExplicitSearch ¶ added in v0.3.2
ExplicitSearch reports that ctx belongs to an explicit search.
func FacetID ¶
FacetID is a facet value's stable identifier (a genre, studio or country as the Jellyfin and Emby surfaces name it): a version-5-shaped UUID of the kind and value, without dashes. The catalogue stores it beside the studio vocabulary so an identifier resolves by index instead of by hashing every stored value.
func FilterOutSurroundAudio ¶
FilterOutSurroundAudio returns codecs without surround audio formats.
func FoldSortTitle ¶
FoldSortTitle normalizes an explicit sort title (such as Plex titleSort or Jellyfin SortName) to lowercase with invisible format characters stripped, Latin diacritics and ligatures folded to base ASCII letters, and digit runs encoded for numeric collation. Explicit sort titles keep their leading articles and punctuation intact.
func FoldedSortTitleForRow ¶
FoldedSortTitleForRow computes the current sort key for an existing stored row during backfill migrations. Stored values matching previous auto-derived rules (pre-fold v0 or pre-punctuation/numeric v1) are recomputed from title; custom source sort titles are preserved and normalized with FoldSortTitle.
func ForegroundReserve ¶ added in v0.2.8
func HasWarmReadWindow ¶
func IndexerPurpose ¶ added in v0.3.3
IndexerPurpose returns ctx's purpose tag, or IndexerPurposeOther.
func IndexerSkipped ¶ added in v0.3.3
IndexerSkipped reports whether ctx's search leaves out the indexer id.
func InheritBackground ¶ added in v0.2.8
InheritBackground carries admission policy into a shared worker whose lifetime belongs to the engine, without tying that worker to one waiter's cancellation.
func InheritIndexerPurpose ¶ added in v0.3.3
InheritIndexerPurpose carries src's purpose tag into dst, for work detached from the caller's cancellation (a search that keeps filling the cache after Play started).
func IsAutoVersionSelector ¶
IsAutoVersionSelector reports whether selector denotes Auto (empty or an encoded {"k":"auto"} configured version slot).
func IsBackgroundAnalysis ¶
func IsBackgroundCheck ¶ added in v0.2.8
func IsBuiltinFormat ¶
IsBuiltinFormat reports whether id names a built-in format.
func IsExplicitVersionSlotSelector ¶
IsExplicitVersionSlotSelector reports whether selector denotes a non-Auto configured version slot (as opposed to Auto or a legacy concrete release ID).
func IsFireTV ¶ added in v0.3.2
IsFireTV reports an Amazon Fire TV. The Plex app there calls itself "Plex for Android (TV)"; the device header carries the model number ("AFTKRT", "AFTMM"), or a name that says Fire TV.
func IsGrantCredential ¶ added in v0.3.0
IsGrantCredential reports whether a credential uses Ether's reserved prefix.
func IsLastViewedSort ¶
IsLastViewedSort reports whether raw names the lastViewed sort or one of its accepted aliases ("lastViewed", "played", "last_viewed").
func IsPlexPart ¶
IsPlexPart reports whether ctx carries the Plex part marker.
func IsPluginPersonID ¶
IsPluginPersonID reports whether id is in the synthetic plugin-person ID range.
func IsPluginRankingStep ¶ added in v0.3.3
IsPluginRankingStep reports whether step is plugin-namespaced ("plugin:<id>/<key>").
func IsProfileMedia ¶
IsProfileMedia reports whether media is one a profile can serve.
func IsSpeculative ¶ added in v0.3.2
IsSpeculative reports whether ctx is still speculative work.
func IsSurroundAudioCodec ¶
IsSurroundAudioCodec reports the Dolby and DTS formats (AC-3, E-AC-3, TrueHD, DTS) that the surround conversion rule replaces with AAC.
func IsUnattendedSearch ¶ added in v0.3.3
IsUnattendedSearch reports whether nobody is waiting on ctx's search: marked unattended, or speculative work (a warm-up) not yet promoted to Play.
func IsWeekend ¶
IsWeekend reports whether t (in its own location) falls in the weekend viewing window: Friday from 17:00 through Sunday. Friday night behaves like a weekend night (films, longer sessions), Sunday daytime does too.
func JobsBusyErrorBody ¶
JobsBusyErrorBody encodes the standard JSON media error envelope for jobs_busy.
func JobsBusyFromPending ¶
JobsBusyFromPending constructs an ErrJobsBusy carrying the refusal message and a retry delay from PendingReply.RetryInMS, defaulting to 5s when unspecified.
func JobsBusyMessage ¶
JobsBusyMessage returns the viewer-facing message for an ErrJobsBusy refusal.
func JobsBusyRetrySeconds ¶
JobsBusyRetrySeconds returns the HTTP Retry-After value in whole seconds for an ErrJobsBusy error, rounding sub-second durations up and using fallback (default 5) when err carries no explicit RetryAfter.
func LocalResponse ¶
LocalResponse reports whether this read must avoid enrichment waits.
func MediaApplies ¶
MediaApplies reports whether a scope (a profile or rule's MediaType) applies when choosing for media. An empty media means the caller has no title context and accepts any scope.
func MediaTypeForApp ¶
MediaTypeForApp maps a Starr app to the media its profiles describe.
func NeedsGeneratedPoster ¶
NeedsGeneratedPoster reports whether a title has its own fallback poster. Seasons and episodes inherit their show's poster instead.
func NormalizeCatalogueTabFacet ¶
NormalizeCatalogueTabFacet normalizes a catalogue library facet name to its canonical singular key, returning ("", false) when unrecognized. For collections, an empty facet means owner collections.
func NormalizeReleasePoster ¶
NormalizeReleasePoster normalizes a Usenet poster string for content identity matching.
func NormalizeRuleDocument ¶
NormalizeRuleDocument repairs media-type fields and canonicalises valid "title" conditions without touching names, search text, or malformed values (which remain intact so validation rejects them).
func NormalizeRuleMediaType ¶
NormalizeRuleMediaType accepts historical labels while preserving unknown values so validation can report them instead of silently changing meaning.
func NoteSearchIncomplete ¶ added in v0.3.3
NoteSearchIncomplete marks ctx's search as missing an indexer's answer.
func OnDemandAllowedAt ¶
OnDemandAllowedAt reports whether ctx may open r, an on-demand stream link ranked at position rank (0 is the top candidate) of a Resolve. Work OnDemandStreamsAllowed admits may; a WithOnDemandWarm warm-up may open the one top-ranked, cached candidate its budgets admit; nothing else may.
func OnDemandCached ¶
OnDemandCached reports whether an add-on marks r cached on a debrid service and nothing about it is uncached: opening it queues no import or download. A Usenet-importing add-on never marks its streams that way, so such streams are never warmed or hedged.
func OnDemandStreamsAllowed ¶
OnDemandStreamsAllowed reports whether ctx may open an on-demand stream link: Play, failover and the owner's own checks may, and a WithOnDemandStreamsForAvailability file-availability check may when the owner enabled it. Speculative indexer work (warm-ups, prefetch, detail discovery), background checks and work marked WithoutOnDemandStreams may not; they answer ErrForegroundOnly.
func OnDemandWarmGranted ¶
OnDemandWarmGranted reports whether ctx's warm-up was granted r's link by OnDemandAllowedAt; the source opening the link checks it.
func ParseCatalogueAddedMonth ¶
ParseCatalogueAddedMonth parses a canonical "YYYY-MM" bucket ID into inclusive UTC Unix bounds.
func ParseCatalogueRatingBand ¶
ParseCatalogueRatingBand maps a canonical rating band ID onto (min, max, maxExclusive).
func ParseCatalogueRuntimeBand ¶
ParseCatalogueRuntimeBand maps a canonical runtime band ID onto inclusive seconds (minSec, maxSec).
func PlexSaferRating ¶ added in v0.3.0
PlexSaferRating reports that catalogue queries on ctx should hide titles whose cached Plex rating exceeds the viewer's limit.
func PluginLibraryKey ¶
PluginLibraryKey is the library key a plugin kind owns (spec §1.1): "pk-" + slug(pluginID) + "-" + slug(kindKey), matching internal/libraries.UpsertPluginLibrary. The key is an opaque unique slug; ownership is always read back from the stored plugin/kind columns, never parsed out of the key.
func PluginPersonID ¶
PluginPersonID derives a deterministic positive synthetic person ID from a person's display name (case- and whitespace-folded). Returns 0 when blank.
func PreFetchContentIDFor ¶
PreFetchContentIDFor builds a pre-fetch Usenet content identity from a byte size, poster, and upload date. Missing fields return "".
func PreparingFromPending ¶
PreparingFromPending constructs an ErrPreparing carrying a retry delay from a plugin's PendingReply.RetryInMS hint, defaulting to 5s when unspecified.
func PreparingRetrySeconds ¶
PreparingRetrySeconds returns the HTTP Retry-After value in whole seconds for err, rounding sub-second durations up and using fallback (default 5) when err carries no explicit RetryAfter.
func ProfileServesEveryMedia ¶
func ProfileServesEveryMedia(profiles []QualityProfile, name string) bool
ProfileServesEveryMedia reports whether a profile named name exists for every profile media, which makes the name shared policy before a title's media is known.
func ProviderLeaseCancel ¶
func ProviderLeaseCancel(ctx context.Context) context.CancelFunc
func PublishDescribeProgress ¶
func PublishDescribeProgress(ctx context.Context, spec *CollectionSpec, items []Title)
PublishDescribeProgress is a no-op outside an active headless search job.
func QualityOrderError ¶
func QualityOrderError(order []QualityItem) string
QualityOrderError checks a profile's quality order: at most 64 items of 1 to 64 "<source>-<height>" qualities, each quality in one item only. An empty order ranks every quality alike.
func ReleaseSizeBucket ¶
ReleaseSizeBucket maps a positive byte size to a logarithmic ~10% bucket so small yEnc/NFO accounting differences across indexers land in the same bucket.
func ReportDetailPending ¶
ReportDetailPending is called only by a producer with queued or running work. Work for nested rows or unrelated titles does not affect the requested page.
func ResolutionLabel ¶ added in v0.3.4
ResolutionLabel is the presentation label for nominal dimensions.
func ResolutionTier ¶ added in v0.3.4
ResolutionTier returns the nominal vertical tier, including cropped video. Zero means unknown and 240 means a known sub-480 SD picture.
func SameReleaseContent ¶
SameReleaseContent reports whether a and b represent the same underlying media release (same ID, content/source/info/stream identity, GUID on the same indexer, or normalized release name). Content-level rejections such as a probed audio language mismatch use this to avoid retrying reposts or vault/indexer copies of the same release within one start without preventing broken-upload repost failover.
func ScoresForMedia ¶
ScoresForMedia is scores without the formats a profile's media can never match: a movie profile scores no TV-only format.
func SearchCategories ¶
SearchCategories parses comma-separated Newznab category IDs or a standard family name. Empty means the normal movie/TV search behaviour.
func SearchClientFrom ¶
SearchClientFrom returns the client/device identifier attached by WithSearchClient.
func SearchListFacts ¶
SearchListFacts reports WithSearchListFacts.
func SearchSummaryFacts ¶
func SessionActiveStream ¶
func SessionActiveStream(ps *PlaySession) bool
SessionActiveStream reports whether ps is an actively playing stream for the restart/update gate and upload budget. Paused, idle, abandoned, prepared-only, and stopped sessions return false.
func SessionCountsForLimit ¶
func SessionCountsForLimit(ps *PlaySession) bool
SessionCountsForLimit reports whether ps counts toward stream limits. Playing streams and freshly starting sessions count; paused, idle, abandoned, and stopped sessions do not.
func SessionPaused ¶
func SessionPaused(ps *PlaySession) bool
SessionPaused reports whether ps is explicitly paused.
func SessionVisible ¶
func SessionVisible(ps *PlaySession) bool
SessionVisible reports whether ps should be shown in Console Overview and Activity (playing or explicitly paused).
func SourceFormat ¶
SourceFormat is the built-in format id of a release type.
func SourceLabel ¶ added in v0.3.4
func SourceRevision ¶ added in v0.3.0
func SourceRevision(s *PlaySession) string
SourceRevision identifies a release/file without exposing its name or upstream identifiers. Local revisions detect filesystem changes; they do not claim content immutability. Unsupported or unknown sources are empty.
func SpeculativeIndexerWork ¶ added in v0.3.4
SpeculativeIndexerWork reports whether ctx's indexer requests are work no viewer pressed Play on: a warm-up not yet promoted to Play, a preload, prefetch, watchlist or cache-fill search (WithUnattendedSearch), a detail-page version discovery, or a background availability check. Such work uses its class's small slice of each indexer's daily limit, asks only the primary query and never fans out into rescue searches. Play and the owner's own console actions are not speculative.
func SpendBackground ¶ added in v0.2.8
func StreamingFormatScores ¶
StreamingFormatScores are the scores the device and identity streaming formats carry on every profile Ether creates or imports. Viewer's language is not among them: a profile scores it only when it expresses that preference (Ether's own profiles do; an imported pack's language formats are its authors' choice).
func TargetReleaseID ¶
func TargetReleaseID(releaseID string, t ReleaseTarget) string
TargetReleaseID derives a stable release ID for one episode of a multi-file release, so health, pins, cache and bad marks apply to the episode file rather than the whole pack.
func TitleSortKey ¶
TitleSortKey derives the normalized sort key for a display title: strips invisible format characters, ignores leading non-alphanumerics, drops a leading English article ("the ", "a ", "an ", case-insensitively), folds Latin accents/diacritics and ligatures to base ASCII letters, and encodes digit runs for numeric collation.
func TorrentOnlySearch ¶
TorrentOnlySearch reports whether ctx's search wants only torrent indexers.
func TrickplayCacheKey ¶
func TrickplayCacheKey(s *PlaySession) string
TrickplayCacheKey binds preview work to the selected item, release and opened source member. An expired local revision is not safe to serve.
func ValidArtworkPath ¶
ValidArtworkPath accepts one TMDB image filename, never a host or traversal.
func ValidCardShape ¶
ValidCardShape reports whether s is a valid stored Library.CardShape value ("" for the library's default, or "poster" | "landscape" | "square").
func ValidDateDisplay ¶
ValidDateDisplay reports whether s is a valid library dateDisplay value.
func ValidExternalID ¶
ValidExternalID reports whether id is a legal plugin external id (spec §2.2: ^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$, no ':' or '/').
func ValidMediaClass ¶
ValidMediaClass reports whether s is a supported content kind media class.
func ValidMediaRole ¶
ValidMediaRole reports whether s is a supported content kind level role.
func ValidTabLayout ¶
ValidTabLayout reports whether s is a valid stored LibraryTab.Layout value ("" for default "grid", or "grid" | "list" | "timeline").
func WarmReadContext ¶
WarmReadContext gives each background GET its own cancellation, leaving ranges at or beyond the playhead running. Future stale runs are refused too.
func WithBackgroundBudget ¶ added in v0.2.8
func WithBackgroundBudget(ctx context.Context, budget BackgroundBudget) context.Context
func WithBrowseScope ¶
WithBrowseScope identifies a tokenless client's section/sort/filter sequence. Protocol adapters omit offsets and page sizes, and never include credentials.
func WithColdDetail ¶
WithColdDetail permits one bounded provider payload for this exact page's missing catalogue record. Nested list rows and unrelated recommendations retain the ordinary local-response policy.
func WithDescribeProgress ¶
func WithDescribeProgress(ctx context.Context, publish func(*CollectionSpec, []Title)) context.Context
WithDescribeProgress observes bounded candidates from the existing Describe tools. The callback must be safe for concurrent read-only tool executions.
func WithExactPeopleOnly ¶
WithExactPeopleOnly marks a people-to-titles lookup where title matches already fill the caller's window, so only exact or near-exact full-name person matches (which rank right after exact title matches) can surface.
func WithExplicitSearch ¶ added in v0.3.2
WithExplicitSearch marks a request as a viewer or owner typing a search. Catalogue visibility then applies only rules scoped everywhere, so a title hidden from browsing alone can still be found.
func WithForegroundReserve ¶ added in v0.2.8
func WithIndexerPurpose ¶ added in v0.3.3
WithIndexerPurpose tags ctx's indexer requests with purpose. The innermost tag wins, so a rescue fan-out started by playback counts as rescue; speculative work is never re-tagged out of its class.
func WithIndexerSkip ¶ added in v0.3.3
WithIndexerSkip marks the indexers (by feed source id, core.ReleaseFeed.ID) a search should leave out: a background probe skips indexers whose release feed has already shown it everything new.
func WithLiveApp ¶
WithLiveApp names the client app (frontend surface id such as "plex" or "jellyfin") a Live TV request is served to, so the owner's per-app channel visibility applies. Requests without an app (the owner console) see every channel; viewer access rules apply either way.
func WithLocalResponse ¶
WithLocalResponse requests an immediate answer from local snapshots and caches. Optional enrichment may refresh behind the response.
func WithMediaCapWait ¶
func WithMediaCapWait(ctx context.Context, m *MediaCapWait) context.Context
func WithOnDemandStreamsForAvailability ¶
WithOnDemandStreamsForAvailability marks ctx as the client's file-availability check with the owner's "let availability checks open add-on streams" setting on. That one check may open on-demand add-on stream links within its existing timeouts and concurrency limits even though it is speculative warm-up work that otherwise must not. The mark is granted to no other work — not warm-ups, prefetch, discovery or background checks — and the caller sets it only when the setting is on. When off, the check is marked WithoutOnDemandStreams instead and answers ErrForegroundOnly.
func WithOnDemandWarm ¶
WithOnDemandWarm marks speculative work that follows a strong play intent (an Up Next or next-episode warm-up, a detail page held by a device with known caps). Such work may open exactly one on-demand stream link: the top-ranked candidate, only when its add-on reports the release cached on a debrid service (no import or download is queued), and only when admit (the caller's per-viewer and per-add-on budgets; nil admits) agrees. Nothing else changes: a failed or refused add-on stream is never followed by a second one in the background.
func WithPlexPart ¶
WithPlexPart marks a byte-range request as a Plex part request, which selects the PMS byte-serving contract without changing the representation semantics of other frontends or the encoder loopback.
func WithPlexSaferRating ¶ added in v0.3.0
WithPlexSaferRating marks a request so catalogue SQL also applies cached Plex content-rating levels. Other frontends leave the context unset.
func WithProviderLeaseCancel ¶
WithProviderLeaseCancel lets a provider limiter stop the HTTP request if a distributed connection lease is lost. Callers still release on body close.
func WithRangeResponse ¶
func WithRangeResponse(ctx context.Context, policy RangeResponse) context.Context
func WithRankingCandidates ¶
func WithRankingCandidates(ctx context.Context, c *SearchCandidates) context.Context
WithRankingCandidates marks titles a caller ranks and filters itself and shows only a page of, in full: a related shelf. A catalogue browse read with it returns its movies and shows with their rows, c.Facts, the facts the catalogue's own policy reads, and the credits a ranking reads (RankCast, RankWriters, RankCrew and every director), not every credit, alternative title and trailer; a title c.Detail reports comes back in full. It records the titles it returned partial (c.Partial), and the caller reads those of its page in full before showing them. Partial titles never reach a cache other callers read. Only a browse reads the mark.
func WithReadOrigin ¶
func WithReadRetirement ¶ added in v0.3.0
func WithReadRetirement(ctx context.Context, tracker *ReadRetirement) context.Context
WithReadRetirement attaches request-scoped retirement tracking.
func WithSearchAffinity ¶ added in v0.3.3
func WithSearchAffinity(ctx context.Context, fn SearchAffinityFunc) context.Context
WithSearchAffinity attaches the searching viewer's affinity to ctx, so the catalogue ranks titles the viewer knows first among equally good matches.
func WithSearchCandidates ¶
func WithSearchCandidates(ctx context.Context, c *SearchCandidates) context.Context
WithSearchCandidates attaches c to a search (see SearchCandidates). A nil c asks for full results again, as for a search ctx hands on to another one.
func WithSearchClient ¶
WithSearchClient attaches the client/device identifier for per-client search-as-you-type single-flight cancellation.
func WithSearchListFacts ¶
WithSearchListFacts marks a search whose results are rendered as list items (a Plex search hub: three cast members, the directors, genres, countries, studios): the catalogue reads those facts for its page, not every credit, keyword and alternative title of every result.
func WithSearchMemo ¶
WithSearchMemo installs a memo for the rest of one search request.
func WithSearchSummaryFacts ¶
WithSearchSummaryFacts marks movie/show searches rendered using scalar title metadata and posters only. Visibility and query-filter facets are still read; credits and other detail facts are not needed. Partial titles must not enter the full-title cache. Searches without this opt-in retain full results.
func WithSearchTypes ¶
WithSearchTypes attaches the media types a search accepts to ctx, so sources with a type-agnostic signature (such as PeopleTitles) restrict their lookup to the caller's requested types.
func WithSpeculative ¶ added in v0.3.2
WithSpeculative marks ctx as speculative work: a warm-up for a title nobody has pressed Play on yet. The returned promote clears the mark when a Play takes the work over, so from then on it runs as a real play.
func WithStreamKey ¶ added in v0.3.0
WithStreamKey tags ctx with the playback stream its reads serve, so the Usenet fetcher can tell a stalled read from ordinary variance between concurrent viewers. key must be comparable (a pointer, typically); nil leaves ctx unchanged.
func WithTorrentOnlySearch ¶
WithTorrentOnlySearch confines a fleet search to indexers that return torrents (Torznab, Stremio addons, torrent built-in sites), leaving Usenet Newznab indexers untouched when the caller only inspects torrent results.
func WithUnattendedSearch ¶ added in v0.3.3
WithUnattendedSearch marks a search nobody is waiting on (a watchlist check, a preload, a next-episode prefetch): it is speculative indexer work (SpeculativeIndexerWork), which asks only each indexer's primary query and never fans out into fallback or rescue queries as Play does.
func WithWarmReadWindow ¶
func WithWarmReadWindow(ctx context.Context, w *WarmReadWindow) context.Context
func WithoutCatalogViewer ¶
WithoutCatalogViewer drops the viewer from ctx, for reads that are the same for every viewer (a facet name's identifier) and must share one cache entry.
func WithoutLocalResponse ¶
WithoutLocalResponse clears LocalResponse on ctx while preserving deadlines, cancellation and other request values.
Types ¶
type ActiveUserSource ¶ added in v0.2.7
ActiveUserSource checks current server membership for delegated stream access.
type ActivityDay ¶
type ActivityDay struct {
Date string `json:"date"` // YYYY-MM-DD, server local time
Plays int `json:"plays"`
Hours float64 `json:"hours"`
UniqueViewers int `json:"uniqueViewers"`
}
ActivityDay is one day of server-wide viewing.
type AiredEpisodeTally ¶
type AiredEpisodeTally struct {
// Total is every aired episode of the show, the total the aired
// episode listing reports.
Total int
// Seasons counts, by season number, the aired episodes not in Judge and
// how many of those the viewer has played.
Seasons map[int]EpisodeTally
// Judge are the aired episodes the counts leave out: released after the
// settled time, or named by the caller.
Judge []RatingKey
}
AiredEpisodeTally counts one show's stored, aired episodes for a viewer without reading them.
type AlignRequest ¶
type AlignRequest struct {
Key RatingKey `json:"key"`
From Release `json:"from"`
To Release `json:"to"`
FromDuration time.Duration `json:"fromDuration,omitempty"`
ToDuration time.Duration `json:"toDuration,omitempty"`
}
AlignRequest names two releases of the same title whose timelines should be matched (for example the failing and the replacement release of a mid-stream failover, or a marker source's reference cut and the release being played).
type AnalysisReaderAt ¶
type AnalysisReaderAt interface {
ReadAtAnalysisContext(context.Context, []byte, int64) (int, error)
}
AnalysisReaderAt is an explicitly admitted background analysis read. It keeps prefetch priority while allowing provider-account pacing and viewer yielding.
type AnalysisSourceStats ¶
AnalysisSourceStats reports only analysis provider requests, bytes and errors.
type ArchiveVolumeSource ¶
type ArchiveVolumeSource interface {
ArchiveVolumes() (volumes []MediaSource, format string, member string)
}
ArchiveVolumeSource is implemented by a MediaSource backed by one or more raw archive volume streams (such as a compressed or solid RAR/7z/ZIP set on Usenet) that a caller can extract through an archive reader. Calling ArchiveVolumes hands volume inspection to the caller; closing the parent MediaSource closes all returned volume MediaSources.
type ArticleFetcher ¶
type ArticleFetcher interface {
// Body returns the decoded payload of one article (one NZB segment).
// Returns ErrArticleMissing when no provider has it.
Body(ctx context.Context, messageID string, groups []string, prio Priority) ([]byte, error)
// BodyPart is Body plus the article's yEnc =ybegin/=ypart header, which
// gives the segment's exact byte range inside the posted file.
BodyPart(ctx context.Context, messageID string, groups []string, prio Priority) ([]byte, ArticlePart, error)
// Stat reports whether any provider has the article.
Stat(ctx context.Context, messageID string) (bool, error)
}
ArticleFetcher fetches and yEnc-decodes articles across the configured providers, primary first, backfilling from block accounts.
type ArticlePart ¶
type ArticlePart struct {
Name string `json:"name"`
FileSize int64 `json:"fileSize"`
Part int `json:"part"`
Total int `json:"total"`
Begin int64 `json:"begin"`
End int64 `json:"end"`
}
ArticlePart is the yEnc header of one article. Begin and End are 1-based inclusive offsets in the posted file, as in =ypart; for single-part posts Begin is 1 and End is FileSize.
type ArtworkAccessPolicy ¶ added in v0.2.7
ArtworkAccessPolicy exposes the optional Restricted capability.
type ArtworkImageFile ¶
type ArtworkImageFile struct {
FilePath string `json:"file_path"`
Width int `json:"width"`
Height int `json:"height"`
ISO639 string `json:"iso_639_1"`
VoteAvg float64 `json:"vote_average"`
}
ArtworkImageFile describes one candidate remote artwork variant.
type ArtworkImages ¶
type ArtworkImages struct {
Backdrops []ArtworkImageFile `json:"backdrops"`
Posters []ArtworkImageFile `json:"posters"`
Logos []ArtworkImageFile `json:"logos"`
Still []ArtworkImageFile `json:"stills"`
}
ArtworkImages groups candidate artwork variants for a title by kind.
type AudioLimit ¶ added in v0.3.3
AudioLimit applies to one audio codec, or all codecs when Codec is "*".
type AuthoritativeTitleRefresher ¶ added in v0.2.37
type AuthoritativeTitleRefresher interface {
RefreshTitle(ctx context.Context, key RatingKey, persist bool) (*Title, error)
}
AuthoritativeTitleRefresher fetches current movie or show details and optionally persists them. It never falls back to cached data on failure and does not apply release visibility.
type AvailabilitySource ¶ added in v0.2.7
AvailabilitySource exposes the optional Available capability.
type BackgroundBudget ¶ added in v0.2.8
BackgroundBudget is an optional admission hook for speculative work. Ordinary playback has no hook. Implementations must be concurrency safe; denied work returns ErrBudgetExhausted and is never evidence of source absence.
type BatchWatchState ¶ added in v0.3.0
type BatchWatchState interface {
ScrobbleMany(context.Context, int64, []RatingKey) error
UnscrobbleMany(context.Context, int64, []RatingKey) error
}
BatchWatchState updates a collection of watched states atomically.
type Bedtime ¶
type Bedtime struct {
Time string `json:"time"`
WakeTime string `json:"wakeTime"`
Timezone string `json:"timezone"`
Days []int `json:"days,omitempty"`
}
Bedtime days name the day the sleep window starts (Sunday=0). An empty list means every day. Empty wakeTime defaults to 06:00; empty timezone uses the server's local timezone.
type BedtimeState ¶
type BitrateAccessPolicy ¶ added in v0.2.7
BitrateAccessPolicy exposes the optional BitrateLimit capability.
type BrowseQuery ¶
type BrowseQuery struct {
// CursorPage selects the console keyset path. AfterKey is also the exclusive
// keyset cursor for SortKey exports, and for a single-type page with one
// scalar sort (title, popularity, rating, year, released, duration, or
// added for movies and series) it continues after that title in the
// sort order, with Offset counted from it. A seek whose title no longer
// matches fails with ErrSeekUnavailable; the caller pages by offset.
CursorPage bool
AfterKey RatingKey
// PlaylistSource evaluates a saved smart membership before applying this
// query's filters and optional episode-to-parent projection.
PlaylistSource *BrowseQuery
PlaylistSourceLimit int
SortLastViewed bool
SortViewerID int64
Filter Filter
Sort SortOrder
Desc bool
SecondarySorts []SortSpec
Offset int
Limit int
// NoTotal skips counting the filter's matches, which reads every title
// the filter admits. Page.Total is then offset plus the items returned.
NoTotal bool
// CheapTotal, when set alongside NoTotal, returns an exact Page.Total
// (with Page.TotalExact = true) only when an exact count is available
// cheaply (tallies, cached counts, or bounded index counts). Otherwise
// it skips counting and leaves Page.TotalExact false.
CheapTotal bool
// SuppressExpand skips starting background plugin facet or person
// expansion when sampling rows or fanning out search queries.
SuppressExpand bool
// ListRows reads a key-ordered (SortKey) page as list rows instead of
// full titles (an export). Other page shapes ignore it.
ListRows *ListRows
}
type BufferedInputSwapper ¶ added in v0.2.8
type BufferedInputSwapper interface {
SwapInputBuffered(context.Context, string, MediaInfo, time.Duration) error
}
BufferedInputSwapper preserves published media before starting replacement input at the contiguous buffer boundary. The caller must verify identity timeline alignment at the playhead and buffer boundary; differing trailing durations alone do not prevent reuse.
type BufferedSource ¶ added in v0.3.3
type BufferedSource interface{ BufferedAhead() int64 }
BufferedSource reports contiguous bytes downloaded ahead of the reader.
type BugSettings ¶
type BugSettings struct {
Position string `json:"position,omitempty"`
Opacity *float64 `json:"opacity,omitempty"`
Style string `json:"style,omitempty"`
Size string `json:"size,omitempty"`
Source string `json:"source,omitempty"`
FadeBreaks *bool `json:"fadeBreaks,omitempty"`
FadeCredits *bool `json:"fadeCredits,omitempty"`
}
BugSettings is a sparse owner override; nil fields inherit the look defaults.
func ResolveBug ¶
func ResolveBug(base, override *BugSettings) BugSettings
func (*BugSettings) Validate ¶
func (b *BugSettings) Validate() error
type BuiltinFormat ¶
type BuiltinFormat struct {
ID string `json:"id"`
Kind string `json:"kind"` // FormatKindRelease or FormatKindStreaming
Family string `json:"family,omitempty"` // FamilySource, FamilyCodec, FamilyAudio
}
BuiltinFormat describes one built-in format.
func BuiltinFormats ¶
func BuiltinFormats() []BuiltinFormat
BuiltinFormats lists every built-in format in console order.
type BurstArticleFetcher ¶ added in v0.2.8
type BurstArticleFetcher interface {
BodyPartBurst(ctx context.Context, messageID string, groups []string, prio Priority, until time.Time) ([]byte, ArticlePart, error)
}
BurstArticleFetcher optionally borrows idle live-reserved capacity for a short, explicitly bounded bulk-read burst. Live waiters retain precedence. The deadline limits new burst admission, not already transmitted bytes.
type CacheCause ¶ added in v0.3.3
type CacheCause struct {
Code string `json:"code"`
FirstSeen time.Time `json:"firstSeen,omitzero"`
Shelf *CacheShelfDetail `json:"shelf,omitempty"`
}
CacheCause is one observed reason for a release, with the first time it was seen.
type CachePlayRecorder ¶ added in v0.2.7
CachePlayRecorder exposes the optional RecordPlay capability.
type CacheProvenance ¶ added in v0.3.3
type CacheProvenance struct {
ReleaseID string
RatingKey RatingKey
File string
Size int64
Source string // release name, else indexer name
Indexer string // indexer / source provider name
Origin string // streaming service ("Usenet", "Real-Debrid", "HTTP", ...)
Title string // cache-facing display title
Cause string
Play bool
Shelf *CacheShelfDetail
}
CacheProvenance is what a caller knows about a release when bytes are written or a cause is established. Empty fields leave the existing metadata alone.
type CacheProvenanceRecorder ¶ added in v0.3.3
type CacheProvenanceRecorder interface {
RecordProvenance(CacheProvenance)
}
CacheProvenanceRecorder is implemented by caches that keep per-release provenance. Recording must never fail or block byte admission.
type CacheShelfDetail ¶ added in v0.3.3
type CacheShelfDetail struct {
ReasonCodes []string `json:"reasonCodes,omitempty"`
Score float64 `json:"score,omitempty"`
State string `json:"state,omitempty"` // fetched | reserved
}
CacheShelfDetail explains a preload-shelf selection for one release.
type CachedTitleSource ¶ added in v0.2.7
CachedTitleSource exposes the optional CachedTitles capability.
type Catalog ¶
type Catalog interface {
Get(ctx context.Context, key RatingKey) (*Title, error)
// Children: seasons of a show, episodes of a season.
Children(ctx context.Context, key RatingKey) ([]Title, error)
// Grandchildren: all episodes of a show.
Grandchildren(ctx context.Context, key RatingKey) ([]Title, error)
Browse(ctx context.Context, q BrowseQuery) (Page, error)
// Search reaches all of TMDB; matched titles join the browsable set.
Search(ctx context.Context, query string, types []MediaType, limit int) ([]Title, error)
// Lists from TMDB: "trending_day", "trending_week", "top_rated", "now_playing", "popular", "airing_today", "upcoming".
List(ctx context.Context, list string, t MediaType, limit int) ([]Title, error)
Similar(ctx context.Context, key RatingKey, limit int) ([]Title, error)
Collection(ctx context.Context, tmdbCollection int64) (name string, items []Title, err error)
// Facets for filter UIs: "genre", "year", "decade", "contentRating", "studio", "country".
Facet(ctx context.Context, t MediaType, facet string) ([]FacetValue, error)
// NextEpisode returns the episode after the given one, or ErrNotFound.
NextEpisode(ctx context.Context, episode RatingKey) (*Title, error)
// ByExternalID looks up a title by imdb ("tt123") or tvdb id.
ByExternalID(ctx context.Context, source, id string) (*Title, error)
}
Catalog is Ether's library: a local mirror of a TMDB slice plus on-demand fetches for anything else.
type CatalogFacetCollection ¶
CatalogFacetCollection is one facet bucket in a catalogue library's collections tab, along with its newest visible title for artwork.
type CatalogFacetCollectionsPage ¶
type CatalogFacetCollectionsPage struct {
Items []CatalogFacetCollection
More bool
}
CatalogFacetCollectionsPage is one page of catalogue facet collections.
type CatalogFacetCollectionsQuery ¶
type CatalogFacetCollectionsQuery struct {
Filter Filter
Facet string // genre|studio|network|country|language|contentRating|year|decade|franchise|tag|keyword|director|writer|resolution|hdr|audioLanguage|rating|runtime|addedMonth
Order string // count (default) | name
Query string // optional folded search string
Offset int
Limit int
}
CatalogFacetCollectionsQuery requests a paged facet listing over catalogue titles matching Filter.
type CatalogFacetPeoplePage ¶
type CatalogFacetPeoplePage struct {
Items []CatalogFacetPerson
More bool
}
CatalogFacetPeoplePage is one page of catalogue facet people.
type CatalogFacetPeopleQuery ¶
type CatalogFacetPeopleQuery struct {
Filter Filter
Facet string // cast | director | writer
Order string // name (default) | count
Query string // optional folded search string
Offset int
Limit int
}
CatalogFacetPeopleQuery requests a paged cast, director, or writer listing over catalogue titles matching Filter.
type CatalogFacetPerson ¶
CatalogFacetPerson is one person entry in a catalogue library's people tab.
type CatalogSchedule ¶ added in v0.2.45
CatalogSchedule exposes metadata-only placeholders when the owner opts in. Only dated, unaired episodes of an already airing regular season are returned. Callers must authorize the parent season and each episode for the viewer, render no media/playback links, and use the same scope for artwork. Ordinary Catalog methods remain released-only; this interface never authorizes playback.
type ChannelGraphics ¶
type ChannelGraphics interface {
Duration(lookID, moment string) (time.Duration, bool)
Clip(context.Context, ClipRequest) (ClipRef, bool)
Ensure(context.Context, ClipRequest)
}
ChannelGraphics never renders synchronously. Clip only reads the local cache.
type ChannelPreparer ¶ added in v0.2.7
type ChannelPreparer interface {
PrepareChannel(context.Context, *User, RatingKey, ClientCaps, string) (*PlaySession, error)
}
ChannelPreparer exposes the optional PrepareChannel capability.
type ChannelSegmentMetadata ¶
ChannelSegmentMetadata adds plugin policy metadata without expanding base fakes.
type Chapter ¶
type Chapter struct {
ID int64 `json:"id"`
Title string `json:"title,omitempty"`
Start time.Duration `json:"start"`
End time.Duration `json:"end"`
}
func ExtractKindItemChapters ¶
func ExtractKindItemChapters(hints json.RawMessage) []Chapter
ExtractKindItemChapters inspects a KindItem's Hints JSON for a non-empty "chapters" array and returns normalized Chapter markers in declaration order.
func ExtractKindItemChaptersFromItem ¶
ExtractKindItemChaptersFromItem inspects a KindItem for declared chapters, checking hints.chapters first and falling back to a declared "chapters" array field when present.
type ClientCapabilityOverride ¶ added in v0.3.0
type ClientCapabilityOverride struct {
Force bool `json:"force,omitempty"`
ID string `json:"id,omitempty"`
Product string `json:"product,omitempty"`
// ProductExact marks a product-only override already scoped by the app editor
// or migrated from the old substring matcher.
ProductExact bool `json:"productExact,omitempty"`
// ProductMatch preserves legacy substring selectors. New app edits are exact.
ProductMatch string `json:"productMatch,omitempty"`
// CopiedFrom identifies a migrated shared selector for the console badge.
CopiedFrom string `json:"copiedFrom,omitempty"`
Platform string `json:"platform,omitempty"`
Device string `json:"device,omitempty"`
// Version is the minimum client version (dotted numbers) this override requires.
Version string `json:"version,omitempty"`
VideoCodecs []string `json:"videoCodecs,omitempty"`
AudioCodecs []string `json:"audioCodecs,omitempty"`
Containers []string `json:"containers,omitempty"`
SubtitleCodecs []string `json:"subtitleCodecs,omitempty"`
DolbyVisionProfiles []int `json:"dolbyVisionProfiles,omitempty"`
MaxHeight int `json:"maxHeight,omitempty"`
MaxBitrateKbps int `json:"maxBitrateKbps,omitempty"`
HDR10 *bool `json:"hdr10,omitempty"`
DolbyVision *bool `json:"dolbyVision,omitempty"`
// AlwaysEncodeVideo forces every transcoded or remuxed video stream for
// matching clients onto the encoded path (keyframes on segment boundaries)
// instead of stream-copying video. Direct play of the original file is
// unaffected. Applies even when Force is false.
AlwaysEncodeVideo bool `json:"alwaysEncodeVideo,omitempty"`
Notes string `json:"notes,omitempty"`
}
ClientCapabilityOverride is an owner edit of one registry client. Nil slices and zero numbers leave the registry value in place. Runtime declarations win unless Force is set for the edited facts.
type ClientCapabilityProfiles ¶ added in v0.3.0
type ClientCapabilityProfiles struct {
DirectPlay []ClientDirectPlayProfile
Transcoding []ClientTranscodeProfile
Subtitles []ClientSubtitleProfile
Containers []ClientContainerProfile
Codecs []ClientCodecProfile
MaxStaticBitrate, MusicStreamingTranscodingBitrate, MaxStaticMusicBitrate int
}
ClientCapabilityProfiles are declared together by a single client. Nil profile collections mean omitted; an explicit empty collection remains empty. A nil pointer on ClientCaps preserves legacy protocol behavior.
type ClientCaps ¶
type ClientCaps struct {
DVProfilesExplicit bool `json:"dvProfilesExplicit,omitempty"` // preserves an owner-forced empty profile set
// DVProfilesForced records an owner-forced non-empty Dolby Vision profile list.
DVProfilesForced bool `json:"-"`
// ForcedOverrideApplied records a runtime declaration replaced by an owner edit.
ForcedOverrideApplied bool `json:"-"`
// Broadcast inputs are selected for the channel rendition, independently
// of viewer quality preferences. Exclusions last only for this airing.
BroadcastBitrateKbps int `json:"-"`
BroadcastExclude []string `json:"-"`
BroadcastReadyRelease string `json:"-"`
// Playback telemetry is supplied by the adapter.
InferBuffering bool `json:"inferBuffering,omitempty"`
NoPlaybackTelemetry bool `json:"noPlaybackTelemetry,omitempty"`
// BestEffortLiveStart bounds startup waits; playlist requests finish admission.
BestEffortLiveStart bool `json:"bestEffortLiveStart,omitempty"`
// ProbeLiveWithoutCodecs requires codec analysis even without declared codecs.
ProbeLiveWithoutCodecs bool `json:"probeLiveWithoutCodecs,omitempty"`
// ProbeLiveInput requests source facts before live delivery selection.
ProbeLiveInput bool `json:"probeLiveInput,omitempty"`
// PreserveEmptyVideoCodecs prevents registry inference when the adapter owns codec defaults.
PreserveEmptyVideoCodecs bool `json:"preserveEmptyVideoCodecs,omitempty"`
// DeferSourceCodecValidation lets delivery selection handle a source codec mismatch.
DeferSourceCodecValidation bool `json:"deferSourceCodecValidation,omitempty"`
// AwaitAdmissionIndex briefly joins the generation-owned index before delivery selection.
AwaitAdmissionIndex bool `json:"awaitAdmissionIndex,omitempty"`
ClientIP string `json:"clientIp,omitempty"` // trusted-proxy-resolved address, when known
// HLSTextRenditions: the client takes an embedded text subtitle as a
// WebVTT rendition of the session's HLS stream (Silo's
// hls_subtitle_renditions_v1), so the cues ride the picture's input read
// instead of a whole-file sidecar extraction. It does not make the
// session prefer HLS: original-file playback stays the client's choice.
HLSTextRenditions bool `json:"hlsTextRenditions,omitempty"`
Profiles *ClientCapabilityProfiles `json:"profiles,omitempty"`
Protocol Protocol `json:"protocol,omitempty"`
Product string `json:"product"` // X-Plex-Product: "Plex Web", "Plex for iOS", "Plex for Apple TV"
Platform string `json:"platform"` // X-Plex-Platform
PlatformVersion string `json:"platformVersion"`
Device string `json:"device"`
DeviceName string `json:"deviceName"`
ClientID string `json:"clientId"` // X-Plex-Client-Identifier
Version string `json:"version"`
// PreferredSourceHeight softly favors a known HD source for a new quality
// request. It never constrains eligibility or replaces an active source.
PreferredSourceHeight int `json:"preferredSourceHeight,omitempty"`
MaxHeight int `json:"maxHeight"` // 2160, 1080, 720...
ExplicitMaxHeight bool `json:"explicitMaxHeight,omitempty"` // true when MaxHeight came from a request header/query limitation rather than a product default
MaxHeightSource string `json:"-"` // declaration, preset or override that established MaxHeight
// HDRFormats preserves explicit display range declarations for Vela.
HDRFormats []string `json:"hdrFormats,omitempty"`
HDR10 bool `json:"hdr10"`
ExplicitNoHDR bool `json:"explicitNoHdr,omitempty"` // true when HDR was explicitly denied by profile-extra limitations
DolbyVision bool `json:"dolbyVision"`
VideoCodecs []string `json:"videoCodecs"` // h264, hevc, av1, vp9
AudioCodecs []string `json:"audioCodecs"` // aac, ac3, eac3, truehd, dts, opus, flac
Containers []string `json:"containers"` // mp4, mkv, mpegts
HLSContainers []string `json:"hlsContainers,omitempty"` // explicit segmented output targets; distinct from direct-play containers
MaxBitrateKbps int `json:"maxBitrateKbps"` // 0 = unlimited
DefaultRemoteBitrate bool `json:"defaultRemoteBitrate,omitempty"` // true when MaxBitrateKbps came from the server's default remote cap rather than a client limitation
SubtitleCodecs []string `json:"subtitleCodecs"` // native image/text subtitle rendering
DVProfiles []int `json:"dvProfiles,omitempty"` // explicit Dolby Vision profiles; empty uses defaults unless DVProfilesExplicit
VideoProfiles map[string][]string `json:"videoProfiles,omitempty"`
VideoLevels map[string]int `json:"videoLevels,omitempty"` // codec level in ffprobe units (H.264 51 = 5.1)
Remote bool `json:"remote"` // not on the server's LAN
// AudioLimits are request-declared limits on source audio and encoded output.
AudioLimits []AudioLimit `json:"audioLimits,omitempty"`
// TranscodeVideoCodecs and TranscodeAudioCodecs describe ordered output
// preferences for the current streaming protocol. Source selection and
// direct play continue to use VideoCodecs and AudioCodecs.
TranscodeVideoCodecs []string `json:"transcodeVideoCodecs,omitempty"`
TranscodeAudioCodecs []string `json:"transcodeAudioCodecs,omitempty"`
// Download marks a request for an offline download (Plex Downloads /
// Sync) rather than live playback: the resolver prefers compact,
// mobile-native releases and the whole file is remuxed (additive).
Download bool `json:"download,omitempty"`
// DownloadSourceMaxHeight permits a higher source on a download retry;
// MaxHeight remains the output constraint at the download remuxer.
DownloadSourceMaxHeight int `json:"downloadSourceMaxHeight,omitempty"`
// DolbyVisionBaseOnly delivers a Dolby Vision 7.6/8.1 source as its
// compatible HDR10 base layer: an owner override turned Dolby Vision off
// for the client, or a Dolby Vision start stalled on this client
// (additive).
DolbyVisionBaseOnly bool `json:"dolbyVisionBaseOnly,omitempty"`
// ConvertSurroundAudio is set by an owner device rule that converts
// Dolby/DTS/TrueHD audio to AAC. SupportsAudio refuses those codecs even
// when a later layer (a client direct-play profile) lists them again
// (additive).
ConvertSurroundAudio bool `json:"convertSurroundAudio,omitempty"`
// VideoMaxHeights bounds one decoder, such as a legacy Plex
// videoDecoders=h264{resolution:1080} declaration. MaxHeight stays the
// ceiling of the tallest codec the client decodes (additive).
VideoMaxHeights map[string]int `json:"videoMaxHeights,omitempty"`
// SegmentedSurroundOff keeps Dolby/DTS/TrueHD audio out of copied
// segmented output because a start stalled on it for this client.
// Direct play of the original file is unaffected (additive).
SegmentedSurroundOff bool `json:"segmentedSurroundOff,omitempty"`
// AlwaysEncodeVideo forces every transcoded or remuxed video stream for
// this client onto the encoded path (keyframes on segment boundaries)
// instead of stream-copying video. Direct play of the original file is
// unaffected (additive).
AlwaysEncodeVideo bool `json:"alwaysEncodeVideo,omitempty"`
}
ClientCaps is what a Plex client can play, derived from X-Plex-* headers, the client profile and its declared limits.
func (ClientCaps) SupportsAudio ¶
func (c ClientCaps) SupportsAudio(codec string) bool
func (ClientCaps) SupportsContainer ¶
func (c ClientCaps) SupportsContainer(ct string) bool
func (ClientCaps) SupportsVideo ¶
func (c ClientCaps) SupportsVideo(codec string) bool
type ClientCodecProfile ¶ added in v0.3.0
type ClientCodecProfile struct {
MediaType string
Codecs, Containers, SubContainers []string
Conditions, ApplyConditions []ClientProfileCondition
}
type ClientContainerProfile ¶ added in v0.3.0
type ClientContainerProfile struct {
MediaType string
Containers, SubContainers []string
Conditions []ClientProfileCondition
}
type ClientDirectPlayProfile ¶ added in v0.3.0
type ClientDirectPlayProfile struct {
MediaType string `json:"mediaType"`
Containers []string `json:"containers"`
VideoCodecs []string `json:"videoCodecs"`
AudioCodecs []string `json:"audioCodecs"`
}
ClientDirectPlayProfile keeps container and codec alternatives paired. Empty alternatives represent an unconstrained field, not another profile.
type ClientProfileCondition ¶ added in v0.3.0
type ClientProfileCondition struct {
Operator string `json:"operator"`
Property string `json:"property"`
Value string `json:"value"`
Required bool `json:"required"`
}
ClientProfileCondition preserves a client-declared condition for the broker. Required conditions unknown to an evaluator must not be silently accepted.
type ClientSubtitleProfile ¶ added in v0.3.0
type ClientSubtitleProfile struct{ Format, Method, DIDLMode, Language, Container string }
type ClientTranscodeProfile ¶ added in v0.3.0
type ClientTranscodeProfile struct {
MediaType, Delivery, Context string
Containers, VideoCodecs, AudioCodecs []string
EstimateContentLength, MPEGTSM2TS, CopyTimestamps, SubtitlesInManifest bool
SeekInfo, MaxAudioChannels string
MinSegments, SegmentLength int
BreakOnNonKeyFrames, AudioVBR *bool
Conditions []ClientProfileCondition
}
type ClipRequest ¶
type ClipRequest struct {
// Boundary is transient render scheduling metadata, excluded from clip hashes
// and serialized requests so identical content keeps its cached master.
Boundary time.Time `json:"-"`
// AssetDigest overrides this channel's moment without changing its shared look.
AssetDigest string `json:"assetDigest,omitempty"`
AssetDuration time.Duration `json:"assetDuration,omitempty"`
// ReelID and ReelClipID identify a break reel clip for playtime link resolution.
ReelID string `json:"reelId,omitempty"`
ReelClipID string `json:"reelClipId,omitempty"`
Bug *BugSettings
LookID string
Moment string
ChannelID string
ViewerID int64
Bind map[string]string
Art map[string]string
Language string
}
ClipRequest binds a look moment to the channel and upcoming programme.
type Collection ¶
type Collection struct {
RankedTop10 bool `json:"rankedTop10,omitempty"`
PreviewOnFocus bool `json:"previewOnFocus,omitempty"`
Key RatingKey `json:"key"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Kind string `json:"kind"` // "franchise", "trending", "smart", "user"
Type MediaType `json:"type"`
Filter *Filter `json:"filter,omitempty"` // smart
Sort SortOrder `json:"sort,omitempty"`
OwnerUserID int64 `json:"ownerUserId,omitempty"` // 0 = server-wide
PosterPath string `json:"posterPath,omitempty"`
BackdropPath string `json:"backdropPath,omitempty"`
ChildCount int `json:"childCount"`
Upcoming bool `json:"upcoming,omitempty"` // admits scoped future placeholders
// UpdatedAt changes when the collection's members or artwork change, so
// Plex clients refetch artwork (additive).
UpdatedAt time.Time `json:"updatedAt,omitempty"`
// MembershipRevision identifies ordered source membership, including changes
// within one timestamp tick. Internal only; wire protocols choose their token.
MembershipRevision string `json:"-"`
}
type CollectionArtwork ¶
type CollectionArtwork struct {
Mode string `json:"mode"` // auto | collage | backdrop | tmdb | custom
URL string `json:"url,omitempty"`
Accent string `json:"accent,omitempty"` // "#rrggbb"
}
CollectionArtwork selects the poster Plex shows for the collection.
type CollectionArtworkSource ¶ added in v0.2.7
type CollectionArtworkSource interface {
CollectionArtwork(context.Context, *User, RatingKey, string, int) ([]byte, string, bool, error)
}
CollectionArtworkSource exposes the optional CollectionArtwork capability.
type CollectionLayoutSource ¶ added in v0.2.7
type CollectionLayoutSource interface {
LayoutRow(context.Context, *User, HubContext, string) (*CollectionRow, error)
}
CollectionLayoutSource exposes the optional LayoutRow capability.
type CollectionPlaceholder ¶ added in v0.2.37
type CollectionPlaceholder interface {
AllowsPlaceholders(context.Context, *User, RatingKey, string) bool
Placeholder(context.Context, *User, RatingKey, RatingKey, string) (*Title, error)
FindPlaceholder(context.Context, *User, RatingKey, string) (*Title, RatingKey, error)
}
CollectionPlaceholder resolves a future title only through a visible, enabled collection in which it is currently a member for this viewer.
type CollectionPreview ¶
type CollectionPreview struct {
Total int `json:"total"`
Items []Title `json:"items"`
Warnings []string `json:"warnings"`
TookMs int64 `json:"tookMs"`
}
CollectionPreview is the result of evaluating an unsaved spec.
type CollectionRotate ¶
type CollectionRotate struct {
Size int `json:"size"`
Every string `json:"every"` // "daily" | "weekly"
}
CollectionRotate shows a rotating subset of the members.
type CollectionRow ¶
type CollectionRow struct {
Hub Hub `json:"hub"`
CollectionID string `json:"collectionId"`
HomeRow bool `json:"homeRow"`
SectionRow bool `json:"sectionRow"`
// Schedule is the collection's schedule. The personalization engine
// applies it (a viewer's Home override may replace it).
Schedule *CollectionSchedule `json:"schedule,omitempty"`
}
CollectionRow is an owner-designed collection offered as a Home or section row for a user in a context (targeting and schedules already applied).
type CollectionRows ¶
type CollectionRows interface {
HomeRowsFor(ctx context.Context, user *User, hc HubContext) ([]CollectionRow, error)
}
CollectionRows is implemented by the collection engine for the personalization engine.
type CollectionRule ¶
type CollectionRule struct {
Field string `json:"field"`
Op string `json:"op"`
Value json.RawMessage `json:"value"`
Label string `json:"label,omitempty"`
Labels []string `json:"labels,omitempty"`
}
CollectionRule is one condition. Value is typed by Field; Label and Labels are display text for ids.
func LibraryPredicateConditions ¶
func LibraryPredicateConditions(f Filter) []CollectionRule
LibraryPredicateConditions converts a browse predicate to the shared rules language. Every persisted field is retained; nested boolean groups become nested rule groups. An empty result means the source needs no visibility rule. There is no saved library predicate after conversion.
type CollectionSchedule ¶
type CollectionSchedule struct {
Days []int `json:"days,omitempty"`
FromHour *int `json:"fromHour,omitempty"`
ToHour *int `json:"toHour,omitempty"`
Devices []string `json:"devices,omitempty"`
Dayparts []string `json:"dayparts,omitempty"`
Months []int `json:"months,omitempty"`
StartDate string `json:"startDate,omitempty"`
EndDate string `json:"endDate,omitempty"`
}
CollectionSchedule limits when a collection's rows appear. It is the one schedule of a collection row: the Collections editor and the Home designer both edit it. Days use 0 = Sunday … 6 = Saturday; hours are local, FromHour inclusive and ToHour exclusive, wrapping past midnight when FromHour > ToHour. Dayparts are DaypartMorning…DaypartLate, Months 1 = January … 12, and StartDate/EndDate inclusive YYYY-MM-DD local dates.
func (*CollectionSchedule) Allows ¶ added in v0.3.2
func (sc *CollectionSchedule) Allows(device string, now time.Time) bool
Allows reports whether the schedule lets the row appear at now (local time) on a device class. A nil schedule always allows; an unknown device ("") passes a device filter; equal From and To hours mean all day.
func (*CollectionSchedule) IsZero ¶ added in v0.3.2
func (sc *CollectionSchedule) IsZero() bool
IsZero reports whether the schedule sets nothing (always on).
type CollectionSource ¶
type CollectionSource struct {
Kind string `json:"kind"`
List string `json:"list,omitempty"`
MediaType string `json:"mediaType,omitempty"`
ID int64 `json:"id,omitempty"`
Label string `json:"label,omitempty"`
Params map[string]string `json:"params,omitempty"`
Region string `json:"region,omitempty"`
URL string `json:"url,omitempty"`
Keys []string `json:"keys,omitempty"`
// Role narrows tmdbPerson credits: "cast", "director", "writer",
// "crew" or "" (every credit). Additive to the contract.
Role string `json:"role,omitempty"`
// MaxItems caps how many items a plugin or add-on list source pulls per
// refresh (1..2000). Additive to the contract.
MaxItems int `json:"maxItems,omitempty"`
}
CollectionSource is one place candidates come from. Kind selects which other fields apply:
catalog the whole browsable catalogue tmdbList List, MediaType trending_day|trending_week|popular|top_rated|now_playing|upcoming|airing_today|on_the_air tmdbCollection ID, Label a TMDB franchise tmdbDiscover Params raw /discover parameters (names allowed for ids) tmdbKeyword | tmdbCompany | tmdbNetwork | tmdbPerson ID, Label (Role for people) watchProvider ID, Region, Label what's streaming on a service traktList | letterboxdList | mdblist URL anilistList URL (an AniList anime list; optionally one named list) stevenlu List: movies (default) or a score-filtered variant plugin:<id>/<key> Params, MaxItems a plugin's or Stremio add-on's list (catalog) titles Keys hand-picked rating keys
When ID is 0 the Label is resolved to a TMDB id by name.
type CollectionSpec ¶
type CollectionSpec struct {
ID string `json:"id,omitempty"` // server-assigned
Name string `json:"name"`
Description string `json:"description,omitempty"`
MediaType string `json:"mediaType"` // "movie" | "show" | "mixed"
Sources []CollectionSource `json:"sources"`
Match string `json:"match"` // "all" | "any"
Rules []CollectionRule `json:"rules"`
Exclude []CollectionRule `json:"exclude"`
// Sort: popularity | rating | released | title | added | random | personal | source.
RankedTop10 bool `json:"rankedTop10,omitempty"`
Sort string `json:"sort"`
SortDesc bool `json:"sortDesc"`
Limit int `json:"limit"` // 0 = no limit
Refresh string `json:"refresh"` // live | hourly | daily | weekly
Rotate *CollectionRotate `json:"rotate,omitempty"`
Artwork CollectionArtwork `json:"artwork"`
Targets CollectionTargets `json:"targets"`
PreviewOnFocus bool `json:"previewOnFocus,omitempty"`
Enabled bool `json:"enabled"`
LocalOnly bool `json:"localOnly,omitempty"` // evaluate rules against the local catalogue only; no remote discovery
ReleaseMode string `json:"releaseMode,omitempty"` // released (default), upcoming, or mixed
LookaheadDays int `json:"lookaheadDays,omitempty"` // 1..366 when upcoming is enabled
TemplateID string `json:"templateId,omitempty"`
// Server-maintained.
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
LastBuiltAt *time.Time `json:"lastBuiltAt,omitempty"`
ItemCount int `json:"itemCount"`
// Additive fields beyond the contract (read-only for clients).
BuiltIn bool `json:"builtIn,omitempty"` // shipped with Ether; only targets/artwork/rotate/enabled are editable
RatingKey string `json:"ratingKey,omitempty"` // the Plex ratingKey of the published collection
Warnings []string `json:"warnings,omitempty"` // from the last build
// OwnerUserID is set for private collections created by a Plex user
// (core.Collections.CreateSmart); 0 = server-wide.
OwnerUserID int64 `json:"ownerUserId,omitempty"`
}
CollectionSpec is an owner-designed collection: candidates gathered from Sources, filtered by Rules, sorted, limited and published to Plex.
type CollectionSpecSource ¶ added in v0.2.7
type CollectionSpecSource interface {
ListSpecs(context.Context) ([]CollectionSpec, error)
}
CollectionSpecSource exposes the optional ListSpecs capability.
type CollectionTargets ¶
type CollectionTargets struct {
CollectionsTab bool `json:"collectionsTab"`
HomeRow bool `json:"homeRow"`
SectionRow bool `json:"sectionRow"`
Users UserTargets `json:"users"`
Schedule *CollectionSchedule `json:"schedule,omitempty"`
}
CollectionTargets says where and for whom the collection is published.
type CollectionTemplate ¶
type CollectionTemplate struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Category string `json:"category"`
Spec CollectionSpec `json:"spec"`
}
CollectionTemplate is a curated starting point in the Collection Studio.
type Collections ¶
type Collections interface {
List(ctx context.Context, user *User, t MediaType) ([]Collection, error)
Get(ctx context.Context, user *User, key RatingKey) (*Collection, error)
Items(ctx context.Context, user *User, key RatingKey, offset, limit int) (Page, error)
CreateSmart(ctx context.Context, c Collection) (*Collection, error)
DeleteSmart(ctx context.Context, key RatingKey) error
}
type CompressedZipMemberSource ¶
type CompressedZipMemberSource interface {
CompressedZipMember() (name string, method uint16, uncompressedSize int64, expectedCRC32 uint32)
}
CompressedZipMemberSource is implemented by a MediaSource backed by the raw compressed byte stream of a single member inside a provider's server-side ZIP archive (such as a deflate-compressed entry inside a TorBox auto-zip). Callers capable of archive extraction decode the stream using method, uncompressedSize and expectedCRC32 and continue container and digest checks on the decoded member.
type ConcurrentRangeReaderAt ¶
type ConcurrentRangeReaderAt interface {
ReadAtConcurrentContext(context.Context, []byte, int64) (int, error)
}
ConcurrentRangeReaderAt keeps active demuxer range requests independent. A container reader can overlap header, cue and media ranges while a prior HTTP response unwinds. Request cancellation still retires its urgent work; unrelated seeks must only cancel speculative read-ahead.
type ContainerRef ¶
type ContainerRef struct {
Format string `json:"format,omitempty"` // "" (sniff) | "rar" | "7z" | "zip"
Volumes []VolumeRef `json:"volumes"`
Member string `json:"member,omitempty"`
MemberIndex *int `json:"memberIndex,omitempty"`
PasswordSecret string `json:"passwordSecret,omitempty"`
}
ContainerRef describes an archive member inside one or more volume streams (spec §4.1, §5.3).
type ContextReaderAt ¶ added in v0.2.7
ContextReaderAt reads source bytes with request cancellation.
type ContextualRecommender ¶
type ContextualRecommender interface {
HomeHubsFor(ctx context.Context, user *User, hc HubContext, limit int) ([]Hub, error)
SectionHubsFor(ctx context.Context, user *User, t MediaType, hc HubContext, limit int) ([]Hub, error)
}
ContextualRecommender is implemented by recommenders that adapt rows to the request context. internal/plex prefers it over Recommender when available.
type CopyTimeline ¶
type CopyTimeline struct {
Version int
Origin, Step, End int64
VideoStream, AudioStream int
VideoAUs, AudioAUs int64
// Ordered packet payloads AND stream/PTS/DTS are committed by this digest.
PacketSHA256 [32]byte
}
CopyTimeline is a source-owner packet-scan fact, bound to the immutable source revision by cluster source authorization. Version 1 admits only a complete, regular no-reorder H264/AAC TS title, with IDR + SPS/PPS at every cut. It is not a caller assertion: workers authenticate it against the source owner. All clocks use 90kHz ticks. AAC access units have 1024 samples at 48kHz.
type CourMapping ¶
CourMapping describes how an anime season entry in anime-lists maps an offset TMDB season episode to its cour (part) and TVDB season/episode.
type CreditFilter ¶ added in v0.3.0
type CreditFilter struct {
People []int64 `json:"people,omitempty"`
Names []string `json:"names,omitempty"` // alternatives to IDs; ASCII-case-insensitive exact names
Kind string `json:"kind,omitempty"`
Exclude bool `json:"exclude,omitempty"`
}
CreditFilter narrows by credited person TMDB IDs or exact names and optional credit kind ("cast", "director", "writer", "crew", or "" for any).
type CustomFormat ¶
type CustomFormat struct {
ID string `json:"trash_id"`
Name string `json:"name"`
Scores map[string]int `json:"trash_scores,omitempty"`
Specifications []FormatSpecification `json:"specifications"`
// App names the Starr app whose enum values the specifications use:
// Sonarr numbers sources differently from Radarr. Empty means Radarr.
App string `json:"app,omitempty"`
// ManagedBy marks a definition an imported profile brought in and the
// guide sync owns ("trash:radarr", "dictionarry:sonarr"). Manual
// definitions leave it empty and the sync never removes them.
ManagedBy string `json:"managedBy,omitempty"`
}
CustomFormat retains the native TRaSH/Radarr/Sonarr JSON for owner editing. Unknown specifications are rejected at import rather than silently matching.
type DASHSession ¶
type DASHSession interface {
HLSSession
// ServeManifest writes the MPD.
ServeManifest(w http.ResponseWriter, r *http.Request)
// ServeInit writes the initialization segment of a representation.
ServeInit(w http.ResponseWriter, r *http.Request, rep int)
// ServeMedia writes media segment n of a representation, waiting for
// ffmpeg and restarting it at the right offset when a seek jumps ahead.
ServeMedia(w http.ResponseWriter, r *http.Request, rep, n int)
}
DASHSession is a running ffmpeg remux or transcode producing MPEG-DASH: a static, full-length MPD with separate video and audio representations of fMP4 segments addressed by number ($Number$, from 0). Its HLSSession methods map onto the first representation; ServePlaylist writes the MPD.
type DamageReporter ¶ added in v0.2.7
DamageReporter exposes the optional SetDamageHandler capability.
type DamagedSegmentSkipper ¶
type DamagedSegmentSkipper interface {
SkipDamagedSegment(ctx context.Context, inputURL string, info MediaInfo, at time.Duration) error
}
DamagedSegmentSkipper advances a mid-stream HLS session past a bounded range of corrupt input segments when no alternate release can recover them.
type DateFilter ¶ added in v0.3.0
type DateFilter struct {
Op string `json:"op,omitempty"`
Unix int64 `json:"unix,omitempty"`
SpanDay bool `json:"spanDay,omitempty"`
}
DateFilter narrows a release timestamp with a comparison operator ("=", "!=", "<<", "<=", ">>", ">="). SpanDay is true when the value was parsed from a calendar day (YYYY-MM-DD), so "=" and "!=" cover the 24-hour UTC day.
type DebridServiceRef ¶
DebridServiceRef identifies one owner-configured debrid service (without exposing credentials) that holds a cached torrent or served an acquisition.
type DecideOptions ¶
type DecideOptions struct {
// ToneMap limits apply only to HDR-to-SDR video conversion, never direct
// playback or copy-only remux. Zero preserves the existing output budget.
ToneMapMaxHeight, ToneMapMaxBitrateKbps int
// DisableVideoTranscode prevents optional enhancement from promoting direct playback.
DisableVideoTranscode bool
DirectPlay bool // client allows direct play
DirectStream bool // client allows remux
MaxBitrateKbps int // client-requested cap (maxVideoBitrate)
MaxHeight int // from videoResolution
MaxWidth int // explicit output width ceiling
AudioStream int // selected stream index, -1 default
SubtitleStream int // -1 none
AudioFilters []string // trusted owner/viewer audio processing; forces audio encoding
BurnSubtitles bool
// BurnTextSubtitles lets BurnSubtitles burn a text track too. Set for
// a client that draws no soft text track in this playback (Plex Web
// asking to burn an ASS track). Additive.
BurnTextSubtitles bool
// Protocol is the conversion protocol the client asked for (hls, dash,
// http). Empty keeps the HLS target. Additive.
Protocol string
}
DecideOptions are per-request choices from the Plex decision request.
type Decision ¶
type Decision struct {
// AndroidMatroskaHLS selects the measured Plex Android HLS transport.
AndroidMatroskaHLS bool `json:"androidMatroskaHLS,omitempty"`
Enhancement VideoEnhancement `json:"enhancement,omitempty"`
Kind DecisionKind `json:"kind"`
VideoCopy bool `json:"videoCopy"`
AudioCopy bool `json:"audioCopy"`
VideoCodec string `json:"videoCodec"` // target codec when transcoding
AudioCodec string `json:"audioCodec"`
Container string `json:"container"` // "mpegts" (HLS) or original
MaxHeight int `json:"maxHeight"`
// H264Level is a verified output level_idc for a constrained H.264 encode.
// Zero retains the encoder's existing automatic selection.
H264Level int `json:"h264Level,omitempty"`
// H264FrameRate bounds the selected encoder output rate for that level.
H264FrameRate float64 `json:"h264FrameRate,omitempty"`
BitrateKbps int `json:"bitrateKbps"`
AudioStream int `json:"audioStream"`
SubtitleStream int `json:"subtitleStream"` // -1 none
BurnSubtitles bool `json:"burnSubtitles"`
Reason string `json:"reason"`
AudioFilters []string `json:"audioFilters,omitempty"`
// AudioChannels and AudioSampleRate keep the already negotiated audio
// decoder configuration across a source change. Zero uses the normal
// encoder defaults.
AudioChannels int `json:"audioChannels,omitempty"`
AudioBitrateKbps int `json:"audioBitrateKbps,omitempty"`
AudioSampleRate int `json:"audioSampleRate,omitempty"`
// ToneMap converts HDR (HDR10, HLG, Dolby Vision) video to SDR while
// transcoding, for clients without HDR support.
ToneMap bool `json:"toneMap,omitempty"`
// StripDolbyVision copies the compatible HDR10 base layer while
// removing Dolby Vision RPU/configuration data; it never re-encodes.
StripDolbyVision bool `json:"stripDolbyVision,omitempty"`
}
func (*Decision) EncodesVideo ¶
EncodesVideo reports whether this decision re-encodes a video stream. Audio-only items (info.Video() == nil) carry VideoCopy=false because there is no video stream to copy, and they never count as video transcodes.
type DecisionCandidate ¶ added in v0.3.0
type DecisionCandidate struct {
ReleaseID string
Name string
Height int
Size int64
Score float64
Rejected bool
Reason string
Healthy bool
HealthChecked bool
}
DecisionCandidate is one ranked or rejected release in a DecisionTrace.
type DecisionKind ¶
type DecisionKind string
const ( DecisionDirectPlay DecisionKind = "directplay" DecisionRemux DecisionKind = "copy" // Plex calls this "direct stream" DecisionTranscode DecisionKind = "transcode" )
type DecisionTrace ¶ added in v0.3.0
type DecisionTrace struct {
QualityFallback string
Profile string
ProfileMaxHeight int
ClientMaxHeight int
EffectiveMaxHeight int
AllowHDR bool
AllowDolbyVision bool
Chooser string
ChosenVersion string
Candidates []DecisionCandidate
}
DecisionTrace is the privacy-safe shape of the latest resolution for a title: ceilings, who chose, and a bounded candidate list. It has no username, address, or stream URL. Release names are the file names the resolver ranked.
type DecisionTraceSource ¶ added in v0.3.0
type DecisionTraceSource interface {
LatestDecision(key RatingKey) (DecisionTrace, bool)
}
DecisionTraceSource is the latest resolution for a title. Plex reads it for the support capture and stays outside the resolver package.
type DelegationAuth ¶ added in v0.2.7
DelegationAuth issues expiring, server-local casting credentials. Implementations must enforce current membership on use and must not delegate owner privileges.
type DeliveryPolicy ¶
type DeliveryPolicy struct {
Route func(string) (canonical, id, protocol string, ok bool)
Session func(*url.URL) (string, bool)
GrantEnvelope func(*http.Request) bool
Headers []string
}
DeliveryPolicy supplies the frontend representation and credential envelope.
type DescriptiveCatalog ¶
type DescriptiveCatalog interface {
DescribeCandidates(context.Context, CollectionSpec, int) ([]Title, error)
}
DescriptiveCatalog evaluates a generated spec locally, without gathering a library-sized in-memory collection or fetching external lists.
type DescriptiveResult ¶
type DescriptiveResult struct {
Spec *CollectionSpec
State string
RetryAfterSeconds int
Title string
Items []Title
}
DescriptiveResult is an AI-generated collection search. Pending requests have no invented results. Partial results are provisional; clients keep polling and replace them with the final ready result.
type DescriptiveSearchController ¶
type DescriptiveSearchController interface {
DescriptiveSearcher
DescribeCached(user *User, query string) bool
CancelDescribeSearch(user *User, query string)
}
DescriptiveSearchController is an optional extension of DescriptiveSearcher for warm-cache checks and cancelling jobs superseded by search-as-you-type.
type DescriptiveSearcher ¶
type DescriptiveSearcher interface {
DescriptiveSearchAvailable() bool
DescribeSearch(context.Context, *User, string, bool) (DescriptiveResult, error)
}
DescriptiveSearcher reuses the collection builder and waits for AI when wait is explicit (protocol AI jobs and bounded descriptive searches).
type DetailPending ¶
type DetailPending struct {
// contains filtered or unexported fields
}
DetailPending records work admitted while reading one exact title. It is a response snapshot: completion after a read cannot make its missing data whole.
func WithDetailPending ¶
WithDetailPending observes admitted work without scheduling any enrichment.
func (*DetailPending) Fields ¶
func (p *DetailPending) Fields() []string
Fields returns a stable copy of the partial response's field names.
type Device ¶ added in v0.3.0
type Device struct {
ID string
Client string
Product string
Version string
Platform string
DeviceName string
Language string
}
Device identifies the client receiving a surface-specific credential.
type DirectDeliverer ¶
type DirectDeliverer interface {
// DirectDelivery reports the provider URL this session's file can be
// fetched from directly, and records the read as a direct play of a live
// session, the way a relayed range read would.
DirectDelivery(sessionID string) (link DirectSourceLink, ok bool)
}
DirectDeliverer is implemented by a Playback that can name the provider URL a direct play of one of its sessions may be redirected to (additive). A runtime without it — a remote cluster playback, a fixture — always relays.
type DirectPlayRetrier ¶ added in v0.2.7
type DirectPlayRetrier interface{ RetryDirectPlay() bool }
DirectPlayRetrier exposes the optional RetryDirectPlay capability.
type DirectSourceLink ¶
DirectSourceLink is one provider-issued URL for a source's file: the same bytes Ether reads, at an address a client may fetch by itself. Edge names the host in the URL so a redirect is auditable without logging a signed link; it is display metadata, never part of the address.
type DirectURLSource ¶
type DirectURLSource interface {
DirectURL() (link DirectSourceLink, ok bool)
}
DirectURLSource is implemented by a MediaSource whose bytes also exist at a provider URL that authorises its own read (additive). A frontend may then redirect a client to that URL instead of relaying the bytes itself, which lets the client re-decide its connection on every request rather than inheriting the one route Ether's session pinned. ok is false when no live URL is held, or when fetching it needs something a client cannot provide (an addon's request headers, a private route, an expired signature).
type DownloadAccessPolicy ¶ added in v0.2.7
DownloadAccessPolicy exposes the optional AllowDownloads capability.
type DownloadRemuxRequest ¶
type DownloadRemuxRequest struct {
// InputURL is the loopback URL of the playback session feeding ffmpeg.
InputURL string
// Info is the probed media info of the resolved source.
Info MediaInfo
// AudioStream is the source stream index to keep; -1 picks the
// default (first) audio stream.
AudioStream int
// ViewerID bounds converting downloads to one encode per viewer.
// Zero skips the per-viewer encode lock (copy remuxes do not take it).
ViewerID int64
// Caps is the requesting client's download profile. Empty uses
// H.264/HEVC + AAC/AC3 in MP4, the mobile download target.
Caps ClientCaps
// Options are the per-request transcode choices (bitrate, height, burn).
Options DecideOptions
}
DownloadRemuxRequest is one whole-file remux to MP4.
type DownloadRemuxer ¶
type DownloadRemuxer interface {
// RemuxDownload copies or converts a resolved source to a temp MP4,
// reporting progress as a fraction in [0,1] when progress is non-nil.
// Cancelling ctx kills ffmpeg and removes the partial file.
RemuxDownload(ctx context.Context, req DownloadRemuxRequest, progress func(fraction float64)) (path string, size int64, err error)
// ReleaseDownload deletes a remuxed file and frees its budget.
// Releasing an unknown path is a no-op.
ReleaseDownload(path string)
}
DownloadRemuxer copies a resolved source into a temporary faststart MP4. Implemented by internal/transcode. The returned path is owned by the remuxer until ReleaseDownload is called; files are never kept permanently and are bounded by a disk budget.
type DurablePrefetcher ¶ added in v0.2.7
type DurablePrefetcher interface {
DurablePrefetch(context.Context, string, []byte, int64, int64) error
}
DurablePrefetcher exposes the optional DurablePrefetch capability.
type EncoderInputLease ¶ added in v0.3.0
type EncoderInputLease interface {
// ClaimInput succeeds once, before seal. Failed claims never call onDrained.
// Successful claims call it exactly once, possibly before this returns,
// after sealed producers and registry ownership are released. The trusted
// callback must only do bounded accounting/requeue; no I/O, waits or source
// operations. It runs outside every manager/session/scope lock.
ClaimInput(onDrained func(error)) error
HeadersForInput(inputURL string) (map[string]string, error)
SealInput()
InputDone() <-chan struct{}
InputErr() error
}
EncoderInputLease is issued by PlaybackEncoderInputs for one exact source lifetime. Host composition passes the opaque object; wire inputs cannot mint one. Each encoder must obtain its own lease, including shared-source owners.
type EncoderRetirement ¶ added in v0.3.0
type EncoderRetirement interface {
EncoderDone() <-chan struct{}
EncoderErr() error
}
EncoderRetirement covers one exact encoder session, including all its runs and preflights. EncoderDone closes only at a terminal result. EncoderErr is ErrEncoderPending before then and is immutable afterwards; only nil proves full retirement. SourceRetirement alone never supplies this proof.
type EncoderStatus ¶ added in v0.3.3
type EncoderStatus struct {
RecoveryReason string `json:"recoveryReason,omitempty"`
PlayerPosition *time.Duration `json:"playerPosition,omitempty"`
Runway *time.Duration `json:"runway,omitempty"`
Decision Decision `json:"decision"`
// Rung is the ABR rung the active run encodes ("" or "base" for the
// session's primary decision).
Rung string `json:"rung,omitempty"`
Processor string `json:"processor"`
Filters string `json:"filters"`
Phase string `json:"phase"`
Reason string `json:"reason,omitempty"`
StartedAt time.Time `json:"startedAt"`
UpdatedAt time.Time `json:"updatedAt"`
Speed float64 `json:"speed"`
OutputTime time.Duration `json:"outputTime"`
ReadyUntil time.Duration `json:"readyUntil"`
MinOffsetAvailable time.Duration `json:"minOffsetAvailable,omitempty"`
HWDecoder string `json:"hwDecoder,omitempty"`
HWEncoder string `json:"hwEncoder,omitempty"`
}
EncoderStatus describes the currently running output process, not the original playback negotiation. Times are media timestamps or wall-clock instants as indicated by their field names.
type Engine ¶
type Engine interface {
// Open builds the byte-offset index for the main video file of an NZB.
Open(ctx context.Context, releaseID string, nzb []byte) (MediaSource, error)
// Prefetch warms [offset, offset+length) at background priority.
Prefetch(ctx context.Context, releaseID string, nzb []byte, offset, length int64) error
}
type EpisodeIdentity ¶
type EpisodeIdentity struct {
OtherShows map[string][]EpisodeNamesake
Seasons map[int]string
// Episodes holds the requested season's other episode titles by number.
Episodes map[int]string
// Genres and Keywords hold the requested show's locally mirrored tags.
Genres []string
Keywords []string
}
EpisodeIdentity contains only locally mirrored metadata. A missing entry is unknown, never evidence that a release belongs to the requested show.
type EpisodeLayout ¶
type EpisodeLayout struct {
Numbers map[EpisodeNumber]int
Seasons map[int]bool
Complete map[int]bool
}
EpisodeLayout contains bounded, local canonical facts. A missing episode in an incompletely mirrored season is unknown, rather than evidence of absence.
type EpisodeNamesake ¶
type EpisodeNamesake struct {
Year int
EpisodeTitle string
Language string
Genres []string
Keywords []string
}
EpisodeNamesake is a show whose own title matches a requested name, with its locally known title and medium metadata for the same season and episode.
type EpisodeNumber ¶
type EpisodeNumber struct{ Season, Episode int }
EpisodeNumber is a season/episode pair in one numbering system.
func EpisodeAliases ¶
func EpisodeAliases(req SearchRequest) []EpisodeNumber
EpisodeAliases returns distinct additional forms, never the canonical form.
type EpisodeTally ¶
type EpisodeTally struct {
Aired, Played int
}
EpisodeTally is a count of aired episodes and how many were played.
type ErrBedtime ¶
ErrBedtime is an admission refusal, never a reason to interrupt an item.
func (*ErrBedtime) Error ¶
func (e *ErrBedtime) Error() string
func (*ErrBedtime) Unwrap ¶
func (e *ErrBedtime) Unwrap() error
type ExactVariantPlayback ¶ added in v0.3.0
type ExactVariantPlayback interface {
PrepareExactVariant(ctx context.Context, user *User, key RatingKey, caps ClientCaps, releaseID string) (*PlaySession, error)
}
ExactVariantPlayback never substitutes a different release, including during later failover. The requested release may instead become unavailable.
type FacetValue ¶
type FacetValue struct {
ID string `json:"id,omitempty"` // Stable namespace-aware neutral identifier.
Key string `json:"key"`
Title string `json:"title"`
Count int `json:"count"`
// Labels are the equivalent values Key stands for, where a facet groups
// them (content-rating levels list every board's label).
Labels []string `json:"labels,omitempty"`
}
type FeedEvaluation ¶ added in v0.3.3
type FeedEvaluation interface {
// Key identifies everything a durable verdict depends on besides the
// title and release, so verdicts persisted under it stay exact.
Key() string
// Evaluate judges each release for t, in order.
Evaluate(ctx context.Context, t *Title, rs []Release) ([]FeedVerdict, error)
// Transient is the rejection a durable acceptance gains from
// short-lived state right now, or "".
Transient(releaseID string) string
Close()
}
FeedEvaluation judges many feed releases under one prepared policy: the profile, compiled release rules and resolver settings are read once.
type FeedVerdict ¶ added in v0.3.3
type FeedVerdict struct {
// Reason is empty when the policy accepts the release.
Reason string
// Volatile verdicts depend on short-lived state (a hosted ranking
// session, a brief health-failure skip, a blocklist mark that can
// expire, a regex timeout) and must not be persisted.
Volatile bool
}
FeedVerdict is one retained feed release judged against the owner's default quality policy: the "When they can play" evidence check.
type Filter ¶
type Filter struct {
// Topic matches a bounded local keyword/overview candidate set.
Topic string `json:"topic,omitempty"`
LocalOnly bool `json:"-"` // console filtering never hydrates remote credits on the request path
CatalogCandidates bool `json:"-"`
CatalogViewerID int64 `json:"-"`
CatalogRuleRevision int64 `json:"-"`
Group *FilterGroup `json:"group,omitempty"`
// DigitalDiscovery applies the availability service's digital-date gate
// before counting and paging a discovery result.
DigitalDiscovery bool `json:"-"`
DigitalDateEvidence bool `json:"-"`
HomeReleaseOffsetDays int `json:"-"`
// AvailabilityKeepKeys are the viewer's active playback sessions.
AvailabilityKeepKeys []RatingKey `json:"-"`
// GatePolicy and Gate* bounds evaluate the sticky availability_gate
// table directly in SQL without materializing hidden sets.
GatePolicy string `json:"-"`
MovieGateCutoff int64 `json:"-"`
ShowGateCutoff int64 `json:"-"`
EpisodeGateCutoff int64 `json:"-"`
GateNow int64 `json:"-"`
GateUpcomingMovies bool `json:"-"`
GateRev uint64 `json:"-"`
// Availability hidden-set seqs pin one evaluated hidden set (an
// interval snapshot) across SQL reads on legacy read-only databases.
HiddenMovieSeq int64 `json:"-"`
HiddenShowSeq int64 `json:"-"`
HiddenEpisodeSeq int64 `json:"-"`
// ChildVisibility is the viewer policy evaluated on hydrated episodes.
ChildVisibility *Filter `json:"-"`
// MovieFilter and EpisodeFilter carry per-kind share predicates across
// mixed movie+episode shelf queries (RecentPage, OnDeckPageSince).
MovieFilter *Filter `json:"-"`
EpisodeFilter *Filter `json:"-"`
RuleVisibility string `json:"-"` // owner-only rules browser: hidden, shown or all
ApplyCanonicalInPreview bool `json:"-"` // filter-library rules preview keeps canonical rules
PreviewRules []LibraryExclusion `json:"-"`
PreviewFallback string `json:"-"`
ExtraRules []LibraryExclusion `json:"-"` // saved rules on a filter library
ExtraFallback string `json:"-"`
TabRules []LibraryExclusion `json:"-"` // saved filters on a library or view tab
TabFallback string `json:"-"`
KnownAddedDate bool `json:"-"` // only released/aired titles, before pagination
// ExcludeKeys applies local visibility policy before counting and pagination.
ExcludeKeys []RatingKey `json:"-"`
// IncludeKeys, when set, restricts the page to these keys before
// counting and pagination. An empty list matches nothing.
IncludeKeys []RatingKey `json:"-"`
// CollectionMembers, when non-zero, restricts the page to the
// materialised members of the owner collection with this id before
// counting and pagination. It is a SQL semi-join on collections_members,
// so a collection library pages in one statement whatever its size. A
// deleted collection (no members) matches nothing.
CollectionMembers int64 `json:"-"`
CatalogueSources []string `json:"catalogueSources,omitempty"`
// ExcludeGenres and ExcludeKeywords remove viewer-blocked facts before
// counting and pagination. Matching is case-insensitive.
ExcludeGenres []string `json:"-"`
ExcludeKeywords []string `json:"-"`
AddedAfter int64 `json:"-"` // inclusive Unix timestamp bound on added/release time
AddedBefore int64 `json:"-"` // inclusive Unix timestamp bound on added/release time
UpdatedAfter int64 `json:"-"` // inclusive Unix timestamp bound on metadata update time
UpdatedBefore int64 `json:"-"` // inclusive Unix timestamp bound on metadata update time
Type MediaType `json:"type,omitempty"` // movie or show
Genres []string `json:"genres,omitempty"`
ReleaseGate string `json:"releaseGate,omitempty"` // admitted, held, unknown in current policy snapshot
Playable string `json:"playable,omitempty"` // yes or unknown from fresh local evidence
DebridCached string `json:"debridCached,omitempty"` //
Qualities []string `json:"qualities,omitempty"` // known 4k, hdr, dv, atmos release facts
EvidenceResolutions []string `json:"evidenceResolutions,omitempty"` // 4k, 1080p, 720p, sd from fresh release evidence
EvidenceHDR []string `json:"evidenceHdr,omitempty"` // dv, hdr10, sdr from fresh release evidence
EvidenceAudioLanguages []string `json:"evidenceAudioLanguages,omitempty"` // normalized audio language codes from fresh release evidence
Anime bool `json:"anime,omitempty"` // positive canonical anime keyword
Kids bool `json:"kids,omitempty"` // positive canonical Kids genre
Tags []string `json:"tags,omitempty"` // owner annotations, distinct from provider keywords
Keywords []string `json:"keywords,omitempty"` // every keyword must match (case-insensitive)
YearFrom int `json:"yearFrom,omitempty"`
YearTo int `json:"yearTo,omitempty"`
Years []int `json:"years,omitempty"`
ExcludeYears []int `json:"excludeYears,omitempty"`
MinVotes int `json:"minVotes,omitempty"`
MaxVotes int `json:"maxVotes,omitempty"`
MinPopularity float64 `json:"minPopularity,omitempty"`
MaxPopularity float64 `json:"maxPopularity,omitempty"`
DateAddedFrom int64 `json:"dateAddedFrom,omitempty"` // release/air date, never insertion
DateAddedTo int64 `json:"dateAddedTo,omitempty"`
EtherAddedFrom int64 `json:"etherAddedFrom,omitempty"`
EtherAddedTo int64 `json:"etherAddedTo,omitempty"`
Statuses []string `json:"statuses,omitempty"`
MinSeasons int `json:"minSeasons,omitempty"`
MaxSeasons int `json:"maxSeasons,omitempty"`
MinEpisodes int `json:"minEpisodes,omitempty"`
MaxEpisodes int `json:"maxEpisodes,omitempty"`
MinRating float64 `json:"minRating,omitempty"`
MaxRating float64 `json:"maxRating,omitempty"`
MaxRatingExclusive bool `json:"maxRatingExclusive,omitempty"`
ExcludeRatings []float64 `json:"excludeRatings,omitempty"`
MaxRuntime time.Duration `json:"maxRuntime,omitempty"`
MinRuntime time.Duration `json:"minRuntime,omitempty"`
ExcludeRuntimes []time.Duration `json:"excludeRuntimes,omitempty"`
Languages []string `json:"languages,omitempty"`
Countries []string `json:"countries,omitempty"`
ExcludeCountries []string `json:"excludeCountries,omitempty"`
ContentRatings []string `json:"contentRatings,omitempty"`
ExcludeContentRatings []string `json:"excludeContentRatings,omitempty"`
MaxContentRating string `json:"maxContentRating,omitempty"` // per-user limit
// SaferPlexRating applies cached Plex content-rating levels in SQL
// together with MaxContentRating so paging and counts stay correct.
SaferPlexRating bool `json:"-"`
Collection int64 `json:"collection,omitempty"`
Collections []int64 `json:"collections,omitempty"`
ExcludeCollections []int64 `json:"excludeCollections,omitempty"`
Person int64 `json:"person,omitempty"` // cast or crew TMDB id
Credits []CreditFilter `json:"credits,omitempty"`
Studio string `json:"studio,omitempty"`
StudioFilters []StringFilter `json:"studioFilters,omitempty"`
FirstCharacter string `json:"firstCharacter,omitempty"`
// NameStartsWith, NameStartsWithOrGreater and NameLessThan are
// Jellyfin and Emby's alphabet jump: bounds on the sort title in the
// same order as FirstCharacter's buckets (catalog sort_name.go).
NameStartsWith string `json:"nameStartsWith,omitempty"`
NameStartsWithOrGreater string `json:"nameStartsWithOrGreater,omitempty"`
NameLessThan string `json:"nameLessThan,omitempty"`
Query string `json:"query,omitempty"` // title / in-library search query
Facets map[string][]string `json:"facets,omitempty"` // plugin library facet bucket filters (OR within field, AND across fields)
TitleFilters []StringFilter `json:"titleFilters,omitempty"`
ReleasedFilters []DateFilter `json:"releasedFilters,omitempty"`
// MinContentRating is an additive share-policy predicate (plex.tv share
// filters). It does not replace MaxContentRating or ContentRatings.
MinContentRating string `json:"-"`
// IncludeCollectionNames / ExcludeCollectionNames match
// Title.CollectionName (plex.tv share label filters). An empty
// collection name is unmappable and is not excluded.
IncludeCollectionNames []string `json:"-"`
ExcludeCollectionNames []string `json:"-"`
}
Filter narrows a browse or a smart collection. Zero values mean "any".
type FilterGroup ¶ added in v0.3.3
type FilterGroup struct {
StateField string `json:"stateField,omitempty"`
StateOperator string `json:"stateOperator,omitempty"`
StateValue int64 `json:"stateValue,omitempty"`
// ParentOnly applies this subtree to the series when browsing episodes.
ParentOnly bool `json:"-"`
LastViewedAfter int64 `json:"lastViewedAfter,omitempty"`
LastViewedBefore int64 `json:"lastViewedBefore,omitempty"`
OnWatchlist *bool `json:"onWatchlist,omitempty"`
Watchlist *bool `json:"watchlist,omitempty"`
Favorite *bool `json:"favorite,omitempty"`
Watched *bool `json:"watched,omitempty"`
Unwatched *bool `json:"unwatched,omitempty"`
InProgress *bool `json:"inProgress,omitempty"`
History *bool `json:"history,omitempty"`
UserID int64 `json:"userId,omitempty"`
Operator string `json:"operator"`
Filter *Filter `json:"filter,omitempty"`
Children []FilterGroup `json:"children,omitempty"`
}
FilterGroup represents a nested boolean expression of browse filters.
type FormatSpecification ¶
type FrontendHostPolicy ¶
type FrontendHostPolicy struct {
// AutomaticSubtitleSelection declares server-side selection of newly attached tracks.
AutomaticSubtitleSelection bool
ProfileQualityEvaluation bool
InferBuffering bool
PlaybackTelemetry bool
LegacySessionIdentity bool
ProbeLiveInput bool
BestEffortLiveStart bool
PublicContentTags bool
ExternalIdentity bool
NativePlaybackCapabilities bool
NativeClientFamilies bool
LandscapeThumb bool
SpikeExperience bool
MainListener bool
PublicURL bool
PasswordConnect bool
}
FrontendHostPolicy contains host integration choices supplied by a frontend. Protocol names select wiring only; shared services consume these options.
type GoodputSession ¶
type GoodputSession interface {
// GoodputKbps is the rolling segment-delivery estimate; 0 unknown.
GoodputKbps() int
}
GoodputSession is a session that measures client delivery goodput.
type HLSDiagnosticRecord ¶
type HLSDiagnosticRecord struct {
At time.Time `json:"at"`
Resource string `json:"resource"`
MIME string `json:"mimeType,omitempty"`
Status int `json:"status,omitempty"`
Bytes int64 `json:"bytes,omitempty"`
Codecs string `json:"codecs,omitempty"`
Playlist string `json:"playlist,omitempty"`
Error string `json:"error,omitempty"`
}
HLSDiagnosticRecord contains bounded local resource facts, never request URLs, source names, scoped credentials, or encoder command lines.
type HLSDiagnosticSession ¶
type HLSDiagnosticSession interface {
PlaybackDiagnostics() HLSPlaybackDiagnostics
}
type HLSIndependentSegments ¶ added in v0.3.0
type HLSIndependentSegments interface {
IndependentSegments() bool
}
HLSIndependentSegments is an optional, session-wide guarantee that every segment in every advertised rendition is independently decodable. A session must not implement it as true unless it can prove that guarantee for copied media, all encoder paths, and every rung it actually advertises.
type HLSLadderSession ¶
type HLSLadderSession interface {
HLSSession
// Rungs lists the ladder, highest first; Rungs()[0] is "base".
Rungs() []HLSRung
// ServeRungPlaylist writes rung's media playlist.
ServeRungPlaylist(w http.ResponseWriter, r *http.Request, rung string)
// ServeRungSegment writes segment n of rung (InitSegment numbering as
// in ServeSegment: the caller passes the parsed segment number).
ServeRungSegment(w http.ResponseWriter, r *http.Request, rung string, n int)
}
HLSLadderSession is an HLSSession that can serve a multi-rung ABR ladder. Encoding begins when a client requests a rendition. A switch retains the previous encoder only until its replacement publishes the requested segment; no unused rung has a persistent encoder.
type HLSPlaybackDiagnostics ¶
type HLSPlaybackDiagnostics struct {
Events []HLSPreparationEvent `json:"events"`
Records []HLSDiagnosticRecord `json:"records"`
}
type HLSPreparationEvent ¶
type HLSPreparationEvent struct {
Stage string `json:"stage"`
At time.Time `json:"at"`
Rung string `json:"rung,omitempty"`
}
HLSPreparationEvent records an observed server milestone, never client readiness.
type HLSRamp ¶
HLSRamp freezes private HLS planning across config changes and replacement. Version 0 is legacy; version 1 with Segments 0 explicitly selects steady HLS. All fields are values so admission/request copies retain an immutable snapshot.
type HLSRequest ¶
type HLSRequest struct {
// PMSDASH selects the single-video PMS manifest and five-second grid for Plex TV apps.
PMSDASH bool
// MediaGeneration is a trusted presentation namespace retained across encoder
// recovery. A new playback start must use a fresh value; empty mints one.
MediaGeneration string `json:",omitempty"`
// QualityRungs explicitly requests the lazy, policy-filtered file-session ladder.
QualityRungs bool
QualityRungIDs []string
QualityVariants []QualityVariant `json:"-"`
// LazyStart defers the first encoder until the client selects a rendition.
LazyStart bool
// LadderVideoCodecs restricts optional encoded rungs when non-nil.
// An empty list permits only the primary decision.
LadderVideoCodecs []string
Diagnostics bool
// Continuous disables ramps and governor changes that introduce discontinuities.
Continuous bool
// FirstSegmentAt is the title time a full-timeline (StartOffset zero)
// client seeks to first, such as a Jellyfin resume point. The encoder
// starts at that segment instead of at zero. Zero starts at the beginning.
FirstSegmentAt time.Duration `json:",omitempty"`
Ramp HLSRamp `json:",omitzero"`
Resume *HLSResume `json:",omitempty"`
// RecoveryStart is trusted composition only; nil preserves legacy behavior.
RecoveryStart *RecoveryStart `json:",omitempty"`
// ManifestSessionID is a trusted host-assigned public session identifier used
// only for DASH representation URL rendering. Empty retains SessionID. It
// never changes encoder registry identity, source scope or retirement ownership.
ManifestSessionID string
// SlateText is trusted server-generated copy for a looping silent card.
// It is never decoded from client requests. Info.Duration bounds the slot.
SlateText []string `json:"-"`
// SoftSubtitleStream, when set, asks the encoder to expose this embedded
// text stream as ASS alongside its ordinary media output.
SoftSubtitleStream *int
// TextSubtitleStreams tees embedded text tracks from the HLS video input.
TextSubtitleStreams []int `json:",omitempty"`
// TextSubtitleSource is the host-verified file revision for durable cue windows.
TextSubtitleSource string `json:",omitempty"`
// RequireIndependentProof emits HLS independence tags only when the
// session can guarantee every advertised segment is independently decodable.
// Zero preserves the legacy playlist contract for existing callers.
RequireIndependentProof bool
SessionID string
// ReleaseID identifies the initial source in manifest diagnostics.
ReleaseID string
InputURL string // ffmpeg input; Ether serves sources on loopback HTTP with range support
// LiveInput permits playlist demuxers for owner-configured live sources.
// Ordinary resolved media must leave this false, even if duration is unknown.
LiveInput bool
// LiveFromBacklog starts a live HLS input at the first segment its
// playlist lists (Live TV's relay trims that playlist to the channel's
// stability reserve), so the backlog primes the reserve instead of the
// demuxer's default three segments from the live edge.
LiveFromBacklog bool
// CopyTimestamps preserves source timestamps for HTTP Matroska output.
CopyTimestamps bool
// InputHeaders are optional HTTP headers ffmpeg must send when reading
// InputURL (e.g. for resolved trailer URLs). Transcoders that cannot
// send headers ignore them; most resolved URLs need none (additive).
InputHeaders map[string]string
// InputLease is trusted host composition only, never decoded from wire
// requests. A caller retains an unclaimed lease if admission fails early.
InputLease EncoderInputLease `json:"-"`
Info MediaInfo
Decision Decision
StartOffset time.Duration
// ResumeHint warms one speculative Matroska copy seek without moving the playlist origin.
ResumeHint time.Duration `json:",omitempty"`
// SegmentDuration defaults to 4s when zero (5s for DASH).
SegmentDuration time.Duration
// Protocol is ProtocolHLS (default when empty), ProtocolDASH, or
// ProtocolHTTP (Plex for Mac / Desktop's chunked Matroska stream;
// the constant lives with the other "http" protocol name in debrid.go).
// A DASH session also implements DASHSession; an HTTP session also
// implements HTTPSession. Transcoder.Session returns either as an
// HLSSession, so type-assert to reach the protocol methods.
Protocol string
}
type HLSRung ¶
type HLSRung struct {
// ID is the rung's URL component: session/{id}/{ID}/index.m3u8. The
// primary rung is always "base" (served by the HLSSession methods).
ID string
// Bandwidth is the peak bitrate in bits per second (#EXT-X-STREAM-INF
// BANDWIDTH / DASH Representation bandwidth).
Bandwidth int
// AverageBandwidth is the average bitrate in bits per second.
AverageBandwidth int
// Explicit quality metadata uses bits/second and describes intended output.
VideoBitrate int
PeakVideoBitrate int
Codec string
DynamicRange string
Width int
Height int
// Codecs is the planned RFC 6381 string; it may contain estimates.
Codecs string
// OutputCodecs is read from an actually produced init segment; empty until known.
OutputCodecs string
OutputAudioChannels int
FrameRate float64
}
HLSRung is one variant of an adaptive HLS/DASH ladder. All rungs of a session share deterministic segment numbering over one segment timeline: segment N covers the same media on every rung.
type HLSSession ¶
type HLSSession interface {
ID() string
// ServePlaylist writes the media playlist (index.m3u8).
ServePlaylist(w http.ResponseWriter, r *http.Request)
// ServeSegment writes segment n, waiting for ffmpeg to produce it and
// restarting ffmpeg at the right offset when a seek jumps ahead.
ServeSegment(w http.ResponseWriter, r *http.Request, n int)
// SwapInput restarts the session on a new input at the given position
// (mid-stream failover). Segment numbering continues.
SwapInput(ctx context.Context, inputURL string, info MediaInfo, at time.Duration) error
LastAccess() time.Time
Close() error
}
HLSSession is one running ffmpeg remux or transcode producing HLS (or DASH; see DASHSession).
type HTTPSession ¶ added in v0.3.0
type HTTPSession interface {
HLSSession
ServeHTTP(w http.ResponseWriter, r *http.Request)
}
HTTPSession is a running ffmpeg remux or transcode writing one streamable Matroska to the client (Plex for Mac protocol=http). ServeHTTP writes the chunked body; a later start with offset is a new StartHLS of the same session id.
type HWAccel ¶
type HWAccel struct {
Name string `json:"name"` // "videotoolbox", "nvenc", "qsv", "vaapi", "none"
Encoders []string `json:"encoders"`
Device string `json:"device,omitempty"`
// NoGPUScale: the encoder works but the device's video processing
// (VAAPI scale_vaapi) does not, so frames are decoded and scaled in
// software and uploaded to the encoder.
NoGPUScale bool `json:"noGpuScale,omitempty"`
// NoGPUTonemap: the device's VAAPI VPP cannot run tonemap_vaapi, so HDR
// tone-mapping falls back to the software zscale/tonemap path.
NoGPUTonemap bool `json:"noGpuTonemap,omitempty"`
// QSV modes are ordered, successfully probed rate-control choices for Device.
QSVQualityModes map[string][]string `json:"qsvQualityModes,omitempty"`
QSVBitrateModes map[string][]string `json:"qsvBitrateModes,omitempty"`
// VAAPIQualityRC / VAAPIBitrateRC record the probed VAAPI rate-control
// modes ("QVBR", "VBR", "CBR", "CQP") per encoder ("h264_vaapi",
// "hevc_vaapi"); nil/empty falls back to the default QVBR/VBR modes.
VAAPIQualityRC map[string]string `json:"vaapiQualityRc,omitempty"`
VAAPIBitrateRC map[string]string `json:"vaapiBitrateRc,omitempty"`
}
type HealthChecker ¶
HealthChecker checks a sample of an NZB's articles exist (NNTP STAT). It also inspects archive headers: compressed or encrypted RARs and releases without a playable video file report healthy=false with a reason. Implemented by internal/stream.
type HistoryEntry ¶
type HistoryQuery ¶
type HistoryQuery struct {
Kind KeyKind
UserID int64 // zero selects all accounts (owner only at the protocol boundary)
Key RatingKey
DeviceID *int64
ViewType int
Since, Until, At *int64 // Unix seconds, inclusive
Asc bool
Offset, Limit int
}
HistoryQuery selects persisted viewing events before applying a bounded page.
type HistoryStore ¶
type HistoryTopStore ¶
type HistoryTopStore interface {
HistoryTop(context.Context, HistoryQuery, KeyKind) ([]HistoryCount, error)
LifetimeUsers(context.Context, RatingKey, HistoryQuery) ([]HistoryCount, error)
}
type HomeCandidateSource ¶ added in v0.2.7
type HomeCandidateSource interface {
HomeCandidatesFor(context.Context, *User, HubContext, int) ([]Hub, error)
}
HomeCandidateSource exposes the optional HomeCandidatesFor capability.
type HomeLayout ¶
type HomeLayout struct {
Global []LayoutPage `json:"global"`
Viewers []ViewerLayout `json:"viewers"`
UpdatedAt time.Time `json:"updatedAt,omitempty"`
// CollectionSchedules carries collection schedules (by collection id)
// for the Home designer: the owner API fills it on read and saves
// entries to their collections on write (null clears), and a draft
// preview applies it. It is never stored with the layout; the
// collection owns its schedule, so Everyone policies for a collection
// row carry no When.
CollectionSchedules map[string]*CollectionSchedule `json:"collectionSchedules,omitempty"`
}
HomeLayout is the owner's global template, with complete row policies in viewer layers replacing matching global policies. Slots are one-based.
type HomeLayoutSource ¶ added in v0.2.7
type HomeLayoutSource interface {
FinalizeHome(context.Context, *User, HubContext, string, []Hub) ([]Hub, error)
}
HomeLayoutSource exposes the optional FinalizeHome capability.
type HomePreview ¶
type HomePreview struct {
Rows []HomeRow `json:"rows"`
GeneratedAt time.Time `json:"generatedAt"`
Context HubContext `json:"context"`
// HomeDeduped counts the titles kept off a Movies or TV Shows page
// because the viewer's Home leads with them (DedupeHome).
HomeDeduped int `json:"homeDeduped,omitempty"`
}
HomePreview is a viewer's assembled rows for one context.
type HomeRow ¶
type HomeRow struct {
HubID string `json:"hubId"`
Layer string `json:"layer,omitempty"`
Slot int `json:"slot,omitempty"`
AnchorSlot int `json:"anchorSlot,omitempty"`
Placement string `json:"placement,omitempty"`
HiddenCode string `json:"hiddenCode,omitempty"`
HiddenReason string `json:"hiddenReason,omitempty"`
Policy *RowPolicy `json:"policy,omitempty"`
PolicyLayer string `json:"policyLayer,omitempty"`
Title string `json:"title"`
Kind string `json:"kind"` // e.g. "because-you-watched", "collection:<id>"
Reason string `json:"reason"`
Score float64 `json:"score"` // predicted engagement used for ordering
Pinned bool `json:"pinned,omitempty"`
Hidden bool `json:"hidden,omitempty"` // hidden by a layout rule: not sent to Plex
Source string `json:"source"`
Items []Title `json:"items"`
ItemReasons map[RatingKey]string `json:"itemReasons,omitempty"`
// Hub is the row as handed to the Plex front end.
Hub Hub `json:"-"`
}
HomeRow is one row of a viewer's Home or section as Plex receives it, with the engine's explanation. Items are catalogue titles; the admin API turns them into TitleCards.
type HomeSituation ¶ added in v0.3.0
type HomeSituation struct {
Device, Daypart string
Weekend bool
Now time.Time
LibraryID int
DefaultMaxRows int
Product, Platform, SessionID, ClientID string
}
HomeSituation describes the viewer's device and local time for row ranking.
type Hub ¶
type Hub struct {
RankedTop10 bool `json:"rankedTop10,omitempty"`
ID string `json:"id"` // stable identifier, e.g. "trending.week.movie"
Title string `json:"title"`
Type MediaType `json:"type"` // item type in the row ("mixed" allowed via "")
Context string `json:"context"` // Plex hub context, e.g. "hub.movie.recentlyreleased"
Style string `json:"style,omitempty"` // "shelf", "hero", "clip"
PreviewOnFocus bool `json:"previewOnFocus,omitempty"`
Promoted bool `json:"promoted"` // show on Home
Items []Title `json:"items"`
More bool `json:"more"`
Key RatingKey `json:"key,omitempty"` // backing collection, if any
// ItemCount carries rendered availability when a front end retains the
// actual metadata and asks only for row placement.
ItemCount int `json:"itemCount,omitempty"`
}
Hub is a Home row or a section row.
func SectionView ¶
SectionView restricts a Home hub to one library section's media type, so mixed rows that belong on a section too (the watchlist, Rediscover) can appear there with only that section's titles. A typed hub passes through when its type matches. Recaps (Year in Review) stay on Home. ok is false when nothing of the type remains.
type HubContext ¶
type HubContext struct {
Device string `json:"device"`
Daypart string `json:"daypart"`
Weekend bool `json:"weekend"`
Now time.Time `json:"now"`
SectionID int `json:"sectionId,omitempty"`
// HomeScoped marks a library-scoped Home request (such as Plex
// /hubs/promoted?contentDirectoryID=N): rows remain scoped to the
// section's media type and library membership, while layout policies and
// collection targeting use the Home ("home") surface.
HomeScoped bool `json:"-"`
Product string `json:"product,omitempty"` // X-Plex-Product
Platform string `json:"platform,omitempty"` // X-Plex-Platform
SessionID string `json:"sessionId,omitempty"`
ClientID string `json:"clientId,omitempty"`
}
HubContext is the situation a Plex client asked for rows in: which kind of device, when, and for which section (empty = Home).
func NewHubContext ¶
func NewHubContext(now time.Time, product, platform, device string) HubContext
NewHubContext derives the request context for a hubs call at now (in the server's local time; pass time.Now() or a time already converted with In(loc)) from the client's X-Plex-* headers.
func (HubContext) Bucket ¶
func (hc HubContext) Bucket() string
Bucket is a stable cache key for the context's coarse shape: "section/device/daypart/weekday|weekend".
type HubImpression ¶
type HubImpression struct {
UserID int64 `json:"userId"`
HubID string `json:"hubId"`
Position int `json:"position"`
Keys []RatingKey `json:"keys"`
Context HubContext `json:"context"`
At time.Time `json:"at"`
}
HubImpression is one row as served to a user, for the personalization feedback loop.
type HubItemSource ¶ added in v0.2.56
type HubItemSource interface {
HubItemsFor(context.Context, *User, HubContext, string, int) (Hub, bool)
}
HubItemSource exposes the optional HubItemsFor capability for resolving a specific hub by identifier even after a model or window transition.
type IDs ¶
type IDs struct {
TMDB int64 `json:"tmdb,omitempty"`
IMDB string `json:"imdb,omitempty"`
TVDB int64 `json:"tvdb,omitempty"`
}
IDs are the external identifiers of a title. Episodes carry their show's IMDb/TVDB ids in ShowIDs on Title, and their own TMDB episode id here.
type Identity ¶ added in v0.3.0
type Identity interface {
Resolve(ctx context.Context, surface, credential string) (*Viewer, error)
}
Identity resolves a credential only for the supplied surface. Surface IDs are protocol-defined strings so additional front ends can register them.
type ImageURLFunc ¶
ImageURL returns a full TMDB image URL for a path and size ("w500", "original").
type ImpressionSink ¶
type ImpressionSink interface {
RecordImpressions(user *User, hc HubContext, hubs []Hub)
}
ImpressionSink receives served rows. Implementations must not block.
type InputSwapState ¶ added in v0.3.3
type InputSwapState interface {
CurrentSwapInput() string
}
InputSwapState identifies the input currently held by an encoder session.
type IntentTracker ¶
type IntentTracker interface {
// RecordDetailOpen notes that a viewer opened a title's detail page.
RecordDetailOpen(ctx context.Context, user *User, t *Title)
// NotePlayback notes that playback of key started; an open for the
// same title moments earlier was a conversion, not browsing intent.
NotePlayback(user *User, key RatingKey)
}
IntentTracker receives live in-session browsing signals (item #32): single-item detail opens that do not turn into playback. Signals are in-memory only and decay over ~45 minutes. Implementations must not block the caller for long.
type ItemRef ¶
type ItemRef string
ItemRef is a plugin item's stable identity: "pk:" + pluginID + ":" + kindKey + ":" + externalID, where the external id never contains ':' or '/'. Ether assigns it; plugins only ever see their own external ids.
func NewItemRef ¶
NewItemRef formats the canonical ItemRef for (pluginID, kindKey, externalID).
func ParseItemRef ¶
ParseItemRef validates s and returns it as an ItemRef.
func (ItemRef) Parse ¶
Parse splits r into (pluginID, kindKey, externalID) and reports whether r is a well-formed ItemRef (spec §2.2).
type ItemUnavailable ¶
type ItemUnavailable struct {
}
ItemUnavailable explains why an item cannot currently be played.
type JobsBusyError ¶
JobsBusyError wraps ErrJobsBusy with an honest refusal message and retry delay (#590).
func (*JobsBusyError) Error ¶
func (e *JobsBusyError) Error() string
func (*JobsBusyError) Is ¶
func (e *JobsBusyError) Is(target error) bool
type KeyframePoint ¶
KeyframePoint ties a byte offset in a media file to the presentation time of the sync sample (keyframe) or cue point that starts there, as read from the container index (Matroska Cues, MP4 stss with stco/co64) or a packet scan. MediaInfo.Keyframes holds them sorted by Offset and Time.
type KindArtRef ¶
type KindArtRef struct {
Role string `json:"role"`
URL string `json:"url"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
}
KindArtRef is one artwork reference on a KindItem.
type KindBrowseRequest ¶
type KindBrowseRequest struct {
ParentID string `json:"parentId,omitempty"`
Level string `json:"level,omitempty"`
Cursor string `json:"cursor,omitempty"`
Limit int `json:"limit,omitempty"`
Sort string `json:"sort,omitempty"`
Desc bool `json:"desc,omitempty"`
// Facets requires any of the listed values per field (OR within a
// field, AND across fields). AllFacets requires every listed value
// per field and ExcludeFacets drops items having any listed value;
// all three maps combine with AND and accept the same per-type
// values (including lo..hi ranges and people names).
Facets map[string][]string `json:"facets,omitempty"`
AllFacets map[string][]string `json:"allFacets,omitempty"`
ExcludeFacets map[string][]string `json:"excludeFacets,omitempty"`
Query string `json:"query,omitempty"`
// Total controls whether kinds.browse computes KindPage.Total (#682):
// - "" or "cheap" (default): populate Total only when O(1) (item or
// field tallies, a cached exact count, or a single-page result) and
// omit Total otherwise instead of running a full COUNT(*).
// - "none": never compute or return Total.
// - "exact": compute an exact Total (cached per library generation).
Total string `json:"total,omitempty"`
}
KindBrowseRequest is the request body sent to a catalog_provider browse or search route (spec §3.1, §3.2) and passed to the viewer-scoped kinds.browse host service (#615).
type KindChangePage ¶
type KindChangePage struct {
Upserts []KindItem `json:"upserts,omitempty"`
Deletes []string `json:"deletes,omitempty"` // externalIDs
NextCursor string `json:"nextCursor,omitempty"`
Complete bool `json:"complete"`
}
KindChangePage is one delta page returned by POST /ether/v1/kinds/{kind}/changes during pull sync (spec §3.5).
type KindExpandRequest ¶
type KindExpandRequest struct {
Facet string `json:"facet,omitempty"`
Value string `json:"value,omitempty"`
ValueID int64 `json:"valueId,omitempty"`
ParentID string `json:"parentId,omitempty"`
Level string `json:"level,omitempty"`
Cursor string `json:"cursor,omitempty"`
}
KindExpandRequest is the request body sent to POST /ether/v1/kinds/{kind}/expand to expand a declared browse facet bucket, people credit, or container on demand.
type KindExpandResponse ¶
type KindExpandResponse struct {
Items []KindItem `json:"items,omitempty"`
Cursor string `json:"cursor,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
Job string `json:"job,omitempty"`
}
KindExpandResponse is the response from POST /ether/v1/kinds/{kind}/expand. Plugins return either {items, cursor} directly or {job: "/ether/job/..."} for long work.
func (KindExpandResponse) EffectiveCursor ¶
func (r KindExpandResponse) EffectiveCursor() string
EffectiveCursor returns Cursor when non-empty, falling back to NextCursor.
type KindInput ¶
type KindInput struct {
// Title is the projected kind item. Its Key must be a plugin key
// (RatingKey.IsPluginKey); its Type selects the profile media scope.
Title *Title
// Open returns the item's byte stream. It is called once per open, inside
// the prepare flight, so stream-limit accounting and cancellation apply.
Open func(ctx context.Context) (MediaSource, error)
// OpenCandidate, when set, opens the next non-excluded candidate from the
// item's kind resolution and returns its concrete Release metadata so
// mid-stream failover can switch to alternative plugin candidates.
OpenCandidate func(ctx context.Context, exclude []string) (MediaSource, Release, error)
// SourceID is a stable identity for the underlying source, used as the
// synthetic release id when OpenCandidate is not provided.
SourceID string
// PreferSourceID, when non-empty, requests opening the version whose
// candidate source id matches, instead of the default winner. The id is
// the stable release id of one of the item's /resolve sources.
PreferSourceID string
// Exact, when true alongside a non-empty PreferSourceID, forbids falling
// back to another candidate if PreferSourceID is unavailable or fails
// mid-stream.
Exact bool
// DeferSupersession keeps the prepared session off Activity and leaves
// other live sessions untouched until MarkSurfaceOpened is called on
// admission (used by broker Plan and SwitchVersion).
DeferSupersession bool
}
KindInput is a non-catalogue playback input: a plugin kind leaf whose bytes arrive as a random-access MediaSource rather than through the release pipeline. It exists so plugin video/audio items run through the same transcode, decision, HLS/DASH and stream-limit machinery as catalogue titles (spec §15.1).
type KindItem ¶
type KindItem struct {
Ref ItemRef `json:"-" ` // assigned by Ether, never sent to the plugin
Key RatingKey `json:"-" ` // allocated PluginKey(seq), populated on store reads
AddedAt int64 `json:"-"` // store insertion unix seconds, populated on store reads
ID string `json:"id"` // externalID
Level string `json:"level"`
ParentID string `json:"parentId,omitempty"`
Index int `json:"index,omitempty"` // position within parent / container leaf index
Title string `json:"title"`
SortTitle string `json:"sortTitle,omitempty"` // Ether derives it when empty
Summary string `json:"summary,omitempty"`
Year int `json:"year,omitempty"`
Released int64 `json:"released,omitempty"` // unix seconds
Rating float64 `json:"rating,omitempty"`
Playable bool `json:"playable,omitempty"`
ChildCount int `json:"childCount,omitempty"`
LeafCount int `json:"leafCount,omitempty"`
Art []KindArtRef `json:"art,omitempty"`
Fields map[string]json.RawMessage `json:"fields,omitempty"` // validated against the kind declaration
Hints json.RawMessage `json:"hints,omitempty"` // opaque; stored and echoed to the resolver verbatim
ETag string `json:"etag,omitempty"`
}
KindItem is the standardised plugin item envelope (spec §3.2).
type KindItemPart ¶
type KindItemPart struct {
Index int `json:"index"`
Name string `json:"name,omitempty"`
MIME string `json:"mime,omitempty"`
Size int64 `json:"size,omitempty"`
DurationSec float64 `json:"durationSec,omitempty"`
FileIndex *int `json:"fileIndex,omitempty"`
}
KindItemPart describes one declared or resolved file/part of a multi-file KindItem (spec §3.2, §4.1, #576).
func ExtractKindItemParts ¶
func ExtractKindItemParts(hints json.RawMessage) []KindItemPart
ExtractKindItemParts inspects a KindItem's Hints JSON for a non-empty "parts" array and returns generic per-part metadata in declaration order. Returns nil when the item does not declare parts.
func ExtractKindItemPartsFromItem ¶
func ExtractKindItemPartsFromItem(item KindItem) []KindItemPart
ExtractKindItemPartsFromItem inspects a KindItem for declared parts, checking hints.parts first and falling back to a declared "parts" array field when present (#576).
type KindMatchRequest ¶
type KindMatchRequest struct {
Item KindItem `json:"item"`
Candidates []SourceCandidate `json:"candidates"`
Settings map[string]any `json:"settings,omitempty"`
}
KindMatchRequest is the request body sent to POST /ether/v1/kinds/{kind}/match (spec §7).
type KindMatchResponse ¶
type KindMatchResponse struct {
Pending bool `json:"pending,omitempty"`
RetryInMS int64 `json:"retryInMs,omitempty"`
Job string `json:"job,omitempty"`
Matches []KindMatchScore `json:"matches"`
}
KindMatchResponse is the response from POST /ether/v1/kinds/{kind}/match (spec §7).
type KindMatchScore ¶
type KindMatchScore struct {
CandidateRef string `json:"candidateRef"`
Score float64 `json:"score"`
Reasons []string `json:"reasons,omitempty"`
}
KindMatchScore is one candidate score returned by a matcher (spec §7).
type KindPage ¶
type KindPage struct {
Items []KindItem `json:"items"`
NextCursor string `json:"nextCursor,omitempty"` // opaque; absent = last page
Total *int `json:"total,omitempty"` // provider claim; Ether never trusts it for its own totals
}
KindPage is one page of kind items.
type KindPlayback ¶
type KindPlayback interface {
PrepareKind(ctx context.Context, user *User, in KindInput, caps ClientCaps) (*PlaySession, error)
// SessionForKind finds the live kind session for a viewer, client and item.
SessionForKind(userID int64, clientID string, key RatingKey) (*PlaySession, bool)
}
KindPlayback opens a non-catalogue (plugin kind) item through the session and decision pipeline. It mirrors Playback.Prepare but takes a KindInput instead of resolving a catalogue title.
type KindResolveRequest ¶
type KindResolveRequest struct {
LibraryKey string `json:"libraryKey"`
Item KindItem `json:"item"`
PartIndex *int `json:"partIndex,omitempty"`
Source string `json:"source,omitempty"`
Client map[string]any `json:"client,omitempty"`
}
KindResolveRequest is the payload sent to a plugin's kind_resolve handler (spec §4.1).
type KindResolveResponse ¶
type KindResolveResponse struct {
Pending bool `json:"pending,omitempty"`
RetryInMS int64 `json:"retryInMs,omitempty"`
Job string `json:"job,omitempty"`
Sources []PlayableSource `json:"sources"`
Parts []KindItemPart `json:"parts,omitempty"`
TTLSec int `json:"ttlSec,omitempty"`
}
KindResolveResponse is the response returned by a plugin's kind_resolve handler (spec §4.1).
type LayoutPage ¶
type LayoutPage struct {
Section string `json:"section"`
MaxRows int `json:"maxRows,omitempty"`
DeviceMaxRows map[string]int `json:"deviceMaxRows,omitempty"`
Rows []RowPolicy `json:"rows"`
// DedupeHome keeps titles the viewer's Home leads with off this page
// (library Recommended pages only). Nil means the default: on.
DedupeHome *bool `json:"dedupeHome,omitempty"`
// Tuning shapes how the page's rows and titles are chosen. Nil fields
// inherit (viewer page → global page → engine default).
Tuning *LayoutTuning `json:"tuning,omitempty"`
}
type LayoutTuning ¶
type LayoutTuning struct {
// Discovery: 0 sticks to proven favourites, 1 explores new territory.
Discovery *float64 `json:"discovery,omitempty"`
// Freshness: 0 favours timeless picks, 1 favours new and trending.
Freshness *float64 `json:"freshness,omitempty"`
// Variety: 0 keeps rows focused on the strongest tastes, 1 spreads
// across genres, eras and moods.
Variety *float64 `json:"variety,omitempty"`
}
LayoutTuning is the owner's three dials for a page, each 0..1 with 0.5 as the engine default.
type LayoutWhen ¶
type LayoutWhen struct {
Days []int `json:"days,omitempty"`
Dayparts []string `json:"dayparts,omitempty"`
Months []int `json:"months,omitempty"`
StartDate string `json:"startDate,omitempty"`
EndDate string `json:"endDate,omitempty"`
FromHour *int `json:"fromHour,omitempty"`
ToHour *int `json:"toHour,omitempty"`
Devices []string `json:"devices,omitempty"`
}
LayoutWhen restricts a Home layout row to days (0 = Sunday … 6 = Saturday), an hour window [FromHour, ToHour) in server local time (wraps past midnight when FromHour > ToHour) and device classes.
type Library ¶
type Library struct {
ID LibraryID `json:"id"`
Key string `json:"key"` // slug, unique, immutable: "movies", "shows", "pk-<plugin>-<kind>", owner slug
Name string `json:"name"` // owner-editable display name
Source LibrarySource `json:"source"`
Sources []string `json:"sources"`
// Builtin only: TypeMovie or TypeShow.
MediaType MediaType `json:"mediaType,omitempty"`
// Plugin only.
PluginID string `json:"pluginId,omitempty"`
KindKey string `json:"kindKey,omitempty"` // MediaKind.Key within that plugin
// Collection only: the owner collection whose titles this library
// shows (an MDBList list, a Trakt list, a smart rule, a hand-made
// list…). MediaType pins movie|show. A deleted
// collection leaves the library empty, never an error.
CollectionID int64 `json:"collectionId,omitempty"`
// Visibility rules for this library. Built-in libraries 1 and 2
// govern canonical movie/show visibility across every protocol; catalogue
// libraries may carry additional rules on top of their canonical library.
RulesBroken bool `json:"rulesBroken,omitempty"`
Rules []LibraryExclusion `json:"rules,omitempty"`
VisibilityDefault string `json:"visibilityDefault,omitempty"`
// Owner-defined Vela tabs. Empty when TabsCustomized is false, in which
// case effective tabs come from the plugin declaration or DefaultCatalogueTabs.
Tabs []LibraryTab `json:"tabs,omitempty"`
TabsCustomized bool `json:"tabsCustomized,omitempty"`
// CardShape overrides how item thumbnails in this library are shaped
// ("poster", "landscape", or "square"). Empty means default: the plugin's
// declared library.card for plugin libraries, or "poster" for catalogue
// libraries.
CardShape string `json:"cardShape,omitempty"`
// Presentation: how protocols expose this library (§6.2). For builtins
// this is synthesised, not stored.
Present Presentations `json:"present,omitempty"`
// PresentOverrides records sticky owner on/off switches per app.
// Nil fields follow the manifest or inferred default; non-nil choices
// survive plugin updates and restarts.
PresentOverrides PresentationOverrides `json:"presentOverrides,omitempty"`
// QualityProfile is the owner-set quality profile name titles in this
// library rank with. Empty means "Default": today's Movies/Shows
// home/away defaults apply. Set on any library, including catalogue
// libraries (an "Anime" library can rank with an anime profile).
QualityProfile string `json:"qualityProfile,omitempty"`
Sort int `json:"sort"` // owner order in every client
Hidden bool `json:"hidden"` // owner hid it from all clients (still in console)
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Library is the one library model for builtins, plugin kinds and owner catalogue libraries alike (spec §1.1).
func (Library) EffectiveCardShape ¶
EffectiveCardShape resolves the library's card shape: the owner's CardShape choice first, then pluginDefault (for plugin libraries), falling back to "poster".
type LibraryExclusion ¶ added in v0.2.12
type LibraryExclusion struct {
// Name is optional. Clients label a rule from its conditions.
Name string `json:"name"`
Action string `json:"action,omitempty"` // show, hide; empty means hide
MediaType string `json:"mediaType"` // movie, show, mixed
Match string `json:"match"` // all, any
Rules []CollectionRule `json:"rules"`
Scope string `json:"scope,omitempty"` // everywhere, discovery; empty means everywhere
}
LibraryExclusion is one ordered visibility rule. Slice order is evaluation order: the first match wins. Action is "show" or "hide"; an empty Action is "hide", so a saved exclusion group stays a hide rule. Conditions inside a rule combine with Match "all" or "any". Watch history and metadata are kept.
Scope limits where a hide rule applies. Empty or "everywhere" hides the title from browsing and search. "discovery" hides it only from browsing, Home and hub rows, recommendations, New Releases, Trending and catalogue collections; search, direct lookup and playback still reach it.
func NormalizeLibraryRules ¶
func NormalizeLibraryRules(rules []LibraryExclusion) []LibraryExclusion
NormalizeLibraryRules returns canonical rules, retaining malformed values unchanged so the compiler can reject them.
type LibraryID ¶
type LibraryID int64
LibraryID identifies one library. 1 = Movies, 2 = TV Shows forever; ids are never reused.
func CanonicalLibraryForTitle ¶
CanonicalLibraryForTitle returns the one canonical library of a TMDB title (§1.2): TypeMovie → 1; TypeShow/Season/Episode → 2. Any other type has no canonical library and returns 0.
type LibrarySource ¶
type LibrarySource string
LibrarySource says where a library's items come from.
const ( LibraryBuiltin LibrarySource = "builtin" // the TMDB catalogue, split by MediaType LibraryPlugin LibrarySource = "plugin" // items owned by one plugin MediaKind instance LibraryCatalog LibrarySource = "catalogue" // owner-selected catalogue sources LibraryCollection LibrarySource = "collection" // exactly the titles of one owner collection )
type LibraryTab ¶
type LibraryTab struct {
Key string `json:"key"`
Label string `json:"label"`
Kind string `json:"kind"` // recommended|library|collections|people|view|live
Level string `json:"level,omitempty"` // optional plugin hierarchy level key (library, view, collections or people)
Facet string `json:"facet,omitempty"` // collections or people facet
Order string `json:"order,omitempty"` // count|name (collections or people)
Sort string `json:"sort,omitempty"` // default sort (library, view, facet collections)
Direction string `json:"direction,omitempty"` // asc|desc
Card string `json:"card,omitempty"` // landscape (default)|poster|square (live tabs only)
Layout string `json:"layout,omitempty"` // grid (default)|list|timeline (view tabs only)
Search *bool `json:"search,omitempty"` // defaults true for library/collections/people/view/live, false for recommended
SearchPlaceholder string `json:"searchPlaceholder,omitempty"` // optional custom search placeholder
Filters *TabFilter `json:"filters,omitempty"` // saved filter rules (view or library)
Hidden bool `json:"hidden,omitempty"` // hidden from Vela while kept in editor
}
LibraryTab configures one tab inside a library in Vela.
func DefaultCatalogueTabs ¶
func DefaultCatalogueTabs() []LibraryTab
DefaultCatalogueTabs returns the default tabs when a catalogue or collection library has no owner-configured tabs.
func (LibraryTab) EffectiveCard ¶
func (t LibraryTab) EffectiveCard() string
EffectiveCard returns the tab's card shape ("landscape" by default for live tabs, empty for other tab kinds).
func (LibraryTab) EffectiveLayout ¶
func (t LibraryTab) EffectiveLayout() string
EffectiveLayout returns the tab's layout ("grid" by default for view tabs, empty for other tab kinds).
func (LibraryTab) EffectiveSearch ¶
func (t LibraryTab) EffectiveSearch() bool
EffectiveSearch reports whether in-tab search is enabled on t.
type LikesState ¶ added in v0.3.0
LikesState atomically applies a viewer's tri-state like to the shared rating. Nil clears the rating; true and false preserve existing compatible ratings.
type ListRows ¶
type ListRows struct {
Facts TitleFacts
Detail func(Title) bool
}
ListRows asks a key-ordered Browse page for a whole-library export's rows: each title with Facts, what the catalogue's own policy reads for the viewer (browsing rules, the release gate), and its directors and first three cast members, but no other credits, alternative titles or aired season and episode counts (a series keeps its stored ones). A title Detail reports (one the caller judges on its full facts) comes back in full. Partial titles never enter a shared cache.
type LiveChannel ¶
type LiveChannel struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Number string `json:"number,omitempty"`
}
LiveChannel identifies a live session's selected channel independently of its programme.
type LocalFileSource ¶ added in v0.3.0
LocalFileSource exposes the opened file for change detection. The path and inode must still identify the same regular file when a revision is checked.
type LookupResult ¶
type LookupResult struct {
ID int64 `json:"id"`
Name string `json:"name"`
Subtitle string `json:"subtitle,omitempty"`
ImagePath string `json:"imagePath,omitempty"` // TMDB image path
}
LookupResult is one TMDB entity (person, keyword, company, network, collection, watch provider) found by name for the collection builder.
type MIMESource ¶
type MIMESource interface {
MIME() string
}
MIMESource is implemented by a MediaSource that knows its declared media MIME type (for example a plugin kind stream declaring audio/flac or application/epub+zip).
type MarkedPlaylists ¶ added in v0.3.0
type MarkedPlaylists interface {
MarkedPlaylist(context.Context, int64, string) (*Playlist, error)
EnsureMarkedPlaylist(context.Context, int64, string, string) (*Playlist, error)
}
MarkedPlaylists provides stable, per-viewer playlist identities independent of names.
type MediaAccessTracker ¶
MediaAccessTracker is an optional output-session extension reporting when client-facing media bytes (segments, init segments, or HTTP stream bytes — never session creation, playlists, or paused timelines) were last served.
type MediaBrowserPresentation ¶
type MediaBrowserPresentation struct {
CollectionType string `json:"collectionType,omitempty"` // movies|tvshows|music|audiobooks|books|photos|homevideos
ItemTypes map[string]string `json:"itemTypes,omitempty"` // level -> Movie|Series|Season|Episode|MusicArtist|MusicAlbum|Audio|AudioBook|Book|PhotoAlbum|Photo
Default *bool `json:"default,omitempty"` // optional manifest default hint (true when omitted)
}
MediaBrowserPresentation describes how Jellyfin and Emby see a library.
type MediaCapWait ¶
type MediaCapWait struct {
// contains filtered or unexported fields
}
MediaCapWait is request-scoped. It measures only the initial source read, because response headers precede the body; later reads cannot amend them.
func MediaCapWaitFrom ¶
func MediaCapWaitFrom(ctx context.Context) *MediaCapWait
func (*MediaCapWait) BeginRead ¶
func (m *MediaCapWait) BeginRead() bool
func (*MediaCapWait) FirstUpstream ¶
func (m *MediaCapWait) FirstUpstream(wait time.Duration)
func (*MediaCapWait) MarkKnown ¶
func (m *MediaCapWait) MarkKnown()
func (*MediaCapWait) Milliseconds ¶
func (m *MediaCapWait) Milliseconds() (int64, bool)
type MediaCapWaitSource ¶
type MediaCapWaitSource interface{ MediaCapWaitKnown() bool }
MediaCapWaitSource identifies sources for which admission wait is measurable. HTTP/add-on and Usenet sources do not claim debrid measurements.
type MediaClass ¶
type MediaClass string
MediaClass names the kind of media a content kind holds.
const ( MediaClassVideo MediaClass = "video" MediaClassMusic MediaClass = "music" MediaClassAudiobook MediaClass = "audiobook" MediaClassBook MediaClass = "book" MediaClassPodcast MediaClass = "podcast" MediaClassPhoto MediaClass = "photo" )
type MediaCredit ¶
type MediaCredit struct {
Name string `json:"name"`
Role string `json:"role"`
PersonID string `json:"personId,omitempty"`
TMDB int64 `json:"tmdb,omitempty"`
ThumbPath string `json:"thumbPath,omitempty"`
}
MediaCredit preserves a plugin item's declared credit role alongside the resolved person identity (for example artist, albumArtist, author, narrator, composer, illustrator, translator, host).
type MediaInfo ¶
type MediaInfo struct {
Has64bitOffsets *bool `json:"has64bitOffsets,omitempty"`
OptimizedForStreaming *bool `json:"optimizedForStreaming,omitempty"`
Chapters []Chapter `json:"chapters,omitempty"`
Container string `json:"container"` // mkv, mp4, avi, mpegts
Duration time.Duration `json:"duration"`
Size int64 `json:"size"`
BitrateKbps int `json:"bitrateKbps"`
Streams []StreamInfo `json:"streams"`
Estimated bool `json:"estimated"` // derived from release name, not probed
// Keyframes is the container's keyframe/cue index, sorted, when it was
// read on open or probe; empty when unknown. Not serialized: it can hold
// thousands of points (additive).
Keyframes []KeyframePoint `json:"-"`
CopyTimeline *CopyTimeline `json:",omitempty"`
}
func CloneMediaInfo ¶ added in v0.3.0
CloneMediaInfo detaches every mutable fact while preserving nil and empty values. The caller must own the input or hold its writer's lock during this copy; cloning does not synchronize concurrent mutation of the input itself.
func (MediaInfo) AudioOnly ¶
HasPlayableMedia reports whether probed facts describe something a client can play: a video stream, or (for music, audiobooks and other audio-only items) at least one audio stream. AudioOnly reports a probed source that has audio streams and no video stream. A source with no stream facts yet is not audio-only.
func (MediaInfo) HasPlayableMedia ¶
func (MediaInfo) Video ¶
func (m MediaInfo) Video() *StreamInfo
type MediaRole ¶
type MediaRole string
MediaRole names what one hierarchy level of a content kind represents.
const ( MediaRoleItem MediaRole = "item" MediaRoleArtist MediaRole = "artist" MediaRoleAlbum MediaRole = "album" MediaRoleTrack MediaRole = "track" MediaRoleSeries MediaRole = "series" MediaRoleBook MediaRole = "book" MediaRoleAudiobook MediaRole = "audiobook" MediaRolePart MediaRole = "part" MediaRoleShow MediaRole = "show" MediaRoleEpisode MediaRole = "episode" MediaRoleCollection MediaRole = "collection" )
type MediaSource ¶
type MediaSource interface {
io.ReaderAt
Size() int64
Name() string // file name inside the release, e.g. "Movie.2024.1080p.mkv"
ReleaseID() string
Close() error
}
MediaSource is a seekable byte stream of one playable file (the video file inside a release, after NZB/RAR/7z unwrapping).
type MediaType ¶
type MediaType string
MediaType matches Plex's metadata "type" attribute.
func SearchTypesFrom ¶
SearchTypesFrom returns WithSearchTypes' media types, or nil.
type MetadataProber ¶
type MetadataProber interface {
ProbeMetadata(context.Context, *User, RatingKey, ClientCaps) error
}
MetadataProber obtains exact pre-play source facts without admitting a live session, subject to owner warm-up settings and a bounded wait. An error means facts are not ready; detail pages should render their normal fallback.
type MetadataProvider ¶ added in v0.3.3
type MetadataProvider interface {
ResolveMetadata(context.Context, MetadataRequest) (*Title, error)
}
MetadataProvider resolves catalogue records during explicit materialization. The catalogue owns identity validation, persistence and visibility policy. No ordinary browse or cached detail read invokes this interface.
type MetadataReaderAt ¶ added in v0.2.7
type MetadataReaderAt interface {
ReadMetadataAtContext(context.Context, []byte, int64) (int, error)
}
MetadataReaderAt reads container metadata without advancing playback or read-ahead.
type MetadataRequest ¶ added in v0.3.3
type MetadataRequest struct {
ID string `json:"id"`
Type MediaType `json:"type"`
IDs IDs `json:"ids,omitempty"`
}
MetadataRequest identifies a record within a provider and, when known, its expected canonical IDs. These are per-caller assertions, never identity hints that let a provider silently rebind a resource. Provider IDs are opaque; they are never used as TMDB IDs.
type MicroReason ¶
type MicroReason struct {
Header string `json:"header,omitempty"`
MatchPercent int `json:"matchPercent,omitempty"`
HasMatch bool `json:"hasMatch,omitempty"`
Reason string `json:"reason,omitempty"`
EndsAt time.Time `json:"endsAt,omitempty"`
HasEnd bool `json:"hasEnd,omitempty"`
}
MicroReason is the per-viewer decision header for a detail page (item #31): a calibrated match percentage, the strongest taste reason and the local finish time, e.g. "96% Match · Directed by Denis Villeneuve · Ends at 10:45 PM". Parts that cannot be supported honestly (low taste confidence, unknown runtime) are left empty.
func (MicroReason) Empty ¶
func (m MicroReason) Empty() bool
Empty reports whether there is nothing worth showing.
type MicroReasoner ¶
type MicroReasoner interface {
MicroReason(ctx context.Context, user *User, t *Title, now time.Time) MicroReason
}
MicroReasoner builds a MicroReason for one viewer and title. The title is only read, never mutated, so a shared catalogue record can never leak one viewer's header to another.
type NeutralEntryRef ¶ added in v0.3.0
type NeutralEntryRef struct{ Kind, ID string }
NeutralEntryRef identifies one delivered entry in a stable namespace.
type NeutralHomeLayoutSource ¶ added in v0.3.0
type NeutralHomeLayoutSource interface {
FinalizeNeutralHome(context.Context, *User, HomeSituation, string, []NeutralHomeRow) ([]NeutralHomeRow, error)
}
NeutralHomeLayoutSource arranges rows without a protocol-specific context.
type NeutralHomeRow ¶ added in v0.3.0
type NeutralHomeRow struct {
ID, Title, Kind string
Purpose RowPurpose
Type MediaType
Items []Title
ItemCount int
RankedTop10 bool
PreviewOnFocus bool
PreviewOnFocusPolicy *bool
Always bool
}
NeutralHomeRow carries a stable producer identity and semantic row type. Kind is the owner-layout identity (for example a collection rule), not a wire context.
type NeutralImpression ¶ added in v0.3.0
type NeutralImpression struct {
Situation HomeSituation
RowID, Kind, Title string
Purpose RowPurpose
Rank int
Items []RatingKey
Collection RatingKey
Item RatingKey // Parent item for detail rows.
Placement, ViewID string
Entries []NeutralEntryRef
}
NeutralImpression is a server-issued snapshot of a delivered row.
type NeutralImpressionSink ¶ added in v0.3.0
type NeutralImpressionSink interface {
RecordNeutralImpression(*User, NeutralImpression)
}
NeutralImpressionSink records a validated server-issued row snapshot.
type OriginSource ¶ added in v0.2.44
type OriginSource interface {
Origin() string
}
OriginSource is implemented by a MediaSource that can name the service its bytes come from, such as "Real-Debrid" (additive). Sources without it are Usenet.
type OwnedCollectionLister ¶
type OwnedCollectionLister interface {
ListOwned(ctx context.Context, user *User, t MediaType) ([]Collection, error)
}
OwnedCollectionLister lists the collections the owner made or enabled, without the movie franchises the catalogue derives. Listing franchises groups the whole movie library, so a search never does it.
type OwnedEncoderSession ¶ added in v0.3.0
type OwnedEncoderSession interface {
HLSSession
EncoderRetirement() EncoderRetirement
RetireEncoder() error
}
OwnedEncoderSession retires this exact object, never a replacement with the same public ID. RetireEncoder admits bounded asynchronous detachment; callers must inspect EncoderRetirement for completion, including input producers.
type OwnedSourcePlayback ¶ added in v0.3.0
type OwnedSourcePlayback interface {
PrepareSurfaceSource(context.Context, *User, RatingKey, ClientCaps, string, bool) (*PlaySession, SourceRetirement, error)
SourceRetirement(string) (SourceRetirement, bool)
// RetireSource detaches the exact captured source lifetime and schedules
// cleanup. Admission failure leaves the session attached. It is idempotent
// for the same lifetime and cannot detach a replacement.
RetireSource(string, SourceRetirement) error
}
OwnedSourcePlayback exposes source responsibility even when preparation fails or its caller cancels while a shared backend Open is still running.
type OwnedTranscoder ¶ added in v0.3.0
type OwnedTranscoder interface {
StartHLSOwned(context.Context, HLSRequest) (HLSSession, EncoderRetirement, error)
}
OwnedTranscoder returns responsibility even when a canceled start is still completing. A late start cannot publish after that responsibility is sealed.
type Page ¶
type Page struct {
Items []Title
Total int
// TotalExact reports whether Total is an exact count of all items matching
// the query (never a page-window estimate).
TotalExact bool
// Expanding reports whether a background plugin facet or person expansion
// is currently running for this slice.
Expanding bool
}
type Person ¶
type Person struct {
TMDB int64 `json:"tmdb,omitempty"`
IMDB string `json:"imdb,omitempty"`
ID string `json:"id,omitempty"` // catalogue person id when there is no TMDB id
Name string `json:"name"`
Role string `json:"role,omitempty"` // character for cast, job for crew
ThumbPath string `json:"thumbPath,omitempty"`
}
type PersonCredit ¶
PersonCredit is one person's credit on one title, as the catalogue stores it: the kind ("cast", "director", "writer", "crew") and the person as credited there (name, role, portrait, ids).
type PersonCreditForm ¶
PersonCreditForm is one way a person's credits name them: the name as credited and whether that credit carries a portrait.
type PersonMetadata ¶
PersonMetadata holds optional cached person profile facts from the metadata provider.
type PersonalPick ¶
PersonalPick is a viewer-safe programming candidate with its explanation.
type PersonalPicker ¶
type PersonalPicker interface {
Picks(context.Context, *User, map[string]float64, int) ([]PersonalPick, error)
}
PersonalPicker supplies background personal-channel rundown builders.
type PersonalScorer ¶
type PersonalScorer interface {
ScoreTitles(ctx context.Context, user *User, titles []Title) (map[RatingKey]float64, error)
}
PersonalScorer scores titles for a user (higher = better fit). The collection engine uses it for the "personal" sort.
type PlayExperience ¶ added in v0.3.3
type PlayExperience struct {
// Requested is set once a play request (decision, start, part or
// stream open) or a client timeline reached the source.
Requested bool `json:"requested"`
// Pictured is set once the client showed a picture; StartTime is the
// time from the play request to it, negative when unknown.
Pictured bool `json:"pictured"`
StartTime time.Duration `json:"startTime"`
// RequestedAt and PicturedAt are the instants behind StartTime (zero
// when unknown), so a history row spanning several sessions can
// measure from its first request to its first picture.
RequestedAt time.Time `json:"requestedAt,omitzero"`
PicturedAt time.Time `json:"picturedAt,omitzero"`
// StartFailure names why a start never reached a picture even though
// the client reported one (a stalled start the server ended).
StartFailure string `json:"startFailure,omitempty"`
// BufferEvents counts mid-play stalls after the first picture; Buffering
// is their total length (startup excluded).
BufferEvents int `json:"bufferEvents"`
Buffering time.Duration `json:"buffering"`
}
PlayExperience measures what the viewer saw (additive).
type PlayMetadataProber ¶
type PlayMetadataProber interface {
ProbePlayMetadata(context.Context, *User, RatingKey, ClientCaps) error
}
PlayMetadataProber joins or starts the shared resolve+probe flight for a client's play-time metadata re-ask (such as Plezy's first play) and waits until the probe lands or the caller's deadline/context expires. Unlike MetadataProber (detail browsing), this carries explicit play intent: it runs under playback resolution rules, bypasses speculative warm-up gates and negative memos, and publishes into the warm cache so the following stream request adopts the same resolved source and probe.
type PlaySession ¶
type PlaySession struct {
Encoder *EncoderStatus `json:"encoder,omitempty"`
PlaybackGroup string `json:"playbackGroup,omitempty"`
// PreparedOnly marks a source reserved for planning but not opened by a
// frontend. Cluster snapshots carry it for owner Activity.
PreparedOnly bool `json:"preparedOnly,omitempty"`
ID string
UserID int64
ClientID string
Key RatingKey
Resolution *Resolution
Source MediaSource // swaps on failover; read through Playback.Source
Info MediaInfo
StartedAt time.Time
// Status for the admin dashboard and /status/sessions, filled on the
// snapshots Playback returns.
TitleName string // "Movie (2024)" or "Show - S01E02 - Episode"
LiveChannel *LiveChannel `json:"liveChannel,omitempty"` // selected channel, including when programme metadata is available
Username string // user display name
Client ClientCaps // the client's product, device and limits
DecisionReason string `json:"decisionReason,omitempty"`
QualityFallback string `json:"qualityFallback,omitempty"`
Decision DecisionKind // directplay once bytes go straight to the client; "" until known
DeliveryDecision *Decision `json:"deliveryDecision,omitempty"` // negotiated output and track selection
// DecisionVideoCopy and DecisionAudioCopy say whether the current
// decision copies each stream (additive): a remux with
// DecisionAudioCopy false is transcoding only the audio.
DecisionVideoCopy bool `json:"decisionVideoCopy,omitempty"`
DecisionAudioCopy bool `json:"decisionAudioCopy,omitempty"`
BytesServed int64 // source bytes delivered (direct play and ffmpeg input)
SpeedBps int64 // recent delivery rate, bytes per second
// BufferedBytes is contiguous media downloaded ahead of the reader; zero
// when the source cannot report it. BufferedUntil is the absolute media
// time that read-ahead reaches, zero when unknown.
BufferedBytes int64
BufferedUntil time.Duration
LastActive time.Time
// Liveness is the session's evaluated state under the shared liveness rule
// (playing, paused, starting, idle, stopped).
Liveness SessionLivenessState `json:"liveness,omitempty"`
// ViewerState is the last client timeline state: playing, paused, or stopped.
ViewerState string `json:"viewerState,omitempty"`
// ViewOffset is the client's last reported playhead in milliseconds.
// Nil means no timeline has arrived; source bytes do not imply progress.
ViewOffset *int64 `json:"viewOffset,omitempty"`
Failovers int // mid-stream release swaps so far
// Origin names where the current release streams from: "Usenet" or the
// debrid service, such as "Real-Debrid" (additive).
Origin string `json:"origin,omitempty"`
// DownFailovers counts speed-driven swaps to a lower-bitrate release
// (a subset of Failovers) (additive).
DownFailovers int `json:"downFailovers,omitempty"`
// RequiresRemux is set when a direct-play failover could not splice or
// find an exact-size replacement: the next decision/start for this
// session must be a zero-encode remux (additive).
RequiresRemux bool `json:"requiresRemux,omitempty"`
// Node is the cluster node serving a session reported by another node
// (empty for this node's own sessions and on a standalone server).
Node string `json:"node,omitempty"`
// Experience is this play's viewer-experience accounting: start time
// and mid-play buffering (additive). Nil for a source no play request
// or client timeline has reached.
Experience *PlayExperience `json:"experience,omitempty"`
// SegmentStart is where the requested episode begins inside a combined
// multi-episode file ("S01E01-E02" played for its second episode):
// server-started streams add it to the client's episode-relative
// position. Zero for a file holding only the requested episode, and
// recomputed on every snapshot so a failover to another release
// re-derives it (additive).
SegmentStart time.Duration `json:"segmentStart,omitempty"`
}
PlaySession binds a user, a title and a client to a resolved, open source.
func (*PlaySession) SourcePosition ¶
func (s *PlaySession) SourcePosition(client time.Duration) time.Duration
SourcePosition translates a client's episode-relative position into the source file's timeline, past any earlier episodes a combined file holds before the requested one (SegmentStart). Server-started streams start at the translated position; client-reported positions stay episode-relative.
func (*PlaySession) SourceReleaseID ¶ added in v0.3.4
func (s *PlaySession) SourceReleaseID() string
SourceReleaseID identifies the selected release when one is available.
type PlayableSource ¶
type PlayableSource struct {
Path string `json:"path,omitempty"`
ID string `json:"id"`
Label string `json:"label,omitempty"`
Pattern string `json:"pattern"` // "range" | "download" | "direct" | "container" | "release" | "file"
MIME string `json:"mime"`
Size int64 `json:"size,omitempty"`
// SizeApproximate marks Size as an approximate hint (for example from a
// Usenet release_files estimate) rather than an exact byte count:
// kindstream applies a tolerance band instead of failing on exact byte
// inequality, while exact sizes (false/omitted) remain strict.
SizeApproximate bool `json:"sizeApproximate,omitempty"`
DurationSec float64 `json:"durationSec,omitempty"`
URL string `json:"url,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
// KeepHeadersOnRedirect lists optional host or wildcard (*.example.org)
// patterns (within permissions.network / granted hosts) that may keep
// credentials and caller headers across redirects when the target is not
// already the same origin or a strict same-site subdomain. Never applies
// across HTTPS -> HTTP downgrades.
KeepHeadersOnRedirect []string `json:"keepHeadersOnRedirect,omitempty"`
BlobRef string `json:"blobRef,omitempty"`
SHA256 string `json:"sha256,omitempty"`
// SHA1 and CRC32 are the digests content catalogues actually publish
// (hex; CRC32 is the IEEE polynomial as 8 hex digits). Any declared
// digest — and Size, when set — is checked against the bytes actually
// served, including a release's selected file or container member.
SHA1 string `json:"sha1,omitempty"`
CRC32 string `json:"crc32,omitempty"`
MaxBytes int64 `json:"maxBytes,omitempty"`
ExpiresAt int64 `json:"expiresAt,omitempty"`
Container *ContainerRef `json:"container,omitempty"`
Release *ReleaseHint `json:"release,omitempty"`
Parts []KindItemPart `json:"parts,omitempty"`
}
PlayableSource is one candidate way to acquire bytes for a KindItem or one of its parts (spec §4.1). Multiple sources are tried in order.
type Playback ¶
type Playback interface {
// Estimate is the virtual media info shown before a title is resolved.
Estimate(ctx context.Context, t *Title, caps ClientCaps) MediaInfo
// Prepare resolves and opens a source for the user and client, enforcing
// stream limits. Reuses an existing session for the same user/client/key.
Prepare(ctx context.Context, user *User, key RatingKey, caps ClientCaps) (*PlaySession, error)
Session(id string) (*PlaySession, bool)
// SessionFor finds the live session of a client for a title.
SessionFor(userID int64, clientID string, key RatingKey) (*PlaySession, bool)
// ServeRange serves the session's current source with HTTP range
// support, failing over to the next release when articles are missing.
ServeRange(w http.ResponseWriter, r *http.Request, sessionID string)
// InputURL is a loopback URL ffmpeg can read the session's source from.
InputURL(sessionID string) string
// Failover swaps the session to the next candidate release, keeping the
// timestamp. Returns the new media info.
Failover(ctx context.Context, sessionID string, at time.Duration) (*PlaySession, error)
Stop(sessionID string)
Sessions() []*PlaySession
}
type PlaybackAccessPolicy ¶ added in v0.2.7
PlaybackAccessPolicy exposes the optional CanPlay capability.
type PlaybackDecisionRecorder ¶ added in v0.3.2
PlaybackDecisionRecorder is implemented by playback managers that accept the delivery decision actually started for a session — a remux, transcode or direct stream begun by a front end or the session broker — so session snapshots report the current delivery. A remux or transcode decision also satisfies a pending RequiresRemux for the session.
type PlaybackDurationSetter ¶ added in v0.3.2
PlaybackDurationSetter exposes the optional SetPlaybackDuration capability: playback reports a probed title's running time so the source can read ahead of the viewer by time (minutes of media) rather than by bytes.
type PlaybackEncoderInputs ¶ added in v0.3.0
type PlaybackEncoderInputs interface {
ReserveEncoderInput(context.Context, string, SourceRetirement) (EncoderInputLease, error)
}
type PlaybackPosition ¶ added in v0.2.7
PlaybackPosition exposes the optional RequestedPosition capability.
type PlaybackPrepareWithin ¶ added in v0.3.3
type PlaybackPrepareWithin interface {
PrepareWithin(context.Context, time.Duration, *User, RatingKey, ClientCaps, string, bool) (*PlaySession, error)
}
PlaybackPrepareWithin joins a shared source preparation. A positive wait permits ErrPrepareSlow while preparation continues; a non-positive wait waits for completion or context cancellation under the service deadline.
type PlaybackPreparer ¶ added in v0.2.7
PlaybackPreparer warms a title without reserving playback or changing history.
type PlaybackRevisionPin ¶ added in v0.3.0
type PlaybackRevisionPin interface {
PinSourceRevision(ctx context.Context, id, revision string) error
UnpinSourceRevision(id string)
}
PlaybackRevisionPin keeps an opened generation from silently failing over while a client consumes metadata bound to its source revision.
type PlaybackSelectionFence ¶
type PlaybackSelectionFence interface {
WithSourceSelection(context.Context, string, string, func(MediaInfo) error) error
}
PlaybackSelectionFence validates an observed selection against the exact current source. fn must be short and must not read media or call a provider. The source fence is acquired before any manual-intent database writer in fn.
type PlaybackSourceHistory ¶ added in v0.3.0
type PlaybackSourceHistory struct {
Revision, ReleaseDigest, VideoCodec string
Height int
HDR *bool
}
PlaybackSourceHistory contains persisted source facts without raw release identifiers. A digest can only be matched against authorized candidates.
type PlaybackSourceObservation ¶ added in v0.3.0
type PlaybackSourceObservation struct {
Revision, ReleaseID string
VideoCodec string
Height int
HDR *bool
}
PlaybackSourceObservation contains scalar facts from one opened source generation. Empty Revision means its identity cannot be established safely; nil HDR and empty codec/zero height remain unknown.
type PlaybackSourceResource ¶
type PlaybackSourceResource interface {
WithSourceResource(ctx context.Context, id, revision string, fn func(ctx context.Context, src io.ReaderAt, size int64) error) error
}
PlaybackSourceResource provides a revision-bound, lifetime-canceled read lease over a session's currently opened source generation without requiring the session to have entered actual playing state.
type PlaybackSourceSnapshot ¶ added in v0.3.0
type PlaybackSourceSnapshot interface {
CurrentSource(context.Context, string) (PlaybackSourceObservation, error)
}
PlaybackSourceSnapshot copies immutable facts validated at source open/probe for the current generation. It performs no filesystem I/O and is not fresh authorization or a claim that a local path has remained unchanged.
type PlaybackTimeline ¶ added in v0.2.8
type PlaybackTimeline interface {
PlaybackProgress(userID int64, clientID string, key RatingKey, position time.Duration, state string)
}
PlaybackTimeline carries actual client position without changing history.
type Playlist ¶
type Playlist struct {
Key RatingKey `json:"key"`
UserID int64 `json:"userId"`
Title string `json:"title"`
Smart bool `json:"smart"`
SmartURI string `json:"-"`
GUID string `json:"-"`
Summary string `json:"summary,omitempty"`
AddedAt time.Time `json:"addedAt"`
ItemIDs []int64 `json:"-"`
Items []RatingKey `json:"items"`
UpdatedAt time.Time `json:"updatedAt"`
}
Playlists are user-created lists.
type PlaylistEdit ¶
PlaylistEdit updates only explicitly supplied fields.
type PlaylistEditor ¶
type PlaylistMutation ¶
PlaylistMutation addresses members by stable item identity.
type PlaylistMutator ¶
type Playlists ¶
type Playlists interface {
List(ctx context.Context, userID int64) ([]Playlist, error)
Get(ctx context.Context, userID int64, key RatingKey) (*Playlist, error)
Create(ctx context.Context, userID int64, title string, items []RatingKey) (*Playlist, error)
Add(ctx context.Context, userID int64, key RatingKey, items []RatingKey) error
Remove(ctx context.Context, userID int64, key RatingKey, itemIndex int) error
Move(ctx context.Context, userID int64, key RatingKey, from, to int) error
Delete(ctx context.Context, userID int64, key RatingKey) error
}
type PlexPresentation ¶
type PlexPresentation struct {
Base string `json:"base,omitempty"` // movie|show|artist|photo
Default *bool `json:"default,omitempty"` // optional manifest default hint (true when omitted)
}
PlexPresentation describes how Plex sees a library.
type PolicyHomeCandidateSource ¶ added in v0.3.0
type PolicyHomeCandidateSource interface {
HomeCandidatesWithPolicy(context.Context, *User, HubContext, int, func(context.Context, *User, *Title) bool) ([]Hub, error)
SectionCandidatesWithPolicy(context.Context, *User, MediaType, HubContext, int, func(context.Context, *User, *Title) bool) ([]Hub, error)
}
PolicyHomeCandidateSource filters a viewer's candidate pool before ranking and row limits. The caller supplies a fail-closed visibility predicate.
type PostPlayPick ¶
type PostPlayPick struct {
Title Title `json:"title"`
Score float64 `json:"score"`
TasteFit float64 `json:"tasteFit"`
Similarity float64 `json:"similarity"`
RuntimeFit float64 `json:"runtimeFit"`
Reason string `json:"reason,omitempty"`
}
PostPlayPick is one ranked post-play recommendation with its explained score components (item #30): Score = taste factor × similarity factor × runtime factor (× a continuation bonus for the franchise's next entry), where TasteFit is the raw taste fit (-1..1), Similarity the feature overlap with the just-watched title (0..1) and RuntimeFit how well the runtime fits the viewer's remaining time tonight (0..1).
type PostPlayer ¶
type PostPlayer interface {
PostPlay(ctx context.Context, user *User, justWatched RatingKey, hc HubContext, limit int) ([]PostPlayPick, error)
}
PostPlayer ranks a personalized post-play "hook queue" after a title. Implementations cache the ranking per user and just-watched title for the session, so the pick pre-buffered during playback is the pick the post-play endpoint returns first.
type PreferenceFallbackObserver ¶
type PreferenceFallbackObserver interface {
RecordPreferenceFallback(context.Context, ResolveRequest, string, string, time.Duration)
PreferredVersionRecovered(*Title, string, string, time.Time) bool
}
PreferenceFallbackObserver records picked-version cooldowns without waiting for persistence, and checks only refreshed in-memory search results for recovery. Recovery permits a new admission attempt; normal policy and health gates still apply.
type PrefetchReaderAt ¶ added in v0.2.7
type PrefetchReaderAt interface {
ReadAtPrefetchContext(context.Context, []byte, int64) (int, error)
}
PrefetchReaderAt reads speculative bytes at background priority.
type PreparingError ¶
PreparingError wraps ErrPreparing with a suggested retry delay (#580). Err, when set, preserves an underlying cause (such as core.ErrDownloadQueued) while keeping ErrPreparing as the primary sentinel.
func (*PreparingError) Error ¶
func (e *PreparingError) Error() string
func (*PreparingError) Is ¶
func (e *PreparingError) Is(target error) bool
func (*PreparingError) Unwrap ¶
func (e *PreparingError) Unwrap() error
type PrerollClip ¶ added in v0.3.3
type PrerollClip struct {
Key RatingKey
Name string
Path string // converted MP4 (H.264/AAC, faststart)
Duration time.Duration
Width int
Height int
BitrateKbps int
Size int64
// Order is PrerollBeforeTrailers or PrerollAfterTrailers.
Order string
UpdatedAt time.Time
}
PrerollClip is a ready pre-roll video on this node.
type PrerollPlay ¶ added in v0.3.3
type PrerollPlay struct {
Viewer *User
Key RatingKey
Feature RatingKey
// FeatureTitle is the display title of the feature, when known.
FeatureTitle string
Client string
}
PrerollPlay records that a pre-roll actually started for a viewer.
type PrerollRequest ¶ added in v0.3.3
type PrerollRequest struct {
Viewer *User
// Device is the form factor: DeviceTV, DeviceMobile, DeviceDesktop or
// DeviceWeb.
Device string
// Away is true when the client is not on the server's local network.
Away bool
// Feature is the title about to play (a movie or an episode).
Feature *Title
// Resume is true when the play continues from a saved position.
Resume bool
// AutoPlay is true when the play is an automatic continuation, such
// as the next episode starting by itself.
AutoPlay bool
// Client names the app ("Plex for Apple TV").
Client string
At time.Time
}
PrerollRequest describes one play a pre-roll may precede.
type Prerolls ¶ added in v0.3.3
type Prerolls interface {
// Active reports, from memory, whether any pre-roll could play. It
// lets callers skip all selection work when none is configured.
Active(ctx context.Context) bool
// Pick returns the pre-roll for a play, or false for none.
Pick(ctx context.Context, req PrerollRequest) (PrerollClip, bool)
// Clip returns a ready pre-roll by key.
Clip(ctx context.Context, key RatingKey) (PrerollClip, bool)
// Thumb returns the pre-roll's JPEG thumbnail path.
Thumb(ctx context.Context, key RatingKey) (string, bool)
// Started records a play once per viewer, pre-roll and feature.
Started(ctx context.Context, play PrerollPlay)
}
Prerolls selects and serves owner pre-rolls (internal/prerolls).
type PresentationOverrides ¶
type PresentationOverrides struct {
AdapterOnly *bool `json:"adapterOnly,omitempty"`
Vela *bool `json:"vela,omitempty"`
Plex *bool `json:"plex,omitempty"`
MediaBrowser *bool `json:"mediaBrowser,omitempty"`
Stremio *bool `json:"stremio,omitempty"`
Xtream *bool `json:"xtream,omitempty"`
Silo *bool `json:"silo,omitempty"`
}
PresentationOverrides records explicit per-app owner publish switches. Nil fields follow the manifest or inferred default; non-nil choices are sticky across plugin updates and server restarts.
func (PresentationOverrides) Get ¶
func (o PresentationOverrides) Get(app string) *bool
Get returns the owner override for app ("vela"|"plex"|"mediaBrowser"| "stremio"|"xtream"|"silo"|"adapterOnly"), or nil if not overridden.
func (PresentationOverrides) IsEmpty ¶
func (o PresentationOverrides) IsEmpty() bool
IsEmpty reports whether no owner overrides are stored.
func (*PresentationOverrides) Set ¶
func (o *PresentationOverrides) Set(app string, val *bool)
Set updates the owner override for app.
type PresentationSource ¶
type PresentationSource string
PresentationSource says where an app's presentation shape came from.
const ( PresentationSourcePlugin PresentationSource = "plugin" PresentationSourceInferred PresentationSource = "inferred" )
type Presentations ¶
type Presentations struct {
AdapterOnly bool `json:"adapterOnly,omitempty"` // only via FrontendAdapter (§6.5)
Vela *VelaPresentation `json:"vela,omitempty"`
Plex *PlexPresentation `json:"plex,omitempty"`
MediaBrowser *MediaBrowserPresentation `json:"mediaBrowser,omitempty"`
Stremio *StremioPresentation `json:"stremio,omitempty"`
Xtream *XtreamPresentation `json:"xtream,omitempty"`
Silo *SiloPresentation `json:"silo,omitempty"`
}
Presentations declares how a library is presented per protocol (§6.2). In a plugin manifest, each app block describes how that app sees the library (and may optionally suggest default: false to start off). On a stored core.Library, non-nil app blocks represent the currently published apps with their resolved per-protocol shapes.
type PrewarmOptions ¶
type PrewarmOptions struct {
// StartOffset warms a bounded indexed window around a known linear-channel
// join point. Trusted host hint; never accepted from frontend JSON.
StartOffset time.Duration `json:"-"`
// Reason labels the trigger for logs and budgets (Prewarm* constants).
Reason string `json:"reason"`
// PrefetchBytes is how much of the opening of the file to pre-buffer at
// background priority once the release is resolved, opened and probed.
// Zero uses the implementation's default for the reason.
PrefetchBytes int64 `json:"prefetchBytes,omitempty"`
// DuringPlayback allows the warm-up while the viewer already has an
// active session (a trailer, or the end of a film, is playing).
DuringPlayback bool `json:"duringPlayback,omitempty"`
// PlayIntent marks a detail warm-up from a device whose real caps are
// known. Held for a moment, it may open the one top-ranked add-on
// stream that its add-on reports debrid-cached (core.WithOnDemandWarm).
// Up Next and next-episode warm-ups imply it. Never set for browsing.
PlayIntent bool `json:"-"`
}
PrewarmOptions tune a speculative warm-up of a title before the viewer presses Play.
type Prewarmer ¶
type Prewarmer interface {
Prewarm(ctx context.Context, user *User, key RatingKey, caps ClientCaps, opts PrewarmOptions) bool
}
Prewarmer is implemented by playback managers that can resolve, open, probe and pre-buffer a title ahead of Play, so the later Prepare for the same user, client and title is near-instant. A warm-up never reserves a stream or writes resume/history records. It reports whether a warm-up was scheduled (false when skipped by budgets or already warm).
type ProcessCPUTime ¶ added in v0.2.7
ProcessCPUTime exposes the optional CPUTime capability.
type ProcessIdentity ¶ added in v0.2.7
type ProcessIdentity interface{ PID() int }
ProcessIdentity exposes the optional PID capability.
type ProcessPeakMemory ¶ added in v0.2.7
ProcessPeakMemory exposes the optional PeakRSSBytes capability.
type ProfileImport ¶
type ProfileImport struct {
Source string `json:"source"` // "trash" or "dictionarry"
App string `json:"app"` // "radarr" or "sonarr"
Profile string `json:"profile"` // source profile id/slug
TrashID string `json:"trashId,omitempty"` // source trash_id
ScoreSet string `json:"scoreSet,omitempty"` // TRaSH score set
Groups []string `json:"groups,omitempty"` // selected cf-group trash IDs
SyncedAt time.Time `json:"syncedAt,omitempty"`
}
ProfileImport records where a synced quality profile came from. Manual profiles leave it nil; a profile with Import set is updated in place by the guide sync instead of being duplicated.
type Protocol ¶ added in v0.3.0
type Protocol string
Protocol identifies a client-facing surface independently of client product.
type QualityItem ¶
type QualityItem struct {
Name string `json:"name,omitempty"`
Qualities []string `json:"qualities"`
}
QualityItem is one entry of a profile's quality order: a single quality or a named group of qualities that rank equally. A quality is "<source>-<height>" ("webdl-1080", "remux-2160"); source is a Source value, or "unknown" for a release that names a resolution but no source.
type QualityLimitation ¶
type QualityProfile ¶
type QualityProfile struct {
ReleaseRules []ReleaseRule `json:"releaseRules,omitempty"`
// PluginScores lists the plugin ranking steps the profile uses, each
// with its settings ({} for none). A step adds the number its plugin
// returns for a release to the release's custom format score.
PluginScores map[string]json.RawMessage `json:"pluginScores,omitempty"`
AllowedQualities []string `json:"allowedQualities,omitempty"` // preferred imported source-resolution pairs
// QualityOrder ranks qualities best first, as Radarr and Sonarr do: a
// release ranks by the first item listing its quality, qualities in one
// item (a group) rank equally, and a quality no item lists ranks below
// all of them. It is the first ranking key; custom format scores order
// releases of equal quality (docs/quality-ranking.md).
QualityOrder []QualityItem `json:"qualityOrder,omitempty"`
// CustomFormatScores scores every format the profile uses, keyed by
// format id: the owner's and imported custom formats, Ether's built-in
// formats ("ether:…", BuiltinFormats) and Prefer rules ("rule:<id>").
// A format the map does not list scores 0, as in Radarr and Sonarr.
CustomFormatScores map[string]int `json:"customFormatScores,omitempty"`
// MinCustomFormatScore prefers releases whose custom formats (the
// owner's and imported ones, not Ether's built-ins, rules or plugins)
// reach this score. Lower scores remain playable. nil sets no preference.
MinCustomFormatScore *int `json:"minCustomFormatScore,omitempty"`
Name string `json:"name"`
MediaType string `json:"mediaType,omitempty"` // "movie" or "tv" (ProfileMediaTypes); empty only in configs saved before profiles were per media
Import *ProfileImport `json:"import,omitempty"` // set on imported, syncable profiles
MaxHeight int `json:"maxHeight"` // cap, e.g. 1080
// ConfiguredMaxHeight is MaxHeight as the owner configured it,
// before download reshaping or a client's caps clamped the
// effective MaxHeight. -1 means the owner set no ceiling ("Any");
// 0 means unset (a profile built outside SelectProfile), in which
// case MaxHeight itself is the configured value. Runtime-only,
// never persisted with the profile.
ConfiguredMaxHeight int `json:"-"`
// CeilingSource names the runtime declaration, registry default, owner
// override, quality rule, or download reshape that lowered MaxHeight
// below ConfiguredMaxHeight. Runtime-only, never persisted.
CeilingSource string `json:"-"`
FallbackBelowMin bool `json:"fallbackBelowMin,omitempty"`
MinHeight int `json:"minHeight"` // floor, e.g. 720
AllowHDR bool `json:"allowHdr"` // only applied when the client also supports it
AllowDolbyVision bool `json:"allowDolbyVision"`
MinSizeMBPerMin float64 `json:"minSizeMbPerMin"` // size sanity, per minute of runtime (movies, and fallback for TV)
MaxSizeMBPerMin float64 `json:"maxSizeMbPerMin"`
EpisodeMinSizeMBPerMin float64 `json:"episodeMinSizeMbPerMin,omitempty"` // optional TV episode size bounds (0 uses MinSizeMBPerMin/MaxSizeMBPerMin)
EpisodeMaxSizeMBPerMin float64 `json:"episodeMaxSizeMbPerMin,omitempty"`
PreferredLanguages []string `json:"preferredLanguages"`
// Language is the profile's audio language, as in Radarr: "" or
// ProfileLanguageOriginal accepts each title's original language
// alongside the preferred ones, ProfileLanguageAny accepts every
// language, and any other value names the one language a release's
// audio must be in (an ISO code or a language name; multi/dual-audio
// releases pass).
Language string `json:"language,omitempty"`
AllowCam bool `json:"allowCam"` // the only pre-release switch; CAM/TS/TC and screener/R5/workprint copies play only for profiles that allow them
// SelectionKey is the canonical hash of this profile's configured
// definition, computed by resolver.SelectProfile from the pristine
// configured profile before download reshaping or client-cap
// clamping. Release rules are part of that definition. The catalogue
// original language is not: it is per-title evaluation context, not a
// profile fact. Runtime-only, never persisted with the profile.
SelectionKey string `json:"-"`
}
QualityProfile is an owner-editable rule set ranking releases for a class of client.
func FindProfile ¶
func FindProfile(profiles []QualityProfile, name, media string) (QualityProfile, bool)
FindProfile returns the profile named name that serves media. Names are unique per media, so the same name can serve movies and shows as two profiles; with no media it is the first profile of that name.
func (QualityProfile) ComputeSelectionKey ¶ added in v0.2.48
func (p QualityProfile) ComputeSelectionKey() string
ComputeSelectionKey returns the canonical key of the configured definition in p: sha256 of its JSON (runtime-only fields tagged json:"-" are excluded) truncated to 16 hex chars. Any selection-field edit (heights, HDR/DV, sizes, qualities, scores, release rules, plugin steps) changes it; client caps never enter it.
func (QualityProfile) SizeBoundsFor ¶ added in v0.2.58
func (p QualityProfile) SizeBoundsFor(t *Title) (minMBPerMin, maxMBPerMin float64)
SizeBoundsFor returns the configured (min, max) MB/min bounds for a title.
func (QualityProfile) SizeBoundsForKey ¶ added in v0.2.58
func (p QualityProfile) SizeBoundsForKey(key RatingKey) (minMBPerMin, maxMBPerMin float64)
SizeBoundsForKey returns the configured (min, max) MB/min bounds for a rating key. TV episodes use EpisodeMinSizeMBPerMin / EpisodeMaxSizeMBPerMin when positive, falling back to MinSizeMBPerMin / MaxSizeMBPerMin.
type QualityVariant ¶
QualityVariant pins a policy-checked explicit rendition to its encode decision. It is trusted host composition, never a client-supplied encode plan.
type RangeRepresentation ¶
type RangeRepresentation struct {
Size int64
ETag, ContentType string
ModTime time.Time
ServeBody func(status int, start, length int64) error
}
RangeRepresentation lets an adapter render byte-response headers and ranges while the shared source retains ownership of reads and cancellation.
type RangeResponse ¶
type RangeResponse struct {
// StrictRanges prevents an original-byte client from receiving a full file
// after a malformed range or a failed representation precondition.
StrictRanges bool
MIME func(string) string
Serve func(http.ResponseWriter, *http.Request, RangeRepresentation) error
}
func RangeResponseFrom ¶
func RangeResponseFrom(ctx context.Context) (RangeResponse, bool)
type RankerFeature ¶
type RankerFeature struct {
Name string `json:"name"`
Label string `json:"label"`
Weight float64 `json:"weight"`
}
RankerFeature is one learned weight, largest magnitude first.
type RankerInsight ¶
type RankerInsight struct {
TrainedAt *time.Time `json:"trainedAt,omitempty"`
// Examples/Positives are the impressions and plays the model last
// trained on.
Examples int `json:"examples"`
Positives int `json:"positives"`
// AUC of the learned model and of the hand-tuned baseline on held-out
// impressions (0.5 = chance). Zero when there is not enough data.
AUC float64 `json:"auc"`
BaselineAUC float64 `json:"baselineAuc"`
// Active is true when the learned model is being used for ranking.
Active bool `json:"active"`
Features []RankerFeature `json:"features"`
}
RankerInsight describes the learned ranking model for the owner UI.
type RatingKey ¶
type RatingKey int64
RatingKey is the Plex ratingKey of an Ether item. It is derived from TMDB identifiers so a title keeps the same key before and after anything about it is resolved or cached.
Layout (decimal, kept below 2^53 so JavaScript clients parse it safely):
kind * 10^15 + payload
KindMovie payload = tmdb movie id
KindShow payload = tmdb tv id
KindSeason payload = show*10^4 + season (season < 10^4)
KindEpisode payload = show*10^7 + season*10^4 + ep (show < 10^8, season < 1000, ep < 10^4)
KindCollection payload = tmdb collection id (franchise)
KindSmart payload = local smart-collection / generated hub id;
payloads 701*10^12 through 703*10^12 are reserved
for section-specific persisted collections;
payloads in [EphemeralSmartBase, EphemeralSmartEnd)
are reserved for ephemeral (in-memory, per-viewer)
generated collections, and payloads from
EphemeralSmartEnd up for personalize's Year in Review
collections; database ids stay far below both
KindPlaylist payload = local playlist id
KindExtra payload = compact extra id from the extras registry
KindLocal payload = local file id (spike / test library), or
PluginKeyBase + seq for plugin items (spec §2.2)
func CollectionKey ¶
func EphemeralSmartKey ¶
EphemeralSmartKey builds an ephemeral collection key from a sequence number (1 .. 10^14-1).
func EpisodeKey ¶
func ParseRatingKey ¶
func PlaylistKey ¶
func PluginKey ¶
PluginKey builds a plugin item RatingKey from a stored sequence number in [1, PluginKeyMaxSeq) (spec §2.2).
func PluginPartKey ¶
PluginPartKey builds a deterministic synthetic RatingKey for zero-based partIndex of a stored plugin item RatingKey. Every valid result stays below 2^53 so JavaScript clients parse it safely.
func PrerollKey ¶ added in v0.3.3
PrerollKey is the rating key of pre-roll id (1..MaxPrerollID).
func SectionCollectionKey ¶ added in v0.3.4
func (RatingKey) CollectionSection ¶ added in v0.3.4
func (RatingKey) IsEphemeral ¶
IsEphemeral reports whether k is an ephemeral generated collection key.
func (RatingKey) IsPluginItemKey ¶
IsPluginItemKey reports whether k is a stored plugin_items RatingKey.
func (RatingKey) IsPluginKey ¶
IsPluginKey reports whether k is a plugin item RatingKey or a synthetic per-part RatingKey derived from a multi-part plugin item (spec §2.2).
func (RatingKey) IsPluginPartKey ¶
IsPluginPartKey reports whether k is a synthetic per-part plugin RatingKey.
func (RatingKey) IsTitleKey ¶
IsTitleKey reports whether k is a catalogue movie, show, or non-plugin local title RatingKey (the keys stored in catalog_titles).
func (RatingKey) PluginPart ¶
PluginPart unpacks a synthetic part RatingKey into its stored parent plugin RatingKey and zero-based partIndex.
func (RatingKey) PluginSeq ¶
PluginSeq returns the stored sequence number (1 .. PluginKeyMaxSeq-1) of a stored plugin item RatingKey, or 0 when k is not a stored plugin item key.
func (RatingKey) PrerollID ¶ added in v0.3.3
PrerollID returns the pre-roll id of a pre-roll key, else 0.
type ReadOrigin ¶
type ReadOrigin struct{ Component, Reason string }
ReadOrigin attributes source I/O without logging URLs or credentials.
func SourceReadOrigin ¶
func SourceReadOrigin(ctx context.Context) ReadOrigin
type ReadRetirement ¶ added in v0.3.0
type ReadRetirement struct {
// contains filtered or unexported fields
}
ReadRetirement tracks producer references belonging to one media request. Seal returns a channel closed only after all registered producers release their references. It does not wait or cancel those producers and does not prove that the underlying MediaSource.Close succeeded.
func ReadRetirementFrom ¶ added in v0.3.0
func ReadRetirementFrom(ctx context.Context) *ReadRetirement
ReadRetirementFrom returns the tracker attached to ctx, if any.
func (*ReadRetirement) Begin ¶ added in v0.3.0
func (t *ReadRetirement) Begin() (func(), bool)
Begin registers one producer before it starts. Once sealed, registrations fail closed; a successful registration must call its returned function once.
func (*ReadRetirement) Interrupt ¶
func (t *ReadRetirement) Interrupt()
Interrupt cuts the owning request short, if it registered how. A retiring session calls it before waiting on Seal, so a reader stalled on a client that stopped reading (a paused or replaced player) cannot hold the retirement, and the next open on that device, for minutes.
func (*ReadRetirement) OnInterrupt ¶
func (t *ReadRetirement) OnInterrupt(f func())
OnInterrupt registers how the owning request is cut short when its session retires. Passing nil clears it: a finished request must not be touched.
func (*ReadRetirement) Seal ¶ added in v0.3.0
func (t *ReadRetirement) Seal() <-chan struct{}
Seal rejects later producers and returns the completion signal.
type ReadingProgress ¶
type ReadingProgress struct {
Locator string `json:"locator"`
Fraction float64 `json:"fraction"`
Label string `json:"label,omitempty"`
ObservedAt time.Time `json:"observedAt,omitempty"`
UpdatedAt time.Time `json:"updatedAt"`
}
ReadingProgress records a viewer's reading position inside a book item.
type ReadingState ¶
type ReadingState interface {
SetReadingProgress(ctx context.Context, userID int64, key RatingKey, progress ReadingProgress) error
}
ReadingState is an optional interface implemented by State stores that persist book reading progress alongside video/audio watch state.
type Recommender ¶
type Recommender interface {
// HomeHubs are the rows on the Home screen across both sections.
HomeHubs(ctx context.Context, user *User, limit int) ([]Hub, error)
// SectionHubs are the rows at the top of a library section.
SectionHubs(ctx context.Context, user *User, t MediaType, limit int) ([]Hub, error)
// Related are rows on a detail page ("More like this", franchise).
Related(ctx context.Context, user *User, key RatingKey, limit int) ([]Hub, error)
}
Recommender produces per-user Home and section rows.
type RecoveryAACCursor ¶
type RecoveryAACCursor struct {
SourceRevision string
StreamIndex int
SampleRate int
Channels int
SamplesPerAU int
NextSample int64
// Initial AAC-LC profile hashes the canonical two-byte AudioSpecificConfig
// (48 kHz, mono/stereo, 1024 samples). A known absent-SBR sync extension
// is normalized away; unknown extensions/configurations are unsupported.
CodecConfigSHA256 [32]byte
// Hashes cover canonical raw AAC payload, excluding ADTS transport headers.
PreviousRawAUSHA256 [32]byte
NextRawAUSHA256 [32]byte
SourceNext RecoveryPacketClock
OutputNext RecoveryPacketClock
}
RecoveryAACCursor describes expected consecutive AAC access units. Every identity/clock/digest must be verified using the same authenticated source lease and retained output. Missing immutable sample/AU indexing is unsupported; timestamps or ordinals must never be synthesized from playlist durations.
type RecoveryBuffer ¶ added in v0.2.8
type RecoveryBuffer struct {
Position, ReadyUntil time.Duration
SeekAt time.Time // a discontinuous output request invalidates older telemetry
// DeliveredUntil is contiguous complete HTTP delivery, not a promise that
// the client retained or decoded it. Zero means unavailable.
DeliveredUntil time.Duration
}
RecoveryBuffer reports contiguous, published media, not the encoder's input offset. It deliberately does not claim that bytes reached the client.
type RecoveryBufferSource ¶ added in v0.2.8
type RecoveryBufferSource interface{ RecoveryBuffer() RecoveryBuffer }
type RecoveryPacketClock ¶
RecoveryPacketClock is an exact rational clock for the same access unit. PTS and DTS are counts in TimeBaseNum/TimeBaseDen seconds, not nanoseconds.
type RecoverySourceReader ¶
type RecoverySourceReader interface {
EncoderInputLease
RecoverySourceIdentity() (revision string, size int64, err error)
ReadRecoveryAt(ctx context.Context, expectedRevision string, p []byte, off int64) (n int, err error)
}
RecoverySourceReader is an optional trusted capability of the SAME claimed EncoderInputLease. Identity comes from its authenticated source scope and immutable size, never from RecoveryStart or a caller-supplied URL. Absence is unsupported. Implementations expose neither credentials nor a raw Reader.
Each synchronous read must register with the lease's existing retirement tracker before leaving its admission lock. SealInput rejects new work and InputDone must include actual completion of every admitted read; cancellation or a deadline alone never proves retirement. Reads share bounded source concurrency and input lifetime cancellation. Callers split reads at 64 KiB.
type RecoveryStart ¶
type RecoveryStart struct {
TitlePosition time.Duration
FirstSequence int64
OutputTimestamp time.Duration
SeekEpoch int64
// AdmittedDecision is an expected original plan, not an attestation. Trusted
// composition must verify it against the actual retained admitted plan.
AdmittedDecision Decision
Audio *RecoveryAACCursor
}
RecoveryStart is an opt-in instruction for one authorized encoder run, never proof of source identity, retirement, mux clocks or successful playback. TitlePosition seeks the source; FirstSequence and OutputTimestamp independently address the public output. StartOffset must be zero when this is present. No implicit retry, seek, fallback or throttle restart may reuse this cursor. Actual held bytes require independent consumer validation before publication.
func CloneRecoveryStart ¶
func CloneRecoveryStart(r *RecoveryStart) *RecoveryStart
CloneRecoveryStart detaches all mutable fields before asynchronous admission, callbacks or transport hashing. The digest arrays and clock structs are values.
type Release ¶
type Release struct {
SourceHash string `json:"sourceHash,omitempty"` // SHA-256 of the fetched source descriptor, when known
ContentID string `json:"contentId,omitempty"` // cross-indexer content identity ("nzb:<sha256>" once NZB is known)
Poster string `json:"poster,omitempty"` // Usenet poster reported by indexer or NZB
UsenetDate time.Time `json:"usenetDate,omitempty"` // Usenet upload timestamp when reported separately from PubDate
Fallbacks []Release `json:"-"` // alternate indexer copies merged during multi-indexer search
ID string `json:"id"` // stable: sha1(indexer + guid)
GUID string `json:"guid"` // indexer guid
Indexer string `json:"indexer"` // indexer name
Name string `json:"name"` // release name
NZBURL string `json:"nzbUrl"`
Size int64 `json:"size"`
PubDate time.Time `json:"pubDate"`
Grabs int `json:"grabs,omitempty"`
Password bool `json:"password,omitempty"` // indexer flagged passworded
Category int `json:"category,omitempty"`
Info ReleaseInfo `json:"info"`
Score float64 `json:"score"`
// IndexerID binds a result to its configured origin; Indexer is a display label.
IndexerID string `json:"indexerId,omitempty"`
// SourceOrder is the 1-based position of this result in the source's own
// response (set for Stremio add-on results so later cache sorting or
// batching cannot lose it). Zero means unset.
SourceOrder int `json:"sourceOrder,omitempty"`
// TitleIDs are movie/series identifiers reported by the indexer. They
// must never be inferred from the search request's identifiers.
TitleIDs IDs `json:"titleIds,omitempty"`
// TitleIDsEchoed marks request IDs echoed by a source, not reported evidence.
TitleIDsEchoed bool `json:"titleIdsEchoed,omitempty"`
// FileName retains the add-on's matched filename for torrent file selection.
FileName string `json:"fileName,omitempty"`
// Torrent releases (additive). Protocol is "" for Usenet and
// ProtocolTorrent for Torznab results; torrents are streamed through
// an owner-configured debrid service (internal/debrid).
Protocol string `json:"protocol,omitempty"`
InfoHash string `json:"infoHash,omitempty"` // lower-case hex BitTorrent v1 info hash
MagnetURL string `json:"magnetUrl,omitempty"`
// TorrentFiles holds the file list parsed from a .torrent metainfo
// document during ResolveTorrent, when available. In-memory only.
TorrentFiles []ReleaseFile `json:"-"`
// FileCount hints how many files a torrent contains when TorrentFiles has
// not been parsed (from indexer metadata or a plugin release hint). Debrid
// providers that zip high-file-count torrents use it to avoid trusting a
// cache-check miss on zip-only torrents.
FileCount int `json:"fileCount,omitempty"`
// Private marks a private-tracker torrent (info.private == 1 or a
// Cardigann definition with type: private). Debrid providers may only
// check or play an existing cache by bare info hash.
Private bool `json:"private,omitempty"`
Seeders int `json:"seeders,omitempty"`
Peers int `json:"peers,omitempty"`
// Target narrows a multi-file release (a season pack) to the wanted
// episode; set by the resolver on candidates before fetching.
Target *ReleaseTarget `json:"target,omitempty"`
// SourceLanguage is the release language of the indexer the result came
// from (a Cardigann definition's `language`, or the owner's per-indexer
// Release language for Newznab/Torznab/Prowlarr/Zilean), as a canonical
// BCP 47 tag ("pt-BR"). It is evidence for a bare DUAL/MULTI whose name
// names no dub; an explicit language in the name always wins (additive).
SourceLanguage string `json:"sourceLanguage,omitempty"`
// DebridCached and DebridUncached name the debrid services (config
// Debrid* kinds) the source reported as holding, or not holding, the
// torrent, such as a Stremio addon's cached marker (additive). Hints
// only: a provider's own answer always wins.
DebridCached []string `json:"debridCached,omitempty"`
DebridUncached []string `json:"debridUncached,omitempty"`
// HTTP stream releases (ProtocolHTTP, additive). StreamURL is the URL
// the addon answered with; it and StreamHeaders (request headers the
// addon requires) can carry the addon's credentials, so they never
// leave the server. StreamOrigin is the owner-configured addon origin
// (scheme://host:port), the only private address the URL may reach.
StreamProvider string `json:"streamProvider,omitempty"` // stored provider connection budget
StreamURL string `json:"streamUrl,omitempty"`
StreamHeaders map[string]string `json:"streamHeaders,omitempty"`
StreamOrigin string `json:"streamOrigin,omitempty"`
// StreamOnDemand marks a StreamURL whose source prepares the release
// when the link is opened (a Stremio add-on resolving, downloading or
// importing it on request), so every open costs the source real work
// (additive). See OpensOnDemand.
StreamOnDemand bool `json:"streamOnDemand,omitempty"`
}
Release is an indexer search result for a title.
func (Release) EffectiveContentID ¶
EffectiveContentID returns r's message-ID content identity once known, falling back to PreFetchContentID before fetching.
func (Release) KnownFileCount ¶
KnownFileCount returns the torrent's known file count from FileCount or parsed TorrentFiles, or 0 when unknown.
func (Release) OpensOnDemand ¶
OpensOnDemand reports whether reading r opens an on-demand stream link.
func (Release) PreFetchContentID ¶
PreFetchContentID returns r's pre-fetch Usenet content identity (size bucket + poster + upload day), or "" when those facts are absent.
func (Release) ProbeContentKeys ¶
ProbeContentKeys returns the durable content-identity keys under which probed container metadata for r may be stored or looked up, ordered from strongest (exact content identity) to weakest (pre-fetch identity). Season packs are episode-scoped via ScopedContentID.
func (Release) ReleaseContentKey ¶
ReleaseContentKey returns a canonical string summarizing a release's content-equivalence keys for deduplication and flight keying.
func (Release) ReportedTitleIDs ¶
ReportedTitleIDs excludes identifiers copied from a search request.
func (Release) ScopedContentID ¶
ScopedContentID narrows base to the targeted episode when r is a season pack, so episode-level health and blocklist state do not bleed across other episodes of the same pack.
type ReleaseBatchBlockChecker ¶
type ReleaseBatchBlockChecker interface {
ReleasesBlocked(context.Context, []string) (map[string]bool, error)
}
ReleaseBatchBlockChecker batches ReleaseBlocked across many release IDs so list pages do not execute one blocklist SELECT per remembered resume row.
type ReleaseBlockChecker ¶ added in v0.2.34
ReleaseBlockChecker lets stored source consumers honor durable owner blocks. Errors must prevent reuse, rather than silently bypassing the blocklist.
type ReleaseCondition ¶ added in v0.2.49
type ReleaseCondition struct {
Field string `json:"field"`
Operator string `json:"operator"` // equals, contains, regex, range
Value string `json:"value,omitempty"`
Min float64 `json:"min,omitempty"`
Max float64 `json:"max,omitempty"`
}
ReleaseCondition inspects declared release metadata, never presumed language. Language and subtitle facts describe the indexer's/name's declarations, not verified tracks. A missing fact is unknown, not a successful negative match. audio_matches_original takes no value: evaluation compares declared audio with the catalogue original language supplied beside the release.
type ReleaseFeed ¶ added in v0.2.8
type ReleaseFeed struct {
Categories []int `json:"categories,omitempty"` // local filter when a feed ignores category queries
ID string `json:"id"`
Name string `json:"name"`
Generation string `json:"-"`
Protocol string `json:"protocol"`
Supported bool `json:"supported"`
Reason string `json:"reason,omitempty"`
// DailyLimit is the indexer's own cap. Zero means unlimited.
DailyLimit int `json:"dailyLimit,omitempty"`
// PageMax is the page size reported by caps. Zero means unknown.
PageMax int `json:"pageMax,omitempty"`
// SinglePage marks a feed that lists only its latest page (a built-in
// site's latest releases); it cannot page back to close a gap.
SinglePage bool `json:"singlePage,omitempty"`
}
ReleaseFeed describes an indexer's recent-release discovery capability.
type ReleaseFile ¶
type ReleaseFile struct {
Index int `json:"index"`
Path string `json:"path"`
Size int64 `json:"size"`
// SizeApproximate is true when Size is a segment-derived decoded estimate
// rather than an exact byte count (e.g. a Usenet NZB whose PAR2/yEnc
// headers could not be read). Exact sizes leave it false/omitted.
SizeApproximate bool `json:"sizeApproximate,omitempty"`
Members []ReleaseMember `json:"members,omitempty"`
}
ReleaseFile is one file inside a candidate release, as returned by a release_files source query. Index is the position Ether's own file selection counts: the debrid provider's file-list order for torrents, NZB document order for Usenet. Hand it back as ReleaseHint.FileIndex, or match Path with ReleaseHint.File. When the file is the first volume of a readable RAR, 7z, or ZIP archive on Usenet, Members lists the non-directory files inside that archive.
type ReleaseHealthChecker ¶
type ReleaseHealthChecker interface {
HealthChecker
CheckRelease(ctx context.Context, releaseID string, nzb []byte) (healthy bool, err error)
}
ReleaseHealthChecker is a HealthChecker that is also told which release the NZB belongs to, so what the check reads (the PAR2 index, archive headers) lands in the segment cache under the ID a following Open uses. Optional: callers fall back to Check when it is not implemented (additive).
type ReleaseHint ¶
type ReleaseHint struct {
// FileIndex overrides candidate.fileIndex; out-of-range indices fail without fallback.
FileIndex *int `json:"fileIndex,omitempty"`
NZBURL string `json:"nzbUrl,omitempty"`
Magnet string `json:"magnet,omitempty"`
InfoHash string `json:"infoHash,omitempty"`
TorrentURL string `json:"torrentUrl,omitempty"`
Candidate *SourceCandidate `json:"candidate,omitempty"`
// File selects an exact torrent path or unique basename, including non-video files.
File string `json:"file,omitempty"`
FileHint string `json:"fileHint,omitempty"`
Track *TrackHint `json:"track,omitempty"`
PasswordSecret string `json:"passwordSecret,omitempty"`
// CachedOnly forces debrid acquisition to require an already-cached copy
// even when the owner turned "Cached torrents only" off. When omitted or
// false, torrent releases follow the owner's debrid setting (queuing
// uncached downloads when cached-only is off).
CachedOnly bool `json:"cachedOnly,omitempty"`
// FileCount optionally hints how many files a torrent contains when Ether
// has not seen its file list yet (for example a magnet for one entry in a
// large collection). Providers whose cache check cannot see zip-only
// high-file-count torrents (such as TorBox at 100+ files) use this to try
// a cached-only add instead of trusting a checkcached miss.
FileCount int `json:"fileCount,omitempty"`
}
ReleaseHint hands an NZB, magnet, infohash, torrent link, or pre-built Candidate to Ether's existing Usenet / debrid / torrent acquisition pipeline (spec §4.1, §4.3).
type ReleaseInfo ¶
type ReleaseInfo struct {
HardSubbed bool `json:"hardSubbed,omitempty"`
Title string `json:"title"`
Edition string `json:"edition,omitempty"`
Year int `json:"year,omitempty"`
Seasons []int `json:"seasons,omitempty"`
Episodes []int `json:"episodes,omitempty"`
FullSeason bool `json:"fullSeason,omitempty"`
Height int `json:"height,omitempty"` // 480, 720, 1080, 2160
Source Source `json:"source,omitempty"`
VideoCodec string `json:"videoCodec,omitempty"` // h264, hevc, av1
HDR10 bool `json:"hdr10,omitempty"`
DolbyVision bool `json:"dolbyVision,omitempty"`
AudioCodec string `json:"audioCodec,omitempty"` // aac, ac3, eac3, truehd, dts, dtshd
Atmos bool `json:"atmos,omitempty"`
Channels string `json:"channels,omitempty"` // "5.1"
Group string `json:"group,omitempty"`
Languages []string `json:"languages,omitempty"`
// SubtitleLanguages are subtitle languages a release declares without
// claiming the audio (VOSTFR, VOSE, SUBFRENCH) (additive).
SubtitleLanguages []string `json:"subtitleLanguages,omitempty"`
// AbsoluteEpisodes are episode numbers counted from the series start,
// as anime releases number them ("Show - 1071") (additive).
AbsoluteEpisodes []int `json:"absoluteEpisodes,omitempty"`
Revision int `json:"revision,omitempty"`
Cour int `json:"cour,omitempty"`
Subbed bool `json:"subbed,omitempty"`
Dubbed bool `json:"dubbed,omitempty"`
Uncensored bool `json:"uncensored,omitempty"`
Proper bool `json:"proper,omitempty"`
Repack bool `json:"repack,omitempty"`
Container string `json:"container,omitempty"`
}
ReleaseInfo is what can be parsed from a release name.
type ReleaseMember ¶
type ReleaseMember struct {
Index int `json:"index"`
Path string `json:"path"`
Size int64 `json:"size"`
Stored bool `json:"stored,omitempty"`
}
ReleaseMember is one non-directory file inside an archive (RAR, 7z, ZIP) returned by a release_files source query. Hand Path back as ReleaseHint.FileHint (or ContainerRef.Member) to open that exact member.
type ReleaseNumbering ¶
type ReleaseNumbering struct {
Aliases []EpisodeNumber
PackTargets []EpisodeNumber
// Explicit reports an owner-chosen episode ordering ("group" mode) that
// should be queried alongside canonical numbering on the initial pass.
Explicit bool
}
type ReleaseRule ¶ added in v0.2.49
type ReleaseRule struct {
ID string `json:"id"`
Name string `json:"name"`
Action string `json:"action"` // require, prefer, avoid (exclude)
Match string `json:"match,omitempty"` // all (default) or any
Conditions []ReleaseCondition `json:"conditions"`
Unless []ReleaseCondition `json:"unless,omitempty"` // any matching exception skips the rule
Fallback []ReleaseCondition `json:"fallback,omitempty"` // require only, any matching condition
Disabled bool `json:"disabled,omitempty"`
}
ReleaseRule is a protocol-neutral owner preference. Ordered soft preferences break ties lexicographically before ordinary quality scores. All hard rules must pass. Empty rules preserve existing profile behavior.
type ReleaseSizeSource ¶ added in v0.2.7
ReleaseSizeSource exposes the optional ReleaseSizes capability.
type ReleaseTarget ¶
type ReleaseTarget struct {
// CanonicalSeason/CanonicalEpisode retain TMDB identity when Season/Episode
// select a file using the owner's alternate release numbering.
CanonicalSeason int `json:"canonicalSeason,omitempty"`
CanonicalEpisode int `json:"canonicalEpisode,omitempty"`
// Aliases lists verified alternate season/episode numbers for the same
// canonical episode so open-time file checks accept alias-numbered files.
Aliases []EpisodeNumber `json:"aliases,omitempty"`
// MovieTitles and MovieYear constrain file selection inside movie collections.
MovieTitles []string `json:"movieTitles,omitempty"`
MovieYear int `json:"movieYear,omitempty"`
// WantedLanguages and OriginalLanguage rank full-length language versions
// inside multi-file movie torrents and NZB archives before falling back to
// byte size (additive).
WantedLanguages []string `json:"wantedLanguages,omitempty"`
OriginalLanguage string `json:"originalLanguage,omitempty"`
// FileIndex is a zero-based index in the complete torrent/NZB file list; the selected file must be a video unless AllowNonVideo is set.
FileIndex *int `json:"fileIndex,omitempty"`
// ExactFile selects a plugin-requested path or unambiguous basename.
ExactFile string `json:"exactFile,omitempty"`
// AllowNonVideo permits an explicit FileIndex/ExactFile, archive member
// selector (Member/MemberIndex), or non-video MIME target to choose a
// non-video file instead of requiring video.
AllowNonVideo bool `json:"allowNonVideo,omitempty"`
// Member selects an archive member path or unambiguous basename (e.g.
// from release.fileHint or container.member) when AllowNonVideo is set.
Member string `json:"member,omitempty"`
// MemberIndex selects a zero-based archive member index when AllowNonVideo
// is set (e.g. from container.memberIndex).
MemberIndex *int `json:"memberIndex,omitempty"`
// Track selects an audio track inside a multi-track release or archive by
// disc/track number first, then normalised title tokens, failing on ambiguity.
Track *TrackHint `json:"track,omitempty"`
// MIME is the declared or kind-default media type for non-video release
// file selection (e.g. "audio/flac", "application/epub+zip", "audio/*").
MIME string `json:"mime,omitempty"`
// ArchivePassword is an optional archive password resolved from a plugin
// secret for opening encrypted Usenet archives; never serialized.
ArchivePassword string `json:"-"`
// FileName is the source-matched file hint, never proof of episode identity.
FileName string `json:"fileName,omitempty"`
// AbsoluteEpisode is the verified anime episode number across seasons.
AbsoluteEpisode int `json:"absoluteEpisode,omitempty"`
// Cour and CourEpisode identify the cour (part) and relative episode
// within a multi-cour anime season pack (0 when unmapped).
Cour int `json:"cour,omitempty"`
CourEpisode int `json:"courEpisode,omitempty"`
Season int `json:"season,omitempty"`
Episode int `json:"episode,omitempty"`
ShowYear int `json:"showYear,omitempty"`
EpisodeTitle string `json:"episodeTitle,omitempty"`
ShowTitles []string `json:"showTitles,omitempty"`
SpecialTitles []string `json:"specialTitles,omitempty"`
// AddonSpecialEpisode is the verified IMDb number before catalogue renumbering.
AddonSpecialEpisode int `json:"addonSpecialEpisode,omitempty"`
// PackID is the untargeted release ID of a FullSeason pack before
// TargetReleaseID derives the per-episode ID (additive).
PackID string `json:"packId,omitempty"`
// ExpectedIDs identify the requested series; ReportedIDs are the
// release's indexer-reported series IDs, retained for file validation.
ExpectedIDs IDs `json:"expectedIds,omitempty"`
ReportedIDs IDs `json:"reportedIds,omitempty"`
}
ReleaseTarget is the episode or movie wanted from a multi-file release such as a season pack or dual-language movie pack.
type ReleaseVariant ¶
type ReleaseVariant struct {
// ID is the stable menu identity; configured slots keep it while the
// concrete Release changes. Frontends encode it in Media/Part ids.
ID string `json:"id"`
// Label is the viewer-facing name, e.g. "4K Dolby Vision Remux" or
// "1080p WEB-DL (High Compatibility)".
Label string `json:"label"`
// Edition is the cut, e.g. "Director's Cut", "Extended", "IMAX"; empty
// for the theatrical/unspecified cut.
Edition string `json:"edition,omitempty"`
// Auto marks the resolver's own pick for this client ("Best for Device").
Auto bool `json:"auto,omitempty"`
// Remembered marks a variant backed by the viewer's remembered choice.
Remembered bool `json:"remembered,omitempty"`
// Pinned marks a variant backed by the owner's pin for this title.
Pinned bool `json:"pinned,omitempty"`
// Availability reports local/cached/fetch/unavailable readiness without
// searching indexers or opening remote sources.
Availability VersionAvailability `json:"availability,omitempty"`
// AvailabilityNote is an optional human-readable note for Availability.
AvailabilityNote string `json:"availabilityNote,omitempty"`
Release Release `json:"release"`
// Info is the expected media info, estimated from the release name until
// the release has been probed.
Info MediaInfo `json:"info"`
}
ReleaseVariant is one playable version of a title, offered in the Plex "Play Version" picker: a distinct candidate release, by quality tier or edition (cut).
type RemuxRequirer ¶
RemuxRequirer is implemented by playback managers that can report whether a session must be (re)started as a zero-encode remux (HLS/DASH) rather than direct play — set when a mid-stream failover of a non-spliceable direct-play session found no exact-size replacement release, so the client needs fresh container headers at the mapped timestamp.
type RepairEvent ¶ added in v0.2.8
type RepairEvent struct {
Key int
Attempt uint64 // distinguishes concurrent readers repairing one article
Offset int64
Approximate bool
Phase string // missing, planning, repairing, repaired, failed, obsolete
Estimate time.Duration
RemainingBytes int64
}
RepairEvent reports verified damage and bounded recovery work. Offset is in the selected media file, never an NNTP article or archive-volume coordinate. Estimate is conservative, not a guarantee; zero means not yet known.
type RepairReporter ¶ added in v0.2.8
type RepairReporter interface {
SetRepairHandler(func(RepairEvent) RepairWindow)
}
type RepairWindow ¶ added in v0.2.8
RepairWindow is playback's current useful repair lifetime. A zero deadline leaves the source's ordinary bound in force. Stop cancels obsolete work.
type ReplacementOutputWaiter ¶ added in v0.3.3
ReplacementOutputWaiter waits for the replacement to extend the contiguous published output. A successful return does not claim client delivery or decode.
type RescueIndexer ¶ added in v0.2.7
type RescueIndexer interface {
SearchRescue(context.Context, SearchRequest) ([]Release, error)
}
RescueIndexer exposes the optional SearchRescue capability.
type Resolution ¶
type Resolution struct {
// VersionSelector is the configured slot that this concrete release fulfilled.
VersionSelector string `json:"versionSelector,omitempty"`
// HealthVerified means the complete volume sample passed, rather than an
// optimistic start or an inconclusive health check.
HealthVerified bool `json:"healthVerified,omitempty"`
QualityFallback string `json:"qualityFallback,omitempty"`
Title RatingKey `json:"title"`
Release Release `json:"release"`
NZB []byte `json:"-"`
Alternates []Release `json:"alternates"` // next candidates, best first
FailedReleases []string `json:"-"` // concrete release IDs rejected during this resolve
ResolvedAt time.Time `json:"resolvedAt"`
}
Resolution is the resolver's answer for a title and client: the winning release, already health-checked, plus fallbacks for mid-stream failover.
func (*Resolution) MatchesVersion ¶
func (r *Resolution) MatchesVersion(id string) bool
MatchesVersion compares concrete picks and resolver-validated logical slots.
type ResolveRequest ¶
type ResolveRequest struct {
// PreferVideoCodec softly preserves the representation family during background replacement.
PreferVideoCodec string
Title *Title
Client ClientCaps
User *User
// PlayedRelease is the release this viewer last played of the title
// (the one a resume opens); Variants names Auto after it (additive).
PlayedRelease string
// PlayedSelector is the version slot selector PlayedRelease fulfilled
// (empty or Auto when played via Auto). When set to a non-Auto slot,
// PlayedRelease stays behind that slot instead of replacing Auto.
PlayedSelector string
// PlayedReleaseRecord carries the persisted release record for
// PlayedRelease when available (e.g. from playback_resume) so the slot
// keeps its release metadata even after the search cache expires.
PlayedReleaseRecord *Release
// Exclude releases already tried (failover).
Exclude []string
// ExcludeReleases excludes every copy/repost matching these releases
// (same content/source/info/stream identity or normalized release name),
// used for content-level rejections such as probed audio language mismatch.
ExcludeReleases []Release
// Prefer is a release ID to try first (the viewer picked a version in
// Plex's "Play Version" picker). It is health-checked like any other
// candidate; when it is unavailable, normal ranking applies (additive).
Prefer string
// PreferredOnly asks whether this explicit pick can open, without
// validating an automatic fallback. Playback uses it when it already
// holds a policy-checked remembered source to fall back to.
PreferredOnly bool
// ExactHEVCTranscode permits the explicitly preferred HEVC source to reach
// playback admission for an H.264 encode. The broker must still validate
// the probed source and the client's complete output profile.
ExactHEVCTranscode bool
}
type ResolvedAppPresentation ¶
type ResolvedAppPresentation struct {
App string `json:"app"` // vela|plex|mediaBrowser|stremio|xtream|silo
Available bool `json:"available"`
Enabled bool `json:"enabled"`
DefaultOn bool `json:"defaultOn"`
Overridden bool `json:"overridden,omitempty"`
Source PresentationSource `json:"source"` // plugin|inferred|unavailable
HintValue string `json:"hintValue,omitempty"` // e.g. movies, show, artist, music, books, photo
Reason string `json:"reason,omitempty"` // plain-language reason when unavailable
}
ResolvedAppPresentation describes one app row for a library in the owner console: whether the app can show the library, whether it is currently published, where the presentation came from, and a plain-language reason when unavailable.
type ResolvedMemberSource ¶
type ResolvedMemberSource interface {
ResolvedArchiveMember() bool
}
ResolvedMemberSource is implemented by a MediaSource that has already extracted or planned the target archive member, so callers should not unwrap an outer archive a second time using release.fileHint.
type ResolvedPresentations ¶
type ResolvedPresentations struct {
MediaClass MediaClass `json:"mediaClass"`
LevelRoles map[string]MediaRole `json:"levelRoles,omitempty"`
AdapterOnly bool `json:"adapterOnly,omitempty"`
Effective Presentations `json:"effective"`
Available Presentations `json:"available"`
Apps []ResolvedAppPresentation `json:"apps"`
}
ResolvedPresentations is the full server-computed presentation picture for a library, separating HOW each app sees the library (Available) from WHETHER each app currently publishes it (Effective / Apps).
type Resolver ¶
type Resolver interface {
// Resolve finds a healthy release. Returns ErrNotAvailable when nothing
// acceptable exists.
Resolve(ctx context.Context, req ResolveRequest) (*Resolution, error)
// MarkBad records a release as broken so nobody gets it again.
MarkBad(ctx context.Context, releaseID string, reason string) error
// Available reports a cached availability answer without searching:
// (known, available).
Available(ctx context.Context, key RatingKey) (known bool, available bool)
}
type RowDescriptor ¶
type RowDescriptor struct {
HubID string `json:"hubId"`
Title string `json:"title"`
Kind string `json:"kind"`
Description string `json:"description"`
// Sections lists the pages this row can appear on ("home", "movies",
// "shows"); empty means every page.
Sections []string `json:"sections,omitempty"`
// Group is the designer's category: "picks", "explore", "shows",
// "household", "collections" or "plex".
Group string `json:"group,omitempty"`
}
RowDescriptor describes a kind of row the owner can place in the Home layout.
type RowInsight ¶
type RowInsight struct {
HubID string `json:"hubId"`
Title string `json:"title"`
Impressions7d int `json:"impressions7d"`
Plays7d int `json:"plays7d"`
PlayRate float64 `json:"playRate"`
}
RowInsight is the 7-day engagement of one row kind.
type RowPolicy ¶
type RowPolicy struct {
RankedTop10 *bool `json:"rankedTop10,omitempty"`
// Nil inherits the collection setting; false explicitly disables previews.
PreviewOnFocus *bool `json:"previewOnFocus,omitempty"`
// ShowRepeats keeps titles that other rows on the page also show (a
// Top 10 under a full Trending row). Such a row neither loses titles to
// other rows nor takes titles from them. Nil or false: page-wide dedupe.
ShowRepeats *bool `json:"showRepeats,omitempty"`
Row string `json:"row"`
Status string `json:"status"`
Slot int `json:"slot,omitempty"`
MinSlot int `json:"minSlot,omitempty"`
MaxSlot int `json:"maxSlot,omitempty"`
Priority float64 `json:"priority,omitempty"`
MaxPerPage int `json:"maxPerPage,omitempty"`
MaxDaysPerWeek int `json:"maxDaysPerWeek,omitempty"`
When *LayoutWhen `json:"when,omitempty"`
}
type RowPurpose ¶ added in v0.3.0
type RowPurpose string
RowPurpose describes the semantic reason for a row, independent of its wire representation.
type SearchAffinityFunc ¶ added in v0.3.3
SearchAffinityFunc reports the searching viewer's affinity level with each of keys (movies and shows) that has one: watched, started or rated, a show through any of its episodes.
func SearchAffinity ¶ added in v0.3.3
func SearchAffinity(ctx context.Context) SearchAffinityFunc
SearchAffinity is ctx's viewer affinity, or nil.
type SearchCacheRefiller ¶ added in v0.2.56
type SearchCacheRefiller interface {
RefillSearchCache(*Title) <-chan struct{}
}
SearchCacheRefiller requests best-effort, non-blocking candidate recovery for an open detail page. Unattended callers use WarmupSearchCacheRefiller. It searches only; it must not resolve or replace a playback source. The resolver owns the work independently of request/warm-up cancellation and joins it on Close. A nil signal means skipped; otherwise the signal closes when the existing or newly admitted refill finishes (not necessarily successfully).
type SearchCandidates ¶
type SearchCandidates struct {
Facts TitleFacts
Detail func(Title) bool
// contains filtered or unexported fields
}
SearchCandidates asks a catalogue search for its candidate window, not its page: the caller ranks and filters the window itself and reads only the page it shows in full. Library movies and shows then come back as their title rows with Facts and the facts the catalogue's own policy reads for the viewer (browsing and search rules, the release gate). A title Detail reports (one the caller judges on its full facts) comes back in full. The catalogue records which titles it returned partial; the caller reads those of its page in full before showing them. Partial titles never enter a cache.
func RankingCandidatesFrom ¶
func RankingCandidatesFrom(ctx context.Context) *SearchCandidates
RankingCandidatesFrom returns WithRankingCandidates' c, or nil.
func SearchCandidatesFrom ¶
func SearchCandidatesFrom(ctx context.Context) *SearchCandidates
SearchCandidatesFrom returns WithSearchCandidates' c, or nil.
func (*SearchCandidates) MarkPartial ¶
func (s *SearchCandidates) MarkPartial(keys []RatingKey)
MarkPartial records titles a search returned partial.
func (*SearchCandidates) Partial ¶
func (s *SearchCandidates) Partial(key RatingKey) bool
Partial reports a title a search returned partial.
type SearchCoverage ¶ added in v0.3.3
type SearchCoverage struct {
// contains filtered or unexported fields
}
SearchCoverage records whether a fleet search heard from every indexer it meant to ask. A search that skipped a paused indexer, or lost one to a timeout or an outage, is incomplete: its answer must not be cached as the fleet's answer or turned into "unavailable", because the missing indexer may hold the release.
func SearchCoverageFrom ¶ added in v0.3.3
func SearchCoverageFrom(ctx context.Context) *SearchCoverage
SearchCoverageFrom returns ctx's coverage record, or nil.
func WithSearchCoverage ¶ added in v0.3.3
func WithSearchCoverage(ctx context.Context) (context.Context, *SearchCoverage)
WithSearchCoverage returns ctx carrying a fresh coverage record.
func (*SearchCoverage) Incomplete ¶ added in v0.3.3
func (c *SearchCoverage) Incomplete() bool
Incomplete reports whether an indexer's answer was missing. A nil record reports false.
type SearchMemo ¶
type SearchMemo struct {
// contains filtered or unexported fields
}
SearchMemo shares one search request's person-name matches between the paths that read them: a search's title results merge the titles of the people it names, and its person results list those same people.
func SearchMemoFrom ¶
func SearchMemoFrom(ctx context.Context) *SearchMemo
SearchMemoFrom returns the request's memo, or nil outside a search request.
func (*SearchMemo) Store ¶
func (m *SearchMemo) Store(key string, v any)
type SearchRequest ¶
type SearchRequest struct {
// Category is an explicit Newznab category list for a generic plugin search.
Category string
Type MediaType // movie or episode
IDs IDs // movie ids, or the show's ids for episodes
Title string
OriginalTitle string // optional original-language or canonical title (additive)
// EnglishTitle is TMDB's primary en-US title when the catalogue language
// is non-English; matching only, never part of a query or cache key (additive).
EnglishTitle string `json:"-"`
Year int
Season int
Episode int
// AltSeason/AltEpisode are additional release numbers from independent release numbering (zero when unset).
AltSeason int
AltEpisode int
ReleaseAliases []EpisodeNumber
ReleasePackTargets []EpisodeNumber
ReleaseNumberingKnown bool
ReleaseAliasesOnly bool // canonical discovery already ran; query additional forms only
EpisodeTitle string // optional title used to distinguish same-numbered episodes
SpecialTitles []string `json:"SpecialTitles,omitempty"` // locally stored sibling special titles
// AbsoluteEpisode is the episode's number counted from the series
// start (0 = unknown), and Anime marks a series whose releases are
// commonly numbered that way (additive).
AbsoluteEpisode int
// Cour and CourEpisode are the 1-based cour (part) number within Season
// and the 1-based episode number within that cour for multi-cour anime
// seasons (0 when unmapped or Cour 1).
Cour int
CourEpisode int
// CourTVDBSeason and CourTVDBEpisode are the anime-lists TVDB season and
// episode for an offset TMDB anime season entry (0 when unmapped).
CourTVDBSeason int
CourTVDBEpisode int
Anime bool
// AlternativeTitles are other names of the movie or series (TMDB
// alternative titles) a release name may use; matching only, never
// part of a query or cache key (additive).
AlternativeTitles []string `json:"-"`
// Released is when the movie came out or the episode aired (zero when
// unknown). Indexer caches keep results for older titles longer; never
// part of a query or cache key (additive).
Released time.Time `json:"-"`
}
func AliasSearchRequest ¶
func AliasSearchRequest(req SearchRequest, n EpisodeNumber) SearchRequest
AliasSearchRequest changes the query's numbers while retaining series IDs.
type SectionCandidateSource ¶ added in v0.2.7
type SectionCandidateSource interface {
SectionCandidatesFor(context.Context, *User, MediaType, HubContext, int) ([]Hub, error)
}
SectionCandidateSource exposes the optional SectionCandidatesFor capability.
type SegmentCache ¶
type SegmentCache interface {
Get(releaseID string, segment int) ([]byte, bool)
Put(releaseID string, segment int, data []byte) error
// Pin protects every segment of a release from eviction.
Pin(releaseID string, reason string) error
Unpin(releaseID string, reason string) error
Usage() (used, budget int64)
}
SegmentCache stores decoded segments on disk under an LRU budget.
type SegmentCacheLimit ¶ added in v0.3.2
type SegmentCacheLimit interface{ UsageLimit() int64 }
SegmentCacheLimit exposes the optional UsageLimit capability: the most the segment cache may hold right now, the budget or the free-space floor's cap when lower. -1 means unbounded and 0 means media bytes are not retained.
type SegmentPresence ¶ added in v0.2.7
SegmentPresence exposes the optional Has capability.
type SessionActivity ¶ added in v0.2.9
type SessionActivity interface{ PlaybackState(state string) }
SessionActivity is an optional output-session extension. Only authenticated, ownership-checked player timelines may renew it; playlist polls may not.
type SessionLiveness ¶
type SessionLiveness struct {
State SessionLivenessState
Expired bool
PlayingWindow time.Duration
}
SessionLiveness is the evaluated liveness classification at a point in time.
func EvaluateSessionLiveness ¶
func EvaluateSessionLiveness(in SessionLivenessInput, now time.Time) SessionLiveness
EvaluateSessionLiveness evaluates the single shared liveness rule for all protocols (Plex, Jellyfin/Emby, Vela, Silo, Stremio, Xtream, Live TV).
func (SessionLiveness) Active ¶
func (l SessionLiveness) Active() bool
Active reports whether the session counts as an active stream for the restart/update gate and upload budget.
func (SessionLiveness) CountsForLimit ¶
func (l SessionLiveness) CountsForLimit() bool
CountsForLimit reports whether the session occupies a stream-limit slot. Playing streams and freshly opened sessions within StartupGraceWindow count; paused, idle, abandoned, and stopped sessions do not.
func (SessionLiveness) Visible ¶
func (l SessionLiveness) Visible() bool
Visible reports whether the session should appear in Console Overview and Activity. Playing sessions appear as playing; explicitly paused sessions appear as Paused. Starting/abandoned, idle/stale, and stopped sessions are hidden.
type SessionLivenessInput ¶
type SessionLivenessInput struct {
Closed bool
PreparedOnly bool
StoppedBySurface bool
BackgroundHeld bool
StopAt time.Time
StartedAt time.Time
OpenedAt time.Time
IsLive bool
IsHLS bool
ViewerState string
PausedAt time.Time
LastProgressAt time.Time
HasPosition bool
ActiveReads int32
MediaBytes int64
LastMediaAt time.Time
LastActive time.Time
PlayingWindow time.Duration
StartupGrace time.Duration
IdleTimeout time.Duration
AbandonedAfter time.Duration
PauseRetention time.Duration
}
SessionLivenessInput holds the session timestamps and counters needed to evaluate the shared liveness rule deterministically at a given clock instant.
type SessionLivenessState ¶
type SessionLivenessState string
SessionLivenessState classifies a playback session under the shared liveness rule.
const ( // SessionLivenessPlaying means the session has recent playing evidence: // an in-flight media read, or media bytes served or a playing // progress/timeline report within the transport's playing window. SessionLivenessPlaying SessionLivenessState = "playing" // SessionLivenessPaused means the client explicitly reported "paused" and // is within PausedSessionRetention. Shown as Paused in Activity/Overview; // NOT counted as an active stream for restart gating, upload budget, or // stream limits. SessionLivenessPaused SessionLivenessState = "paused" // SessionLivenessStarting means the session was just opened/prepared within // StartupGraceWindow and has not yet served media bytes or reported a // playback position. Holds a brief stream-limit slot during client startup; // hidden from Activity/Overview and excluded from restart/upload-budget. SessionLivenessStarting SessionLivenessState = "starting" // SessionLivenessIdle means the session has no recent playing evidence and // was not explicitly paused. Hidden from Activity/Overview and excluded // from restart gating, upload budget, and stream limits. SessionLivenessIdle SessionLivenessState = "idle" // SessionLivenessStopped means the session was closed, explicitly stopped, // or returned to prepared-only after stop. SessionLivenessStopped SessionLivenessState = "stopped" )
func PlaySessionLiveness ¶
func PlaySessionLiveness(ps *PlaySession) SessionLivenessState
PlaySessionLiveness returns the evaluated liveness state of a PlaySession snapshot. Real session managers populate Liveness explicitly; minimal test fixtures with an unset Liveness fall back to PreparedOnly/ViewerState.
type SessionPolicy ¶
type SessionPolicy struct {
// ExternalAdmission keeps adapter-owned source admission, public session IDs,
// progress identities and encoder lifetime rules.
ExternalAdmission bool
// DistributedBindings enables durable broker HLS bindings and item telemetry.
DistributedBindings bool
// MasterMetadata emits HLS version and verified independent-segment tags.
MasterMetadata bool
// PlainSourceGone uses the adapter plain-text missing-source response.
PlainSourceGone bool
}
SessionPolicy describes adapter-owned session semantics. Identity is never a substitute for these capabilities; callers supply policies at construction.
type ShowTrajectory ¶ added in v0.2.7
type ShowTrajectory struct {
ShowKey RatingKey `json:"showKey"`
EarlyRating float64 `json:"earlyRating,omitempty"`
FinaleRating float64 `json:"finaleRating,omitempty"`
PeakRating float64 `json:"peakRating,omitempty"`
RatedSeasons int `json:"ratedSeasons,omitempty"`
SticksLanding bool `json:"sticksLanding,omitempty"`
}
ShowTrajectory summarizes a series' season/episode rating arc (additive).
type SiloPresentation ¶
type SiloPresentation struct {
Type string `json:"type,omitempty"` // movies|tvshows (mirrors MediaBrowser family)
Default *bool `json:"default,omitempty"` // optional manifest default hint (true when omitted)
}
SiloPresentation describes how Silo sees a library.
type SmartPlaylists ¶ added in v0.3.4
type SmartPlaylists interface {
CreateSmartPlaylist(ctx context.Context, userID int64, title, uri string) (*Playlist, error)
}
SmartPlaylists persists a section query for evaluation at read time.
type SortOrder ¶
type SortOrder string
const ( SortPopularity SortOrder = "popularity" SortKey SortOrder = "key" SortTitle SortOrder = "title" SortReleased SortOrder = "released" SortYear SortOrder = "year" SortRating SortOrder = "rating" SortDuration SortOrder = "duration" SortIndex SortOrder = "index" // plugin item ordinal index SortAdded SortOrder = "added" // movie/episode release or air date; series and seasons use the latest aired episode, then the premiere SortUpdated SortOrder = "updated" // actual catalogue metadata update time // SortPlayed orders a viewer's played titles by when they last played // them (Jellyfin/Emby "DatePlayed"). It is served from the viewer's watch // rows, never the catalogue's sort columns. SortPlayed SortOrder = "played" // SortLastViewed is the canonical Vela/tab sort ID for ordering titles by // when the requesting viewer last viewed them. SortLastViewed SortOrder = "lastViewed" )
func (SortOrder) IsLastViewed ¶
IsLastViewed reports whether s requests viewer watch-recency ordering.
type Source ¶
type Source string
Source is the release source parsed from a release name.
const ( SourceUnknown Source = "" SourceCam Source = "cam" // CAM, TS, TC, HDCAM, telesync SourceScreener Source = "screener" // SCR, DVDSCR, R5, workprint SourceDVD Source = "dvd" SourceHDTV Source = "hdtv" SourceWEBRip Source = "webrip" SourceWEBDL Source = "webdl" SourceBluRay Source = "bluray" SourceRemux Source = "remux" )
type SourceCandidate ¶
type SourceCandidate struct {
InfoHash string `json:"infoHash,omitempty"`
Magnet string `json:"magnet,omitempty"`
TorrentURL string `json:"torrentUrl,omitempty"`
NZBURL string `json:"nzbUrl,omitempty"`
// FileIndex selects a zero-based entry in the torrent provider file list; nil uses video selection.
FileIndex *int `json:"fileIndex,omitempty"`
Title string `json:"title,omitempty"`
Size int64 `json:"size,omitempty"`
Seeders int `json:"seeders,omitempty"`
Cached bool `json:"cached,omitempty"`
// CachedBy lists the owner-configured debrid services holding this
// torrent in the order Ether would acquire from them (or, on
// debrid_acquire, the service that served it). Omitted when uncached.
CachedBy []DebridServiceRef `json:"cachedBy,omitempty"`
// Indexer and IndexerID name the indexer an indexer_search result came
// from, so a plugin that hands the candidate back can be fetched
// through that indexer (an NZB needs its originating indexer).
Indexer string `json:"indexer,omitempty"`
IndexerID string `json:"indexerId,omitempty"`
// Category is the standard Newznab/Torznab category ID reported for this
// release when known, preserving media type for follow-up downloads.
Category int `json:"category,omitempty"`
// Score, Resolution, Source and Codec are populated on indexer_search
// candidates whose release name identifies video, scored against the
// requested (or owner default) quality profile; non-video candidates
// leave them empty.
Score *int `json:"score,omitempty"`
Resolution int `json:"resolution,omitempty"`
Source string `json:"source,omitempty"`
Codec string `json:"codec,omitempty"`
// Files is populated only by a release_files query: the files inside
// this candidate release.
Files []ReleaseFile `json:"files,omitempty"`
// FileCount is the torrent's known file count when reported by an indexer
// or release_files query, allowing zip-only debrid caches to be probed by
// cached-only add even when Files is omitted.
FileCount int `json:"fileCount,omitempty"`
// UsenetCheck is populated only by a usenet_check query: the sampled
// article availability verdict and any recorded playback failure for
// this NZB release.
UsenetCheck *UsenetCheckResult `json:"usenetCheck,omitempty"`
}
SourceCandidate is one Ether-found release for a resolver to rank, carrying the release-hint fields plus the facts matching needs. Torrent candidates carry their infoHash, magnet, and/or torrentUrl and never populate nzbUrl; Usenet candidates populate nzbUrl. Same-origin download links returned by indexer_search are stripped of indexer API keys and secrets (Ether re-attaches them at fetch time on the originating indexer's origin), so plugins can safely cache candidates without storing credentials.
type SourceDelivery ¶
type SourceDelivery struct {
Bytes int64 // decoded bytes fetched from the network
Fetches int64 // completed network fetches
Busy time.Duration // wall time with at least one fetch outstanding
// Diagnostics of the moment.
InFlight int // fetches outstanding now, including source/pool queue wait
Parallel int // shared speculative fetch budget (not sockets)
PipelineDepth int // normal (non-burst) read-ahead BODY depth ceiling
PerFetchBps float64 // recent fetch completion rate including queue wait
}
SourceDelivery accounts decoded article-fetch completions owned by this source, including demand, near read-ahead and disk play-ahead. Engine cache hits and joined engine flights do not count. Fetcher-level coalescing can share wire work; these bytes must not be summed across sources as unique provider traffic. Difference Bytes across snapshots and divide by elapsed wall time for delivery. Busy excludes idle gaps, includes queue wait, and is diagnostic only.
type SourceDeliveryObserver ¶ added in v0.2.9
type SourceDeliveryObserver interface {
ObserveSourceDelivery(Release, float64)
ObserveSourceStall(Release, float64)
}
SourceDeliveryObserver receives uncached source throughput and stall evidence. It is neither client bandwidth nor a claim about an entire provider network.
type SourceDeliveryReporter ¶
type SourceDeliveryReporter interface{ SourceDelivery() SourceDelivery }
SourceDeliveryReporter exposes the optional SourceDelivery capability.
type SourceQuery ¶
type SourceQuery struct {
Kind string `json:"kind"` // indexer_search|debrid_check|debrid_acquire|release_files|usenet_check
Query string `json:"query,omitempty"`
// Category accepts comma-separated Newznab IDs or standard family names.
// When set with an empty Query, indexer_search requests recent releases.
Category string `json:"category,omitempty"`
// Profile names the quality profile to score video release names against
// on indexer_search; empty uses the owner's default profile.
Profile string `json:"profile,omitempty"`
InfoHashes []string `json:"infoHashes,omitempty"`
InfoHash string `json:"infoHash,omitempty"`
Magnet string `json:"magnet,omitempty"`
// TorrentURL carries a torrent download or details page link for torrent
// indexers that do not emit an info hash or magnet in search results.
TorrentURL string `json:"torrentUrl,omitempty"`
// NZBURL carries a Usenet NZB link for usenet_check when the plugin does
// not pass a full Candidate from indexer_search.
NZBURL string `json:"nzbUrl,omitempty"`
// Candidate carries a candidate previously returned by indexer_search
// back for release_files or usenet_check, so an NZB or torrent link is
// resolved through its originating indexer.
Candidate *SourceCandidate `json:"candidate,omitempty"`
// FileCount optionally hints how many files a torrent contains when Ether
// has not seen its file list yet (e.g. a magnet for a large collection),
// so zip-only debrid caches are checked via cached-only add.
FileCount int `json:"fileCount,omitempty"`
}
SourceQuery asks Ether to find sources for a kind resolver (spec §4.5).
type SourceRetirement ¶ added in v0.3.0
type SourceRetirement interface {
Done() <-chan struct{}
Err() error
}
SourceRetirement reports backend responsibility for one exact manager source lifetime, including provisional and prior generations. Done is terminal; Err is nil only after Done, successful Close of every acquired source and settlement of its durable payload cleanup. Pending cleanup keeps Done open; a terminal backend Close error never becomes success. This does not prove encoder retirement or a durable ownership transfer.
type State ¶
type State interface {
Get(ctx context.Context, userID int64, key RatingKey) (WatchStatus, error)
GetMany(ctx context.Context, userID int64, keys []RatingKey) (map[RatingKey]WatchStatus, error)
// Progress records a timeline update. Crossing 90% marks it watched.
Progress(ctx context.Context, userID int64, key RatingKey, offset, duration time.Duration, state string) error
Scrobble(ctx context.Context, userID int64, key RatingKey) error // mark watched
Unscrobble(ctx context.Context, userID int64, key RatingKey) error // mark unwatched
Rate(ctx context.Context, userID int64, key RatingKey, rating float64) error
// OnDeck: in-progress items and next episodes, most recent first.
InProgress(ctx context.Context, userID int64, limit int) ([]WatchStatus, error)
History(ctx context.Context, userID int64, since time.Time, limit int) ([]HistoryEntry, error)
// InProgressAny lists keys in progress for any user (cache protection, prefetch).
InProgressAny(ctx context.Context) ([]RatingKey, error)
}
type StoredTitleLookup ¶ added in v0.2.37
StoredTitleLookup reads local metadata without remote discovery. Callers must apply their own authorization before exposing the returned title.
type StreamInfo ¶
type StreamInfo struct {
// MalformedHEVC marks an invalid SPS header found in the probe data.
MalformedHEVC bool `json:"malformedHEVC,omitempty"`
// Probe hints for enhancement backends that require progressive, steady-rate input.
Interlaced bool `json:"interlaced,omitempty"`
VariableFrameRate bool `json:"variableFrameRate,omitempty"`
Index int `json:"index"`
// ContainerTrackID is the Matroska TrackNumber when the probe read it:
// the id a player's own demuxer gives the track. Zero is unknown.
ContainerTrackID int `json:"containerTrackId,omitempty"`
Type string `json:"type"` // video, audio, subtitle
Codec string `json:"codec"`
Profile string `json:"profile,omitempty"`
Level int `json:"level,omitempty"`
Language string `json:"language,omitempty"`
Title string `json:"title,omitempty"`
CodecLongName string `json:"codecLongName,omitempty"`
Default bool `json:"default,omitempty"`
Forced bool `json:"forced,omitempty"`
// Nil means the source did not report this ffprobe disposition.
DefaultDisposition *bool `json:"defaultDisposition,omitempty"`
ForcedDisposition *bool `json:"forcedDisposition,omitempty"`
HearingImpaired *bool `json:"hearingImpaired,omitempty"`
Original *bool `json:"original,omitempty"`
VisualImpaired *bool `json:"visualImpaired,omitempty"`
Commentary *bool `json:"commentary,omitempty"`
Dub *bool `json:"dub,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
FrameRate float64 `json:"frameRate,omitempty"`
// Optional probe facts are nil/empty when the source did not report them.
AverageFrameRate *float64 `json:"averageFrameRate,omitempty"`
ReferenceFrameRate *float64 `json:"referenceFrameRate,omitempty"`
DisplayAspectRatio string `json:"displayAspectRatio,omitempty"`
PixelFormat string `json:"pixelFormat,omitempty"`
SampleFormat string `json:"sampleFormat,omitempty"`
StreamIdentifier string `json:"streamIdentifier,omitempty"`
CodedWidth int `json:"codedWidth,omitempty"`
ChromaLocation string `json:"chromaLocation,omitempty"`
CodedHeight int `json:"codedHeight,omitempty"`
CodecTag string `json:"codecTag,omitempty"`
TimeBase string `json:"timeBase,omitempty"`
NALLengthSize *int `json:"nalLengthSize,omitempty"`
ReferenceFrames *int `json:"referenceFrames,omitempty"`
BitsPerRawSample *int `json:"bitsPerRawSample,omitempty"`
ProbedLevel *int `json:"probedLevel,omitempty"`
FieldOrder string `json:"fieldOrder,omitempty"`
ProbedInterlaced *bool `json:"probedInterlaced,omitempty"`
// Rotation is ffprobe display-matrix rotation in degrees (counterclockwise).
// Nil means no rotation evidence, distinct from an explicit zero.
Rotation *float64 `json:"rotation,omitempty"`
BitDepth int `json:"bitDepth,omitempty"`
ColorTransfer string `json:"colorTransfer,omitempty"` // smpte2084 = HDR10, arib-std-b67 = HLG
// HEVCParameterSets reports a complete VPS/SPS/PPS hvcC record, safe for mp4toannexb.
HEVCParameterSets bool `json:"hevcParameterSets,omitempty"`
// Signalled picture format, in ffprobe's names; empty when the stream
// and container leave it unspecified (decoders then assume square
// pixels and limited range).
SampleAspectRatio string `json:"sampleAspectRatio,omitempty"` // "N:D"
ColorRange string `json:"colorRange,omitempty"` // tv, pc
ColorPrimaries string `json:"colorPrimaries,omitempty"` // bt709, bt2020, smpte170m...
ColorSpace string `json:"colorSpace,omitempty"` // matrix: bt709, bt2020nc, smpte170m...
DolbyVision bool `json:"dolbyVision,omitempty"`
// HDR10Plus is nil unless the probe provides affirmative or explicit negative evidence.
HDR10Plus *bool `json:"hdr10Plus,omitempty"`
Channels int `json:"channels,omitempty"`
ChannelLayout string `json:"channelLayout,omitempty"`
// AACProgramConfig records a verified AAC channel_configuration=0 with
// an in-band program configuration element. Segmented TS needs a safe
// audio plan because later packets may omit that element.
AACProgramConfig bool `json:"aacProgramConfig,omitempty"`
// Times (microseconds on the source clock) let a bounded seek prime the
// decoder with the source's initial PCE before seeking to a later packet.
AACConfigPTS *int64 `json:"aacConfigPts,omitempty"`
AACSourceStart *int64 `json:"aacSourceStart,omitempty"`
// DecodedPadding is source priming removed by the demuxer from its frame clock.
DecodedPadding int `json:"decodedPadding,omitempty"`
SampleRate int `json:"sampleRate,omitempty"`
BitrateKbps int `json:"bitrateKbps,omitempty"`
ProviderTitle string `json:"providerTitle,omitempty"`
External bool `json:"external,omitempty"` // sidecar subtitle (OpenSubtitles)
ExternalURL string `json:"externalUrl,omitempty"`
// DolbyVisionProfile is the DV profile (5, 7, 8...) from the DOVI
// configuration record; 0 when unknown or not Dolby Vision.
DolbyVisionProfile int `json:"dolbyVisionProfile,omitempty"`
DolbyVisionLevel int `json:"dolbyVisionLevel,omitempty"`
DolbyVisionCompatibilityID int `json:"dolbyVisionCompatibilityId,omitempty"`
CodecString string `json:"codecString,omitempty"` // RFC 6381, derived from the codec configuration
// Configuration presence is known from a completed MP4/Matroska container
// probe; nil means unprobed, unsupported or ambiguous. Codec tags alone do
// not establish whether enhancement/base layers or RPU are present.
DolbyVisionConfigurationPresent *bool `json:"dolbyVisionConfigurationPresent,omitempty"`
DolbyVisionBLCompatibilityIDPresent *bool `json:"dolbyVisionBLCompatibilityIdPresent,omitempty"`
ProbedDolbyVisionProfile *int `json:"probedDolbyVisionProfile,omitempty"`
ProbedDolbyVisionLevel *int `json:"probedDolbyVisionLevel,omitempty"`
DolbyVisionVersion string `json:"dolbyVisionVersion,omitempty"`
DolbyVisionBLPresent *bool `json:"dolbyVisionBLPresent,omitempty"`
DolbyVisionELPresent *bool `json:"dolbyVisionELPresent,omitempty"`
DolbyVisionRPUPresent *bool `json:"dolbyVisionRPUPresent,omitempty"`
}
type StreamingIndexer ¶ added in v0.2.7
type StreamingIndexer interface {
SearchWith(context.Context, SearchRequest, func([]Release)) ([]Release, error)
}
StreamingIndexer exposes the optional SearchWith capability.
type StreamingRescueIndexer ¶ added in v0.2.7
type StreamingRescueIndexer interface {
SearchRescueWith(context.Context, SearchRequest, func([]Release)) ([]Release, error)
}
StreamingRescueIndexer exposes the optional SearchRescueWith capability.
type StremioPresentation ¶
type StremioPresentation struct {
Type string `json:"type,omitempty"` // movie|series|channel|tv
Default *bool `json:"default,omitempty"` // optional manifest default hint (true when omitted)
}
StremioPresentation describes how Stremio sees a library.
type StringFilter ¶ added in v0.3.0
StringFilter narrows a string column with a Plex string operator ("=", "!=", "==", "!==", "<=", ">=").
type SubtitleExtractor ¶ added in v0.2.49
type SubtitleExtractor interface {
ExtractSubtitle(ctx context.Context, inputURL string, streamIndex int, codec string, w io.Writer) error
}
SubtitleExtractor is optionally implemented by transcoders that can write an embedded text subtitle stream as WebVTT, so a track picked mid-playback can be served from the transcode session without a restart. Image subtitles (PGS/VobSub) return an error.
type SurfaceScopedPlayback ¶ added in v0.3.0
type SurfaceScopedPlayback interface {
PrepareSurface(ctx context.Context, user *User, key RatingKey, caps ClientCaps, releaseID string, exact bool) (*PlaySession, error)
SessionForSurface(surface string, userID int64, clientID string, key RatingKey, releaseID string, exact bool) (*PlaySession, bool)
MarkSurfaceOpened(id string) bool
MarkSurfacePrepared(id string) bool
}
SurfaceScopedPlayback separates client identifiers by their authenticated protocol surface, even when different clients supply identical IDs.
type TabFilter ¶
type TabFilter struct {
Match string `json:"match,omitempty"` // "all" (default) or "any" for Rules
Rules []CollectionRule `json:"rules,omitempty"` // positive conditions
Exclude []CollectionRule `json:"exclude,omitempty"` // negative conditions (any match hides)
Groups []LibraryExclusion `json:"groups,omitempty"` // ordered show/hide groups (custom-library style)
VisibilityDefault string `json:"visibilityDefault,omitempty"`
}
TabFilter narrows a library or view tab using the same rule model as collections (match/rules/exclude) and custom libraries (ordered show/hide rule groups). Either representation may be sent; ToPolicy compiles both into ordered LibraryExclusion rules for libraryfilter.
func (*TabFilter) ToPolicy ¶
func (f *TabFilter) ToPolicy(mediaType MediaType) ([]LibraryExclusion, string)
ToPolicy converts f into ordered LibraryExclusion rules and a fallback ("show" or "hide") suitable for libraryfilter.CompilePolicy and pluginitems.CompilePolicy.
func (*TabFilter) UnmarshalJSON ¶
UnmarshalJSON accepts either a TabFilter object or a bare []LibraryExclusion array so both Collection Studio rule builders and Library Visibility rule editors serialize cleanly.
type TasteDecade ¶
TasteDecade is an affinity for a release decade (1990 = the 90s).
type TasteHabits ¶
type TasteHabits struct {
WeeknightMinutes float64 `json:"weeknightMinutes"` // typical minutes watched on an active weeknight
WeekendMinutes float64 `json:"weekendMinutes"` // typical minutes watched on an active weekend day
PreferredDevice string `json:"preferredDevice"` // DeviceTV, DeviceMobile, ... or ""
BingeScore float64 `json:"bingeScore"` // 0..1: share of episodes watched in same-day runs of 3+
RewatchScore float64 `json:"rewatchScore"` // 0..1: share of finished titles watched again
PeakHours []int `json:"peakHours"` // most common start hours (local), busiest first
}
TasteHabits are a viewer's learned viewing habits.
type TasteLanguage ¶
TasteLanguage is an affinity for an original language (ISO 639-1).
type TasteOverride ¶
type TasteOverride struct {
Kind string `json:"kind"`
Value string `json:"value"`
Weight float64 `json:"weight"`
}
TasteOverride is an owner correction applied on top of the learned model: Kind "genre" (Value = genre name), "person" (Value = TMDB person id) or "keyword" (Value = keyword); Weight -1..1 replaces the learned weight.
type TastePerson ¶
type TastePerson struct {
ID int64 `json:"id"`
Name string `json:"name"`
Role string `json:"role"` // "director", "writer", "actor"
Weight float64 `json:"weight"`
Image string `json:"image,omitempty"` // browser-loadable URL
}
TastePerson is an affinity for a cast or crew member.
type TasteProfile ¶
type TasteProfile struct {
UserID int64 `json:"userId"`
UpdatedAt time.Time `json:"updatedAt"`
Confidence float64 `json:"confidence"` // 0..1, grows with history
Genres []TasteWeight `json:"genres"`
People []TastePerson `json:"people"`
Keywords []TasteWeight `json:"keywords"`
Decades []TasteDecade `json:"decades"`
Languages []TasteLanguage `json:"languages"`
Habits TasteHabits `json:"habits"`
Overrides []TasteOverride `json:"overrides"`
}
TasteProfile is the explainable view of one viewer's taste model.
type TasteWeight ¶
TasteWeight is one named affinity, weight in -1..1.
type TimelineAligner ¶
type TimelineAligner interface {
AlignTime(ctx context.Context, req AlignRequest, at time.Duration) (mapped time.Duration, ok bool)
}
TimelineAligner maps a moment in one release to the same moment in another release of the title using dialogue (subtitle) timing rather than video, so nothing has to be downloaded. The mapping may be piecewise (different cuts or intros shift later timestamps). ok is false when there is no confident alignment; callers then fall back to duration-based alignment.
type Title ¶
type Title struct {
Key RatingKey `json:"key"`
Type MediaType `json:"type"`
IDs IDs `json:"ids"`
// Plugin kind projections (spec §6.3, additive). KindLevel is the
// declared MediaKindMeta level key a projected plugin item came from
// (empty for catalogue titles); LibraryID is the owning library, set so
// protocols can type and section a plugin item without a re-lookup.
KindLevel string `json:"kindLevel,omitempty"`
LibraryID LibraryID `json:"-"`
ItemIndex int `json:"-"`
PluginAddedAt int64 `json:"-"`
LandscapeCard bool `json:"-"`
DateDisplay string `json:"-"`
// MBItemType is the MediaBrowser (Jellyfin/Emby) item type the owning
// kind's presentation declares for KindLevel (MusicAlbum, Audio, Book,
// AudioBook, …); empty for catalogue titles and for levels the kind
// does not map, which keep the video projection. ParentKey/ParentTitle
// name the item's immediate parent in the declared hierarchy (a
// track's album, an album's artist) where ShowKey names only the root.
MBItemType string `json:"-"`
ParentKey RatingKey `json:"-"`
ParentTitle string `json:"-"`
// SelfChild marks the synthetic playable-leaf incarnation of a
// single-level playable container item (a flat MusicAlbum kind whose
// album is one playable item): the title is the item itself, presented
// once as its own child (an Audio track / Plex track, same Key) so
// clients that only play leaf items can play it.
SelfChild bool `json:"-"`
// Media class, role, and structured non-video presentation metadata
// (docs/plugin-kinds.md, additive). Never serialized to catalogue caches.
MediaClass MediaClass `json:"-"`
MediaRole MediaRole `json:"-"`
IndexDisplay string `json:"-"` // optional display string for fractional/non-integer series index (e.g. "1.5")
Disc int `json:"-"` // disc / volume number for multi-disc albums
MediaParents []TitleParent `json:"-"` // ancestors nearest first
MediaCredits []MediaCredit `json:"-"` // declared credits preserving role
MediaReading *TitleReading `json:"-"` // readable document metadata (format, pages)
MediaFacts []TitleFact `json:"-"` // plain label/value detail facts
// Seasons and episodes.
ShowKey RatingKey `json:"showKey,omitempty"`
ShowIDs IDs `json:"showIds,omitempty"`
ShowTitle string `json:"showTitle,omitempty"`
ShowOriginalTitle string `json:"showOriginalTitle,omitempty"` // canonical original series name, distinct from episode title
ShowEnglishTitle string `json:"-"` // canonical en-US series name when catalogue language is non-English; release matching only
ShowYear int `json:"showYear,omitempty"` // series premiere year, distinct from episode air year
SeasonTitle string `json:"seasonTitle,omitempty"`
Season int `json:"season,omitempty"`
Episode int `json:"episode,omitempty"`
// AbsoluteEpisode counts an episode from the series start across its
// regular seasons; 0 when an earlier season's size is unknown (additive).
AbsoluteEpisode int `json:"absoluteEpisode,omitempty"`
Title string `json:"title"`
OriginalTitle string `json:"originalTitle,omitempty"`
// EnglishTitle is TMDB's primary en-US title when the catalogue language
// is non-English; release matching only, never serialized (additive).
EnglishTitle string `json:"-"`
SortTitle string `json:"sortTitle,omitempty"`
Tagline string `json:"tagline,omitempty"`
Summary string `json:"summary,omitempty"`
Year int `json:"year,omitempty"`
// PrimaryReleased is TMDB's primary release_date for a movie. The title
// year comes from it. Released stays the date added (theatrical, when
// one exists). Empty when the year came from a premiere or the release
// itself. Not serialized.
PrimaryReleased time.Time `json:"-"`
// YearSource records which date produced Year: primary, premiere,
// released, none, or missing. Empty means a row stored before that
// date was kept. Not serialized.
YearSource string `json:"-"`
Released time.Time `json:"released,omitempty"` // first air / release date
AddedAt time.Time `json:"addedAt,omitzero"` // series/season latest aired episode, or a derived air date; not a catalogue insertion time
LastAirDate time.Time `json:"lastAirDate,omitzero"` // last aired episode date when known
HomeReleaseChecked bool `json:"homeReleaseChecked,omitempty"`
HomeReleased time.Time `json:"homeReleased,omitempty"`
HomeReleaseFallbackAdmitted bool `json:"homeReleaseFallbackAdmitted,omitempty"`
Runtime time.Duration `json:"runtime,omitempty"`
Status string `json:"status,omitempty"` // TMDB status: Released, In Production, Ended...
Genres []string `json:"genres,omitempty"`
Keywords []string `json:"keywords,omitempty"` // TMDB keywords (lower-case), for content-based recommendations
// AlternativeTitles are other names the title goes by (TMDB alternative
// titles: romanized originals, regional and working titles). Release
// matching only; never serialized (additive). Episodes and seasons carry
// their series' in ShowAlternativeTitles.
AlternativeTitles []string `json:"-"`
ShowAlternativeTitles []string `json:"-"`
RemoteTrailerName string `json:"remoteTrailerName,omitempty"`
RemoteTrailerURL string `json:"remoteTrailerURL,omitempty"`
Studios []string `json:"studios,omitempty"`
Countries []string `json:"countries,omitempty"`
Language string `json:"language,omitempty"` // ISO 639-1 original language
// ContentRating is the certification in contentrating's stored form:
// bare US labels ("PG", "TV-14"), region-qualified otherwise ("de/6").
ContentRating string `json:"contentRating,omitempty"`
// ContentRatingSource records where ContentRating came from: "tmdb:US:6"
// (TMDB, country, movie release type), "tmdb:CA" (TV), "omdb", "mdblist".
ContentRatingSource string `json:"contentRatingSource,omitempty"`
// ContentRatings holds per-country bare certificates keyed by uppercase
// ISO 3166-1 country code (for example "US": "PG-13", "GB": "12A", "DE": "12")
// so viewer-localized surfaces can pick the viewer's preferred region.
ContentRatings map[string]string `json:"-"`
// EnforcementRating maps certifications to the US scale ("G", "PG",
// "PG-13", "R", "NC-17") or marks uncertified adult/adult-keyword titles
// ("XXX") for viewer rating enforcement without altering ContentRating.
EnforcementRating string `json:"-"`
Adult bool `json:"adult,omitempty"`
Rating float64 `json:"rating,omitempty"` // TMDB vote average 0-10
VoteCount int `json:"voteCount,omitempty"`
Popularity float64 `json:"popularity,omitempty"`
// SearchScore is how well the title answers the search that returned it
// (1 is the exact title; zero outside search results). Frontends order
// result groups and report relevance from it. Never persisted.
SearchScore float64 `json:"-"`
PosterPath string `json:"posterPath,omitempty"`
BackdropPath string `json:"backdropPath,omitempty"`
StillPath string `json:"stillPath,omitempty"` // episodes
LogoPath string `json:"logoPath,omitempty"`
ThumbPath string `json:"-"` // plugin item 16:9 thumb role when present
Cast []Person `json:"cast,omitempty"`
Directors []Person `json:"directors,omitempty"`
Writers []Person `json:"writers,omitempty"`
Crew []Person `json:"crew,omitempty"` // creators, cinematographers, composers (additive)
CollectionID int64 `json:"collectionId,omitempty"` // TMDB franchise
CollectionName string `json:"collectionName,omitempty"`
ChildCount int `json:"childCount,omitempty"` // seasons of a show, episodes of a season
LeafCount int `json:"leafCount,omitempty"` // episodes of a show
UpdatedAt time.Time `json:"updatedAt,omitempty"`
}
Title is a catalogue item: movie, show, season or episode. Image paths are TMDB paths ("/abc.jpg"); the front end turns them into URLs.
func (*Title) DateAdded ¶ added in v0.3.0
DateAdded is the owner date-added rule. A movie uses its release date and an episode uses its air date. A series uses the air date of its most recently aired episode, then its first-air date. A season uses the latest aired episode in that season, then the season premiere. Those series and season dates are carried on AddedAt after catalogue hydration; a virtual season with no premiere of its own uses the same field. Catalogue insertion, first observation, metadata refresh, file modification and release-publication times are never the date added. Future dates are unknown.
func (*Title) IsFutureRelease ¶
IsFutureRelease distinguishes a future cinema date from a movie already released digitally. Released remains the date used for date-added display.
type TitleFact ¶
TitleFact is one plain label/value metadata pair surfaced on a title's detail page (for example label, publisher, ISBN, release type).
type TitleFacts ¶
type TitleFacts uint8
TitleFacts is a set of the facts a title keeps outside its own row, in tables of their own: what a visibility rule, a viewer's policy, the release gate or a query filter may read beyond the row.
const ( FactGenres TitleFacts = 1 << iota FactStudios FactCountries FactKeywords FactHomeRelease )
type TitleParent ¶
type TitleParent struct {
Key RatingKey `json:"-"`
FacetID string `json:"facetId,omitempty"`
Title string `json:"title"`
Role MediaRole `json:"role"`
Index int `json:"index,omitempty"`
IndexDisplay string `json:"indexDisplay,omitempty"`
}
TitleParent names one ancestor in a plugin item's declared hierarchy, ordered nearest first (for example a track's [album, artist] or a book's [series]). Real hierarchy parents carry Key; synthetic facet-backed parents (such as a 1-level book's series facet) carry FacetID (e.g. "facet:series:Dune").
type TitleReading ¶
type TitleReading struct {
Format string `json:"format"` // "epub" | "pdf" | "cbz"
Pages int `json:"pages,omitempty"` // page count when known
}
TitleReading describes readable document metadata for book-role items.
type TrackHint ¶
type TrackHint struct {
Disc int `json:"disc,omitempty"`
Number int `json:"number,omitempty"`
Title string `json:"title,omitempty"`
}
TrackHint identifies one track inside a multi-track audio release or archive when exact filenames cannot be known before opening (for example scene RARs). Ether matches by disc/track number first, then normalised title tokens, failing on ambiguity. Exact fileHint semantics remain unchanged.
type TransactionalMarkedPlaylists ¶ added in v0.3.0
type TransactionalMarkedPlaylists interface {
EnsureMarkedPlaylistTx(context.Context, *sql.Tx, int64, string, string) (RatingKey, error)
DeleteMarkedPlaylistTx(context.Context, *sql.Tx, int64, string) error
MarkedPlaylistKeyTx(context.Context, *sql.Tx, int64, string) (RatingKey, error)
}
TransactionalMarkedPlaylists joins marked-playlist creation to an existing shared database transaction.
type Transcoder ¶
type Transcoder interface {
Probe(ctx context.Context, inputURL string) (*MediaInfo, error)
Decide(info MediaInfo, caps ClientCaps, opts DecideOptions) Decision
// StartHLS starts an HLS session, a DASH session (a DASHSession)
// when req.Protocol is ProtocolDASH, or an HTTP Matroska session
// (an HTTPSession) when req.Protocol is ProtocolHTTP.
StartHLS(ctx context.Context, req HLSRequest) (HLSSession, error)
Session(id string) (HLSSession, bool)
Stop(id string)
HWAccel() HWAccel
}
type TrickplayCanceler ¶ added in v0.2.7
type TrickplayCanceler interface{ CancelTrickplay(string) }
TrickplayCanceler exposes the optional CancelTrickplay capability.
type TrickplayLease ¶ added in v0.3.0
type TrickplayLease interface {
Ensure(context.Context, TrickplaySource)
Release(cancelIfIdle bool)
}
TrickplayLease holds one release. Ensure after Release is inert. Release is idempotent; cancelIfIdle applies the caller's idle policy only when no other holder remains. Only the runtime owner can Close the provider.
type TrickplayLeaser ¶ added in v0.3.0
type TrickplayLeaser interface {
AcquireTrickplay(context.Context, TrickplaySource) (TrickplayLease, error)
}
TrickplayLeaser is supplied by the runtime-owned shared provider. Acquire registers a holder and starts generation atomically with idle cancellation. Calls return promptly; consumers retain one lease until their source ends.
type TrickplayProvider ¶
type TrickplayProvider interface {
// EnsureTrickplay starts (or continues) progressive thumbnail
// generation for the source in the background. It returns
// immediately; duplicate calls for a release already generating are
// no-ops.
EnsureTrickplay(ctx context.Context, src TrickplaySource)
// TrickplayAvailable reports whether thumbnails for the release
// exist or are being generated, so a front end can advertise them
// (Plex's indexes="sd").
TrickplayAvailable(releaseID string) bool
// TrickplayBIF returns a snapshot of the release's sparse BIF index
// built from the frames generated so far.
TrickplayBIF(releaseID string) ([]byte, bool)
// TrickplayFrame returns the JPEG of the latest generated frame at
// or before at (a fallback still when no real frame precedes it).
TrickplayFrame(releaseID string, at time.Duration) ([]byte, bool)
// SetTrickplayFallback records a low-fidelity still (TMDB episode
// still or backdrop, already JPEG at roughly BIF width) used to fill
// not-yet-generated intervals. Real frames replace it as they arrive.
SetTrickplayFallback(releaseID string, jpeg []byte)
}
TrickplayProvider supplies on-the-fly preview thumbnails (Plex "BIF" indexes) for releases as they stream. It is an optional capability: callers reach it through a type assertion or an optional dependency and must tolerate its absence. Implementations only extract from sources handed to EnsureTrickplay (an active playback or warmup session); they never resolve or download a title just for thumbnails.
type TrickplaySource ¶
type TrickplaySource struct {
// Current fences publication after the owning source changes or disappears.
Current func() bool `json:"-"`
ReleaseID string
InputURL string
Info MediaInfo
// AvailableUntil is the playback position already read by the client.
// Generators must only fill intervals at or before this point and may
// advance it on later calls as playback progresses.
AvailableUntil time.Duration
}
TrickplaySource identifies one playable source thumbnails can be extracted from: the release being streamed and the loopback URL its bytes are readable through (Playback.InputURL). Info carries the duration and, when known, the container keyframe index used to align extractions to keyframes.
type UncachedError ¶ added in v0.3.3
type UncachedError struct {
Err error
// CachedOnly is the owner's "Cached torrents only" setting at the time.
CachedOnly bool
// Usenet is what Usenet contributed: UsenetNone (a Usenet provider is
// set up but the search found no Usenet release), UsenetFailed (Usenet
// releases were found and none played), or "" (no Usenet provider).
Usenet string
}
UncachedError is a resolve that failed only because no debrid account holds a torrent release of the title. It wraps the per-release errors and says what the owner's settings and other sources contributed, so a player message can name the real reason.
func (*UncachedError) Error ¶ added in v0.3.3
func (e *UncachedError) Error() string
func (*UncachedError) Unwrap ¶ added in v0.3.3
func (e *UncachedError) Unwrap() error
type UsenetCheckResult ¶
type UsenetCheckResult struct {
Available bool `json:"available"`
Checked int `json:"checked"`
Missing int `json:"missing"`
// Cached is true when this verdict came from Ether's bounded per-NZB
// cache (including a recorded playback failure) rather than a fresh
// NNTP check on this call.
Cached bool `json:"cached,omitempty"`
// PlaybackFailed is true when a previous real playback attempt against
// this NZB failed with an article or release error (such as missing or
// corrupt articles), overriding or pre-empting any sampled check.
PlaybackFailed bool `json:"playbackFailed,omitempty"`
// Reason carries a short diagnostic code when Available is false
// (e.g. "articles_missing", "playback_article_missing",
// "playback_article_corrupt", "playback_release_rejected").
Reason string `json:"reason,omitempty"`
// CheckedAt is the Unix timestamp (seconds) when this verdict or
// playback failure was recorded.
CheckedAt int64 `json:"checkedAt,omitempty"`
}
UsenetCheckResult reports the sampled article availability verdict for one Usenet NZB release, as returned by a usenet_check source query.
type User ¶
type User struct {
// Timestamps are internal identity metadata and do not change existing wire JSON.
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
// Delegated marks short-lived server credentials; these never grant owner access.
Delegated bool `json:"-"`
ID int64 `json:"id"` // local id
PlexID int64 `json:"plexId"`
UUID string `json:"uuid,omitempty"`
Username string `json:"username"`
Title string `json:"title"` // display name
Email string `json:"email,omitempty"`
Thumb string `json:"thumb,omitempty"`
IsOwner bool `json:"isOwner"`
StreamLimit int `json:"streamLimit"` // 0 = server default
MaxContentRating string `json:"maxContentRating"` // "" = unrestricted, e.g. "PG-13", "TV-14"
SubtitleLanguages []string `json:"subtitleLanguages"` // ISO 639-1, preference order
AudioLanguages []string `json:"audioLanguages"`
PreferOriginal bool `json:"preferOriginal,omitempty"`
AllowedLibraries []LibraryID `json:"allowedLibraries"` // empty = all libraries (§1.4)
}
User is a Plex account with access to this server: the owner or a friend the owner shared with on plex.tv.
func (*User) AllowsLibrary ¶
AllowsLibrary reports whether u may open library id (§1.4): the owner and a viewer with no restriction see every library; otherwise the library must be listed. A nil user sees nothing.
type UserPolicySource ¶ added in v0.2.7
UserPolicySource exposes the optional UserPolicy capability.
type UserTargets ¶
UserTargets is either every user ("all" in JSON) or a list of local user ids.
func (UserTargets) Includes ¶
func (u UserTargets) Includes(user *User) bool
Includes reports whether a user (nil = anonymous) is targeted.
func (UserTargets) MarshalJSON ¶
func (u UserTargets) MarshalJSON() ([]byte, error)
func (*UserTargets) UnmarshalJSON ¶
func (u *UserTargets) UnmarshalJSON(b []byte) error
type VariantPlayback ¶
type VariantPlayback interface {
PrepareVariant(ctx context.Context, user *User, key RatingKey, caps ClientCaps, releaseID string) (*PlaySession, error)
}
VariantPlayback is implemented by playback managers that can prepare a session on a specific release (the viewer picked a version). The release is health-checked like any other; when it is unavailable the manager falls back to the normal choice for the client.
type VariantResolver ¶
type VariantResolver interface {
Variants(ctx context.Context, req ResolveRequest, max int) ([]ReleaseVariant, error)
}
VariantResolver lists distinct candidate releases of a title for a client, best first, without health-checking every one of them. Implemented by internal/resolver.
type VelaPresentation ¶
type VelaPresentation struct {
Type string `json:"type,omitempty"` // movies|shows
Default *bool `json:"default,omitempty"` // optional manifest default hint (true when omitted)
}
VelaPresentation describes how Vela sees a library.
type VersionAvailability ¶
type VersionAvailability string
VersionAvailability classifies how quickly a version can start playback without spending any indexer or provider searches.
const ( VersionInstant VersionAvailability = "instant" VersionCached VersionAvailability = "cached" VersionFetch VersionAvailability = "fetch" )
type VersionHeaderProber ¶
type VersionHeaderProber interface {
ProbeVersionHeaders(context.Context, *User, RatingKey, ClientCaps) error
}
VersionHeaderProber runs bounded header probes on unprobed offered versions that can be opened without indexer searches or NZB grabs (already-cached debrid torrents, direct HTTP streams, or vaulted Usenet NZBs) so play-time metadata reads can return real container tracks for non-Auto picks too.
type VersionProfile ¶
type VersionProfile struct {
Height int `json:"height,omitempty"`
DynamicRange string `json:"dynamicRange,omitempty"` // "dv", "hdr10", "hdr10+", "hlg", "sdr"
SourceClass string `json:"sourceClass,omitempty"` // "remux", "disc", "web", "other"
}
VersionProfile is the quality/source signature stored for a viewer's show-level episode version preference (e.g. "4K DV" or "1080p Remux").
type VibeSearcher ¶
type VibeSearcher interface {
VibeCollection(ctx context.Context, user *User, query string) (c *Collection, items []Title, ok bool, err error)
// PromoteEphemeral saves an ephemeral collection as a persisted
// personal smart collection for its owner. ok is false when key is
// not a live ephemeral collection owned by user.
PromoteEphemeral(ctx context.Context, user *User, key RatingKey) (c *Collection, ok bool, err error)
}
VibeSearcher is optionally implemented by the collections engine: it returns a cached AI-generated collection for the viewer, alongside its top items. A cache miss schedules bounded work and returns ok=false; ordinary title search remains available without waiting for the model.
type VideoEnhancement ¶ added in v0.2.4
type VideoEnhancement struct {
Backend string `json:"backend,omitempty"`
State string `json:"state,omitempty"` // off, unavailable, ineligible, selected, starting, running, fallback, stopped
Reason string `json:"reason,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Quality int `json:"quality,omitempty"`
}
VideoEnhancement is an observable plan/run status, never a promise based solely on installed hardware. Only running means enhanced segments have actually been produced in the current run. Fallback always carries a reason.
type VideoEnhancementSupport ¶ added in v0.2.4
type VideoEnhancementSupport struct {
// SetupState is off, checking, installing, ready, or unavailable.
SetupState string `json:"setupState,omitempty"`
Backend string `json:"backend"`
Available bool `json:"available"`
Reason string `json:"reason,omitempty"`
Version string `json:"version,omitempty"`
Protocols []string `json:"protocols,omitempty"`
Active int `json:"active"`
}
VideoEnhancementSupport is detection, not successful execution. Its protocols are the transports verified for this backend version.
type Viewer ¶ added in v0.3.0
type Viewer = User
Viewer is the household member that owns per-viewer state. Its ID is the existing local auth_users ID, independent of any identity provider.
type ViewerActivity ¶
type ViewerActivity struct {
Title Title `json:"title"`
At time.Time `json:"at"`
Completed bool `json:"completed"`
Progress float64 `json:"progress"` // 0..1
}
ViewerActivity is one recent viewing.
type ViewerChoiceSummary ¶
type ViewerChoiceSummary struct {
Scope string `json:"scope"` // "title" or "show"
Active bool `json:"active"`
Label string `json:"label"`
Profile VersionProfile `json:"profile,omitempty"`
Selector string `json:"selector,omitempty"`
ReleaseID string `json:"releaseId,omitempty"`
}
ViewerChoiceSummary describes a viewer's remembered version choice for a title or its show, projected for frontends.
type ViewerInvalidator ¶ added in v0.2.7
type ViewerInvalidator interface{ Invalidate(userID int64) }
ViewerInvalidator exposes the optional Invalidate capability.
type ViewerLayout ¶
type ViewerLayout struct {
UserID int64 `json:"userId"`
Pages []LayoutPage `json:"pages"`
}
type ViewerStats ¶
type ViewerStats struct {
UserID int64 `json:"userId"`
LastActive time.Time `json:"lastActive,omitempty"`
Plays30d int `json:"plays30d"`
HoursWatched30d float64 `json:"hoursWatched30d"`
}
ViewerStats is a viewer's recent activity summary.
type VolumeRef ¶
type VolumeRef struct {
URL string `json:"url,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
KeepHeadersOnRedirect []string `json:"keepHeadersOnRedirect,omitempty"`
BlobRef string `json:"blobRef,omitempty"`
Size int64 `json:"size"`
}
VolumeRef locates one archive volume by URL or blobcache reference (spec §4.1).
type WarmProbeWaiter ¶ added in v0.2.52
type WarmProbeWaiter interface {
WaitWarmProbe(ctx context.Context, user *User, caps ClientCaps, key RatingKey, budget time.Duration) (MediaInfo, bool)
}
WarmProbeWaiter is optionally implemented by playback managers that can wait up to a bounded budget for an already-scheduled warm probe (PreResolve) to finish, so the first detail-page open can render the file's real audio and subtitle streams instead of an estimate. It never cancels the background warm-up when the budget expires.
type WarmProber ¶ added in v0.2.49
type WarmProber interface {
WarmProbeInfo(user *User, caps ClientCaps, key RatingKey) (MediaInfo, bool)
}
WarmProber is optionally implemented by playback managers that complete a speculative probe (Prewarm/PreResolve) before Play. WarmProbeInfo returns the probed media info a warm-up already produced for this user/client/key, so metadata and play-queue renders can list the file's real audio and subtitle tracks instead of the single invented audio track of the estimate. ok=false when no warm probe has completed (or it has expired). It never starts a probe or blocks on one in flight.
It complements ResumedTracks, which only covers a viewer's later opens: this covers the first open, once the detail-page warm-up has landed.
type WarmReadWindow ¶
type WarmReadWindow struct {
// contains filtered or unexported fields
}
WarmReadWindow retires startup speculation behind the actual media Range. It belongs to one source generation, never to a shared release.
func (*WarmReadWindow) Observe ¶
func (w *WarmReadWindow) Observe(off int64)
Observe records a media Range, excluding header/tail probes at the caller. A later backward seek lowers the floor so its new warming can proceed.
type WarmupSearchCacheRefiller ¶
type WarmupSearchCacheRefiller interface {
RefillWarmupSearchCache(*Title) <-chan struct{}
}
WarmupSearchCacheRefiller requests the same bounded search recovery as SearchCacheRefiller for unattended work. Its requests spend the warm-up allowance rather than the viewer detail allowance.
type WatchPage ¶
type WatchPage struct {
Page
Anchors map[RatingKey]WatchStatus
}
WatchPage carries the anchor clocks used to select next-up items. The row's own offset and counters remain separate from its show's selection anchor.
type WatchStatus ¶
type WatchStatus struct {
Key RatingKey `json:"key"`
ViewOffset time.Duration `json:"viewOffset"`
ViewCount int `json:"viewCount"`
LastViewedAt time.Time `json:"lastViewedAt,omitempty"`
LastRatedAt time.Time `json:"lastRatedAt,omitempty"`
UserRating float64 `json:"userRating,omitempty"` // 0-10
InWatchlist bool `json:"inWatchlist,omitempty"`
IsFavorite bool `json:"isFavorite,omitempty"` // Derived from the viewer’s favorites set.
IsNotInterested bool `json:"isNotInterested,omitempty"` // Derived from the viewer’s recommendation exclusions.
Duration time.Duration `json:"duration,omitempty"`
Reading *ReadingProgress `json:"reading,omitempty"`
UpdatedAt time.Time `json:"updatedAt"`
}
type XtreamPresentation ¶
type XtreamPresentation struct {
Category string `json:"category,omitempty"` // movie|series|live
Default *bool `json:"default,omitempty"` // optional manifest default hint (true when omitted)
}
XtreamPresentation describes how Xtream sees a library.
Source Files
¶
- align.go
- artwork.go
- background.go
- batch_watch.go
- bedtime.go
- browse_scope.go
- capabilities.go
- client_override.go
- client_profiles.go
- collectionspec.go
- copy_timeline.go
- customformats.go
- debrid.go
- descriptive_search.go
- detail_burst.go
- downloads.go
- encoder_input.go
- encoder_retirement.go
- episode_identity.go
- episode_numbering.go
- facet_id.go
- feed_verdict.go
- formats.go
- frontend.go
- frontend_host_policy.go
- hls_diagnostics.go
- hls_ladder.go
- homelayout.go
- hubcontext.go
- identity.go
- indexer_purpose.go
- interfaces.go
- keyframes.go
- kinditem.go
- kindplayback.go
- library.go
- library_predicate.go
- libraryfilter.go
- likes.go
- live_app.go
- local_response.go
- marked_playlists.go
- media_cap_wait.go
- media_snapshot.go
- metadata.go
- neutral_home.go
- onair.go
- ondemand.go
- person_credit.go
- personalhooks.go
- personalize.go
- personalize_owner.go
- playback.go
- playbackcore.go
- plex_part.go
- preroll.go
- prewarm.go
- provenance.go
- provider_lease.go
- quality_order.go
- range_response.go
- ratingkey.go
- read_retirement.go
- recovery_source.go
- recovery_start.go
- release.go
- release_rules.go
- repair.go
- resolution.go
- resolver.go
- row_provenance.go
- rule_normalize.go
- safer_rating.go
- search_category.go
- search_coverage.go
- search_memo.go
- session_activity.go
- session_policy.go
- sort_title.go
- source_label.go
- source_resource.go
- source_retirement.go
- source_revision.go
- source_revision_unix.go
- speculative.go
- streamkey.go
- title_dates.go
- trickplay.go
- trickplay_identity.go
- types.go
- variants.go
- vibesearch.go
- video_enhancement.go
- warm_read.go
- watch_page.go