nzbget

package
v0.0.0-...-6079cd8 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2021 License: AGPL-3.0 Imports: 17 Imported by: 0

Documentation

Overview

Package jsonrpc provides a JSON-RPC 2.0 client that sends JSON-RPC requests and receives JSON-RPC responses using HTTP.

Index

Constants

View Source
const PriorityForce = 900
View Source
const PriorityHigh = 50
View Source
const PriorityLow = -50
View Source
const PriorityNormal = 0
View Source
const PriorityVeryHigh = 100
View Source
const PriorityVeryLow = -100

Variables

This section is empty.

Functions

func Params

func Params(params ...interface{}) interface{}

Params is a helper function that uses the same parameter syntax as Call(). But you should consider to always use NewRequest() instead.

e.g. to manually create an RPCRequest object:

request := &RPCRequest{
  Method: "myMethod",
  Params: Params("Alex", 35, true),
}

same with new request: request := NewRequest("myMethod", "Alex", 35, true)

If you know what you are doing you can omit the Params() call but potentially create incorrect rpc requests:

request := &RPCRequest{
  Method: "myMethod",
  Params: 2, <-- invalid since a single primitive value must be wrapped in an array --> no magic without Params()
}

correct:

request := &RPCRequest{
  Method: "myMethod",
  Params: []int{2}, <-- invalid since a single primitive value must be wrapped in an array
}

Types

type AppendOptions

type AppendOptions struct {
	NiceName   string
	Category   string
	Priority   int
	AddToTop   bool
	AddPaused  bool
	DupeKey    string
	DupeScore  int
	DupeMode   string
	Parameters []struct {
		Name  string
		Value string
	}
}

func NewOptions

func NewOptions() *AppendOptions

type Client

type Client struct {
	URL string
	// contains filtered or unexported fields
}

func NewClient

func NewClient(endpoint string) *Client

func (*Client) Add

func (c *Client) Add(URL string, options *AppendOptions) (int64, error)

func (*Client) Delete

func (c *Client) Delete(number int) error

func (*Client) Destroy

func (c *Client) Destroy(number int) error

func (*Client) EditQueue

func (c *Client) EditQueue(command, param string, ids []int) error

func (*Client) Groups

func (c *Client) Groups() ([]Group, error)

func (*Client) History

func (c *Client) History(hidden bool) ([]History, error)

func (*Client) List

func (c *Client) List() (*GroupResponse, error)

func (*Client) Pause

func (c *Client) Pause(number int) error

func (*Client) PauseAll

func (c *Client) PauseAll() error

func (*Client) Remove

func (c *Client) Remove(number int) error

func (*Client) Resume

func (c *Client) Resume(number int) error

func (*Client) ResumeAll

func (c *Client) ResumeAll() error

func (*Client) Status

func (c *Client) Status() (*Status, error)

func (*Client) Version

func (c *Client) Version() (string, error)

type Group

type Group struct {
	ID                 int    `json:"nzbid"` // 4
	RemainingSizeMB    int    // 3497
	PausedSizeMB       int    // 3497
	RemainingFileCount int    // 73
	RemainingParCount  int    // 9
	MinPriority        int    // 0
	MaxPriority        int    // 0
	ActiveDownloads    int    // 0
	Status             string // PAUSED
	NZBName            string // Brave.Are.the.Fallen.2020.1080p.AMZN.WEB-DL.DDP2.0.H.264-ExREN,
	NZBNicename        string // Brave.Are.the.Fallen.2020.1080p.AMZN.WEB-DL.DDP2.0.H.264-ExREN,
	Kind               string // NZB
	URL                string // ,
	NZBFilename        string // Brave.Are.the.Fallen.2020.1080p.AMZN.WEB-DL.DDP2.0.H.264-ExREN,
	DestDir            string // /data/intermediate/Brave.Are.the.Fallen.2020.1080p.AMZN.WEB-DL.DDP2.0.H.264-ExREN.#4,
	FinalDir           string // ,
	Category           string // ,
	ParStatus          string // NONE
	ExParStatus        string // NONE
	UnpackStatus       string // NONE
	MoveStatus         string // NONE
	ScriptStatus       string // NONE
	DeleteStatus       string // NONE
	MarkStatus         string // NONE
	UrlStatus          string // NONE
	FileSizeMB         int    // 3651
	FileCount          int    // 77
	MinPostTime        int    // 1586073677
	MaxPostTime        int    // 1586073793
	TotalArticles      int    // 4992
	SuccessArticles    int    // 212
	FailedArticles     int    // 0
	Health             int    // 1000
	CriticalHealth     int    // 898
	DupeKey            string //
	DupeScore          int    // 0
	DupeMode           string // SCORE
	Deleted            bool
	DownloadedSizeMB   int // 235
	DownloadTimeSec    int // 44
	PostTotalTimeSec   int // 0
	ParTimeSec         int // 0
	RepairTimeSec      int // 0
	UnpackTimeSec      int // 0
	MessageCount       int // 95
	ExtraParBlocks     int // 0
	Parameters         []Parameter
	ScriptStatuses     []ScriptStatus
	ServerStats        []ServerStat
	PostInfoText       string // NONE
	PostStageProgress  int    // 9193728
	PostStageTimeSec   int    // 0
	Log                []Log
}

