starr

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2023 License: MIT Imports: 19 Imported by: 29

README ¶

Starr

GoDoc Go Report Card MIT License discord

The correct way to say *arr.

Go library to interact with APIs in all the Starr apps.

Custom Scripts support is also included. Check out the types and methods to get that data.

One 🌟 To Rule Them All

This library is slowly updated as new methods are needed or requested. If you have specific needs this library doesn't currently meet, but should or could, please let us know!

This library is currently in use by:

Usage

Get it:

go get golift.io/starr

Use it:

import "golift.io/starr"

Example

package main

import (
	"fmt"

	"golift.io/starr"
	"golift.io/starr/lidarr"
)

func main() {
	// Get a starr.Config that can plug into any Starr app.
	// starr.New(apiKey, appURL string, timeout time.Duration)
	c := starr.New("abc1234ahsuyka123jh12", "http://localhost:8686", 0)
	// Lets make a lidarr server with the default starr Config.
	l := lidarr.New(c)

	// In addition to GetSystemStatus, you have things like:
	// * l.GetAlbum(albumID int)
	// * l.GetQualityDefinition()
	// * l.GetQualityProfiles()
	// * l.GetRootFolders()
	// * l.GetQueue(maxRecords int)
	// * l.GetAlbum(albumUUID string)
	// * l.GetArtist(artistUUID string)
	status, err := l.GetSystemStatus()
	if err != nil {
		panic(err)
	}

	fmt.Println(status)
}

Documentation ¶

Overview ¶

Package starr is a library for interacting with the APIs in Radarr, Lidarr, Sonarr and Readarr. It consists of the main starr package and one sub package for each starr application. In the basic use, you create a starr Config that contains an API key and an App URL. Pass this into one of the other packages (like radarr), and it's used as an interface to make API calls.

You can either call starr.New() to build an http.Client for you, or create a starr.Config that contains one you control. If you pass a starr.Config into a sub package without an http Client, it will be created for you. There are a lot of option to set this code up from simple and easy to more advanced.

The sub package contain methods and data structures for a number of API endpoints. Each app has somewhere between 50 and 100 API endpoints. This library currently covers about 10% of those. You can retrieve things like movies, albums, series and books. You can retrieve server status, authors, artists and items in queues. You can also add new media to each application with this library.

Index ¶

Constants ¶

View Source
const API = "api"

API is the beginning of every API path.

View Source
const CalendarTimeFilterFormat = "2006-01-02T03:04:05.000Z"

CalendarTimeFilterFormat is the Go time format the calendar expects the filter to be in.

View Source
const (
	DefaultTimeout = 30 * time.Second
)

Defaults for New().

Variables ¶

View Source
var (
	// ErrInvalidStatusCode matches ANY ReqError when using errors.Is.
	// You should instead use errors.As if you need the response data.
	// Find an example of errors.As in the Login() method.
	ErrInvalidStatusCode = &ReqError{Code: -1}
	// ErrNilClient is returned if you attempt a request with a nil http.Client.
	ErrNilClient = fmt.Errorf("http.Client must not be nil")
	// ErrNilInterface is returned by *Into() methods when a nil interface is provided.
	ErrNilInterface = fmt.Errorf("cannot unmarshal data into a nil or empty interface")
	// ErrInvalidAPIKey is returned if we know the API key didn't work.
	ErrInvalidAPIKey = fmt.Errorf("API Key may be incorrect")
	// ErrRequestError is returned when bad input is provided.
	ErrRequestError = fmt.Errorf("request error")
)

Errors you may receive from this package.

Functions ¶

func AdjustPerPage ¶ added in v0.12.0

func AdjustPerPage(records, total, collected, perPage int) int

AdjustPerPage to make sure we don't go over, or ask for more records than exist. This is used by paginated methods in the starr modules. 'records' is the number requested, 'total' is the number in the app, 'collected' is how many we have so far, and 'perPage' is the current perPage setting.

func Client ¶ added in v1.0.0

func Client(timeout time.Duration, verifySSL bool) *http.Client

Client returns the default client, and is used if one is not passed in.

func ClientWithDebug ¶ added in v1.0.0

func ClientWithDebug(timeout time.Duration, verifySSL bool, logConfig debuglog.Config) *http.Client

ClientWithDebug returns an http client with a debug logger enabled.

func False ¶ added in v1.0.0

func False() *bool

False returns a pointer to a false boolean.

func Int64 ¶ added in v1.0.0

func Int64(s int64) *int64

Int64 returns a pointer to the provided integer.

