mediaservers

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: AGPL-3.0 Imports: 28 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 mediaservers talks to the media servers people watch their library with (Plex, Jellyfin and Emby): it tests a connection, asks the server to rescan the library folder a new file landed in, and finds a title on the server so the web UI can link to it ("Watch in Plex").

It stands on its own: it knows nothing about downloads, the queue or the API, and is handed plain file paths and TMDB ids by its callers.

Index

Constants

View Source
const MaxSubnets = 8

MaxSubnets is how many networks one search covers at most.

View Source
const PlexTVURL = "https://plex.tv"

PlexTVURL is plex.tv's address.

Variables

View Source
var CommonSubnets = []string{"192.168.0.0/24", "192.168.1.0/24", "10.0.0.0/24", "10.0.1.0/24", "172.16.0.0/24"}

CommonSubnets are home networks scanned besides Mediarium's own.

View Source
var DefaultProbes = []Probe{{Port: 32400, Scheme: "http", Plex: true}, {Port: 8096, Scheme: "http"}}

DefaultProbes are Plex's and Jellyfin/Emby's standard http ports.

View Source
var ErrPlexPINExpired = errors.New("plex pin expired")

ErrPlexPINExpired means the PIN is gone: it timed out or was never ours.

View Source
var (
	// ErrQuickConnectExpired means the Quick Connect code is no longer valid.
	ErrQuickConnectExpired = errors.New("quick connect code expired")
)
View Source
var NeighbourNames = []string{"host.docker.internal", "host.containers.internal", "jellyfin", "plex", "emby"}

NeighbourNames are host names tried besides the networks when a search has no networks of its own: Docker's name for the machine it runs on, and the usual container names of the three servers on the same Docker network.

Functions

func HomeURL

func HomeURL(s Server) string

HomeURL is where "Open my media server" goes.

func MapPath

func MapPath(path string, mappings []PathMapping) string

MapPath rewrites path from Mediarium's view to the media server's using the longest matching mapping. Without a match it returns path unchanged. The rest of the path takes the separator style of the mapping's target, so a Windows Plex server gets backslashes.

func MarkAdded

func MarkAdded(found []Found, saved []Server)

MarkAdded sets AlreadyAdded on every found server that is already saved: the same server id, or the same address.

func NewID

func NewID() (string, error)

NewID returns a random id for a pending sign-in.

func NormalizeURL

func NormalizeURL(raw string) (string, error)

NormalizeURL checks an http(s) address and returns it without a trailing slash. An address typed without a scheme gets http://.

func PlexAuthURL

func PlexAuthURL(clientID, code string) string

PlexAuthURL is the app.plex.tv page where the person approves a PIN.

func PrivateIPv4

func PrivateIPv4(ip net.IP) bool

PrivateIPv4 reports whether ip is an IPv4 address on a private network: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, or 100.64.0.0/10 (carrier-grade NAT, which Tailscale uses).

Types

type Client

type Client struct {
	HTTP    *http.Client
	Version string // Mediarium's version, sent to Jellyfin in its auth header
	// MaxBytes is the most of an answer that is read; 0 means maxAnswerBytes.
	MaxBytes int64
}

Client makes the HTTP calls to media servers. It holds no per-server state; caching lives in Finder and Refresher.

func NewClient

func NewClient(version string) *Client

NewClient returns a client with sensible timeouts.

func (*Client) ConnectPlex

func (c *Client) ConnectPlex(ctx context.Context, r PlexResource, preferred string) (Server, TestResult, error)

ConnectPlex tries a server's addresses in Candidates order with its access token and returns the first one that works, as a server ready to save.

func (*Client) Find

func (c *Client) Find(ctx context.Context, s Server, kind MediaKind, tmdbID int) (item Item, found bool, err error)

Find looks a title up by its TMDB id. found is false when the server doesn't have it.

func (*Client) PublicInfo

func (c *Client) PublicInfo(ctx context.Context, kind Kind, baseURL string) (PublicInfo, error)

PublicInfo asks a Jellyfin or Emby server who it is. kind is what the person chose; a server of the other kind is a UserError saying so.