type GroupResponse

type GroupResponse struct {
	*Response
	Result []Group
}

type HTTPError

type HTTPError struct {
	Code int
	// contains filtered or unexported fields
}

HTTPError represents a error that occurred on HTTP level.

An error of type HTTPError is returned when a HTTP error occurred (status code) and the body could not be parsed to a valid RPCResponse object that holds a RPCError.

Otherwise a RPCResponse object is returned with a RPCError field that is not nil.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error function is provided to be used as error object.

type History

type History struct {
	ID                 int `json:"nzbid"`
	Name               string
	RemainingFileCount int
	RetryData          bool
	HistoryTime        int
	Status             string
	Log                []string
	NZBName            string
	NZBNicename        string
	Kind               string
	URL                string
	NZBFilename        string
	DestDir            string
	FinalDir           string
	Category           string
	ParStatus          string
	ExParStatus        string
	UnpackStatus       string
	MoveStatus         string
	ScriptStatus       string
	DeleteStatus       string
	MarkStatus         string
	UrlStatus          string
	FileSizeLo         int
	FileSizeHi         int
	FileSizeMB         int
	FileCount          int
	MinPostTime        int
	MaxPostTime        int
	TotalArticles      int
	SuccesArticles     int
	FailedArticles     int
	Health             int
	CriticalHealth     int
	DupeKey            string
	DupeScore          int
	DupeMode           string
	Deleted            bool
	DownloadedSizeLo   int
	DownloadedSizeHi   int
	DownloadedSizeMB   int
	DownloadTimeSec    int
	PostTotalTimeSec   int
	ParTimeSec         int
	RepairTimeSec      int
	UnpackTimeSec      int
	MessageCount       int
	ExtraParBlocks     int
	Parameters         []Parameter
	ScriptStatuses     []ScriptStatus
	ServerStats        []ServerStat
}

type HistoryResponse

type HistoryResponse struct {
	*Response
	Result []History `json:"Result"`
}

type Log

type Log struct {
}

type NewsServer

type NewsServer struct {
	ID     int
	Active bool
}

type Parameter

type Parameter struct {
	Name  string
	Value string
}

type RPCClient