func SetAPIPath ¶ added in v1.0.0

func SetAPIPath(uriPath string) string

SetAPIPath makes sure the path starts with /api.

func SetPerPage ¶ added in v0.12.0

func SetPerPage(records, perPage int) int

SetPerPage returns a proper perPage value that is not equal to zero, and not larger than the record count desired. If the count is zero, then perPage can be anything other than zero. This is used by paginated methods in the starr modules.

func String ¶ added in v1.0.0

func String(s string) *string

String returns a pointer to a string.

func True ¶ added in v1.0.0

func True() *bool

True returns a pointer to a true boolean.

Types ¶

type APIer ¶ added in v0.9.9

type APIer interface {
	GetInitializeJS(ctx context.Context) (*InitializeJS, error)
	// Login is used for non-API paths, like downloading backups or the initialize.js file.
	Login(ctx context.Context) error
	// Normal data, returns response. Do not use these in starr app methods.
	// These methods are generally for non-api paths and will not ensure an /api uri prefix.
	Get(ctx context.Context, req Request) (*http.Response, error)    // Get request; Params are optional.
	Post(ctx context.Context, req Request) (*http.Response, error)   // Post request; Params should contain io.Reader.
	Put(ctx context.Context, req Request) (*http.Response, error)    // Put request; Params should contain io.Reader.
	Delete(ctx context.Context, req Request) (*http.Response, error) // Delete request; Params are optional.
	// Normal data, unmarshals into provided interface. Use these because they close the response body.
	GetInto(ctx context.Context, req Request, output interface{}) error  // API GET Request.
	PostInto(ctx context.Context, req Request, output interface{}) error // API POST Request.
	PutInto(ctx context.Context, req Request, output interface{}) error  // API PUT Request.
	DeleteAny(ctx context.Context, req Request) error                    // API Delete request.
}

APIer is used by the sub packages to allow mocking the http methods in tests. It changes once in a while, so avoid making hard dependencies on it.

type App ¶ added in v0.10.4

type App string

App can be used to satisfy a context value key. It is not used in this library; provided for convenience.

const (
	Emby     App = "Emby"
	Lidarr   App = "Lidarr"
	Plex     App = "Plex"
	Prowlarr App = "Prowlarr"
	Radarr   App = "Radarr"
	Readarr  App = "Readarr"
	Sonarr   App = "Sonarr"
	Whisparr App = "Whisparr"
)

These constants are just here for convenience.

func (App) Lower ¶ added in v0.10.5

func (a App) Lower() string

Lower turns an App name into a lowercase string.

func (App) String ¶ added in v0.10.4

func (a App) String() string

String turns an App name into a string.

type ApplyTags ¶ added in v1.0.0

type ApplyTags string

ApplyTags is an enum used as an input for Bulk editors, and perhaps other places.

const (
	TagsAdd     ApplyTags = "add"
	TagsRemove  ApplyTags = "remove"
	TagsReplace ApplyTags = "replace"
)

ApplyTags enum constants. Use these as inputs for "ApplyTags" member values. Schema doc'd here: https://radarr.video/docs/api/#/MovieEditor/put_api_v3_movie_editor

func (ApplyTags) Ptr ¶ added in v1.0.0

func (a ApplyTags) Ptr() *ApplyTags

Ptr returns a pointer to an apply tags value. Useful for a BulkEdit struct.

type BackupFile ¶ added in v0.12.0

type BackupFile struct {
	Name string    `json:"name"`
	Path string    `json:"path"`
	Type string    `json:"type"`
	Time time.Time `json:"time"`
	ID   int64     `json:"id"`
	Size int64     `json:"size"`
}

BackupFile comes from the system/backup paths in all apps.

type BaseQuality ¶ added in v0.9.11

type BaseQuality struct {
	ID         int64  `json:"id"`
	Name       string `json:"name"`
	Source     string `json:"source,omitempty"`
	Resolution int    `json:"resolution,omitempty"`
	Modifier   string `json:"modifier,omitempty"`
}

BaseQuality is a base quality profile.

type Config ¶

type Config struct {
	APIKey   string       `json:"apiKey" toml:"api_key" xml:"api_key" yaml:"apiKey"`
	URL      string       `json:"url" toml:"url" xml:"url" yaml:"url"`
	HTTPPass string       `json:"httpPass" toml:"http_pass" xml:"http_pass" yaml:"httpPass"`
	HTTPUser string       `json:"httpUser" toml:"http_user" xml:"http_user" yaml:"httpUser"`
	Username string       `json:"username" toml:"username" xml:"username" yaml:"username"`
	Password string       `json:"password" toml:"password" xml:"password" yaml:"password"`
	Client   *http.Client `json:"-" toml:"-" xml:"-" yaml:"-"`
	// contains filtered or unexported fields
}

