/
bg_fg.go
89 lines (78 loc) · 1.57 KB
/
bg_fg.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
package pcscommand
import (
"fmt"
"github.com/iikira/BaiduPCS-Go/pcstable"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
)
var (
// BgMap 后台
BgMap = BgTasks{
tasks: sync.Map{},
sig: make(chan int64),
}
)
type (
// BgTasks 后台任务
BgTasks struct {
lastID int64
tasks sync.Map
started bool
sig chan int64
}
// BgDTaskItem 后台任务详情
BgDTaskItem struct {
id int
downloadOptions *DownloadOptions
pcspaths []string
}
)
// NewID 返回生成的 ID
func (b *BgTasks) NewID() int64 {
id := atomic.AddInt64(&b.lastID, 1)
return id
}
// TaskID 返回后台任务 id
func (t *BgDTaskItem) TaskID() int {
return t.id
}
// PrintAllBgTask 输出所有的后台任务
func (b *BgTasks) PrintAllBgTask() {
tb := pcstable.NewTable(os.Stdout)
tb.SetHeader([]string{"task_id", "files"})
b.tasks.Range(func(id, v interface{}) bool {
tb.Append([]string{strconv.FormatInt(id.(int64), 10), strings.Join(v.(*BgDTaskItem).pcspaths, ",")})
return true
})
tb.Render()
}
// RunBgDownload 执行后台下载
func RunBgDownload(paths []string, options *DownloadOptions) {
if !BgMap.started {
go func() {
for {
select {
case id := <-BgMap.sig:
BgMap.tasks.Delete(id)
fmt.Printf("任务:%d 已完成\n", id)
}
}
}()
} else {
BgMap.started = true
}
if options.Out == nil {
options.Out, _ = os.Open(os.DevNull)
}
task := new(BgDTaskItem)
task.pcspaths = paths
id := BgMap.NewID()
BgMap.tasks.Store(id, task)
go func(taskID int64) {
RunDownload(paths, options)
BgMap.sig <- taskID
}(id)
}