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
- Variables
- func HomeURL(s Server) string
- func MapPath(path string, mappings []PathMapping) string
- func MarkAdded(found []Found, saved []Server)
- func NewID() (string, error)
- func NormalizeURL(raw string) (string, error)
- func PlexAuthURL(clientID, code string) string
- func PrivateIPv4(ip net.IP) bool
- type Client
- func (c *Client) ConnectPlex(ctx context.Context, r PlexResource, preferred string) (Server, TestResult, error)
- func (c *Client) Find(ctx context.Context, s Server, kind MediaKind, tmdbID int) (item Item, found bool, err error)
- func (c *Client) PublicInfo(ctx context.Context, kind Kind, baseURL string) (PublicInfo, error)
- func (c *Client) QuickConnectCheck(ctx context.Context, base, deviceID, secret string) (bool, error)
- func (c *Client) QuickConnectFinish(ctx context.Context, base, deviceID, secret string) (Server, error)
- func (c *Client) QuickConnectStart(ctx context.Context, baseURL, deviceID string) (base, code, secret string, err error)
- func (c *Client) RefreshAll(ctx context.Context, s Server) error
- func (c *Client) RefreshFolders(ctx context.Context, s Server, kind MediaKind, folders []string) ([]string, error)
- func (c *Client) SignIn(ctx context.Context, kind Kind, baseURL, deviceID, username, password string) (Server, error)
- func (c *Client) Test(ctx context.Context, s Server) (TestResult, error)
- type Discoverer
- type Discovery
- type Finder
- type Found
- type Item
- type Kind
- type Library
- type Link
- type MediaKind
- type PathMapping
- type Pending
- type PlexAddress
- type PlexConnection
- type PlexPIN
- type PlexResource
- type PlexTV
- type Probe
- type PublicInfo
- type Refresher
- type Repo
- type Server
- type ServerStore
- type TestResult
- type UserError
Constants ¶
const MaxSubnets = 8
MaxSubnets is how many networks one search covers at most.
const PlexTVURL = "https://plex.tv"
PlexTVURL is plex.tv's address.
Variables ¶
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.
var DefaultProbes = []Probe{{Port: 32400, Scheme: "http", Plex: true}, {Port: 8096, Scheme: "http"}}
DefaultProbes are Plex's and Jellyfin/Emby's standard http ports.
var ErrPlexPINExpired = errors.New("plex pin expired")
ErrPlexPINExpired means the PIN is gone: it timed out or was never ours.
var ( // ErrQuickConnectExpired means the Quick Connect code is no longer valid. ErrQuickConnectExpired = errors.New("quick connect code expired") )
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 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 ¶
MarkAdded sets AlreadyAdded on every found server that is already saved: the same server id, or the same address.
func NormalizeURL ¶
NormalizeURL checks an http(s) address and returns it without a trailing slash. An address typed without a scheme gets http://.
func PlexAuthURL ¶
PlexAuthURL is the app.plex.tv page where the person approves a PIN.
func PrivateIPv4 ¶
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 (*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 ¶
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 ¶
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.
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 ¶
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 (*Finder) Invalidate ¶
func (f *Finder) Invalidate()
Invalidate forgets every cached answer (after an import, or when servers change).
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 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 ¶
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.
type MediaKind ¶
type MediaKind string
MediaKind is what was imported or is being looked up.
func ParseMediaKind ¶
ParseMediaKind accepts "movie" or "tv" (also "series"/"show").
type PathMapping ¶
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.
type PlexAddress ¶
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 ¶
CheckPIN reads a PIN back; AuthToken is set once it was approved. A PIN plex.tv no longer knows is ErrPlexPINExpired.
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 ¶
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.
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 (*Repo) RecordCheck ¶
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.
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.
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.