Config is the data needed to poll Radarr or Sonarr or Lidarr or Readarr. At a minimum, provide a URL and API Key. HTTPUser and HTTPPass are used for Basic HTTP auth, if enabled (not common). Username and Password are for non-API paths with native authentication enabled.

func New ¶ added in v0.9.9

func New(apiKey, appURL string, timeout time.Duration) *Config

New returns a *starr.Config pointer. This pointer is safe to modify further before passing it into one of the starr app New() procedures.

func (*Config) Delete ¶ added in v0.9.9

func (c *Config) Delete(ctx context.Context, req Request) (*http.Response, error)

Delete makes a DELETE http request and returns the body.

func (*Config) DeleteAny ¶ added in v1.0.0

func (c *Config) DeleteAny(ctx context.Context, req Request) error

DeleteAny performs an HTTP DELETE against an API path, output is ignored.

func (*Config) Get ¶ added in v0.9.9

func (c *Config) Get(ctx context.Context, req Request) (*http.Response, error)

Get makes a GET http request and returns the body.

func (*Config) GetInitializeJS ¶ added in v1.0.0

func (c *Config) GetInitializeJS(ctx context.Context) (*InitializeJS, error)

GetInitializeJS returns the data from the initialize.js file. If the instance requires authentication, you must call Login() before this method.

func (*Config) GetInto ¶ added in v0.9.9

func (c *Config) GetInto(ctx context.Context, req Request, output interface{}) error

GetInto performs an HTTP GET against an API path and unmarshals the payload into the provided pointer interface.

func (*Config) Login ¶ added in v0.12.0

func (c *Config) Login(ctx context.Context) error

Login POSTs to the login form in a Starr app and saves the authentication cookie for future use.

func (*Config) Post ¶ added in v0.9.9

func (c *Config) Post(ctx context.Context, req Request) (*http.Response, error)

Post makes a POST http request and returns the body.

func (*Config) PostInto ¶ added in v0.9.9

func (c *Config) PostInto(ctx context.Context, req Request, output interface{}) error

PostInto performs an HTTP POST against an API path and unmarshals the payload into the provided pointer interface.

func (*Config) Put ¶ added in v0.9.9

func (c *Config) Put(ctx context.Context, req Request) (*http.Response, error)

Put makes a PUT http request and returns the body.

func (*Config) PutInto ¶ added in v0.9.9

func (c *Config) PutInto(ctx context.Context, req Request, output interface{}) error

PutInto performs an HTTP PUT against an API path and unmarshals the payload into the provided pointer interface.

func (*Config) Req ¶

func (c *Config) Req(ctx context.Context, method string, req Request) (*http.Response, error)

Req makes an authenticated request to a starr application and returns the response. Do not forget to read and close the response Body if there is no error.

func (*Config) SetHeaders ¶ added in v0.13.0

func (c *Config) SetHeaders(req *http.Request)

SetHeaders sets all our request headers based on method and other data.

type FieldInput ¶ added in v1.0.0

type FieldInput struct {
	Name  string      `json:"name"`
	Value interface{} `json:"value,omitempty"`
}

FieldInput is generic Name/Value struct applied to a few places.

type FieldOutput ¶ added in v1.0.0

type FieldOutput struct {
	Advanced                    bool            `json:"advanced,omitempty"`
	Order                       int64           `json:"order,omitempty"`
	HelpLink                    string          `json:"helpLink,omitempty"`
	HelpText                    string          `json:"helpText,omitempty"`
	Hidden                      string          `json:"hidden,omitempty"`
	Label                       string          `json:"label,omitempty"`
	Name                        string          `json:"name"`
	SelectOptionsProviderAction string          `json:"selectOptionsProviderAction,omitempty"`
	Type                        string          `json:"type,omitempty"`
	Privacy                     string          `json:"privacy"`
	Value                       interface{}     `json:"value,omitempty"`
	SelectOptions               []*SelectOption `json:"selectOptions,omitempty"`
}

FieldOutput is generic Name/Value struct applied to a few places.

type Filtering ¶ added in v0.14.0

type Filtering int

Filtering is used as a request parameter value to filter lists, like History and Queue. The filter values are different per-app, so find their values in their respective modules.

func (Filtering) Param ¶ added in v0.14.0

