-
Notifications
You must be signed in to change notification settings - Fork 3
/
task.go
186 lines (165 loc) · 4.34 KB
/
task.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
package main
import (
"bufio"
"context"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
)
// TaskStatus is status indicator consisted with limited int consts
type TaskStatus int
// const for indicating each task's status
const (
TaskStatusQueued TaskStatus = iota
TaskStatusDownloading
TaskStatusComplete
TaskStatusFail
TaskStatusCancel
)
// Task is model of downloading task
type Task struct {
Name string `json:"name"`
Address string `json:"address"`
Status TaskStatus `json:"status"`
Info string `json:"info"`
rawProgress string
Progress *TaskProgress `json:"progress"`
fullLog string
context context.Context
cancel context.CancelFunc
}
// TaskProgress is model of task's progress detail
type TaskProgress struct {
Total string `json:"total"`
Current string `json:"current"`
Speed string `json:"speed"`
Percentage string `json:"percentage"`
TimeLeft string `json:"time_left"`
}
// NewTask is initiator of Task struct for context assigning
func NewTask(videoAddress string) *Task {
ctx, can := context.WithCancel(context.Background())
return &Task{Address: videoAddress, context: ctx, cancel: can}
}
// Start starts downloading
func (t *Task) Start() {
go func() {
var (
log strings.Builder
err error
line string
buf []byte
linenum int
)
defer func() {
t.fullLog = log.String()
}()
cmd := exec.Command("./annie", "-o", CurrentConfig.DownloadDirectory, t.Address)
if CurrentConfig.HTTPProxy {
cmd.Env = append(
os.Environ(),
"HTTP_PROXY="+CurrentConfig.HTTPProxyAddress,
)
}
std, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
errString := fmt.Sprintf("\n%s", err)
t.Info += errString
t.fullLog += errString
t.Status = TaskStatusFail
return
}
t.Status = TaskStatusDownloading
reader := bufio.NewReader(std)
for err == nil {
select {
case <-t.context.Done():
log.WriteString("\nexit because context canceled")
t.Status = TaskStatusCancel
return
default:
}
buf, err = reader.ReadBytes(13)
line = string(buf)
if linenum == 0 {
t.Info = line
t.ParseInfo()
} else {
t.rawProgress = line
t.ParseProgress()
}
log.WriteString(line)
linenum++
}
cmd.Wait()
exitDetail := fmt.Sprintf("\ntask success? = %t, exit code = %d", cmd.ProcessState.Success(), cmd.ProcessState.ExitCode())
log.WriteString(exitDetail)
t.Info += exitDetail
exitString := fmt.Sprintf("\nexited with %s", err)
log.WriteString(exitString)
t.Info += exitString
if !CurrentConfig.IgnoreExitError && !cmd.ProcessState.Success() {
t.Status = TaskStatusFail
} else {
t.Status = TaskStatusComplete
}
}()
}
// Stop stops (cancels) downloading
func (t *Task) Stop() {
if t.cancel != nil {
t.cancel()
}
}
// ParseInfo tries parsing downloading information from annie's stdout
func (t *Task) ParseInfo() {
rawInfo := strings.Trim(t.Info, " ")
InfoLines := strings.Split(rawInfo, "\n")
for _, l := range InfoLines {
if strings.Contains(l, "Title") {
t.Name = strings.Trim(strings.ReplaceAll(l, "Title:", ""), " ")
}
}
}
// ParseProgress tries parsing downloading progress from annie's stdout
func (t *Task) ParseProgress() {
//pre processing
rawProgress := strings.Trim(t.rawProgress, " ")
re := regexp.MustCompile("[-=>]")
rawProgress = string(re.ReplaceAll([]byte(rawProgress), []byte("")))
raw := strings.Split(rawProgress, " ")
tp := TaskProgress{}
var (
slashAppear bool = false
digitReg *regexp.Regexp = regexp.MustCompile("[0-9]+")
)
for i := 0; i < len(raw); i++ {
if strings.Contains(raw[i], "/s") {
if len(digitReg.FindAllString(raw[i-1], -1)) > 0 {
tp.Speed = raw[i-1] + " " + raw[i]
}
} else if strings.ContainsAny(raw[i], "hms") {
if len(digitReg.FindAllString(raw[i], -1)) > 0 && !strings.Contains(raw[i], "\n") && len(raw[i]) < 12 {
tp.TimeLeft = raw[i]
}
} else if strings.Contains(raw[i], "B") {
if slashAppear {
if len(digitReg.FindAllString(raw[i-1], -1)) > 0 {
tp.Total = raw[i-1] + " " + raw[i]
}
} else {
if len(digitReg.FindAllString(raw[i-1], -1)) > 0 {
slashAppear = true
tp.Current = raw[i-1] + " " + raw[i]
}
}
} else if strings.Contains(raw[i], "%") {
if len(digitReg.FindAllString(raw[i], -1)) > 0 {
tp.Percentage = raw[i]
}
}
}
t.Progress = &tp
}