scan

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: AGPL-3.0 Imports: 25 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 scan walks library folders and keeps the items table in sync with disk.

Index

Constants

View Source
const (
	ExtraTrailer         = "trailer"
	ExtraBehindTheScenes = "behindTheScenes"
	ExtraDeleted         = "deleted"
	ExtraFeaturette      = "featurette"
	ExtraInterview       = "interview"
	ExtraScene           = "scene"
	ExtraShort           = "short"
	ExtraOther           = "other"
)

The kinds of extra, as the API names them.

View Source
const (
	MinScanInterval = 15 * time.Minute
	MaxScanInterval = 7 * 24 * time.Hour
)

The intervals an admin can pick from, besides off. Shorter than MinScanInterval would rescan a big library on a network share before the last rescan finished.

View Source
const (
	MinWatchPoll = 10 * time.Second
	MaxWatchPoll = time.Hour
)

How often an admin can have polled folders checked.

View Source
const (
	MethodEvents  = "events"
	MethodPolling = "polling"
	MethodOff     = "off"
)

How a folder is being watched, for FolderWatch.Method.

View Source
const SettingScanInterval = "scan_interval"

SettingScanInterval is how often every library is rescanned in full, in seconds; "0" turns full rescans off. Unset, the server's MATINEE_SCAN_INTERVAL applies.

View Source
const SettingWatch = "library_watch"

SettingWatch holds the WatchMode.

View Source
const SettingWatchPoll = "watch_poll"

SettingWatchPoll is how often polled folders are checked, in seconds. Unset, the server's MATINEE_WATCH_POLL_INTERVAL applies.

Variables

View Source
var ErrAlreadyRunning = errors.New("scan already running")
View Source
var ErrSkip = errUnplayable

ErrSkip from Index leaves a file out, like one with nothing playable.

View Source
var ErrStopped = errors.New("scan stopped")

ErrStopped is the error of a scan an admin stopped.

ExtraKinds is the order extras are listed in.

Functions

func DailyEpisode added in v0.2.4

func DailyEpisode(season, episode int) string

DailyEpisode turns a daily show's season and episode back into its air date, as 2024-03-15.

func DailySeason added in v0.2.4

func DailySeason(n int) bool

DailySeason reports whether a season number is a daily show's year.

func Edition added in v0.2.1

func Edition(path string) string

Edition is the edition a video file's name says it is, such as "Director's Cut", or "" when it names none. A file named only "movie.mkv" takes its folder's.

func ExtraDirKind added in v0.2.1

func ExtraDirKind(name string) (string, bool)

ExtraDirKind says which kind of extra a folder holds, if any.

func ExtraFileKind added in v0.2.1

func ExtraFileKind(name string) (string, bool)

ExtraFileKind says which kind of extra a file's name marks it as, if any.

func ExtraName added in v0.2.1

func ExtraName(path string, titles ...string) string

ExtraName is what an extra is called on screen: its file name without the kind's suffix, unless that leaves only one of the title's names. Empty means it has no name of its own, so players call it by its kind.

func FolderTrailers

func FolderTrailers(dir string) []string

FolderTrailers lists the trailers in a show's or season's folder.

func IsExtraDir added in v0.2.1

func IsExtraDir(name string, nested bool) bool

IsExtraDir reports whether a folder holds extras. Only a Trailers folder counts right in a library's folder: there, "Shorts" or "Other" is more likely a group of titles than a title's extras. nested is whether the folder is inside a title's folder.

func IsExtraFile added in v0.2.1

func IsExtraFile(name string) bool

IsExtraFile reports whether a file name marks an extra.

func IsTrailerFile

func IsTrailerFile(name string) bool

IsTrailerFile reports whether a file name marks a trailer.

func KindNames

func KindNames() []string

KindNames lists the registered library kinds.

func MovieTrailers

func MovieTrailers(root, path string) []string

MovieTrailers lists the trailers for a movie file (see MovieExtras).

func Part added in v0.2.4

func Part(path string) (rest string, part int)

Part reads a movie file's part number from its name, and returns the name without it, so the parts of one movie share the rest. part is 0 when the name names no part. "Part" counts only after the year, as in "Heat.1995.Part1.avi", or in a file whose folder has the year, so "Deathly Hallows Part 1 (2010)" stays a title of its own.