func (f Filtering) Param() string

Param returns the string value of a Filter eventType.

type FormatItem ¶ added in v1.0.0

type FormatItem struct {
	Format int64  `json:"format"`
	Name   string `json:"name"`
	Score  int64  `json:"score"`
}

FormatItem is part of a quality profile.

type Image ¶ added in v0.9.9

type Image struct {
	CoverType string `json:"coverType"`
	URL       string `json:"url,omitempty"`
	RemoteURL string `json:"remoteUrl,omitempty"`
	Extension string `json:"extension,omitempty"`
}

Image is used in a few places.

type InitializeJS ¶ added in v1.0.0

type InitializeJS struct {
	App          string
	APIRoot      string
	APIKey       string
	Release      string
	Version      string
	InstanceName string
	Theme        string
	Branch       string
	Analytics    string
	UserHash     string
	URLBase      string
	IsProduction bool
}

InitializeJS is the data contained in the initialize.js file.

type IsLoaded ¶ added in v0.9.9

type IsLoaded struct {
	IsLoaded bool `json:"isLoaded"`
}

IsLoaded is a generic struct used in a few places.

type KeyValue ¶ added in v0.9.11

type KeyValue struct {
	Key   string `json:"key"`
	Value int    `json:"value"`
}

KeyValue is yet another reusable generic type.

type Link struct {
	URL  string `json:"url"`
	Name string `json:"name"`
}

Link is used in a few places.

type OpenRatings ¶ added in v1.0.0

type OpenRatings map[string]Ratings

OpenRatings is a ratings type that has a source and type.

type PageReq ¶ added in v1.0.0

type PageReq struct {
	PageSize   int       // 10 is default if not provided.
	Page       int       // 1 is default if not provided.
	SortKey    string    // date, timeleft, others?
	SortDir    Sorting   // ascending, descending
	Filter     Filtering // enums for eventTypes. App specific.
	url.Values           // Additional values that may be set.
}

PageReq is the input to search requests that have page-able responses. These are turned into HTTP parameters.

func (*PageReq) CheckSet ¶ added in v1.0.0

func (r *PageReq) CheckSet(key, value string)

CheckSet sets a request parameter if it's not already set.

func (*PageReq) Encode ¶ added in v1.0.0

func (r *PageReq) Encode() string

Encode turns our request parameters into a URI string.

func (*PageReq) Params ¶ added in v1.0.0

func (r *PageReq) Params() url.Values

Params returns a brand new url.Values with all request parameters combined.

func (*PageReq) Set ¶ added in v1.0.0

func (r *PageReq) Set(key, value string)

Set sets a request parameter.

type Path ¶ added in v0.9.9

type Path struct {
	Name string `json:"name"`
	Path string `json:"path"`
}

Path is for unmanaged folder paths.

type PlayTime ¶ added in v0.14.0

type PlayTime struct {
	Original string
	time.Duration
}

PlayTime is used in at least Sonarr, maybe other places. Holds a string duration converted from hh:mm:ss.

func (*PlayTime) MarshalJSON ¶ added in v0.14.0

func (d *PlayTime) MarshalJSON() ([]byte, error)

func (*PlayTime) UnmarshalJSON ¶ added in v0.14.0

func (d *PlayTime) UnmarshalJSON(b []byte) error

UnmarshalJSON parses a run time duration in format hh:mm:ss.

type Quality ¶ added in v0.9.4

type Quality struct {
	Name     string           `json:"name,omitempty"`
	ID       int              `json:"id,omitempty"`
	Quality  *BaseQuality     `json:"quality,omitempty"`
	Items    []*Quality       `json:"items,omitempty"`
	Allowed  bool             `json:"allowed"`
	Revision *QualityRevision `json:"revision,omitempty"` // Not sure which app had this....
}

Quality is a download quality profile attached to a movie, book, track or series. It may contain 1 or more profiles. Sonarr nor Readarr use Name or ID in this struct.

type QualityRevision ¶ added in v0.9.11

type QualityRevision struct {
	Version  int64 `json:"version"`
	Real     int64 `json:"real"`
	IsRepack bool  `json:"isRepack,omitempty"`
}

QualityRevision is probably used in Sonarr.

type QueueDeleteOpts ¶ added in v1.0.0

type QueueDeleteOpts struct {
	// Default True, use starr.False() to change it.
	RemoveFromClient *bool
	// Default False
	BlockList bool
	// Default False
	SkipRedownload bool
}

