putio

package module
v0.0.0-...-16d982c Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2020 License: MIT Imports: 12 Imported by: 5

Documentation

Overview

Package putio is the Put.io API v2 client for Go.

The go-putio package does not directly handle authentication. Instead, when creating a new client, pass an http.Client that can handle authentication for you. The easiest and recommended way to do this is using the golang.org/x/oauth2 library, but you can always use any other library that provides an http.Client.

Note that when using an authenticated Client, all calls made by the client will include the specified OAuth token. Therefore, authenticated clients should almost never be shared between different users.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/putdotio/go-putio/putio"
	"golang.org/x/oauth2"
)

const token = "<YOUR-TOKEN-HERE>"

func main() {
	tokenSource := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	oauthClient := oauth2.NewClient(context.TODO(), tokenSource)
	client := putio.NewClient(oauthClient)

	// get root directory
	root, err := client.Files.Get(context.TODO(), 0)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Name of root folder is: %s\n", root.Name)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountInfo

type AccountInfo struct {
	AccountActive           bool   `json:"account_active"`
	AvatarURL               string `json:"avatar_url"`
	DaysUntilFilesDeletion  int    `json:"days_until_files_deletion"`
	DefaultSubtitleLanguage string `json:"default_subtitle_language"`
	Disk                    struct {
		Avail int64 `json:"avail"`
		Size  int64 `json:"size"`
		Used  int64 `json:"used"`
	} `json:"disk"`
	HasVoucher                bool     `json:"has_voucher"`
	Mail                      string   `json:"mail"`
	PlanExpirationDate        string   `json:"plan_expiration_date"`
	Settings                  Settings `json:"settings"`
	SimultaneousDownloadLimit int      `json:"simultaneous_download_limit"`
	SubtitleLanguages         []string `json:"subtitle_languages"`
	UserID                    int64    `json:"user_id"`
	Username                  string   `json:"username"`
}

AccountInfo represents user's account information.

type AccountService

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

AccountService is the service to gather information about user account.

func (*AccountService) Info

Info retrieves user account information.

func (*AccountService) Settings

func (a *AccountService) Settings(ctx context.Context) (Settings, error)

Settings retrieves user preferences.

type Client

type Client struct {

	// Base URL for API requests
	BaseURL *url.URL

	// User agent for client
	UserAgent string

	// Override host header for API requests
	Host string

	// ExtraHeaders are passed to the API server on every request.
	ExtraHeaders http.Header

	// Services used for communicating with the API
	Account   *AccountService
	Files     *FilesService
	Transfers *TransfersService
	Zips      *ZipsService
	Friends   *FriendsService
	Events    *EventsService
	// contains filtered or unexported fields
}

Client manages communication with Put.io v2 API.

func NewClient

func NewClient(httpClient *http.Client) *Client

NewClient returns a new Put.io API client, using the htttpClient, which must be a new Oauth2 enabled http.Client. If httpClient is not defined, default HTTP client is used.

func (*Client) Do

func (c *Client) Do(r *http.Request, v interface{}) (*http.Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. Response body is closed at all cases except v is nil. If v is nil, response body is not closed and the body can be used for streaming.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method, relURL string, body io.Reader) (*http.Request, error)

NewRequest creates an API request. A relative URL can be provided via relURL, which will be resolved to the BaseURL of the Client.

func (*Client) ValidateToken

func (c *Client) ValidateToken(ctx context.Context) (userID *int64, err error)

type ErrorResponse

type ErrorResponse struct {
	// Original http.Response
	Response *http.Response `json:"-"`

	// Body read from Response
	Body []byte `json:"-"`

	// Error while parsing the response
	ParseError error

	// These fileds are parsed from response if JSON.
	Message string `json:"error_message"`
	Type    string `json:"error_type"`
}

ErrorResponse reports the error caused by an API request.

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

type Event

type Event struct {
	ID           int64  `json:"id"`
	FileID       int64  `json:"file_id"`
	Source       string `json:"source"`
	Type         string `json:"type"`
	TransferName string `json:"transfer_name"`
	TransferSize int64  `json:"transfer_size"`
	CreatedAt    *Time  `json:"created_at"`
}

Event represents a Put.io event. It could be a transfer or a shared file.

type EventsService

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

EventsService is the service to gather information about user's events.

func (*EventsService) Delete

func (e *EventsService) Delete(ctx context.Context) error

Delete Clears all all dashboard events.

func (*EventsService) List

func (e *EventsService) List(ctx context.Context) ([]Event, error)

List gets list of dashboard events. It includes downloads and share events.

type File

type File struct {
	ID                int64  `json:"id"`
	Name              string `json:"name"`
	Size              int64  `json:"size"`
	ContentType       string `json:"content_type"`
	CreatedAt         *Time  `json:"created_at"`
	UpdatedAt         *Time  `json:"updated_at"`
	FirstAccessedAt   *Time  `json:"first_accessed_at"`
	ParentID          int64  `json:"parent_id"`
	Screenshot        string `json:"screenshot"`
	OpensubtitlesHash string `json:"opensubtitles_hash"`
	IsMP4Available    bool   `json:"is_mp4_available"`
	Icon              string `json:"icon"`
	CRC32             string `json:"crc32"`
	IsShared          bool   `json:"is_shared"`
}

File represents a Put.io file.

func (*File) IsDir

func (f *File) IsDir() bool

IsDir reports whether the file is a directory.

func (*File) String

func (f *File) String() string

type FilesService

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

FilesService is a general service to gather information about user files, such as listing, searching, creating new ones, or just fetching a single file.

func (*FilesService) CreateFolder

func (f *FilesService) CreateFolder(ctx context.Context, name string, parent int64) (File, error)

CreateFolder creates a new folder under parent.

func (*FilesService) Delete

func (f *FilesService) Delete(ctx context.Context, files ...int64) error

Delete deletes given files.

func (*FilesService) DeleteVideoPosition

func (f *FilesService) DeleteVideoPosition(ctx context.Context, id int64) error

DeleteVideoPosition deletes video position for a video file.

func (*FilesService) DownloadSubtitle

func (f *FilesService) DownloadSubtitle(ctx context.Context, id int64, key string, format string) (io.ReadCloser, error)

DownloadSubtitle sends the contents of the subtitle file. If the key is empty string, `default` key is used. This key is used to search for a subtitle in the following order and returns the first match: - A subtitle file that has identical parent folder and name with the video. - Subtitle file extracted from video if the format is MKV. - First match from OpenSubtitles.org.

func (*FilesService) Get

func (f *FilesService) Get(ctx context.Context, id int64) (File, error)

Get fetches file metadata for given file ID.

func (*FilesService) HLSPlaylist

func (f *FilesService) HLSPlaylist(ctx context.Context, id int64, subtitleKey string) (io.ReadCloser, error)

HLSPlaylist serves a HLS playlist for a video file. Use “all” as subtitleKey to get available subtitles for user’s preferred languages.

func (*FilesService) List

func (f *FilesService) List(ctx context.Context, id int64) (children []File, parent File, err error)

List fetches children for given directory ID.

func (*FilesService) Move

func (f *FilesService) Move(ctx context.Context, parent int64, files ...int64) error

Move moves files to the given destination.

func (*FilesService) Rename

func (f *FilesService) Rename(ctx context.Context, id int64, newname string) error

Rename change the name of the file to newname.

func (*FilesService) Search

func (f *FilesService) Search(ctx context.Context, query string, page int64) (Search, error)

Search makes a search request with the given query. Servers return 50 results at a time. The URL for the next 50 results are in Next field. If page is -1, all results are returned.

func (*FilesService) SetVideoPosition

func (f *FilesService) SetVideoPosition(ctx context.Context, id int64, t int) error

SetVideoPosition sets default video position for a video file.

func (*FilesService) Subtitles

func (f *FilesService) Subtitles(ctx context.Context, id int64) ([]Subtitle, error)

Subtitles lists available subtitles for the given file for user's preferred subtitle language.

func (*FilesService) URL

func (f *FilesService) URL(ctx context.Context, id int64, useTunnel bool) (string, error)

URL returns a URL of the file for downloading or streaming.

func (*FilesService) Upload

func (f *FilesService) Upload(ctx context.Context, r io.Reader, filename string, parent int64) (Upload, error)

Upload reads from given io.Reader and uploads the file contents to Put.io servers under directory given by parent. If parent is negative, user's preferred folder is used.

If the uploaded file is a torrent file, Put.io will interpret it as a transfer and Transfer field will be present to represent the status of the tranfer. Likewise, if the uploaded file is a regular file, Transfer field would be nil and the uploaded file will be represented by the File field.

This method reads the file contents into the memory, so it should be used for <150MB files.

type Friend

type Friend struct {
	ID        int64  `json:"id"`
	Name      string `json:"name"`
	AvatarURL string `json:"avatar_url"`
}

Friend represents Put.io user's friend.

type FriendsService

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

FriendsService is the service to operate on user friends.

func (*FriendsService) Approve

func (f *FriendsService) Approve(ctx context.Context, username string) error

Approve approves a friend request from the given username.

func (*FriendsService) Deny

func (f *FriendsService) Deny(ctx context.Context, username string) error

Deny denies a friend request from the given username.

func (*FriendsService) List

func (f *FriendsService) List(ctx context.Context) ([]Friend, error)

List lists users friends.

func (*FriendsService) Request

func (f *FriendsService) Request(ctx context.Context, username string) error

Request sends a friend request to the given username.

func (*FriendsService) Unfriend

func (f *FriendsService) Unfriend(ctx context.Context, username string) error

Unfriend removed friend from user's friend list.

func (*FriendsService) WaitingRequests

func (f *FriendsService) WaitingRequests(ctx context.Context) ([]Friend, error)

WaitingRequests lists user's pending friend requests.

type Search struct {
	Files []File `json:"files"`
	Next  string `json:"next"`
}

Search represents a search response.

type Settings

type Settings struct {
	CallbackURL             string      `json:"callback_url"`
	DefaultDownloadFolder   int64       `json:"default_download_folder"`
	DefaultSubtitleLanguage string      `json:"default_subtitle_language"`
	DownloadFolderUnset     bool        `json:"download_folder_unset"`
	IsInvisible             bool        `json:"is_invisible"`
	Nextepisode             bool        `json:"nextepisode"`
	PrivateDownloadHostIP   interface{} `json:"private_download_host_ip"`
	PushoverToken           string      `json:"pushover_token"`
	Routing                 string      `json:"routing"`
	Sorting                 string      `json:"sorting"`
	SSLEnabled              bool        `json:"ssl_enabled"`
	StartFrom               bool        `json:"start_from"`
	SubtitleLanguages       []string    `json:"subtitle_languages"`
}

Settings represents user's personal settings.

type Subtitle

type Subtitle struct {
	Key      string
	Language string
	Name     string
	Source   string
}

Subtitle represents a subtitle.

type Time

type Time struct {
	time.Time
}

Time is a wrapper around time.Time that can be unmarshalled from a JSON string formatted as "2016-04-19T15:44:42". All methods of time.Time can be called on Time.

func (*Time) String

func (t *Time) String() string

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type Transfer

type Transfer struct {
	Availability   int    `json:"availability"`
	CallbackURL    string `json:"callback_url"`
	CreatedAt      *Time  `json:"created_at"`
	CreatedTorrent bool   `json:"created_torrent"`
	ClientIP       string `json:"client_ip"`

	DownloadSpeed      int    `json:"down_speed"`
	Downloaded         int64  `json:"downloaded"`
	DownloadID         int64  `json:"download_id"`
	ErrorMessage       string `json:"error_message"`
	EstimatedTime      int64  `json:"estimated_time"`
	Extract            bool   `json:"extract"`
	FileID             int64  `json:"file_id"`
	FinishedAt         *Time  `json:"finished_at"`
	ID                 int64  `json:"id"`
	IsPrivate          bool   `json:"is_private"`
	MagnetURI          string `json:"magneturi"`
	Name               string `json:"name"`
	PeersConnected     int    `json:"peers_connected"`
	PeersGettingFromUs int    `json:"peers_getting_from_us"`
	PeersSendingToUs   int    `json:"peers_sending_to_us"`
	PercentDone        int    `json:"percent_done"`
	SaveParentID       int64  `json:"save_parent_id"`
	SecondsSeeding     int    `json:"seconds_seeding"`
	Size               int    `json:"size"`
	Source             string `json:"source"`
	Status             string `json:"status"`
	StatusMessage      string `json:"status_message"`
	SubscriptionID     int    `json:"subscription_id"`
	TorrentLink        string `json:"torrent_link"`
	TrackerMessage     string `json:"tracker_message"`
	Trackers           string `json:"tracker"`
	Type               string `json:"type"`
	UploadSpeed        int    `json:"up_speed"`
	Uploaded           int64  `json:"uploaded"`
}

Transfer represents a Put.io transfer state.

type TransfersService

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

TransfersService is the service to operate on torrent transfers, such as adding a torrent or magnet link, retrying a current one etc.

func (*TransfersService) Add

func (t *TransfersService) Add(ctx context.Context, urlStr string, parent int64, callbackURL string) (Transfer, error)

Add creates a new transfer. A valid torrent or a magnet URL is expected. Parent is the folder where the new transfer is downloaded to. If a negative value is given, user's preferred download folder is used. CallbackURL is used to send a POST request after the transfer is finished downloading.

func (*TransfersService) Cancel

func (t *TransfersService) Cancel(ctx context.Context, ids ...int64) error

Cancel deletes given transfers.

func (*TransfersService) Clean

func (t *TransfersService) Clean(ctx context.Context) error

Clean removes completed transfers from the transfer list.

func (*TransfersService) Get

func (t *TransfersService) Get(ctx context.Context, id int64) (Transfer, error)

Get returns the given transfer's properties.

func (*TransfersService) List

func (t *TransfersService) List(ctx context.Context) ([]Transfer, error)

List lists all active transfers. If a transfer is completed, it will not be available in response.

func (*TransfersService) Retry

func (t *TransfersService) Retry(ctx context.Context, id int64) (Transfer, error)

Retry retries previously failed transfer.

type Upload

type Upload struct {
	File     *File     `json:"file"`
	Transfer *Transfer `json:"transfer"`
}

Upload represents a Put.io upload. If the uploaded file is a torrent file, Transfer field will represent the status of the transfer.

type Zip

type Zip struct {
	ID        int64 `json:"id"`
	CreatedAt *Time `json:"created_at"`

	Size   int64  `json:"size"`
	Status string `json:"status"`
	URL    string `json:"url"`
}

Zip represents Put.io zip file.

type ZipsService

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

ZipsService is the service manage zip streams.

func (*ZipsService) Create

func (z *ZipsService) Create(ctx context.Context, fileIDs ...int64) (int64, error)

Create creates zip files for given file IDs. If the operation is successful, a zip ID will be returned to keep track of zip process.

func (*ZipsService) Get

func (z *ZipsService) Get(ctx context.Context, id int64) (Zip, error)

Get gives detailed information about the given zip file id.

func (*ZipsService) List

func (z *ZipsService) List(ctx context.Context) ([]Zip, error)

List lists active zip files.

Jump to

Keyboard shortcuts

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