func (*Client) QuickConnectCheck

func (c *Client) QuickConnectCheck(ctx context.Context, base, deviceID, secret string) (bool, error)

QuickConnectCheck reports whether the code has been approved yet. An expired code is ErrQuickConnectExpired.

func (*Client) QuickConnectFinish

func (c *Client) QuickConnectFinish(ctx context.Context, base, deviceID, secret string) (Server, error)

QuickConnectFinish trades an approved code for an access token and returns the server ready to save.

func (*Client) QuickConnectStart

func (c *Client) QuickConnectStart(ctx context.Context, baseURL, deviceID string) (base, code, secret string, err error)

QuickConnectStart asks a Jellyfin server for a Quick Connect code. The person enters code in a Jellyfin app they are signed in to; secret is how Mediarium then asks whether they did, and must stay on the server side.

func (*Client) RefreshAll

func (c *Client) RefreshAll(ctx context.Context, s Server) error

RefreshAll asks the server to scan every library.

func (*Client) RefreshFolders

func (c *Client) RefreshFolders(ctx context.Context, s Server, kind MediaKind, folders []string) ([]string, error)

RefreshFolders asks the server to scan the given folders (as Mediarium sees them; the server's path mapping is applied here). It returns a short description of each scan it started, for the log.

func (*Client) SignIn

func (c *Client) SignIn(ctx context.Context, kind Kind, baseURL, deviceID, username, password string) (Server, error)

SignIn signs in to Jellyfin or Emby with a username and password and returns the server, holding the access token it got, ready to save. The password is not kept anywhere. deviceID identifies this install.

func (*Client) Test

func (c *Client) Test(ctx context.Context, s Server) (TestResult, error)

Test checks the address and token and lists the server's libraries.

type Discoverer

type Discoverer struct {
	Budget        time.Duration // whole search; default 10s
	BroadcastWait time.Duration // how long to listen for broadcast answers; default 2s, negative skips broadcasts
	DialTimeout   time.Duration // per address and port; default 600ms
	Workers       int           // addresses tried at once; default 256 (8 networks x 254 hosts x 2 ports fit the budget even when nothing answers)
	Probes        []Probe       // default DefaultProbes

	// Where the broadcasts go ("host:port"); empty means the standard
	// addresses plus every local network's broadcast address.
	EmbyTargets []string
	PlexTargets []string
	// contains filtered or unexported fields
}

Discoverer finds media servers. The zero value is ready to use; the fields exist so tests can point it at local fakes.

func (*Discoverer) DefaultSubnets

func (d *Discoverer) DefaultSubnets() []*net.IPNet

DefaultSubnets is what a search without networks covers: Mediarium's own private networks (a larger one narrowed to the /24 around Mediarium's own address), then CommonSubnets, then Mediarium's own Docker-range networks (172.16.0.0/12), at most MaxSubnets in all. Docker networks come last because a machine that runs Docker has many of them and they would crowd the home network out.

func (*Discoverer) Discover

func (d *Discoverer) Discover(ctx context.Context, subnets []*net.IPNet) Discovery

Discover searches the given networks and listens for broadcast answers at the same time. With no networks it searches DefaultSubnets and also tries the default gateway and the NeighbourNames. It never fails: whatever was found within the time budget is returned.

func (*Discoverer) ParseSubnets

func (d *Discoverer) ParseSubnets(in []string) ([]*net.IPNet, error)

ParseSubnets checks networks typed by the person: IPv4, private, a /24 or smaller, at most MaxSubnets. A plain address counts as that one address. Problems are UserErrors. Duplicates are dropped.

type Discovery

type Discovery struct {
	Found   []Found  `json:"found"`
	Scanned []string `json:"scanned"` // the networks scanned, as CIDR
	Note    string   `json:"note,omitempty"`
}

Discovery is the outcome of one search.

type Finder

type Finder struct {

	// TTL is how long an answer is kept; ErrorTTL how long a failed lookup
	// is (so a server that is down isn't asked on every page view).
	TTL      time.Duration
	ErrorTTL time.Duration
	// contains filtered or unexported fields
}

