starr

package module
v0.0.0-...-f1df713 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2022 License: MIT Imports: 20 Imported by: 0

README ¶

Starr

GoDoc Go Report Card MIT License travis 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 (
	// Error body for 401 response.
	BodyUnauthorized = `{"error": "Unauthorized"}`
	// Error body for 404 response.
	BodyNotFound = `{"message": "NotFound"}`
	// Error body for 405 response.
	BodyMethodNotAllowed = `{"message": "MethodNotAllowed"}`
)
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 is returned when the server (*arr app) returns a bad status code during an API request.
	ErrInvalidStatusCode = fmt.Errorf("invalid status code, <200||>299")
	// 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 ¶

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 ¶

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 ¶

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

ClientWithDebug returns an http client with a debug logger enabled.

func False ¶

func False() *bool

False returns a pointer to a false boolean.

func Int64 ¶

func Int64(s int64) *int64

Int64 returns a pointer to the provided integer.

func SetAPIPath ¶

func SetAPIPath(uriPath string) string

SetAPIPath makes sure the path starts with /api.

func SetPerPage ¶

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 ¶

func String(s string) *string

String returns a pointer to a string.

func True ¶

func True() *bool

True returns a pointer to a true boolean.

Types ¶

type APIer ¶

type APIer interface {
	Login(ctx context.Context) error // Login is used for non-API paths, like downloading backups.
	// 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 ¶

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"
)

These constants are just here for convenience. If you add more here, add them to String() below.

func (App) Lower ¶

func (a App) Lower() string

Lower turns an App name into a lowercase string.

func (App) String ¶

func (a App) String() string

String turns an App name into a string.

type ApplyTags ¶

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 ¶

func (a ApplyTags) Ptr() *ApplyTags

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

type BackupFile ¶

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 ¶

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 ¶

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 ¶

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 ¶

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 ¶

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

Get makes a GET http request and returns the body.

func (*Config) GetInto ¶

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 ¶

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 ¶

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 ¶

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 ¶

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 ¶

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 ¶

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

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

type FieldInput ¶

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 ¶

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"`
	Value                       interface{}     `json:"value,omitempty"`
	SelectOptions               []*SelectOption `json:"selectOptions,omitempty"`
}

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

type Filtering ¶

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 ¶

func (f Filtering) Param() string

Param returns the string value of a Filter eventType.

type FormatItem ¶

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

FormatItem is part of a quality profile.

type Image ¶

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 IsLoaded ¶

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

IsLoaded is a generic struct used in a few places.

type KeyValue ¶

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 ¶

type OpenRatings map[string]Ratings

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

type PageReq ¶

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 ¶

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

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

func (*PageReq) Encode ¶

func (r *PageReq) Encode() string

Encode turns our request parameters into a URI string.

func (*PageReq) Params ¶

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

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

func (*PageReq) Set ¶

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

Set sets a request parameter.

type Path ¶

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

Path is for unmanaged folder paths.

type PlayTime ¶

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 ¶

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

func (*PlayTime) UnmarshalJSON ¶

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

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

type Quality ¶

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 ¶

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

QualityRevision is probably used in Sonarr.

type Ratings ¶

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 Request ¶

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 ¶

func (r *Request) String() string

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

type SelectOption ¶

type SelectOption struct {
	Order int64  `json:"order"`
	Value int64  `json:"value"`
	Hint  string `json:"hint"`
	Name  string `json:"name"`
}

SelectOption is part of Field.

type Sorting ¶

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 ¶

func (s *Sorting) Set(val string)

Set makes sure the sort direction is valid.

type StatusMessage ¶

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

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

type Tag ¶

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

Tag may be applied to nearly anything.

type TestMockData ¶

type TestMockData struct {
	Name            string      // A name for the test.
	ExpectedPath    string      // The path expected in the request ie. /api/v1/thing
	ExpectedRequest string      // The request body (json) expected from the caller.
	ExpectedMethod  string      // The request method (GET/POST) expected from the caller.
	ResponseStatus  int         // This is the status that gets returned the caller.
	ResponseBody    string      // The (json) response body returned to caller.
	WithRequest     interface{} // Caller's request.
	WithResponse    interface{} // Caller's response.
	WithError       error       // Caller's response.
}

TestMockData allows generic testing of http inputs and outputs. This is used by the submodule tests.

func (*TestMockData) GetMockServer ¶

func (test *TestMockData) GetMockServer(t *testing.T) *httptest.Server

GetMockServer is used in all the http tests.

type Value ¶

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.

Jump to

Keyboard shortcuts

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