scheduler

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package scheduler provides the core scheduling engine for Schedularr.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FilterPrograms

func FilterPrograms(programs []tunarr.Program, f Filter) ([]tunarr.Program, error)

FilterPrograms filters a list of programs based on the provided filter criteria.

Types

type Block

type Block struct {
	Type                       BlockType `mapstructure:"type" yaml:"type" json:"type"` // "filter" or "series", default "filter"
	Name                       string    `mapstructure:"name" yaml:"name" json:"name"`
	Cron                       string    `mapstructure:"cron" yaml:"cron" json:"cron"`             // Cron expression for start time
	Duration                   int       `mapstructure:"duration" yaml:"duration" json:"duration"` // Duration in minutes
	Filter                     Filter    `mapstructure:"filter" yaml:"filter" json:"filter,omitempty"`
	ChannelID                  string    `mapstructure:"channel_id" yaml:"channel_id" json:"channel_id"`
	Priority                   int       `mapstructure:"priority" yaml:"priority" json:"priority"` // Higher priority overrides overlapping blocks
	MaxDurationOverflowMinutes int       ``                                                        // Max minutes a block's actual duration can exceed its planned duration
	/* 128-byte string literal not displayed */
	Filler   FillerConfig   `mapstructure:"filler" yaml:"filler" json:"filler,omitempty"`                 // Filler content configuration
	Series   []SeriesConfig `mapstructure:"series" yaml:"series" json:"series,omitempty"`                 // For BlockTypeSeries
	Fallback SeriesFallback `mapstructure:"fallback" yaml:"fallback,omitempty" json:"fallback,omitempty"` // For BlockTypeSeries
}

Block defines a scheduled programming block

type BlockType

type BlockType string

BlockType defines the type of scheduling block

const (
	// BlockTypeFilter schedules content based on filter criteria
	BlockTypeFilter BlockType = "filter"
	// BlockTypeSeries schedules specific series in sequential order
	BlockTypeSeries BlockType = "series"
)

type CompletionAction

type CompletionAction string

CompletionAction defines what to do when a series completes all episodes

const (
	// CompletionActionContinue keeps the series in the block but marks it complete (default)
	CompletionActionContinue CompletionAction = "continue"
	// CompletionActionRestart restarts the series from the beginning
	CompletionActionRestart CompletionAction = "restart"
	// CompletionActionDisable removes the series from future scheduling
	CompletionActionDisable CompletionAction = "disable"
)

type Config

type Config struct {
	Blocks []Block `mapstructure:"blocks" yaml:"blocks" json:"blocks"`
}

Config holds the scheduling configuration

type Engine

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

Engine is the scheduling engine that generates programming schedules.

func NewEngine

func NewEngine(client *tunarr.Client, blocks []Block, store StateStore, logger *slog.Logger, loc *time.Location) *Engine

NewEngine creates a new scheduling engine with the given Tunarr client and scheduling blocks, using the default 7-day history window. Callers that need a configured window (e.g. service.NewRunner, which threads through maintenance.history_retention) should use NewEngineWithOptions instead.

func NewEngineWithOptions

func NewEngineWithOptions(client *tunarr.Client, blocks []Block, store StateStore, opts EngineOptions) *Engine

NewEngineWithOptions creates a new scheduling engine with optional configuration. Any zero-valued field in opts falls back to the same default NewEngine uses: opts.Logger -> slog.Default(), opts.Location -> time.Local, opts.HistoryWindow -> defaultHistoryWindow (7 days).

func (*Engine) Commit

func (e *Engine) Commit() error

Commit persists all pending state changes to the store.

func (*Engine) GenerateForTimeRange

func (e *Engine) GenerateForTimeRange(start, end time.Time, availablePrograms []tunarr.Program) (map[string][]ScheduledSlot, error)

GenerateForTimeRange generates a schedule for the given window with priority-based conflict resolution. It returns a map of ChannelID -> []ScheduledSlot.

func (*Engine) PlanBlock

func (e *Engine) PlanBlock(block Block, availablePrograms []tunarr.Program) ([]tunarr.Program, error)

PlanBlock generates a list of programs to fill the block's duration

type EngineOptions

type EngineOptions struct {
	// HistoryWindow bounds both the in-memory dedup check (filterByHistory)
	// and, via Commit's CleanupScheduleHistory call, how much of the
	// persisted schedule_history table survives each apply. service.Runner
	// sets this from the maintenance.history_retention config key so the
	// two stay coherent: GET /history?days=N (api/openapi.yaml, 1..90) can
	// only ever return data as far back as this window allows -- a wider
	// history_retention is required to actually query a wider days range.
	// Zero uses defaultHistoryWindow (7 days).
	HistoryWindow time.Duration
	Logger        *slog.Logger
	Location      *time.Location
}

EngineOptions contains optional configuration for the scheduling engine.

type FallbackMode

type FallbackMode string

FallbackMode defines how to handle empty time in a series block

const (
	// FallbackModeRedistribute redistributes remaining time to other series
	FallbackModeRedistribute FallbackMode = "redistribute"
	// FallbackModeFiller fills remaining time with content matching FillerFilter
	FallbackModeFiller FallbackMode = "filler"
)

type FillerConfig