Finder finds titles on media servers by TMDB id, remembering answers for a few minutes so opening a title page doesn't query every server each time.

func NewFinder

func NewFinder(client *Client) *Finder

NewFinder returns a finder that keeps answers for five minutes.

func (*Finder) Invalidate

func (f *Finder) Invalidate()

Invalidate forgets every cached answer (after an import, or when servers change).

func (f *Finder) Links(ctx context.Context, servers []Server, kind MediaKind, tmdbID int) []Link

Links looks the title up on every enabled server at once and returns the servers that have it, in server order. A server that can't be asked is left out (and logged), never an error for the page.

type Found

type Found struct {
	Kind         Kind   `json:"kind"`
	Name         string `json:"name"`
	Address      string `json:"address"` // base URL, e.g. http://192.168.1.10:32400
	Version      string `json:"version,omitempty"`
	ID           string `json:"id,omitempty"` // Plex machineIdentifier / Jellyfin or Emby server Id
	AlreadyAdded bool   `json:"alreadyAdded"`
	Via          string `json:"via"` // "broadcast" | "scan"
}

Found is one media server that answered.

type Item

type Item struct {
	ID     string // Plex ratingKey / Jellyfin or Emby item Id
	URL    string // where to open it
	AppURL string // Plex only: the same item on app.plex.tv
}

Item is a title found on a server.

type Kind

type Kind string

Kind is the type of media server.

const (
	KindPlex     Kind = "plex"
	KindJellyfin Kind = "jellyfin"
	KindEmby     Kind = "emby"
)

func ParseKind

func ParseKind(s string) (Kind, bool)

ParseKind accepts a kind in any case.

func (Kind) Label

func (k Kind) Label() string

Label is the product name as people know it.

type Library

type Library struct {
	ID        string   `json:"id"`
	Title     string   `json:"title"`
	Type      string   `json:"type"` // movie | show (Plex); movies | tvshows | ... (Jellyfin/Emby)
	Locations []string `json:"locations"`
}

Library is one library (Plex "section", Jellyfin/Emby "virtual folder").

type Link struct {
	ServerID int64  `json:"serverId"`
	Name     string `json:"name"`
	Kind     Kind   `json:"kind"`
	URL      string `json:"url"`
	AppURL   string `json:"appUrl,omitempty"` // Plex: the same item on app.plex.tv
}

Link is one place a title (or the server itself) can be opened.

func HomeLinks(servers []Server) []Link

HomeLinks lists "Open my media server" links for the enabled servers.

type MediaKind

type MediaKind string

MediaKind is what was imported or is being looked up.

const (
	MediaMovie MediaKind = "movie"
	MediaTV    MediaKind = "tv"
	// MediaMusic is only ever refreshed (an album folder was imported); it
	// has no TMDB id, so it is never looked up by ParseMediaKind or Find.
	MediaMusic MediaKind = "music"
)

func ParseMediaKind

func ParseMediaKind(s string) (MediaKind, bool)

ParseMediaKind accepts "movie" or "tv" (also "series"/"show").

type PathMapping

type PathMapping struct {
	From string `json:"from"`
	To   string `json:"to"`
}

PathMapping rewrites a folder as Mediarium sees it (From) into the same folder as the media server sees it (To), for when the two run in different containers or machines with the library mounted in different places.

func NormalizePathMap

func NormalizePathMap(in []PathMapping) ([]PathMapping, error)

NormalizePathMap drops empty rows, trims whitespace and trailing separators, and rejects a row that has only one side.

type Pending

type Pending[T any] struct {
	TTL time.Duration
	Now func() time.Time // time.Now; tests replace it
	Max int              // most entries kept at once; the oldest go first (default 64)
	// contains filtered or unexported fields
}

Pending holds sign-ins in progress (a Plex PIN, a Quick Connect code) in memory only, each for a limited time. What they hold (account tokens, Quick Connect secrets) never goes to the browser or the database.

func (*Pending[T]) Delete

func (p *Pending[T]) Delete(key string)