QueueDeleteOpts are the extra inputs when deleting an item from the Activity Queue. Set these appropriately for your expectations. All inputs are the same in all apps. Providing this input to the QueueDelete methods is optional; nil sets the defaults shown.

func (*QueueDeleteOpts) Values ¶ added in v1.0.0

func (o *QueueDeleteOpts) Values() url.Values

Values turns delete options into http get query parameters.

type Ratings ¶ added in v0.9.9

type Ratings struct {
	Votes      int64   `json:"votes"`
	Value      float64 `json:"value"`
	Popularity float64 `json:"popularity,omitempty"`
	Type       string  `json:"type,omitempty"`
}

Ratings belong to a few types.

type RemotePathMapping ¶ added in v1.0.0

type RemotePathMapping struct {
	ID         int64  `json:"id,omitempty"`
	Host       string `json:"host"`
	RemotePath string `json:"remotePath"`
	LocalPath  string `json:"localPath"`
}

RemotePathMapping is the remotePathMapping endpoint.

type ReqError ¶ added in v1.0.0

type ReqError struct {
	Code int
	Body []byte
	Msg  string
	Name string
	Err  error // sub error, often nil, or not useful.
	http.Header
}

ReqError is returned when a Starr app returns an invalid status code.

func (*ReqError) Error ¶ added in v1.0.0

func (r *ReqError) Error() string

Error returns the formatted error message for an invalid status code.

func (*ReqError) Is ¶ added in v1.0.0

func (r *ReqError) Is(tgt error) bool

Is provides a custom error match facility.

type Request ¶ added in v1.0.0

type Request struct {
	URI   string     // Required: path portion of the URL.
	Query url.Values // GET parameters work for any request type.
	Body  io.Reader  // Used in PUT, POST, DELETE. Not for GET.
}

Request contains the GET and/or POST values for an HTTP request.

func (*Request) String ¶ added in v1.0.0

func (r *Request) String() string

String turns a request into a string. Usually used in error messages.

type SelectOption ¶ added in v1.0.0

type SelectOption struct {
	DividerAfter bool   `json:"dividerAfter,omitempty"`
	Order        int64  `json:"order"`
	Value        int64  `json:"value"`
	Hint         string `json:"hint"`
	Name         string `json:"name"`
}

SelectOption is part of Field.

type Sorting ¶ added in v0.14.0

type Sorting string

Sorting is used as a request parameter value to sort lists, like History and Queue.

const (
	// SortAsc is the default, and sorts lists in ascending order.
	SortAscend Sorting = "ascending"
	// SortDesc flips the sort order to descending.
	SortDescend Sorting = "descending"
)

func (*Sorting) Set ¶ added in v0.14.0

func (s *Sorting) Set(val string)

Set makes sure the sort direction is valid.

type StatusMessage ¶ added in v0.9.4

type StatusMessage struct {
	Title    string   `json:"title"`
	Messages []string `json:"messages"`
}

StatusMessage represents the status of the item. All apps use this.

type Tag ¶ added in v0.9.9

type Tag struct {
	ID    int    `json:"id,omitempty"`
	Label string `json:"label"`
}

Tag may be applied to nearly anything.

type TimeSpan ¶ added in v1.0.0

type TimeSpan struct {
	Ticks             int64 `json:"ticks"`
	Days              int64 `json:"days"`
	Hours             int64 `json:"hours"`
	Milliseconds      int64 `json:"milliseconds"`
	Minutes           int64 `json:"minutes"`
	Seconds           int64 `json:"seconds"`
	TotalDays         int64 `json:"totalDays"`
	TotalHours        int64 `json:"totalHours"`
	TotalMilliseconds int64 `json:"totalMilliseconds"`
	TotalMinutes      int64 `json:"totalMinutes"`
	TotalSeconds      int64 `json:"totalSeconds"`
}

TimeSpan is part of AudioTags and possibly used other places.

type Value ¶ added in v0.9.9

type Value struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

Value is generic ID/Name struct applied to a few places.

Directories ¶

Path Synopsis
Package debuglog provides a RoundTripper you can put into an HTTP client Transport to log requests made with that client.
Package debuglog provides a RoundTripper you can put into an HTTP client Transport to log requests made with that client.
Package starrcmd provides the bindings to consume a custom script command hook from any Starr app.
Package starrcmd provides the bindings to consume a custom script command hook from any Starr app.
Package starrtest provides methods that are shared by all the tests in the other sub packages.
Package starrtest provides methods that are shared by all the tests in the other sub packages.

Jump to

Keyboard shortcuts

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