func PartKey added in v0.2.4

func PartKey(path string) (key string, part int)

PartKey says which movie a file is a part of: files in the same folder whose names match but for the part. key is "" when the name names no part.

func ReadNFOs added in v0.2.4

func ReadNFOs(ctx context.Context, st *store.Store, lib store.Library) error

ReadNFOs applies the .nfo files next to a movie or TV library's files (see store.ApplyLocal): <file>.nfo or movie.nfo for a movie, <file>.nfo for an episode, and tvshow.nfo in a show's folder. Files whose .nfo hasn't changed since it was last read are left alone, so this is cheap to run after every scan.

func Register

func Register(k Kind)

Register adds a library kind. Built-in kinds register from init; plugins register theirs while the server runs.

func ShowFolders

func ShowFolders(root, episodePath string) (show, season string)

ShowFolders returns a show's folder and, when episodes are filed by season, the season's folder, given one of the episodes under it.

func Skip added in v0.2.7

func Skip(reason, group string) error

Skip from Index leaves a file out and says why, so admins are told (ScanReport.Skipped) instead of the file just not showing up. Reason is a short key the apps word, such as "arcade"; Group is what it's about, such as the folder the file is in.

func SkipOf added in v0.2.7

func SkipOf(err error) (reason, group string)

SkipOf is the reason and group of an error from Skip, or "" for others.

func SortExtras added in v0.2.1

func SortExtras(extras []Extra)

SortExtras puts extras in ExtraKinds order, then by file.

func TrailerName

func TrailerName(path string) string

TrailerName is what a trailer file is called on screen.

func Trailers added in v0.2.1

func Trailers(extras []Extra) []string

Trailers keeps the extras that are trailers.

func Unregister added in v0.1.1

func Unregister(name string)

Unregister removes a library kind, when a plugin is turned off. Libraries of that kind keep their items but aren't scanned.

func ValidScanInterval added in v0.2.4

func ValidScanInterval(d time.Duration) bool

ValidScanInterval says whether d is an interval an admin can pick.

func WithReason added in v0.2.4

func WithReason(ctx context.Context, r Reason) context.Context

WithReason marks the scans run with ctx as started by r.

Types

type BookFile added in v0.1.2

type BookFile struct {
	Author      string
	Book        string
	Series      string
	SeriesIndex *float64
	Year        int
	Narrators   []string
	Overview    string
	Part        string // the file's own title
	PartIndex   int
	Disc        int
	Whole       bool // the file is the whole book, chapters and all
	// The book's and author's own folders, for artwork and notes; empty
	// when the book or author has no folder of its own.
	BookDir, AuthorDir string
}

BookFile is what an audiobook file's place on disk and its tags say.

func ParseBookPath added in v0.1.2

func ParseBookPath(libraryRoot, path string) BookFile

ParseBookPath reads the author, series and book from the folders above a file, for files without tags.

type EpisodeInfo

type EpisodeInfo struct {
	Show    string
	Season  int
	Episode int
	// EndEpisode is the last episode of a file that holds several, such
	// as 2 in S01E01E02; 0 when it holds one.
	EndEpisode int
	Title      string // episode title when the name carries one
	// ShowYear is the year in the show's folder name, as in
	// "Doctor Who (2005)", which tells same-named shows apart; 0 when the
	// folder names none.
	ShowYear int
	// ShowIDs are the ids in the show's folder name, as in
	// "Breaking Bad {tvdb-81189}".
	ShowIDs mediaid.IDs
	// Absolute is the episode's number counted from the show's first, when
	// that's how the file is named ("Show - 0123"). The scanner files it as
	// season 1, episode Absolute until the show is matched online; then
	// it moves to the season it's in (see metadata.PlaceEpisodes).
	// Compact says the number might instead be a season and an episode
	// run together, as 104 for season 1, episode 4.
	Absolute int
	Compact  bool
	// AirDate is the day a daily show's episode aired, as 2024-03-15, when
	// that's how it's named. Its season is the year, and its episode the
	// month and day as one number (315), so a year's episodes sort by date.
	AirDate string
	OK      bool
}

EpisodeInfo is what an episode's path says about it.

func ParseEpisode

func ParseEpisode(libraryRoot, path string) EpisodeInfo