Delete forgets key.

func (*Pending[T]) Get

func (p *Pending[T]) Get(key string) (T, bool)

Get returns the value under key, unless it expired.

func (*Pending[T]) Put

func (p *Pending[T]) Put(key string, v T)

Put stores v under key, replacing what was there.

func (*Pending[T]) Take

func (p *Pending[T]) Take(key string) (T, bool)

Take returns the value under key and removes it, so only one caller gets it.

type PlexAddress

type PlexAddress struct {
	URI   string `json:"uri"`
	Local bool   `json:"local"`
}

PlexAddress is one address to reach a Plex server at.

type PlexConnection

type PlexConnection struct {
	Protocol string `json:"protocol"`
	Address  string `json:"address"`
	Port     int    `json:"port"`
	URI      string `json:"uri"`
	Local    bool   `json:"local"`
	Relay    bool   `json:"relay"`
	IPv6     bool   `json:"IPv6"`
}

PlexConnection is one address a Plex server can be reached at.

type PlexPIN

type PlexPIN struct {
	ID        int64  `json:"id"`
	Code      string `json:"code"`
	AuthToken string `json:"authToken"` // empty until the person approves the PIN
	ExpiresIn int    `json:"expiresIn"` // seconds
}

PlexPIN is a PIN as plex.tv reports it.

type PlexResource

type PlexResource struct {
	Name             string           `json:"name"`
	Product          string           `json:"product"`
	ProductVersion   string           `json:"productVersion"`
	ClientIdentifier string           `json:"clientIdentifier"` // the server's machineIdentifier
	Provides         string           `json:"provides"`
	Owned            bool             `json:"owned"`
	AccessToken      string           `json:"accessToken"`
	HTTPSRequired    bool             `json:"httpsRequired"`
	Connections      []PlexConnection `json:"connections"`
}

PlexResource is one server on a Plex account.

func (PlexResource) Addresses

func (r PlexResource) Addresses() []PlexAddress

Addresses lists the server's addresses in the order Candidates tries them without a preference: local ones first, relays left out.

func (PlexResource) Candidates

func (r PlexResource) Candidates(preferred string) []string