type FillerConfig struct {
	Enabled       bool   `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                                   // Whether to use filler content
	FillerListID  string `mapstructure:"filler_list_id" yaml:"filler_list_id" json:"filler_list_id,omitempty"`    // ID of filler list to use
	MaxFillerTime int    `mapstructure:"max_filler_time" yaml:"max_filler_time" json:"max_filler_time,omitempty"` // Max minutes of filler allowed (0 = unlimited)
	MinGapTime    int    `mapstructure:"min_gap_time" yaml:"min_gap_time" json:"min_gap_time,omitempty"`          // Minimum gap (minutes) before adding filler
}

FillerConfig defines filler content configuration for a block

type Filter

type Filter struct {
	TitlePattern string   `mapstructure:"title_pattern" yaml:"title_pattern" json:"title_pattern,omitempty"`
	Genres       []string `mapstructure:"genres" yaml:"genres" json:"genres,omitempty"`
	Ratings      []string `mapstructure:"ratings" yaml:"ratings" json:"ratings,omitempty"`
	YearFrom     int      `mapstructure:"year_from" yaml:"year_from" json:"year_from,omitempty"`
	YearTo       int      `mapstructure:"year_to" yaml:"year_to" json:"year_to,omitempty"`
	MinDuration  int      `mapstructure:"min_duration" yaml:"min_duration" json:"min_duration,omitempty"` // in minutes
	MaxDuration  int      `mapstructure:"max_duration" yaml:"max_duration" json:"max_duration,omitempty"` // in minutes
	Tags         []string `mapstructure:"tags" yaml:"tags" json:"tags,omitempty"`
}

Filter defines criteria for selecting content

type ScheduleHistory

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

ScheduleHistory tracks what content has been scheduled to prevent repetition

func NewScheduleHistory

func NewScheduleHistory(window time.Duration) *ScheduleHistory

NewScheduleHistory creates a new schedule history tracker

func (*ScheduleHistory) RecordPrograms

func (sh *ScheduleHistory) RecordPrograms(programs []tunarr.Program, channelID, blockName string, scheduledAt time.Time)

RecordPrograms records multiple programs as scheduled

func (*ScheduleHistory) RecordScheduled

func (sh *ScheduleHistory) RecordScheduled(programID, channelID, blockName string, scheduledAt time.Time)

RecordScheduled records that a program was scheduled

func (*ScheduleHistory) WasRecentlyScheduled

func (sh *ScheduleHistory) WasRecentlyScheduled(programID string, channelID string) bool

WasRecentlyScheduled checks if a program was scheduled within the tracking window

func (*ScheduleHistory) Window

func (sh *ScheduleHistory) Window() time.Duration

Window returns the configured tracking window for history entries.

type ScheduleHistoryEntry

type ScheduleHistoryEntry struct {
	ProgramID   string    `db:"program_id"`
	ChannelID   string    `db:"channel_id"`
	ScheduledAt time.Time `db:"scheduled_at"`
	BlockName   string    `db:"block_name"`
}

ScheduleHistoryEntry represents a single program that was scheduled.

type ScheduledSlot

type ScheduledSlot struct {
	StartTime time.Time
	EndTime   time.Time
	Block     Block
	Programs  []tunarr.Program
}

ScheduledSlot represents a scheduled time slot with its block and priority

type SeriesConfig

type SeriesConfig struct {
	ShowTitle        string           `mapstructure:"show_title" yaml:"show_title" json:"show_title"`
	EpisodesPerBlock int              `mapstructure:"episodes_per_block" yaml:"episodes_per_block" json:"episodes_per_block"`
	StartSeason      int              `mapstructure:"start_season" yaml:"start_season" json:"start_season,omitempty"`    // Optional: override start point
	StartEpisode     int              `mapstructure:"start_episode" yaml:"start_episode" json:"start_episode,omitempty"` // Optional: override start point
	OnComplete       CompletionAction `mapstructure:"on_complete" yaml:"on_complete" json:"on_complete,omitempty"`       // Action when series completes (default: continue)
	SkipEpisodes     []string         `mapstructure:"skip_episodes" yaml:"skip_episodes" json:"skip_episodes,omitempty"` // Episodes to skip (format: "S01E05", "S02E10")
	MaxRuns          int              `mapstructure:"max_runs" yaml:"max_runs" json:"max_runs,omitempty"`                // Max times to run through series (0 = unlimited)
}

SeriesConfig defines configuration for a specific series in a block

type SeriesFallback

type SeriesFallback struct {
	Mode         FallbackMode `mapstructure:"mode" yaml:"mode" json:"mode,omitempty"`
	FillerFilter Filter       `mapstructure:"filler_filter" yaml:"filler_filter" json:"filler_filter,omitempty"` // Used if Mode is Filler
}

SeriesFallback defines fallback behavior when series content runs out or doesn't fill duration

type SeriesState

type SeriesState struct {
	ShowTitle      string     `json:"show_title" db:"show_title"`           // Primary key (or part of it)
	CurrentSeason  int        `json:"current_season" db:"current_season"`   // Next season to air
	CurrentEpisode int        `json:"current_episode" db:"current_episode"` // Next episode to air
	Completed      bool       `json:"completed" db:"completed"`             // True if all available episodes have aired
	LastAired      *time.Time `json:"last_aired" db:"last_aired"`           // Timestamp of last successful schedule (nullable)
	RunCount       int        `json:"run_count" db:"run_count"`             // Number of times series has been completed (for restart tracking)
	Disabled       bool       `json:"disabled" db:"disabled"`               // True if series has been disabled due to completion
}

SeriesState tracks the playback progress of a specific series.

type StateStore

type StateStore interface {
	GetSeriesState(ctx context.Context, showTitle string) (*SeriesState, error)
	UpdateSeriesState(ctx context.Context, state *SeriesState) error
	RecordScheduleHistory(ctx context.Context, entries []ScheduleHistoryEntry) error
	WasRecentlyScheduled(ctx context.Context, programID, channelID string, window time.Duration) (bool, error)
	CleanupScheduleHistory(ctx context.Context, window time.Duration) (int64, error)
}

StateStore defines the interface for persisting series state.

Jump to

Keyboard shortcuts

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