This repository was archived by the owner on Jun 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdropbox.go
More file actions
47 lines (37 loc) · 1.31 KB
/
dropbox.go
File metadata and controls
47 lines (37 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package filecache
import (
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
// DropboxDownload will download a file from the specified Dropbox location into localFile
func DropboxDownload(dr *DownloadRecord, localFile io.Writer, downloadTimeout time.Duration) error {
// In the case of Dropbox files, the path will contain the base64-encoded file URL after dropbox/
fileURL, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(dr.Path, "dropbox/"))
if err != nil {
return fmt.Errorf("could not base64 decode file URL: %s", err)
}
startTime := time.Now()
ctx, cancelFunc := context.WithTimeout(context.Background(), downloadTimeout)
defer cancelFunc()
req, err := http.NewRequest(http.MethodGet, string(fileURL), nil)
if err != nil {
return fmt.Errorf("could not create HTTP request for URL %q: %s", fileURL, err)
}
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return fmt.Errorf("failed to download file %q: %s", fileURL, err)
}
defer resp.Body.Close()
numBytes, err := io.Copy(localFile, resp.Body)
if err != nil {
return fmt.Errorf("failed to write local file: %s", err)
}
log.Debugf("Took %.2fms to download %d bytes from Dropbox for %s", time.Since(startTime).Seconds()*1000, numBytes, dr.Path)
return nil
}