Debian Codegraph @

putio/client.go

raw symbols SCIP
1 package putio
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "net/http"
10 "net/url"
11 )
12
13 const (
14 defaultUserAgent = "go-putio"
15 defaultMediaType = "application/json"
16 defaultBaseURL = "https://api.put.io"
17 defaultUploadURL = "https://upload.put.io"
18 )
19
20 // Client manages communication with Put.io v2 API.
21 type Client struct {
22 // HTTP client used to communicate with Put.io API
23 client *http.Client
24
25 // Base URL for API requests
26 BaseURL *url.URL
27
28 // base url for upload requests
29 uploadURL *url.URL
30
31 // User agent for client
32 UserAgent string
33
34 // ExtraHeaders are passed to the API server on every request.
35 ExtraHeaders http.Header
36
37 // Services used for communicating with the API
38 Account *AccountService
39 Files *FilesService
40 Transfers *TransfersService
41 Zips *ZipsService
42 Friends *FriendsService
43 Events *EventsService
44 }
45
46 // NewClient returns a new Put.io API client, using the htttpClient, which must
47 // be a new Oauth2 enabled http.Client. If httpClient is not defined, default
48 // HTTP client is used.
49 func NewClient(httpClient *http.Client) *Client {
50 if httpClient == nil {
51 httpClient = http.DefaultClient
52 }
53
54 baseURL, _ := url.Parse(defaultBaseURL)
55 uploadURL, _ := url.Parse(defaultUploadURL)
56 c := &Client{
57 client: httpClient,
58 BaseURL: baseURL,
59 uploadURL: uploadURL,
60 UserAgent: defaultUserAgent,
61 ExtraHeaders: make(http.Header),
62 }
63
64 c.Account = &AccountService{client: c}
65 c.Files = &FilesService{client: c}
66 c.Transfers = &TransfersService{client: c}
67 c.Zips = &ZipsService{client: c}
68 c.Friends = &FriendsService{client: c}
69 c.Events = &EventsService{client: c}
70
71 return c
72 }
73
74 func (c *Client) ValidateToken(ctx context.Context) (userID *int64, err error) {
75 req, err := c.NewRequest(ctx, "GET", "/v2/oauth2/validate", nil)
76 if err != nil {
77 return
78 }
79 var r struct {
80 UserID *int64 `json:"user_id"`
81 }
82 _, err = c.Do(req, &r)
83 return r.UserID, err
84 }
85
86 // NewRequest creates an API request. A relative URL can be provided via
87 // relURL, which will be resolved to the BaseURL of the Client.
88 func (c *Client) NewRequest(ctx context.Context, method, relURL string, body io.Reader) (*http.Request, error) {
89 rel, err := url.Parse(relURL)
90 if err != nil {
91 return nil, err
92 }
93
94 var u *url.URL
95 // XXX: workaroud for upload endpoint. upload method has a different base url,
96 // so we've a special case for testing purposes.
97 if relURL == "/v2/files/upload" {
98 u = c.uploadURL.ResolveReference(rel)
99 } else {
100 u = c.BaseURL.ResolveReference(rel)
101 }
102
103 req, err := http.NewRequest(method, u.String(), body)
104 if err != nil {
105 return nil, err
106 }
107
108 req = req.WithContext(ctx)
109 req.Header.Set("Accept", defaultMediaType)
110 req.Header.Set("User-Agent", c.UserAgent)
111
112 // merge headers with extra headers
113 for header, values := range c.ExtraHeaders {
114 for _, value := range values {
115 req.Header.Add(header, value)
116 }
117 }
118
119 return req, nil
120 }
121
122 // Do sends an API request and returns the API response. The API response is
123 // JSON decoded and stored in the value pointed to by v, or returned as an
124 // error if an API error has occurred. Response body is closed at all cases except
125 // v is nil. If v is nil, response body is not closed and the body can be used
126 // for streaming.
127 func (c *Client) Do(r *http.Request, v interface{}) (*http.Response, error) {
128 resp, err := c.client.Do(r)
129 if err != nil {
130 return nil, err
131 }
132
133 err = checkResponse(resp)
134 if err != nil {
135 // close the body at all times if there is an http error
136 resp.Body.Close()
137 return resp, err
138 }
139
140 if v == nil {
141 return resp, nil
142 }
143
144 // close the body for all cases from here
145 defer resp.Body.Close()
146
147 err = json.NewDecoder(resp.Body).Decode(v)
148 if err != nil {
149 return resp, err
150 }
151
152 return resp, nil
153 }
154
155 // checkResponse is the entrypoint to reading the API response. If the response
156 // status code is not in success range, it will try to return a structured
157 // error.
158 func checkResponse(r *http.Response) error {
159 status := r.StatusCode
160 switch {
161 case status >= 200 && status <= 399:
162 return nil
163 case status >= 400 && status <= 599:
164 // server returns json
165 default:
166 return fmt.Errorf("unexpected status code: %d", status)
167 }
168 errorResponse := &ErrorResponse{Response: r}
169 data, err := ioutil.ReadAll(r.Body)
170 if err != nil {
171 return fmt.Errorf("body read error: %s. status: %v. Details: %v:", err, status, string(data[:250]))
172 }
173 if len(data) > 0 {
174 err = json.Unmarshal(data, errorResponse)
175 if err != nil {
176 return fmt.Errorf("json decode error: %s. status: %v. Details: %v:", err, status, string(data[:250]))
177 }
178 }
179 return errorResponse
180 }