type RPCClient interface {
	// Call is used to send a JSON-RPC request to the server endpoint.
	//
	// The spec states, that params can only be an array or an object, no primitive values.
	// So there are a few simple rules to notice:
	//
	// 1. no params: params field is omitted. e.g. Call("getinfo")
	//
	// 2. single params primitive value: value is wrapped in array. e.g. Call("getByID", 1423)
	//
	// 3. single params value array or object: value is unchanged. e.g. Call("storePerson", &Person{Name: "Alex"})
	//
	// 4. multiple params values: always wrapped in array. e.g. Call("setDetails", "Alex, 35, "Germany", true)
	//
	// Examples:
	//   Call("getinfo") -> {"method": "getinfo"}
	//   Call("getPersonId", 123) -> {"method": "getPersonId", "params": [123]}
	//   Call("setName", "Alex") -> {"method": "setName", "params": ["Alex"]}
	//   Call("setMale", true) -> {"method": "setMale", "params": [true]}
	//   Call("setNumbers", []int{1, 2, 3}) -> {"method": "setNumbers", "params": [1, 2, 3]}
	//   Call("setNumbers", 1, 2, 3) -> {"method": "setNumbers", "params": [1, 2, 3]}
	//   Call("savePerson", &Person{Name: "Alex", Age: 35}) -> {"method": "savePerson", "params": {"name": "Alex", "age": 35}}
	//   Call("setPersonDetails", "Alex", 35, "Germany") -> {"method": "setPersonDetails", "params": ["Alex", 35, "Germany"}}
	//
	// for more information, see the examples or the unit tests
	Call(method string, params ...interface{}) (*RPCResponse, error)

	// CallRaw is like Call() but without magic in the requests.Params field.
	// The RPCRequest object is sent exactly as you provide it.
	// See docs: NewRequest, RPCRequest, Params()
	//
	// It is recommended to first consider Call() and CallFor()
	CallRaw(request *RPCRequest) (*RPCResponse, error)

	// CallFor is a very handy function to send a JSON-RPC request to the server endpoint
	// and directly specify an object to store the response.
	//
	// out: will store the unmarshaled object, if request was successful.
	// should always be provided by references. can be nil even on success.
	// the behaviour is the same as expected from json.Unmarshal()
	//
	// method and params: see Call() function
	//
	// if the request was not successful (network, http error) or the rpc response returns an error,
	// an error is returned. if it was an JSON-RPC error it can be casted
	// to *RPCError.
	//
	CallFor(out interface{}, method string, params ...interface{}) error

	// CallBatch invokes a list of RPCRequests in a single batch request.
	//
	// Most convenient is to use the following form:
	// CallBatch(RPCRequests{
	//   Batch("myMethod1", 1, 2, 3),
	//   Batch("myMethod2), "Test"),
	// })
	//
	// You can create the []*RPCRequest array yourself, but it is not recommended and you should notice the following:
	// - field Params is sent as provided, so Params: 2 forms an invalid json (correct would be Params: []int{2})
	// - you can use the helper function Params(1, 2, 3) to use the same format as in Call()
	// - field JSONRPC is overwritten and set to value: "2.0"
	// - field ID is overwritten and set incrementally and maps to the array position (e.g. requests[5].ID == 5)
	//
	//
	// Returns RPCResponses that is of type []*RPCResponse
	// - note that a list of RPCResponses can be received unordered so it can happen that: responses[i] != responses[i].ID
	// - RPCPersponses is enriched with helper functions e.g.: responses.HasError() returns  true if one of the responses holds an RPCError
	CallBatch(requests RPCRequests) (RPCResponses, error)

	// CallBatchRaw invokes a list of RPCRequests in a single batch request.
	// It sends the RPCRequests parameter is it passed (no magic, no id autoincrement).
	//
	// Consider to use CallBatch() instead except you have some good reason not to.
	//
	// CallBatchRaw(RPCRequests{
	//   &RPCRequest{
	//     ID: 123,            // this won't be replaced in CallBatchRaw
	//     JSONRPC: "wrong",   // this won't be replaced in CallBatchRaw
	//     Method: "myMethod1",
	//     Params: []int{1},   // there is no magic, be sure to only use array or object
	//   },
	//   &RPCRequest{
	//     ID: 612,
	//     JSONRPC: "2.0",
	//     Method: "myMethod2",
	//     Params: Params("Alex", 35, true), // you can use helper function Params() (see doc)
	//   },
	// })
	//
	// Returns RPCResponses that is of type []*RPCResponse
	// - note that a list of RPCResponses can be received unordered
	// - the id's must be mapped against the id's you provided
	// - RPCPersponses is enriched with helper functions e.g.: responses.HasError() returns  true if one of the responses holds an RPCError
	CallBatchRaw(requests RPCRequests) (RPCResponses, error)
}

RPCClient sends JSON-RPC requests over HTTP to the provided JSON-RPC backend.

RPCClient is created using the factory function NewClient().

func NewClientWithOpts

func NewClientWithOpts(endpoint string, opts *RPCClientOpts) RPCClient

NewClientWithOpts returns a new RPCClient instance with custom configuration.

endpoint: JSON-RPC service URL to which JSON-RPC requests are sent.

opts: RPCClientOpts provide custom configuration

func NewJsonClient

func NewJsonClient(endpoint string) RPCClient

NewClient returns a new RPCClient instance with default configuration.

endpoint: JSON-RPC service URL to which JSON-RPC requests are sent.

type RPCClientOpts

type RPCClientOpts struct {
	HTTPClient    *http.Client
	CustomHeaders map[string]string
}

RPCClientOpts can be provided to NewClientWithOpts() to change configuration of RPCClient.

HTTPClient: provide a custom http.Client (e.g. to set a proxy, or tls options)

CustomHeaders: provide custom headers, e.g. to set BasicAuth

type RPCError

type RPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

RPCError represents a JSON-RPC error object if an RPC error occurred.

Code: holds the error code

Message: holds a short error message

Data: holds additional error data, may be nil

See: http://www.jsonrpc.org/specification#error_object

func (*RPCError) Error

func (e *RPCError) Error() string

Error function is provided to be used as error object.

type RPCRequest

type RPCRequest struct {
	Method  string      `json:"method"`
	Params  interface{} `json:"params,omitempty"`
	ID      int         `json:"id"`
	JSONRPC string      `json:"jsonrpc"`
}

RPCRequest represents a JSON-RPC request object.

Method: string containing the method to be invoked

Params: can be nil. if not must be an json array or object

ID: may always set to 1 for single requests. Should be unique for every request in one batch request.

JSONRPC: must always be set to "2.0" for JSON-RPC version 2.0

See: http://www.jsonrpc.org/specification#request_object

Most of the time you shouldn't create the RPCRequest object yourself. The following functions do that for you: Call(), CallFor(), NewRequest()