Candidates lists the addresses to try for this server, best first: preferred (when it is one of the server's addresses), then the local ones (the plex.direct https address, then plain http on the same IP, which works where DNS rebinding protection blocks plex.direct), then the remote ones. Relays are never used.

func (PlexResource) HasAddress

func (r PlexResource) HasAddress(u string) bool

HasAddress reports whether u is one of the addresses Candidates lists.

type PlexTV

type PlexTV struct {
	HTTP     *http.Client
	BaseURL  string // PlexTVURL; tests point it at a fake
	ClientID string // this install's X-Plex-Client-Identifier; must stay the same for a PIN's lifetime
	Version  string
}

PlexTV talks to plex.tv.

func (*PlexTV) CheckPIN

func (p *PlexTV) CheckPIN(ctx context.Context, id int64) (PlexPIN, error)

CheckPIN reads a PIN back; AuthToken is set once it was approved. A PIN plex.tv no longer knows is ErrPlexPINExpired.

func (*PlexTV) CreatePIN

func (p *PlexTV) CreatePIN(ctx context.Context) (PlexPIN, error)

CreatePIN asks plex.tv for a new PIN.

func (*PlexTV) Servers

func (p *PlexTV) Servers(ctx context.Context, accountToken string) ([]PlexResource, error)

Servers lists the Plex servers the account can use, owned or shared with it.

type Probe

type Probe struct {
	Port   int
	Scheme string // http | https
	Plex   bool   // Plex (/identity) rather than Jellyfin/Emby (/System/Info/Public)
}

Probe is one port the scan tries on every address.

type PublicInfo

type PublicInfo struct {
	Kind    Kind
	Name    string
	Version string
	ID      string
}

PublicInfo is what a Jellyfin or Emby server tells anyone who asks, without signing in (GET /System/Info/Public).

type Refresher

type Refresher struct {

	// Delay is how long to wait for more imports after the last one; MaxWait
	// caps the total wait from the first one.
	Delay   time.Duration
	MaxWait time.Duration
	// OnDone, when set, runs after each round of refreshes (the API uses it
	// to forget cached "Watch in" lookups, since a new title may now be
	// there).
	OnDone func()
	// contains filtered or unexported fields
}

Refresher asks media servers to rescan the folders new files were imported into. Imports are collected for a short while first, so a season pack (or several downloads finishing together) causes one scan per folder rather than one per file. It runs in the background and never reports back to the import: a media server that is down only shows up in the log and on the dashboard.

func NewRefresher

func NewRefresher(store ServerStore, client *Client) *Refresher

NewRefresher returns a refresher with a 15-second quiet period.

func (*Refresher) Flush

func (r *Refresher) Flush()

Flush runs any waiting refresh now and waits for it to finish.

func (*Refresher) Imported

func (r *Refresher) Imported(kind MediaKind, files ...string)

Imported records that files were imported; the folders holding them are scanned once things have been quiet for Delay.

type Repo

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

Repo stores media servers. The token is kept encrypted with the app's secret key, like every other credential.

func NewRepo

func NewRepo(db *sql.DB, box *crypto.Box) *Repo

func (*Repo) Create

func (r *Repo) Create(s Server) (Server, error)

Create saves a new server and returns it with its id.

func (*Repo) Delete

func (r *Repo) Delete(id int64) error

Delete removes a server; deleting one that doesn't exist is sql.ErrNoRows.

func (*Repo) Get

func (r *Repo) Get(id int64) (Server, error)

Get returns one server, or an error wrapping sql.ErrNoRows.

func (*Repo) List

func (r *Repo) List() ([]Server, error)

List returns every server in the order they were added.

func (*Repo) RecordCheck

func (r *Repo) RecordCheck(id int64, serverID string, checkErr error) error

RecordCheck stores the outcome of a test or refresh: a nil err clears the last error. A non-empty serverID (learned from a good test) is saved too.

func (*Repo) Update

func (r *Repo) Update(s Server) (Server, error)

Update replaces a server's settings. The caller fills Token (an empty one is stored as empty); the last test result and server id are kept unless the address, kind or token changed, in which case they are cleared. The server id itself only changes through RecordCheck.

type Server

type Server struct {
	ID                 int64
	Name               string
	Kind               Kind
	BaseURL            string // how Mediarium reaches the server
	PublicURL          string // what people open in their browser; empty means BaseURL
	Token              string // Plex token or Jellyfin/Emby API key (plain text in memory only)
	Enabled            bool
	RefreshAfterImport bool
	PathMap            []PathMapping
	ServerID           string // Plex machineIdentifier or Jellyfin/Emby server Id
	LastError          string
	LastCheckedAt      time.Time // zero when never checked
}

Server is one configured media server.

func FindSaved

func FindSaved(saved []Server, kind Kind, serverID, address string) (Server, bool)

FindSaved finds the saved server that is the same as the one described: the same server id, or the same address (scheme and trailing slash aside). A non-empty kind must match too.

func (Server) WebURL

func (s Server) WebURL() string

WebURL is the address people open, without a trailing slash.

type ServerStore

type ServerStore interface {
	List() ([]Server, error)
	RecordCheck(id int64, serverID string, checkErr error) error
}

ServerStore is what the Refresher needs from the Repo.

type TestResult

type TestResult struct {
	ServerName string    `json:"serverName,omitempty"`
	Version    string    `json:"version,omitempty"`
	ServerID   string    `json:"serverId,omitempty"` // Plex machineIdentifier / Jellyfin or Emby server Id
	Libraries  []Library `json:"libraries"`
}

TestResult is what a successful connection test learned about the server.

type UserError

type UserError struct {
	Message string
	Err     error // the underlying cause, for logs; may be nil
}

UserError is a problem worth showing to the person as it is: a wrong token, an address that doesn't answer, a server of another kind.

func (*UserError) Error

func (e *UserError) Error() string

func (*UserError) Unwrap

func (e *UserError) Unwrap() error

Jump to

Keyboard shortcuts

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