-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
85 lines (75 loc) · 1.9 KB
/
utils.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
)
func getFileName(file string) string {
tokens := strings.Split(file, string(os.PathSeparator))
return tokens[len(tokens)-1]
}
func downloadFile(url string, path string) (string, error) {
tokens := strings.Split(url, "/")
fileName := tokens[len(tokens)-1]
// support for twitter https://pbs.twimg.com/media/DdFIBS0VQAMhpmv.png:orig
if subToken := strings.Split(fileName, ":"); len(subToken) == 2 {
fileName = subToken[0]
}
// support for twitter https://pbs.twimg.com/media/xxxx.mp4?tag=3
if subToken := strings.Split(fileName, "?"); len(subToken) == 2 {
fileName = subToken[0]
}
fullPath := path + string(os.PathSeparator) + fileName
if _, err := os.Stat(fullPath); err == nil {
logger.Infof("%s exists", fullPath)
return fullPath, nil
}
output, err := os.Create(fullPath)
if err != nil {
logger.Errorf("%s", err)
return "", err
}
defer output.Close()
logger.Debugf("--> Downloading %s", url)
response, err := http.Get(url)
if err != nil {
logger.Errorf("%s", err)
return "", err
}
defer response.Body.Close()
n, err := io.Copy(output, response.Body)
if err != nil {
logger.Errorf("%s", err)
return "", err
}
logger.Debugf("%s: %s", fullPath, ByteCountIEC(n))
return fullPath, nil
}
func removeFile(url string, path string) error {
tokens := strings.Split(url, "/")
fileName := tokens[len(tokens)-1]
logger.Debugf("--> Deleting %s", fileName)
fullPath := path + string(os.PathSeparator) + fileName
err := os.Remove(fullPath)
if err != nil {
logger.Errorf("%s", err)
return err
}
logger.Debugf("--> Deleted %s", fullPath)
return nil
}
func ByteCountIEC(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB",
float64(b)/float64(div), "KMGTPE"[exp])
}