-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
221 lines (186 loc) · 5.01 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package main
import (
"os"
"io"
"fmt"
"log"
"time"
"flag"
"path"
"sync"
"syscall"
"strconv"
"net/url"
"net/http"
"io/ioutil"
"encoding/json"
)
// Settings
var RemoteFolderId int
var RemoteFolderName = flag.String("putio-folder", "",
"putio folder name under your root")
var AccessToken = flag.String("oauth-token", "", "Oauth Token")
var LocalFolderPath = flag.String("local-path", "", "local folder to fetch")
const ApiUrl = "https://api.put.io/v2/"
const DownloadExtension = ".putiodl"
const MaxConnection = 10
// Putio api response types
type FilesResponse struct {
Files []File `json:"files"`
}
type File struct {
Id int `json:"id"`
Name string `json:"name"`
ContentType string `json:"content_type"`
Size int `json:"size"`
}
func (file *File) DownloadUrl() string {
method := "files/" + strconv.Itoa(file.Id) + "/download"
return MakeUrl(method, map[string]string{})
}
// Utility functions
func ParamsWithAuth(params map[string]string) string {
newParams := url.Values{}
for k, v := range params {
newParams.Add(k, v)
}
newParams.Add("oauth_token", *AccessToken)
return newParams.Encode()
}
func MakeUrl(method string, params map[string]string) string {
newParams := ParamsWithAuth(params)
return ApiUrl + method + "?" + newParams
}
func SaveRemoteFolderId() {
// Making sure this folder exits. Creating if necessary
// and updating global variable
files := FilesListRequest(0)
log.Println(files)
// Looping through files to get the putitin folder
for _, file := range files {
if file.Name == *RemoteFolderName {
log.Println("Found putitin folder")
RemoteFolderId = file.Id
}
}
}
func FilesListRequest(parentId int) []File {
// Preparing url
params := map[string]string{"parent_id": strconv.Itoa(parentId)}
folderUrl := MakeUrl("files/list", params)
log.Println(folderUrl)
resp, err := http.Get(folderUrl)
if err != nil {
log.Fatal(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
filesResponse := FilesResponse{}
json.Unmarshal(body, &filesResponse)
return filesResponse.Files
}
func WalkAndDownload(parentId int, folderPath string) {
// Creating if the encapsulating folder is absent
if _, err := os.Stat(folderPath); err != nil {
err := os.Mkdir(folderPath, 0755)
if err != nil {
log.Fatal(err)
}
}
files := FilesListRequest(parentId)
log.Println("Walking in", folderPath)
for _, file := range files {
path := path.Join(folderPath, file.Name)
if file.ContentType == "application/x-directory" {
go WalkAndDownload(file.Id, path)
} else {
if _, err := os.Stat(path); err != nil {
log.Println(err)
DownloadFile(&file, path)
}
}
}
}
func DownloadChunk(file *File, fp *os.File, offset int,
size int, chunkWg *sync.WaitGroup) {
defer chunkWg.Done()
log.Println("Downloading chunk starting from:", offset, "bytes:", size)
req, err := http.NewRequest("GET", file.DownloadUrl(), nil)
if err != nil {
log.Fatal(err)
}
rangeHeader := fmt.Sprintf("bytes=%d-%d\r\n", offset, offset + size)
log.Println(rangeHeader)
req.Header.Add("Range", rangeHeader)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
buffer := make([]byte, 32*1024)
for {
nr, er := resp.Body.Read(buffer)
if nr > 0 {
nw, ew := fp.WriteAt(buffer[0:nr], int64(offset))
offset += nw
if ew != nil {
log.Fatal(ew)
}
}
if er == io.EOF {
log.Println("Seen EOF")
break
}
if er != nil {
log.Println(er)
break
}
}
}
func DownloadFile(file *File, path string) {
// Creating a waitgroup to wait for all chunks to be
// downloaded before exiting
var chunkWg sync.WaitGroup
fp, err := os.Create(path + DownloadExtension)
if err != nil {
log.Fatal(err)
}
defer fp.Close()
// Allocating space for the file
syscall.Fallocate(int(fp.Fd()), 0, 0, int64(file.Size))
chunkSize := file.Size / MaxConnection
excessBytes := file.Size % MaxConnection
log.Println("Chunk size:", chunkSize, "Excess:", excessBytes)
offset := 0
for i := MaxConnection; i > 0; i-- {
if i == 1 {
// Add excess bytes to last connection
chunkSize += excessBytes
}
chunkWg.Add(1)
go DownloadChunk(file, fp, offset, chunkSize, &chunkWg)
offset += chunkSize
}
chunkWg.Wait()
fp.Close()
er := os.Rename(path + DownloadExtension, path)
if er != nil {
log.Fatal(err)
}
log.Println("Download completed")
}
func init() {
flag.Parse()
SaveRemoteFolderId()
}
func main() {
log.Println("Starting...")
for {
WalkAndDownload(RemoteFolderId, *LocalFolderPath)
time.Sleep(10 * time.Minute)
}
log.Println("Exiting...")
}