ParseEpisode understands "Show/Season 1/Show - S01E02 - Title.mkv", release-style "Show.Name.S01E02.720p.mkv", daily shows named by date ("Show/2024-03-15.mkv"), and, inside a season folder, names without a season ("Season 2/04 - Title.mkv", "Season 2/Episode 4.mkv"), and outside one, names numbered from the show's first episode ("Show - 0123.mkv", see EpisodeInfo.Absolute). The show name comes from the library folder layout when it's there, since file names are often abbreviated.

func ShowOf added in v0.2.4

func ShowOf(libraryRoot, path string) EpisodeInfo

ShowOf names the show a file in a TV library belongs to, from its folder, for files that don't name an episode, such as a special.

type Extra added in v0.2.1

type Extra struct {
	Path string
	Kind string
}

Extra is one extra's file and kind.

func FolderExtras added in v0.2.1

func FolderExtras(dir string) []Extra

FolderExtras lists the extras in a movie's, show's or season's folder: files named as extras, and the videos in folders for extras, two levels deep ("Extras/Deleted Scenes/Bank job.mkv"). An inner folder's kind wins.

func MovieExtras added in v0.2.1

func MovieExtras(root, path string) []Extra

MovieExtras lists a movie's extras. A movie in its own folder takes every extra there; one sharing the library folder with others only takes those named after it.

type File

type File struct {
	Library store.Library
	Root    string // the library folder the file was found under
	Path    string
	Info    fs.FileInfo
	Probe   probe.Result
}

File is one media file found during a scan.

type Finisher added in v0.1.2

type Finisher interface {
	Kind
	FinishScan(ctx context.Context, st *store.Store, lib store.Library) error
}

Finisher is a Kind with work to do once a scan has filed every file, such as adding up a book's parts.

type FolderWatch

type FolderWatch struct {
	Path   string `json:"path"`
	Method string `json:"method"`
	// Reason says why a folder is polled: "network share (cifs)", or that
	// change notifications couldn't be set up.
	Reason string `json:"reason,omitempty"`
}

FolderWatch tells admins how one library folder is watched.

type Kind

type Kind interface {
	Name() string
	Wants(path string) bool
	// Playable reports whether a probed file has what this library plays.
	// Files that don't are left out, along with folders holding nothing else.
	Playable(pr probe.Result) bool
	// Index files one file, creating any containers it lives in, and returns
	// the playable item. The scanner fills in the file and probe fields.
	Index(ctx context.Context, st *store.Store, f File) (store.Item, error)
}

Kind is a type of library: which files belong in it and how they're filed. Movies, TV, music and audiobooks are built in; library-type plugins register more.

func KindByName

func KindByName(name string) (Kind, bool)

KindByName returns a registered library kind.

type MovieInfo

type MovieInfo struct {
	Title string
	Year  int // 0 when unknown
}

MovieInfo is what a movie's file or folder name says about it.

func ParseMovie

func ParseMovie(path string) MovieInfo

ParseMovie reads "Title (Year)" or release-style "Title.Year.1080p.BluRay" from the file name, falling back to the folder name when the file is generic.

type Reason added in v0.2.4

type Reason string

Reason is what started a scan.

const (
	ReasonSchedule Reason = "schedule" // the periodic full rescan
	ReasonWatcher  Reason = "watcher"  // files that changed in a watched folder
	ReasonManual   Reason = "manual"   // an admin pressed Scan
	ReasonServer   Reason = "server"   // anything else, such as a new library or TMDB key
)

type Remote added in v0.1.7

type Remote interface {
	Kind
	Remote()
}

Remote is a Kind whose items aren't files in folders but come from elsewhere, such as podcasts from their feeds. Scanning a library of it refreshes it with Scanner.Refresh instead of walking folders.

type ScanReport added in v0.1.11

type ScanReport struct {
	Started    int64 `json:"started"` // milliseconds
	TookMs     int64 `json:"tookMs"`
	Added      int   `json:"added"`
	Updated    int   `json:"updated"`
	Removed    int   `json:"removed"`
	Replaced   int   `json:"replaced"`
	Failed     int   `json:"failed"`
	Unplayable int   `json:"unplayable"`
	// Skipped says why files were left out, where the library's kind said.
	Skipped []SkipCount `json:"skipped,omitempty"`
	Error   string      `json:"error,omitempty"`
	// Reason is what started it; Stopped says an admin stopped it before
	// it finished.
	Reason  Reason `json:"reason,omitempty"`
	Stopped bool   `json:"stopped,omitempty"`
}

