forked from iawia002/lux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
downloader.go
701 lines (649 loc) · 17.4 KB
/
downloader.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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
package downloader
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"sync"
"time"
"github.com/cheggaaa/pb/v3"
"github.com/pkg/errors"
"github.com/iawia002/lux/extractors"
"github.com/iawia002/lux/request"
"github.com/iawia002/lux/utils"
)
// Options defines options used in downloading.
type Options struct {
InfoOnly bool
Silent bool
Stream string
AudioOnly bool
Refer string
OutputPath string
OutputName string
FileNameLength int
Caption bool
MultiThread bool
ThreadNumber int
RetryTimes int
ChunkSizeMB int
// Aria2
UseAria2RPC bool
Aria2Token string
Aria2Method string
Aria2Addr string
}
// Downloader is the default downloader.
type Downloader struct {
bar *pb.ProgressBar
option Options
}
const (
DOWNLOAD_FILE_EXT = ".download"
)
func progressBar(size int64) *pb.ProgressBar {
tmpl := `{{counters .}} {{bar . "[" "=" ">" "-" "]"}} {{speed .}} {{percent . | green}} {{rtime .}}`
return pb.New64(size).
Set(pb.Bytes, true).
SetMaxWidth(1000).
SetTemplate(pb.ProgressBarTemplate(tmpl))
}
// New returns a new Downloader implementation.
func New(option Options) *Downloader {
downloader := &Downloader{
option: option,
}
return downloader
}
// caption downloads danmaku, subtitles, etc
func (downloader *Downloader) caption(url, fileName, ext string, transform func([]byte) ([]byte, error)) error {
refer := downloader.option.Refer
if refer == "" {
refer = url
}
body, err := request.GetByte(url, refer, nil)
if err != nil {
return err
}
if transform != nil {
body, err = transform(body)
if err != nil {
return err
}
}
filePath, err := utils.FilePath(fileName, ext, downloader.option.FileNameLength, downloader.option.OutputPath, true)
if err != nil {
return err
}
file, fileError := os.Create(filePath)
if fileError != nil {
return fileError
}
defer file.Close() // nolint
if _, err = file.Write(body); err != nil {
return err
}
return nil
}
func (downloader *Downloader) writeFile(url string, file *os.File, headers map[string]string) (int64, error) {
res, err := request.Request(http.MethodGet, url, nil, headers)
if err != nil {
return 0, err
}
defer res.Body.Close() // nolint
barWriter := downloader.bar.NewProxyWriter(file)
// Note that io.Copy reads 32kb(maximum) from input and writes them to output, then repeats.
// So don't worry about memory.
written, copyErr := io.Copy(barWriter, res.Body)
if copyErr != nil && copyErr != io.EOF {
return written, errors.Errorf("file copy error: %s", copyErr)
}
return written, nil
}
func (downloader *Downloader) save(part *extractors.Part, refer, fileName string) error {
filePath, err := utils.FilePath(fileName, part.Ext, downloader.option.FileNameLength, downloader.option.OutputPath, false)
if err != nil {
return err
}
fileSize, exists, err := utils.FileSize(filePath)
if err != nil {
return err
}
// Skip segment file
// TODO: Live video URLs will not return the size
if exists && fileSize == part.Size {
downloader.bar.Add64(fileSize)
return nil
}
tempFilePath := filePath + DOWNLOAD_FILE_EXT
tempFileSize, _, err := utils.FileSize(tempFilePath)
if err != nil {
return err
}
headers := map[string]string{
"Referer": refer,
}
var (
file *os.File
fileError error
)
if tempFileSize > 0 {
// range start from 0, 0-1023 means the first 1024 bytes of the file
headers["Range"] = fmt.Sprintf("bytes=%d-", tempFileSize)
file, fileError = os.OpenFile(tempFilePath, os.O_APPEND|os.O_WRONLY, 0644)
downloader.bar.Add64(tempFileSize)
} else {
file, fileError = os.Create(tempFilePath)
}
if fileError != nil {
return fileError
}
// close and rename temp file at the end of this function
defer func() {
// must close the file before rename or it will cause
// `The process cannot access the file because it is being used by another process.` error.
file.Close() // nolint
if err == nil {
os.Rename(tempFilePath, filePath) // nolint
}
}()
if downloader.option.ChunkSizeMB > 0 {
var start, end, chunkSize int64
chunkSize = int64(downloader.option.ChunkSizeMB) * 1024 * 1024
remainingSize := part.Size
if tempFileSize > 0 {
start = tempFileSize
remainingSize -= tempFileSize
}
chunk := remainingSize / chunkSize
if remainingSize%chunkSize != 0 {
chunk++
}
var i int64 = 1
for ; i <= chunk; i++ {
end = start + chunkSize - 1
headers["Range"] = fmt.Sprintf("bytes=%d-%d", start, end)
temp := start
for i := 0; ; i++ {
written, err := downloader.writeFile(part.URL, file, headers)
if err == nil {
break
} else if i+1 >= downloader.option.RetryTimes {
return err
}
temp += written
headers["Range"] = fmt.Sprintf("bytes=%d-%d", temp, end)
time.Sleep(1 * time.Second)
}
start = end + 1
}
} else {
temp := tempFileSize
for i := 0; ; i++ {
written, err := downloader.writeFile(part.URL, file, headers)
if err == nil {
break
} else if i+1 >= downloader.option.RetryTimes {
return err
}
temp += written
headers["Range"] = fmt.Sprintf("bytes=%d-", temp)
time.Sleep(1 * time.Second)
}
}
return nil
}
func (downloader *Downloader) multiThreadSave(dataPart *extractors.Part, refer, fileName string) error {
filePath, err := utils.FilePath(fileName, dataPart.Ext, downloader.option.FileNameLength, downloader.option.OutputPath, false)
if err != nil {
return err
}
fileSize, exists, err := utils.FileSize(filePath)
if err != nil {
return err
}
// Skip segment file
// TODO: Live video URLs will not return the size
if exists && fileSize == dataPart.Size {
downloader.bar.Add64(fileSize)
return nil
}
tmpFilePath := filePath + DOWNLOAD_FILE_EXT
tmpFileSize, tmpExists, err := utils.FileSize(tmpFilePath)
if err != nil {
return err
}
if tmpExists {
if tmpFileSize == dataPart.Size {
downloader.bar.Add64(dataPart.Size)
return os.Rename(tmpFilePath, filePath)
}
if err = os.Remove(tmpFilePath); err != nil {
return err
}
}
// Scan all parts
parts, err := readDirAllFilePart(filePath, fileName, dataPart.Ext)
if err != nil {
return err
}
var unfinishedPart []*FilePartMeta
savedSize := int64(0)
if len(parts) > 0 {
lastEnd := int64(-1)
for i, part := range parts {
// If some parts are lost, re-insert one part.
if part.Start-lastEnd != 1 {
newPart := &FilePartMeta{
Index: part.Index - 0.000001,
Start: lastEnd + 1,
End: part.Start - 1,
Cur: lastEnd + 1,
}
tmp := append([]*FilePartMeta{}, parts[:i]...)
tmp = append(tmp, newPart)
parts = append(tmp, parts[i:]...)
unfinishedPart = append(unfinishedPart, newPart)
}
// When the part has been downloaded in whole, part.Cur is equal to part.End + 1
if part.Cur <= part.End+1 {
savedSize += part.Cur - part.Start
if part.Cur < part.End+1 {
unfinishedPart = append(unfinishedPart, part)
}
} else {
// The size of this part has been saved greater than the part size, delete it transparently and re-download.
err = os.Remove(filePartPath(filePath, part))
if err != nil {
return err
}
part.Cur = part.Start
unfinishedPart = append(unfinishedPart, part)
}
lastEnd = part.End
}
if lastEnd != dataPart.Size-1 {
newPart := &FilePartMeta{
Index: parts[len(parts)-1].Index + 1,
Start: lastEnd + 1,
End: dataPart.Size - 1,
Cur: lastEnd + 1,
}
parts = append(parts, newPart)
unfinishedPart = append(unfinishedPart, newPart)
}
} else {
var start, end, partSize int64
var i float32
partSize = dataPart.Size / int64(downloader.option.ThreadNumber)
i = 0
for start < dataPart.Size {
end = start + partSize - 1
if end > dataPart.Size {
end = dataPart.Size - 1
} else if int(i+1) == downloader.option.ThreadNumber && end < dataPart.Size {
end = dataPart.Size - 1
}
part := &FilePartMeta{
Index: i,
Start: start,
End: end,
Cur: start,
}
parts = append(parts, part)
unfinishedPart = append(unfinishedPart, part)
start = end + 1
i++
}
}
if savedSize > 0 {
downloader.bar.Add64(savedSize)
if savedSize == dataPart.Size {
return mergeMultiPart(filePath, parts)
}
}
wgp := utils.NewWaitGroupPool(downloader.option.ThreadNumber)
var errs []error
var mu sync.Mutex
for _, part := range unfinishedPart {
wgp.Add()
go func(part *FilePartMeta) {
file, err := os.OpenFile(filePartPath(filePath, part), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
mu.Lock()
errs = append(errs, err)
mu.Unlock()
return
}
defer func() {
file.Close() // nolint
wgp.Done()
}()
var end, chunkSize int64
headers := map[string]string{
"Referer": refer,
}
if downloader.option.ChunkSizeMB <= 0 {
chunkSize = part.End - part.Start + 1
} else {
chunkSize = int64(downloader.option.ChunkSizeMB) * 1024 * 1024
}
remainingSize := part.End - part.Cur + 1
if part.Cur == part.Start {
// Only write part to new file.
err = writeFilePartMeta(file, part)
if err != nil {
mu.Lock()
errs = append(errs, err)
mu.Unlock()
return
}
}
for remainingSize > 0 {
end = computeEnd(part.Cur, chunkSize, part.End)
headers["Range"] = fmt.Sprintf("bytes=%d-%d", part.Cur, end)
temp := part.Cur
for i := 0; ; i++ {
written, err := downloader.writeFile(dataPart.URL, file, headers)
if err == nil {
remainingSize -= chunkSize
break
} else if i+1 >= downloader.option.RetryTimes {
mu.Lock()
errs = append(errs, err)
mu.Unlock()
return
}
temp += written
headers["Range"] = fmt.Sprintf("bytes=%d-%d", temp, end)
}
part.Cur = end + 1
}
}(part)
}
wgp.Wait()
if len(errs) > 0 {
return errs[0]
}
return mergeMultiPart(filePath, parts)
}
func filePartPath(filepath string, part *FilePartMeta) string {
return fmt.Sprintf("%s.part%f", filepath, part.Index)
}
func computeEnd(s, chunkSize, max int64) int64 {
var end int64
end = s + chunkSize - 1
if end > max {
end = max
}
return end
}
func readDirAllFilePart(filePath, filename, extname string) ([]*FilePartMeta, error) {
dirPath := filepath.Dir(filePath)
dir, err := os.Open(dirPath)
if err != nil {
return nil, errors.WithStack(err)
}
defer dir.Close() // nolint
fns, err := dir.Readdir(0)
if err != nil {
return nil, errors.WithStack(err)
}
var metas []*FilePartMeta
reg := regexp.MustCompile(fmt.Sprintf("%s.%s.part.+", regexp.QuoteMeta(filename), extname))
for _, fn := range fns {
if reg.MatchString(fn.Name()) {
meta, err := parseFilePartMeta(path.Join(dirPath, fn.Name()), fn.Size())
if err != nil {
return nil, errors.WithStack(err)
}
metas = append(metas, meta)
}
}
sort.SliceStable(metas, func(i, j int) bool {
return metas[i].Index < metas[j].Index
})
return metas, nil
}
func parseFilePartMeta(filepath string, fileSize int64) (*FilePartMeta, error) {
meta := new(FilePartMeta)
size := binary.Size(*meta)
file, err := os.OpenFile(filepath, os.O_RDWR, 0666)
if err != nil {
return nil, errors.WithStack(err)
}
defer file.Close() // nolint
var buf [512]byte
readSize, err := file.ReadAt(buf[0:size], 0)
if err != nil && err != io.EOF {
return nil, errors.WithStack(err)
}
if readSize < size {
return nil, errors.Errorf("the file has been broked, please delete all part files and re-download")
}
err = binary.Read(bytes.NewBuffer(buf[:size]), binary.LittleEndian, meta)
if err != nil {
return nil, errors.WithStack(err)
}
savedSize := fileSize - int64(binary.Size(meta))
meta.Cur = meta.Start + savedSize
return meta, nil
}
func writeFilePartMeta(file *os.File, meta *FilePartMeta) error {
return binary.Write(file, binary.LittleEndian, meta)
}
func mergeMultiPart(filepath string, parts []*FilePartMeta) error {
tempFilePath := filepath + DOWNLOAD_FILE_EXT
tempFile, err := os.OpenFile(tempFilePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return err
}
var partFiles []*os.File
defer func() {
for _, f := range partFiles {
f.Close() // nolint
os.Remove(f.Name()) // nolint
}
}()
for _, part := range parts {
file, err := os.Open(filePartPath(filepath, part))
if err != nil {
return err
}
partFiles = append(partFiles, file)
_, err = file.Seek(int64(binary.Size(part)), 0)
if err != nil {
return err
}
_, err = io.Copy(tempFile, file)
if err != nil {
return err
}
}
tempFile.Close() // nolint
err = os.Rename(tempFilePath, filepath)
return err
}
func (downloader *Downloader) aria2(title string, stream *extractors.Stream) error {
rpcData := Aria2RPCData{
JSONRPC: "2.0",
ID: "lux", // can be modified
Method: "aria2.addUri",
}
rpcData.Params[0] = "token:" + downloader.option.Aria2Token
var urls []string
for _, p := range stream.Parts {
urls = append(urls, p.URL)
}
var inputs Aria2Input
inputs.Header = append(inputs.Header, "Referer: "+downloader.option.Refer)
for i := range urls {
rpcData.Params[1] = urls[i : i+1]
inputs.Out = fmt.Sprintf("%s[%d].%s", title, i, stream.Parts[0].Ext)
rpcData.Params[2] = &inputs
jsonData, err := json.Marshal(rpcData)
if err != nil {
return err
}
reqURL := fmt.Sprintf("%s://%s/jsonrpc", downloader.option.Aria2Method, downloader.option.Aria2Addr)
req, err := http.NewRequest(http.MethodPost, reqURL, bytes.NewBuffer(jsonData))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
var client = http.Client{Timeout: 30 * time.Second}
res, err := client.Do(req)
if err != nil {
return err
}
// The http Client and Transport guarantee that Body is always
// non-nil, even on responses without a body or responses with
// a zero-length body.
res.Body.Close() // nolint
}
return nil
}
// Download download urls
func (downloader *Downloader) Download(data *extractors.Data) error {
if len(data.Streams) == 0 {
return errors.Errorf("no streams in title %s", data.Title)
}
sortedStreams := genSortedStreams(data.Streams)
if downloader.option.InfoOnly {
printInfo(data, sortedStreams)
return nil
}
title := downloader.option.OutputName
if title == "" {
title = data.Title
}
title = utils.FileName(title, "", downloader.option.FileNameLength)
streamName := downloader.option.Stream
if streamName == "" {
streamName = sortedStreams[0].ID
}
stream, ok := data.Streams[streamName]
if !ok {
return errors.Errorf("no stream named %s", streamName)
}
if downloader.option.AudioOnly {
var isFound bool
reg, err := regexp.Compile("audio+")
if err != nil {
return err
}
for _, s := range sortedStreams {
// Looking for the best quality
if reg.MatchString(s.Quality) {
isFound = true
stream = data.Streams[s.ID]
break
}
}
if !isFound {
return errors.Errorf("No audio stream found")
}
}
if !downloader.option.Silent {
printStreamInfo(data, stream)
}
// download caption
if downloader.option.Caption && data.Captions != nil {
fmt.Println("\nDownloading captions...")
for k, v := range data.Captions {
if v != nil {
fmt.Printf("Downloading %s ...\n", k)
downloader.caption(v.URL, title, v.Ext, v.Transform) // nolint
}
}
}
// Use aria2 rpc to download
if downloader.option.UseAria2RPC {
return downloader.aria2(title, stream)
}
// Skip the complete file that has been merged
mergedFilePath, err := utils.FilePath(title, stream.Ext, downloader.option.FileNameLength, downloader.option.OutputPath, false)
if err != nil {
return err
}
_, mergedFileExists, err := utils.FileSize(mergedFilePath)
if err != nil {
return err
}
// After the merge, the file size has changed, so we do not check whether the size matches
if mergedFileExists {
fmt.Printf("%s: file already exists, skipping\n", mergedFilePath)
return nil
}
downloader.bar = progressBar(stream.Size)
if !downloader.option.Silent {
downloader.bar.Start()
}
if len(stream.Parts) == 1 {
// only one fragment
var err error
if downloader.option.MultiThread {
err = downloader.multiThreadSave(stream.Parts[0], data.URL, title)
} else {
err = downloader.save(stream.Parts[0], data.URL, title)
}
if err != nil {
return err
}
downloader.bar.Finish()
return nil
}
wgp := utils.NewWaitGroupPool(downloader.option.ThreadNumber)
// multiple fragments
errs := make([]error, 0)
lock := sync.Mutex{}
parts := make([]string, len(stream.Parts))
for index, part := range stream.Parts {
if len(errs) > 0 {
break
}
partFileName := fmt.Sprintf("%s[%d]", title, index)
partFilePath, err := utils.FilePath(partFileName, part.Ext, downloader.option.FileNameLength, downloader.option.OutputPath, false)
if err != nil {
return err
}
parts[index] = partFilePath
wgp.Add()
go func(part *extractors.Part, fileName string) {
defer wgp.Done()
var err error
if downloader.option.MultiThread {
err = downloader.multiThreadSave(part, data.URL, fileName)
} else {
err = downloader.save(part, data.URL, fileName)
}
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
}
}(part, partFileName)
}
wgp.Wait()
if len(errs) > 0 {
return errs[0]
}
downloader.bar.Finish()
if data.Type != extractors.DataTypeVideo {
return nil
}
if !downloader.option.Silent {
fmt.Printf("Merging video parts into %s\n", mergedFilePath)
}
if stream.Ext != "mp4" || stream.NeedMux {
return utils.MergeFilesWithSameExtension(parts, mergedFilePath)
}
return utils.MergeToMP4(parts, mergedFilePath, title)
}