-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.go
More file actions
542 lines (442 loc) · 11.9 KB
/
main.go
File metadata and controls
542 lines (442 loc) · 11.9 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
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
package main
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"flag"
"github.com/gofrs/uuid"
"github.com/kelseyhightower/envconfig"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
"github.com/joho/godotenv"
"github.com/schollz/progressbar/v3"
)
var Info = log.New(os.Stdout, "\u001b[34mINFO: \u001B[0m", log.LstdFlags|log.Lshortfile)
var Warning = log.New(os.Stdout, "\u001b[33mWARNING: \u001B[0m", log.LstdFlags|log.Lshortfile)
var Error = log.New(os.Stdout, "\u001b[31mERROR: \u001b[0m", log.LstdFlags|log.Lshortfile)
var Debug = log.New(os.Stdout, "\u001b[36mDEBUG: \u001B[0m", log.LstdFlags|log.Lshortfile)
type Config struct {
ApiURL string `envconfig:"API_URL" required:"true"`
SessionToken string `envconfig:"SESSION_TOKEN" required:"true"`
PartSize fs.SizeSuffix `envconfig:"PART_SIZE"`
Workers int `envconfig:"WORKERS" default:"4"`
RandomisePart bool `envconfig:"RANDOMISE_PART" default:"true"`
ChannelID int64 `envconfig:"CHANNEL_ID"`
}
type UploadPartOut struct {
ID string `json:"id"`
Name string `json:"name"`
PartId int `json:"partId"`
PartNo int `json:"partNo"`
TotalParts int `json:"totalParts"`
ChannelID int64 `json:"channelId"`
Size int64 `json:"size"`
}
type Part struct {
ID int64 `json:"id"`
PartNo int `json:"partNo"`
}
type FilePayload struct {
Name string `json:"name"`
Type string `json:"type"`
Parts []Part `json:"parts,omitempty"`
MimeType string `json:"mimeType"`
Path string `json:"path"`
Size int64 `json:"size"`
ChannelID int64 `json:"channelId"`
}
type CreateDirRequest struct {
Path string `json:"path"`
}
type MetadataRequestOptions struct {
PerPage uint64
SearchField string
Search string
NextPageToken string
}
type FileInfo struct {
Id string `json:"id"`
Name string `json:"name"`
MimeType string `json:"mimeType"`
Size int64 `json:"size"`
ParentId string `json:"parentId"`
Type string `json:"type"`
ModTime string `json:"updatedAt"`
}
type ReadMetadataResponse struct {
Files []FileInfo `json:"results"`
NextPageToken string `json:"nextPageToken,omitempty"`
}
type Uploader struct {
http *rest.Client
numWorkers int
partSize int64
channelID int64
pacer *fs.Pacer
ctx context.Context
}
var retryErrorCodes = []int{
429, // Too Many Requests.
500, // Internal Server Error
502, // Bad Gateway
503, // Service Unavailable
504, // Gateway Timeout
509, // Bandwidth Limit Exceeded
}
func shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, error) {
if fserrors.ContextError(ctx, &err) {
return false, err
}
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
}
func loadConfigFromEnv() (*Config, error) {
var config Config
err := godotenv.Load("upload.env")
if err != nil {
return nil, err
}
err = envconfig.Process("", &config)
if err != nil {
panic(err)
}
if config.PartSize == 0 {
config.PartSize = 1000 * fs.Mebi
}
return &config, nil
}
type ProgressReader struct {
io.Reader
Reporter func(r int64)
}
func (pr *ProgressReader) Read(p []byte) (n int, err error) {
n, err = pr.Reader.Read(p)
pr.Reporter(int64(n))
return
}
func (u *Uploader) uploadFile(filePath string, destDir string, randomisePart bool) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
buffer := make([]byte, 512)
_, err = file.Read(buffer)
if err != nil {
Error.Println("Error reading file:", filePath, err)
return nil
}
mimeType := http.DetectContentType(buffer)
fileInfo, _ := file.Stat()
fileSize := fileInfo.Size()
fileName := filepath.Base(filePath)
input := fmt.Sprintf("%s:%s:%d", fileName, destDir, fileSize)
hash := md5.Sum([]byte(input))
hashString := hex.EncodeToString(hash[:])
uploadURL := fmt.Sprintf("/api/uploads/%s", hashString)
var wg sync.WaitGroup
numParts := fileSize / u.partSize
if fileSize%u.partSize != 0 {
numParts++
}
uploadedParts := make(chan UploadPartOut, numParts)
concurrentWorkers := make(chan struct{}, u.numWorkers)
bar := progressbar.NewOptions64(fileSize,
progressbar.OptionSetWriter(os.Stderr),
progressbar.OptionEnableColorCodes(true),
progressbar.OptionShowBytes(true),
progressbar.OptionSetWidth(10),
progressbar.OptionThrottle(65*time.Millisecond),
progressbar.OptionSetDescription(fileName),
progressbar.OptionSetTheme(progressbar.Theme{
Saucer: "[green]=[reset]",
SaucerHead: "[green]>[reset]",
SaucerPadding: " ",
BarStart: "[",
BarEnd: "]",
}),
progressbar.OptionFullWidth(),
progressbar.OptionSetRenderBlankState(true))
go func() {
wg.Wait()
close(uploadedParts)
bar.Finish()
bar.Close()
}()
for i := int64(0); i < numParts; i++ {
start := i * u.partSize
end := start + u.partSize
if end > fileSize {
end = fileSize
}
concurrentWorkers <- struct{}{}
wg.Add(1)
go func(partNumber int64, start, end int64) {
defer wg.Done()
defer func() {
<-concurrentWorkers
}()
partFile, err := os.Open(filePath)
if err != nil {
Error.Println("Error:", err)
return
}
defer partFile.Close()
_, err = partFile.Seek(start, io.SeekStart)
if err != nil {
Error.Println("Error:", err)
return
}
name := fileName
if randomisePart {
u1, _ := uuid.NewV4()
name = hex.EncodeToString(u1.Bytes())
} else if numParts > 1 {
name = fmt.Sprintf("%s.part.%03d", fileName, partNumber+1)
}
pr := &ProgressReader{partFile, func(r int64) {
bar.Add64(r)
}}
contentLength := end - start
reader := io.LimitReader(pr, contentLength)
opts := rest.Opts{
Method: "POST",
Path: uploadURL,
Body: reader,
ContentLength: &contentLength,
Parameters: url.Values{
"fileName": []string{name},
"partNo": []string{strconv.FormatInt(partNumber+1, 10)},
"totalparts": []string{strconv.FormatInt(int64(numParts), 10)},
"channelId": []string{strconv.FormatInt(int64(u.channelID), 10)},
},
}
var part UploadPartOut
resp, err := u.http.CallJSON(context.TODO(), &opts, nil, &part)
if err != nil {
Error.Println("Error:", err)
return
}
if resp.StatusCode == 200 {
uploadedParts <- part
}
}(i, start, end)
}
var parts []Part
for uploadPart := range uploadedParts {
parts = append(parts, Part{ID: int64(uploadPart.PartId), PartNo: uploadPart.PartNo})
}
if len(parts) != int(numParts) {
return fmt.Errorf("upload failed: %s", fileName)
}
sort.Slice(parts, func(i, j int) bool {
return parts[i].PartNo < parts[j].PartNo
})
filePayload := FilePayload{
Name: fileName,
Type: "file",
Parts: parts,
MimeType: mimeType,
Path: destDir,
Size: fileSize,
ChannelID: u.channelID,
}
json.Marshal(filePayload)
if err != nil {
return err
}
opts := rest.Opts{
Method: "POST",
Path: "/api/files",
}
err = u.pacer.Call(func() (bool, error) {
resp, err := u.http.CallJSON(u.ctx, &opts, &filePayload, nil)
return shouldRetry(u.ctx, resp, err)
})
if err != nil {
return err
}
err = u.pacer.Call(func() (bool, error) {
resp, err := u.http.CallJSON(u.ctx, &rest.Opts{Method: "DELETE", Path: uploadURL}, nil, nil)
return shouldRetry(u.ctx, resp, err)
})
if err != nil {
return err
}
return nil
}
func (u *Uploader) createRemoteDir(path string) error {
opts := rest.Opts{
Method: "POST",
Path: "/api/files/makedir",
}
if len(path) == 0 || path[0] != '/' {
path = "/" + path
}
mkdir := CreateDirRequest{
Path: path,
}
err := u.pacer.Call(func() (bool, error) {
resp, err := u.http.CallJSON(u.ctx, &opts, &mkdir, nil)
return shouldRetry(u.ctx, resp, err)
})
if err != nil {
return err
}
return nil
}
func (u *Uploader) readMetaDataForPath(path string, options *MetadataRequestOptions) (*ReadMetadataResponse, error) {
opts := rest.Opts{
Method: "GET",
Path: "/api/files",
Parameters: url.Values{
"path": []string{path},
"perPage": []string{strconv.FormatUint(options.PerPage, 10)},
"sort": []string{"name"},
"order": []string{"asc"},
"op": []string{"list"},
"nextPageToken": []string{options.NextPageToken},
},
}
var err error
var info ReadMetadataResponse
var resp *http.Response
err = u.pacer.Call(func() (bool, error) {
resp, err = u.http.CallJSON(u.ctx, &opts, nil, &info)
return shouldRetry(u.ctx, resp, err)
})
if err != nil && resp.StatusCode == 404 {
return nil, fs.ErrorDirNotFound
}
if err != nil {
return nil, err
}
return &info, nil
}
func (u *Uploader) list(path string) (files []FileInfo, err error) {
var limit uint64 = 500
var nextPageToken string = ""
for {
opts := &MetadataRequestOptions{
PerPage: limit,
NextPageToken: nextPageToken,
}
info, err := u.readMetaDataForPath(path, opts)
if err != nil {
return nil, err
}
files = append(files, info.Files...)
nextPageToken = info.NextPageToken
if nextPageToken == "" {
break
}
}
return files, nil
}
func (u *Uploader) checkFileExists(name string, files []FileInfo) bool {
for _, item := range files {
if item.Name == name {
return true
}
}
return false
}
func (u *Uploader) uploadFilesInDirectory(sourcePath string, destDir string, randomisePart bool) error {
entries, err := os.ReadDir(sourcePath)
if err != nil {
return err
}
destDir = strings.ReplaceAll(destDir, "\\", "/")
files, err := u.list(destDir)
if err != nil {
return err
}
for _, entry := range entries {
fullPath := filepath.Join(sourcePath, entry.Name())
if entry.IsDir() {
subDir := filepath.Join(destDir, entry.Name())
subDir = strings.ReplaceAll(subDir, "\\", "/")
err := u.createRemoteDir(subDir)
if err != nil {
Error.Fatalln(err)
}
err = u.uploadFilesInDirectory(fullPath, subDir, randomisePart)
if err != nil {
Error.Println(err)
}
} else {
exists := u.checkFileExists(entry.Name(), files)
if !exists {
err := u.uploadFile(fullPath, destDir, randomisePart)
if err != nil {
Error.Println("upload failed:", entry.Name(), err)
}
} else {
Info.Println("file exists:", entry.Name())
}
}
}
return nil
}
func main() {
sourcePath := flag.String("path", "", "File or directory path to upload")
destDir := flag.String("dest", "", "Remote directory for uploaded files")
flag.Parse()
if *sourcePath == "" || *destDir == "" {
fmt.Println("Usage: ./uploader -path <file_or_directory_path> -dest <remote_directory>")
return
}
config, err := loadConfigFromEnv()
if err != nil {
Error.Fatalln(err)
}
authCookie := &http.Cookie{
Name: "user-session",
Value: config.SessionToken,
}
ctx := context.Background()
httpClient := rest.NewClient(http.DefaultClient).SetRoot(config.ApiURL).SetCookie(authCookie)
pacer := fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(400*time.Millisecond),
pacer.MaxSleep(5*time.Second), pacer.DecayConstant(2), pacer.AttackConstant(0)))
uploader := &Uploader{
http: httpClient,
numWorkers: config.Workers,
channelID: config.ChannelID,
partSize: int64(config.PartSize),
pacer: pacer,
ctx: ctx,
}
err = uploader.createRemoteDir(*destDir)
if err != nil {
Error.Fatalln(err)
}
if fileInfo, err := os.Stat(*sourcePath); err == nil {
if fileInfo.IsDir() {
err := uploader.uploadFilesInDirectory(*sourcePath, *destDir, config.RandomisePart)
if err != nil {
Error.Println("upload failed:", err)
}
} else {
if err := uploader.uploadFile(*sourcePath, *destDir, config.RandomisePart); err != nil {
Error.Println("upload failed:", err)
}
}
} else {
Error.Fatalln(err)
}
Info.Println("Uploads complete!")
}