-
Notifications
You must be signed in to change notification settings - Fork 5
/
fetching.go
90 lines (83 loc) · 2.2 KB
/
fetching.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
86
87
88
89
90
package imageio
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
const (
RemoteResourceUrl = "https://github.com/imageio/imageio-binaries/raw/master/ffmpeg"
)
var (
FnamePerPlatform = map[string]string{
"osx32": "ffmpeg.osx",
"osx64": "ffmpeg.osx",
"win32": "ffmpeg.win32.exe",
"win64": "ffmpeg.win32.exe",
"linux32": "ffmpeg.linux32",
"linux64": "ffmpeg.linux64",
}
)
// The results from individual calls to it.
type PassThru struct {
io.Reader
CurrentSize int // Current # of bytes transferred
TotalSize int // Total # of bytes transferred
}
// Read 'overrides' the underlying io.Reader's Read method.
// This is the one that will be called by io.Copy(). We simply
// use it to keep track of byte counts and then forward the call.
func (pt *PassThru) Read(p []byte) (int, error) {
n, err := pt.Reader.Read(p)
pt.CurrentSize += n
if err == nil {
totalNum := pt.TotalSize / n
currentNum := pt.CurrentSize / n
if currentNum != 0 {
fmt.Printf("\r Downloading: %.0f%%", float64(currentNum) / float64(totalNum) * 100)
if float64(currentNum) / float64(totalNum) == 1.0 {
fmt.Println()
}
os.Stdout.Sync()
}
}
return n, err
}
// Get a filename for the local version of a file from the web
func GetRomoteFile(fname string) error {
url := RemoteResourceUrl + "/" + FnamePerPlatform[fname]
return downloadFromUrl(url, FnamePerPlatform[fname])
}
// Load requested file, downloading it if needed or requested.
func downloadFromUrl(url string, filename string) error {
log.Println("FFmpeg was not found on your computer; downloading it now from", url)
tmpFilename := filename + ".cache"
output, err := os.Create(tmpFilename)
if err != nil {
return err
}
response, err := http.Get(url)
fileSize := response.ContentLength
log.Printf("Total file size : %v bytes\n", fileSize)
if err != nil {
return err
}
defer response.Body.Close()
src := &PassThru{Reader: response.Body, TotalSize: int(fileSize)}
count, err := io.Copy(output, src)
if err != nil {
return err
}
if err := output.Close(); err != nil {
return err
}
if count == fileSize {
fmt.Println("Transferred", count, "bytes")
err := os.Rename(tmpFilename, filename)
if err != nil {
return err
}
}
return nil
}