ScanReport is how a library's last full scan went, for the admin dashboard.

type Scanner

type Scanner struct {
	Store  *store.Store
	Prober probe.Prober
	Log    *slog.Logger
	// AfterScan runs once a library scan finishes, e.g. to fetch metadata.
	AfterScan func(ctx context.Context, lib store.Library)
	// Added runs for each file a scan adds, e.g. to tell plugins.
	Added func(ctx context.Context, lib store.Library, itemID int64)
	// Refresh brings a library of a Remote kind, such as podcasts, up to
	// date; nil leaves them as they are.
	Refresh func(ctx context.Context, lib store.Library) (added, failed int, err error)
	// MissingGrace is how long a file that a scan of just some paths (the
	// watcher's) finds missing stays listed, waiting for the file that
	// takes its place. Download tools often delete the old copy first and
	// move the new one in later, and the watcher sees the two apart. Zero
	// removes missing files right away. A full scan always does, once it has
	// matched them with what replaced them (see store.Replacements).
	MissingGrace time.Duration
	// contains filtered or unexported fields
}

func (*Scanner) Reason added in v0.2.4

func (s *Scanner) Reason(libraryID int64) Reason

Reason says what started a library's running scan, "" when there's none.

func (*Scanner) Report added in v0.1.11

func (s *Scanner) Report(libraryID int64) (since time.Time, why Reason, last *ScanReport)

