forked from iyear/tdl
/
dl.go
205 lines (178 loc) · 5.11 KB
/
dl.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
package dl
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/Mistolotus/tdl/app/internal/dliter"
"github.com/Mistolotus/tdl/app/internal/tgc"
"github.com/Mistolotus/tdl/pkg/consts"
"github.com/Mistolotus/tdl/pkg/dcpool"
"github.com/Mistolotus/tdl/pkg/downloader"
"github.com/Mistolotus/tdl/pkg/key"
"github.com/Mistolotus/tdl/pkg/kv"
"github.com/Mistolotus/tdl/pkg/logger"
"github.com/fatih/color"
"github.com/gotd/contrib/middleware/floodwait"
"github.com/gotd/td/telegram"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/spf13/viper"
"go.uber.org/multierr"
"go.uber.org/zap"
)
type Options struct {
Dir string
RewriteExt bool
SkipSame bool
Template string
URLs []string
Files []string
Include []string
Exclude []string
Desc bool
PoolSize int64
// resume opts
Continue, Restart bool
}
type parser struct {
Data []string
Parser func(ctx context.Context, pool dcpool.Pool, kvd kv.KV, data []string) ([]*dliter.Dialog, error)
}
func Run(ctx context.Context, opts *Options) error {
c, kvd, err := tgc.NoLogin(ctx)
if err != nil {
return err
}
return ExecDownload(c, kvd, ctx, opts)
}
func ExecDownload(c *telegram.Client, kvd kv.KV, ctx context.Context, opts *Options) error {
return tgc.RunWithAuth(ctx, c, func(ctx context.Context) (rerr error) {
color.Green("Preparing DC pool... It may take a while. size: %d", opts.PoolSize)
start := time.Now()
pool, err := dcpool.NewPool(ctx, c, opts.PoolSize, floodwait.NewSimpleWaiter())
if err != nil {
return err
}
defer multierr.AppendInvoke(&rerr, multierr.Close(pool))
// clear prepare message
fmt.Printf("%s%s", text.CursorUp.Sprint(), text.EraseLine.Sprint())
color.Green("DC pool prepared in %s", time.Since(start))
parsers := []parser{
{Data: opts.URLs, Parser: parseURLs},
{Data: opts.Files, Parser: parseFiles},
}
dialogs, err := collectDialogs(ctx, pool, kvd, parsers)
if err != nil {
return err
}
logger.From(ctx).Debug("Collect dialogs",
zap.Any("dialogs", dialogs))
iter, err := dliter.New(&dliter.Options{
Pool: pool,
KV: kvd,
Template: opts.Template,
Include: opts.Include,
Exclude: opts.Exclude,
Desc: opts.Desc,
Dialogs: dialogs,
})
if err != nil {
return err
}
if !opts.Restart {
// resume download and ask user to continue
if err = resume(ctx, kvd, iter, !opts.Continue); err != nil {
return err
}
} else {
color.Yellow("Restart download by 'restart' flag")
}
defer func() { // save progress
if rerr != nil { // download is interrupted
multierr.AppendInto(&rerr, saveProgress(ctx, kvd, iter))
} else { // if finished, we should clear resume key
multierr.AppendInto(&rerr, kvd.Delete(key.Resume(iter.Fingerprint())))
}
}()
options := &downloader.Options{
Pool: pool,
Dir: opts.Dir,
RewriteExt: opts.RewriteExt,
SkipSame: opts.SkipSame,
PartSize: viper.GetInt(consts.FlagPartSize),
Threads: viper.GetInt(consts.FlagThreads),
Iter: iter,
}
limit := viper.GetInt(consts.FlagLimit)
logger.From(ctx).Info("Start download",
zap.String("dir", options.Dir),
zap.Bool("rewrite_ext", options.RewriteExt),
zap.Bool("skip_same", options.SkipSame),
zap.Int("part_size", options.PartSize),
zap.Int("threads", options.Threads),
zap.Int("limit", limit))
return downloader.New(options).Download(ctx, limit)
})
}
func collectDialogs(ctx context.Context, pool dcpool.Pool, kvd kv.KV, parsers []parser) ([][]*dliter.Dialog, error) {
var dialogs [][]*dliter.Dialog
for _, p := range parsers {
d, err := p.Parser(ctx, pool, kvd, p.Data)
if err != nil {
return nil, err
}
dialogs = append(dialogs, d)
}
return dialogs, nil
}
func resume(ctx context.Context, kvd kv.KV, iter *dliter.Iter, ask bool) error {
logger.From(ctx).Debug("Check resume key",
zap.String("fingerprint", iter.Fingerprint()))
b, err := kvd.Get(key.Resume(iter.Fingerprint()))
if err != nil && !errors.Is(err, kv.ErrNotFound) {
return err
}
if len(b) == 0 { // no progress
return nil
}
finished := make(map[int]struct{})
if err = json.Unmarshal(b, &finished); err != nil {
return err
}
// finished is empty, no need to resume
if len(finished) == 0 {
return nil
}
confirm := false
resumeStr := fmt.Sprintf("Found unfinished download, continue from '%d/%d'", len(finished), iter.Total(ctx))
if ask {
if err = survey.AskOne(&survey.Confirm{
Message: color.YellowString(resumeStr + "?"),
}, &confirm); err != nil {
return err
}
} else {
color.Yellow(resumeStr)
confirm = true
}
logger.From(ctx).Debug("Resume download",
zap.Int("finished", len(finished)))
if !confirm {
// clear resume key
return kvd.Delete(key.Resume(iter.Fingerprint()))
}
iter.SetFinished(finished)
return nil
}
func saveProgress(ctx context.Context, kvd kv.KV, it *dliter.Iter) error {
finished := it.Finished()
logger.From(ctx).Debug("Save progress",
zap.Int("finished", len(finished)))
b, err := json.Marshal(finished)
if err != nil {
return err
}
return kvd.Set(key.Resume(it.Fingerprint()), b)
}