Debian Codegraph @

download.go

raw
1 package b2
2
3 import (
4 "io"
5 "net/http"
6 "strconv"
7 "strings"
8 "time"
9 )
10
11 // DownloadFileByID gets file contents by file ID. The ReadCloser must be
12 // closed by the caller once done reading.
13 //
14 // Note: the (*FileInfo).CustomMetadata values returned by this function are
15 // all represented as strings, because they are delivered by HTTP headers.
16 func (c *Client) DownloadFileByID(id string) (io.ReadCloser, *FileInfo, error) {
17 downloadURL := c.loginInfo.Load().(*LoginInfo).DownloadURL
18 res, err := c.hc.Get(downloadURL + apiPath + "b2_download_file_by_id?fileId=" + id)
19 if e, ok := UnwrapError(err); ok && e.Status == http.StatusUnauthorized {
20 if err = c.login(res); err == nil {
21 res, err = c.hc.Get(downloadURL + apiPath + "b2_download_file_by_id?fileId=" + id)
22 }
23 }
24 if err != nil {
25 debugf("download %s: %s", id, err)
26 return nil, nil, err
27 }
28 debugf("download %s (%s)", id, res.Header.Get("X-Bz-Content-Sha1"))
29
30 fi, err := parseFileInfoHeaders(res.Header)
31 return res.Body, fi, err
32 }
33
34 // DownloadFileByName gets file contents by file and bucket name.
35 // The ReadCloser must be closed by the caller once done reading.
36 //
37 // Note: the (*FileInfo).CustomMetadata values returned by this function are
38 // all represented as strings, because they are delivered by HTTP headers.
39 func (c *Client) DownloadFileByName(bucket, file string) (io.ReadCloser, *FileInfo, error) {
40 downloadURL := c.loginInfo.Load().(*LoginInfo).DownloadURL
41 res, err := c.hc.Get(downloadURL + "/file/" + bucket + "/" + file)
42 if e, ok := UnwrapError(err); ok && e.Status == http.StatusUnauthorized {
43 if err = c.login(res); err == nil {
44 res, err = c.hc.Get(downloadURL + "/file/" + bucket + "/" + file)
45 }
46 }
47 if err != nil {
48 debugf("download %s: %s", file, err)
49 return nil, nil, err
50 }
51 debugf("download %s (%s)", file, res.Header.Get("X-Bz-Content-Sha1"))
52
53 fi, err := parseFileInfoHeaders(res.Header)
54 return res.Body, fi, err
55 }
56
57 func parseFileInfoHeaders(h http.Header) (*FileInfo, error) {
58 fi := &FileInfo{
59 ID: h.Get("X-Bz-File-Id"),
60 Name: h.Get("X-Bz-File-Name"),
61 ContentType: h.Get("Content-Type"),
62 ContentSHA1: h.Get("X-Bz-Content-Sha1"),
63 Action: "upload",
64 }
65 timestamp, err := strconv.ParseInt(h.Get("X-Bz-Upload-Timestamp"), 10, 64)
66 if err != nil {
67 return nil, err
68 }
69 fi.UploadTimestamp = time.Unix(timestamp/1e3, timestamp%1e3*1e6)
70 fi.ContentLength, err = strconv.Atoi(h.Get("Content-Length"))
71 if err != nil {
72 return nil, err
73 }
74
75 fi.CustomMetadata = make(map[string]interface{})
76 for name := range h {
77 if !strings.HasPrefix(name, "X-Bz-Info-") {
78 continue
79 }
80 fi.CustomMetadata[name[len("X-Bz-Info-"):]] = h.Get(name)
81 }
82
83 return fi, nil
84 }