Debian Codegraph @

putio/files.go

raw symbols SCIP
1 package putio
2
3 import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "mime/multipart"
9 "net/url"
10 "strconv"
11 "strings"
12 )
13
14 // FilesService is a general service to gather information about user files,
15 // such as listing, searching, creating new ones, or just fetching a single
16 // file.
17 type FilesService struct {
18 client *Client
19 }
20
21 // Get fetches file metadata for given file ID.
22 func (f *FilesService) Get(ctx context.Context, id int64) (File, error) {
23 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/"+itoa(id), nil)
24 if err != nil {
25 return File{}, err
26 }
27
28 var r struct {
29 File File `json:"file"`
30 }
31 _, err = f.client.Do(req, &r)
32 if err != nil {
33 return File{}, err
34 }
35 return r.File, nil
36 }
37
38 // List fetches children for given directory ID.
39 func (f *FilesService) List(ctx context.Context, id int64) (children []File, parent File, err error) {
40 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/list?parent_id="+itoa(id)+"&per_page=1000", nil)
41 if err != nil {
42 return
43 }
44 var r struct {
45 Files []File `json:"files"`
46 Parent File `json:"parent"`
47 Cursor string `json:"cursor"`
48 }
49 _, err = f.client.Do(req, &r)
50 if err != nil {
51 return
52 }
53 children = append(children, r.Files...)
54 parent = r.Parent
55 for r.Cursor != "" {
56 body := strings.NewReader(`{"cursor": "` + r.Cursor + `"}`)
57 req, err = f.client.NewRequest(ctx, "POST", "/v2/files/list/continue", body)
58 if err != nil {
59 return
60 }
61 req.Header.Set("content-type", "application/json")
62 r.Files = nil
63 r.Cursor = ""
64 _, err = f.client.Do(req, &r)
65 if err != nil {
66 return
67 }
68 children = append(children, r.Files...)
69 }
70 return
71 }
72
73 // URL returns a URL of the file for downloading or streaming.
74 func (f *FilesService) URL(ctx context.Context, id int64, useTunnel bool) (string, error) {
75 notunnel := "notunnel=1"
76 if useTunnel {
77 notunnel = "notunnel=0"
78 }
79
80 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/"+itoa(id)+"/url?"+notunnel, nil)
81 if err != nil {
82 return "", err
83 }
84
85 var r struct {
86 URL string `json:"url"`
87 }
88
89 _, err = f.client.Do(req, &r)
90 if err != nil {
91 return "", err
92 }
93
94 return r.URL, nil
95 }
96
97 // CreateFolder creates a new folder under parent.
98 func (f *FilesService) CreateFolder(ctx context.Context, name string, parent int64) (File, error) {
99 if name == "" {
100 return File{}, fmt.Errorf("empty folder name")
101 }
102
103 params := url.Values{}
104 params.Set("name", name)
105 params.Set("parent_id", itoa(parent))
106
107 req, err := f.client.NewRequest(ctx, "POST", "/v2/files/create-folder", strings.NewReader(params.Encode()))
108 if err != nil {
109 return File{}, err
110 }
111 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
112
113 var r struct {
114 File File `json:"file"`
115 }
116 _, err = f.client.Do(req, &r)
117 if err != nil {
118 return File{}, err
119 }
120
121 return r.File, nil
122 }
123
124 // Delete deletes given files.
125 func (f *FilesService) Delete(ctx context.Context, files ...int64) error {
126 if len(files) == 0 {
127 return fmt.Errorf("no file id is given")
128 }
129
130 var ids []string
131 for _, id := range files {
132 ids = append(ids, itoa(id))
133 }
134
135 params := url.Values{}
136 params.Set("file_ids", strings.Join(ids, ","))
137
138 req, err := f.client.NewRequest(ctx, "POST", "/v2/files/delete", strings.NewReader(params.Encode()))
139 if err != nil {
140 return err
141 }
142 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
143
144 _, err = f.client.Do(req, &struct{}{})
145 if err != nil {
146 return err
147 }
148 return nil
149 }
150
151 // Rename change the name of the file to newname.
152 func (f *FilesService) Rename(ctx context.Context, id int64, newname string) error {
153 if newname == "" {
154 return fmt.Errorf("new filename cannot be empty")
155 }
156
157 params := url.Values{}
158 params.Set("file_id", itoa(id))
159 params.Set("name", newname)
160
161 req, err := f.client.NewRequest(ctx, "POST", "/v2/files/rename", strings.NewReader(params.Encode()))
162 if err != nil {
163 return err
164 }
165 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
166
167 _, err = f.client.Do(req, &struct{}{})
168 if err != nil {
169 return err
170 }
171
172 return nil
173 }
174
175 // Move moves files to the given destination.
176 func (f *FilesService) Move(ctx context.Context, parent int64, files ...int64) error {
177 if len(files) == 0 {
178 return fmt.Errorf("no files given")
179 }
180
181 var ids []string
182 for _, file := range files {
183 ids = append(ids, itoa(file))
184 }
185
186 params := url.Values{}
187 params.Set("file_ids", strings.Join(ids, ","))
188 params.Set("parent_id", itoa(parent))
189
190 req, err := f.client.NewRequest(ctx, "POST", "/v2/files/move", strings.NewReader(params.Encode()))
191 if err != nil {
192 return err
193 }
194 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
195
196 _, err = f.client.Do(req, &struct{}{})
197 if err != nil {
198 return err
199 }
200 return nil
201 }
202
203 // Upload reads from given io.Reader and uploads the file contents to Put.io
204 // servers under directory given by parent. If parent is negative, user's
205 // prefered folder is used.
206 //
207 // If the uploaded file is a torrent file, Put.io will interpret it as a
208 // transfer and Transfer field will be present to represent the status of the
209 // tranfer. Likewise, if the uploaded file is a regular file, Transfer field
210 // would be nil and the uploaded file will be represented by the File field.
211 //
212 // This method reads the file contents into the memory, so it should be used for
213 // <150MB files.
214 func (f *FilesService) Upload(ctx context.Context, r io.Reader, filename string, parent int64) (Upload, error) {
215 if filename == "" {
216 return Upload{}, fmt.Errorf("filename cannot be empty")
217 }
218
219 var buf bytes.Buffer
220 mw := multipart.NewWriter(&buf)
221
222 // negative parent means use user's prefered download folder.
223 if parent >= 0 {
224 err := mw.WriteField("parent_id", itoa(parent))
225 if err != nil {
226 return Upload{}, err
227 }
228 }
229
230 formfile, err := mw.CreateFormFile("file", filename)
231 if err != nil {
232 return Upload{}, err
233 }
234
235 _, err = io.Copy(formfile, r)
236 if err != nil {
237 return Upload{}, err
238 }
239
240 err = mw.Close()
241 if err != nil {
242 return Upload{}, err
243 }
244
245 req, err := f.client.NewRequest(ctx, "POST", "/v2/files/upload", &buf)
246 if err != nil {
247 return Upload{}, err
248 }
249 req.Header.Set("Content-Type", mw.FormDataContentType())
250
251 var response struct {
252 Upload
253 }
254 _, err = f.client.Do(req, &response)
255 if err != nil {
256 return Upload{}, err
257 }
258 return response.Upload, nil
259 }
260
261 // Search makes a search request with the given query. Servers return 50
262 // results at a time. The URL for the next 50 results are in Next field. If
263 // page is -1, all results are returned.
264 func (f *FilesService) Search(ctx context.Context, query string, page int64) (Search, error) {
265 if page == 0 || page < -1 {
266 return Search{}, fmt.Errorf("invalid page number")
267 }
268 if query == "" {
269 return Search{}, fmt.Errorf("no query given")
270 }
271
272 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/search/"+query+"/page/"+itoa(page), nil)
273 if err != nil {
274 return Search{}, err
275 }
276
277 var r Search
278 _, err = f.client.Do(req, &r)
279 if err != nil {
280 return Search{}, err
281 }
282
283 return r, nil
284 }
285
286 // Shared returns list of shared files and share information.
287 func (f *FilesService) shared(ctx context.Context) ([]share, error) {
288 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/shared", nil)
289 if err != nil {
290 return nil, err
291 }
292
293 var r struct {
294 Shared []share
295 }
296 _, err = f.client.Do(req, &r)
297 if err != nil {
298 return nil, err
299 }
300
301 return r.Shared, nil
302 }
303
304 // SharedWith returns list of users the given file is shared with.
305 func (f *FilesService) sharedWith(ctx context.Context, id int64) ([]share, error) {
306 // FIXME: shared-with returns different json structure than /shared/
307 // endpoint. so it's not an exported method until a common structure is
308 // decided
309 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/"+itoa(id)+"/shared-with", nil)
310 if err != nil {
311 return nil, err
312 }
313
314 var r struct {
315 Shared []share `json:"shared-with"`
316 }
317 _, err = f.client.Do(req, &r)
318 if err != nil {
319 return nil, err
320 }
321
322 return r.Shared, nil
323 }
324
325 // Subtitles lists available subtitles for the given file for user's prefered
326 // subtitle language.
327 func (f *FilesService) Subtitles(ctx context.Context, id int64) ([]Subtitle, error) {
328 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/"+itoa(id)+"/subtitles", nil)
329 if err != nil {
330 return nil, err
331 }
332
333 var r struct {
334 Subtitles []Subtitle
335 Default string
336 }
337 _, err = f.client.Do(req, &r)
338 if err != nil {
339 return nil, err
340 }
341
342 return r.Subtitles, nil
343 }
344
345 // DownloadSubtitle sends the contents of the subtitle file. If the key is empty string,
346 // `default` key is used. This key is used to search for a subtitle in the
347 // following order and returns the first match:
348 // - A subtitle file that has identical parent folder and name with the video.
349 // - Subtitle file extracted from video if the format is MKV.
350 // - First match from OpenSubtitles.org.
351 func (f *FilesService) DownloadSubtitle(ctx context.Context, id int64, key string, format string) (io.ReadCloser, error) {
352 if key == "" {
353 key = "default"
354 }
355 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/"+itoa(id)+"/subtitles/"+key, nil)
356 if err != nil {
357 return nil, err
358 }
359
360 resp, err := f.client.Do(req, nil)
361 if err != nil {
362 return nil, err
363 }
364
365 return resp.Body, nil
366 }
367
368 // HLSPlaylist serves a HLS playlist for a video file. Use “all” as
369 // subtitleKey to get available subtitles for user’s preferred languages.
370 func (f *FilesService) HLSPlaylist(ctx context.Context, id int64, subtitleKey string) (io.ReadCloser, error) {
371 if subtitleKey == "" {
372 return nil, fmt.Errorf("empty subtitle key is given")
373 }
374
375 req, err := f.client.NewRequest(ctx, "GET", "/v2/files/"+itoa(id)+"/hls/media.m3u8?subtitle_key"+subtitleKey, nil)
376 if err != nil {
377 return nil, err
378 }
379
380 resp, err := f.client.Do(req, nil)
381 if err != nil {
382 return nil, err
383 }
384
385 return resp.Body, nil
386 }
387
388 // SetVideoPosition sets default video position for a video file.
389 func (f *FilesService) SetVideoPosition(ctx context.Context, id int64, t int) error {
390 if t < 0 {
391 return fmt.Errorf("time cannot be negative")
392 }
393
394 params := url.Values{}
395 params.Set("time", strconv.Itoa(t))
396
397 req, err := f.client.NewRequest(ctx, "POST", "/v2/files/"+itoa(id)+"/start-from", strings.NewReader(params.Encode()))
398 if err != nil {
399 return err
400 }
401 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
402
403 _, err = f.client.Do(req, &struct{}{})
404 if err != nil {
405 return err
406 }
407
408 return nil
409 }
410
411 // DeleteVideoPosition deletes video position for a video file.
412 func (f *FilesService) DeleteVideoPosition(ctx context.Context, id int64) error {
413 req, err := f.client.NewRequest(ctx, "POST", "/v2/files/"+itoa(id)+"/start-from/delete", nil)
414 if err != nil {
415 return err
416 }
417 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
418
419 _, err = f.client.Do(req, &struct{}{})
420 if err != nil {
421 return err
422 }
423
424 return nil
425 }
426
427 func itoa(i int64) string {
428 return strconv.FormatInt(i, 10)
429 }