Report says since when a library is being scanned (zero when it isn't) and what started that, and how its last full scan went, if there was one since the server started.

func (*Scanner) Running

func (s *Scanner) Running(libraryID int64) bool

Running reports whether a library is being scanned right now.

func (*Scanner) Scan

func (s *Scanner) Scan(ctx context.Context, lib store.Library) (Stats, error)

Scan brings one library in line with its folders. Unchanged files (same size and mtime) are skipped, so rescans are cheap.

func (*Scanner) ScanAll

func (s *Scanner) ScanAll(ctx context.Context)

ScanAll scans every library, one at a time.

func (*Scanner) ScanPaths

func (s *Scanner) ScanPaths(ctx context.Context, lib store.Library, paths []string) (Stats, error)

ScanPaths brings just these files and folders of a library in line with disk: what's there is added or updated, and what's listed under a path that's gone is removed. The watcher uses it to pick up changes without walking the whole library.

func (*Scanner) Skipped added in v0.2.7

func (s *Scanner) Skipped(libraryID int64) []SkipCount

Skipped is what the library's last full scan left out, and why.

func (*Scanner) Start added in v0.1.16

func (s *Scanner) Start(ctx context.Context, lib store.Library) bool

Start scans a library in the background. The library counts as being scanned (Running) before Start returns, so whoever asked for the scan, and anyone polling for it to finish, never sees it idle before it has begun. It reports false when a scan of the library is already running.

func (*Scanner) Stop added in v0.2.4

func (s *Scanner) Stop(libraryID int64) bool

Stop stops a library's running scan, keeping what it found so far. A file call stuck on a network share that stopped answering ends only when the share answers or the kernel gives up on it. It reports false when the library isn't being scanned.

type Schedule added in v0.2.4

type Schedule struct {
	Scanner *Scanner
	// Default is how often until the admin changes it: MATINEE_SCAN_INTERVAL.
	Default time.Duration
	// Wait, when set, reports whether a rescan that's due should wait,
	// because something is playing; it starts once that's over.
	Wait func(ctx context.Context) bool
	// contains filtered or unexported fields
}

Schedule rescans every library in full every so often, to catch what the watcher can't, such as a file replaced in place on a share. The admin sets how often in Settings.

func (*Schedule) Interval added in v0.2.4

func (s *Schedule) Interval(ctx context.Context) (time.Duration, error)

Interval returns how often every library is rescanned; 0 means never.

func (*Schedule) Next added in v0.2.4

func (s *Schedule) Next() time.Time

Next says when the next full rescan starts; zero when they're off.

func (*Schedule) Run added in v0.2.4

func (s *Schedule) Run(ctx context.Context)

Run rescans every library once at startup, when rescans are on, and then every interval until ctx ends.

func (*Schedule) SetInterval added in v0.2.4

func (s *Schedule) SetInterval(ctx context.Context, d time.Duration) error

SetInterval changes how often every library is rescanned; 0 turns full rescans off. The next rescan is that long from now.

type Session added in v0.1.1

type Session interface {
	Kind
	BeginScan(ctx context.Context, lib store.Library) (end func())
}

Session is a Kind that sets something up for a whole scan, such as a plugin's sandbox. The scanner calls BeginScan before the first file and the function it returns after the last.

type SkipCount added in v0.2.7

type SkipCount struct {
	Reason  string `json:"reason"`
	Group   string `json:"group,omitempty"`
	Count   int    `json:"count"`
	Example string `json:"example,omitempty"` // one of the files, by name
}

SkipCount is how many files a scan left out for one reason.

type Stats

type Stats struct {
	Added, Updated, Unchanged, Removed, Failed int
	// Replaced counts files that took the place of a missing one (a better
	// copy, or the same file renamed or moved); the old item took the new
	// file and kept everyone's watch history.
	Replaced   int
	Unplayable int // files with no playable stream, left out
	// Skipped are the files a Kind left out with a reason (see Skip),
	// most first.
	Skipped []SkipCount
	Took    time.Duration
}

type TrackInfo

type TrackInfo struct {
	Artist string // the album's artist, which the album is filed under
	// TrackArtist is the track's own artist from its tags, when they name one.
	TrackArtist string
	Album       string
	Title       string
	Track       int
	Disc        int
	Year        int
}

TrackInfo is a music file's place in the library, from tags or folders.

func ParseTrackPath

func ParseTrackPath(libraryRoot, path string) TrackInfo

ParseTrackPath reads "Artist/Album/01 - Title.flac" for files without tags.

type Unprobed added in v0.1.1

type Unprobed interface {
	Kind
	Unprobed()
}

Unprobed is a Kind whose files aren't audio or video, such as a plugin's games. They aren't run through ffprobe, so Playable isn't asked.

type WatchMode

type WatchMode string

WatchMode says how library folders are watched.

const (
	// WatchAuto uses change notifications on local disks and polling on
	// network shares.
	WatchAuto WatchMode = "auto"
	// WatchPoll polls every folder, for disks that look local but aren't,
	// like a share mounted inside a container's own filesystem.
	WatchPoll WatchMode = "poll"
	// WatchOff leaves it to the periodic rescan.
	WatchOff WatchMode = "off"
)

type Watcher

type Watcher struct {
	Scanner *Scanner
	Log     *slog.Logger
	// PollInterval is how often polled folders are checked until an admin
	// picks in Settings (see Poll). A pass that takes long (a big library on
	// a slow share) waits longer, so polling never keeps the share busy.
	PollInterval time.Duration
	// Quiet is how long a path must hold still before it's scanned, so a
	// file still being copied isn't read half way.
	Quiet time.Duration
	// contains filtered or unexported fields
}

func NewWatcher

func NewWatcher(s *Scanner, log *slog.Logger) *Watcher

func (*Watcher) Mode

func (w *Watcher) Mode(ctx context.Context) (WatchMode, error)

Mode reads the admin's WatchMode.

func (*Watcher) Poll added in v0.2.4

func (w *Watcher) Poll(ctx context.Context) (time.Duration, error)

Poll is how often polled folders are checked: the admin's pick, or PollInterval.

func (*Watcher) Reload

func (w *Watcher) Reload()

Reload starts over with the current libraries and mode. Call it when either changes.

func (*Watcher) Run

func (w *Watcher) Run(ctx context.Context)

Run watches every library until ctx ends.

func (*Watcher) SetMode

func (w *Watcher) SetMode(ctx context.Context, m WatchMode) error

func (*Watcher) SetPoll added in v0.2.4

func (w *Watcher) SetPoll(ctx context.Context, d time.Duration) error

SetPoll changes how often polled folders are checked, from the next check.

func (*Watcher) Status

func (w *Watcher) Status(libraryID int64) []FolderWatch

Status says how each folder of a library is watched; nil until the watcher has set it up.

Jump to

Keyboard shortcuts

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