If you want to create it yourself (e.g. in batch or CallRaw()), consider using Params(). Params() is a helper function that uses the same parameter syntax as Call().

e.g. to manually create an RPCRequest object:

request := &RPCRequest{
  Method: "myMethod",
  Params: Params("Alex", 35, true),
}

If you know what you are doing you can omit the Params() call to avoid some reflection but potentially create incorrect rpc requests:

request := &RPCRequest{
  Method: "myMethod",
  Params: 2, <-- invalid since a single primitive value must be wrapped in an array --> no magic without Params()
}

correct:

request := &RPCRequest{
  Method: "myMethod",
  Params: []int{2}, <-- invalid since a single primitive value must be wrapped in an array
}

func NewRequest

func NewRequest(method string, params ...interface{}) *RPCRequest

NewRequest returns a new RPCRequest that can be created using the same convenient parameter syntax as Call()

e.g. NewRequest("myMethod", "Alex", 35, true)

type RPCRequests

type RPCRequests []*RPCRequest

RPCRequests is of type []*RPCRequest. This type is used to provide helper functions on the request list

type RPCResponse

type RPCResponse struct {
	JSONRPC string      `json:"jsonrpc"`
	Result  interface{} `json:"result,omitempty"`
	Error   *RPCError   `json:"error,omitempty"`
	ID      int         `json:"id"`
}

RPCResponse represents a JSON-RPC response object.

Result: holds the result of the rpc call if no error occurred, nil otherwise. can be nil even on success.

Error: holds an RPCError object if an error occurred. must be nil on success.

ID: may always be 0 for single requests. is unique for each request in a batch call (see CallBatch())

JSONRPC: must always be set to "2.0" for JSON-RPC version 2.0

See: http://www.jsonrpc.org/specification#response_object

func (*RPCResponse) GetBool

func (RPCResponse *RPCResponse) GetBool() (bool, error)

GetBool converts the rpc response to a bool and returns it.

If result was not a bool an error is returned.

func (*RPCResponse) GetFloat

func (RPCResponse *RPCResponse) GetFloat() (float64, error)

GetFloat converts the rpc response to float64 and returns it.

If result was not an float64 an error is returned.

func (*RPCResponse) GetInt

func (RPCResponse *RPCResponse) GetInt() (int64, error)

GetInt converts the rpc response to an int64 and returns it.

If result was not an integer an error is returned.

func (*RPCResponse) GetObject

func (RPCResponse *RPCResponse) GetObject(toType interface{}) error

GetObject converts the rpc response to an arbitrary type.

The function works as you would expect it from json.Unmarshal()

func (*RPCResponse) GetString

func (RPCResponse *RPCResponse) GetString() (string, error)

GetString converts the rpc response to a string and returns it.

If result was not a string an error is returned.

type RPCResponses

type RPCResponses []*RPCResponse

RPCResponses is of type []*RPCResponse. This type is used to provide helper functions on the result list

func (RPCResponses) AsMap

func (res RPCResponses) AsMap() map[int]*RPCResponse

AsMap returns the responses as map with response id as key.

func (RPCResponses) GetByID

func (res RPCResponses) GetByID(id int) *RPCResponse

GetByID returns the response object of the given id, nil if it does not exist.

func (RPCResponses) HasError

func (res RPCResponses) HasError() bool

HasError returns true if one of the response objects has Error field != nil

type Response

type Response struct {
	APIVersion string `json:"version"`
	Error      string
	Status     *Status
	Timestamp  time.Time
}

type ScriptStatus

type ScriptStatus struct {
	Name   string
	Status string
}

type ServerStat

type ServerStat struct {
	ServerID        int
	SuccessArticles int
	FailedArticles  int
}

type Status

type Status struct {
	RemainingSizeMB     int  // 0
	ForcedSizeMB        int  // 0
	DownloadedSizeMB    int  // 0
	MonthSizeMB         int  // 0
	DaySizeMB           int  // 0
	ArticleCacheMB      int  // 0
	DownloadRate        int  // 0
	AverageDownloadRate int  // 0
	DownloadLimit       int  // 0
	UpTimeSec           int  // 2281
	DownloadTimeSec     int  // 0
	ServerPaused        bool // false
	DownloadPaused      bool // false
	Download2Paused     bool // false
	ServerStandBy       bool // true
	PostPaused          bool // false
	ScanPaused          bool // false
	QuotaReached        bool // false
	FreeDiskSpaceMB     int  // 134539
	ServerTime          int  // 1586063906
	ResumeTime          int  // 0
	FeedActive          bool // false
	QueueScriptCount    int  // 0
	NewsServers         []NewsServer
}

type StatusResponse

type StatusResponse struct {
	*Response
	Result *Status
}

type VersionResponse

type VersionResponse struct {
	*Response
	Version string `json:"result"`
}

Jump to

Keyboard shortcuts

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