-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
cli.go
340 lines (296 loc) · 8.59 KB
/
cli.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
package main
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/jvatic/audible-downloader/audible"
"github.com/jvatic/audible-downloader/internal/common"
"github.com/jvatic/audible-downloader/internal/config"
"github.com/jvatic/audible-downloader/internal/downloader"
"github.com/jvatic/audible-downloader/internal/ffmpeg"
"github.com/jvatic/audible-downloader/internal/prompt"
"github.com/jvatic/audible-downloader/internal/utils"
log "github.com/sirupsen/logrus"
mpb "github.com/vbauerster/mpb/v5"
"github.com/vbauerster/mpb/v5/decor"
)
func main() {
if err := config.Init(); err != nil {
log.Fatalf("Error: %s", err)
}
ctx := common.InitShutdownSignals(context.Background())
cli := &CLI{}
if err := cli.Run(ctx); err != nil {
log.Fatalf("Error: %v", err)
}
}
type CLI struct {
DstDir string
}
func (cli *CLI) Run(runCtx context.Context) error {
// Ask user which Audible region/domain to use
region := RegionPrompt()
u, err := url.Parse(fmt.Sprintf("https://www.audible.%s", region.TLD))
if err != nil {
log.Fatalf("Unable to parse domain: %v", err)
}
log.Infof("Using %s (%s)\n", u.Host, region.Name)
var username string
var password string
for {
username = PromptString("Audible Username")
if username == "" {
log.Error("Audible Username required")
continue
}
break
}
for {
password = PromptPassword("Audible Password")
if password == "" {
log.Error("Audible Password required")
continue
}
break
}
c, err := audible.NewClient(
audible.OptionBaseURL(u.String()),
audible.OptionUsername(username),
audible.OptionPassword(password),
audible.OptionCaptcha(PromptCaptcha),
audible.OptionAuthCode(func() string {
return PromptString("Auth Code (OTP)")
}),
audible.OptionPromptChoice(func(msg string, opts []string) int {
return PromptChoice(msg, opts)
}),
)
if err != nil {
return fmt.Errorf("error creating client: %w", err)
}
if err := c.Authenticate(utils.ContextWithCancelChan(context.Background(), runCtx.Done())); err != nil {
return fmt.Errorf("error authenticating: %w", err)
}
if err := cli.DownloadLibrary(
utils.ContextWithCancelChan(context.Background(), runCtx.Done()),
c,
); err != nil {
return fmt.Errorf("error downloading library: %w", err)
}
return nil
}
func (cli *CLI) GetNewBooks(books []*audible.Book) ([]*audible.Book, []*audible.Book, error) {
localBooks, err := common.ListDownloadedBooks(cli.DstDir)
if err != nil {
return nil, nil, fmt.Errorf("GetNewBooks Error: Unable to enumerate downloaded books: %w", err)
}
localBooksByID := make(map[string]*audible.Book, len(localBooks))
for _, b := range localBooks {
localBooksByID[b.ID()] = b
}
newBooks := make([]*audible.Book, 0)
downloadedBooks := make([]*audible.Book, 0, len(localBooks))
for _, b := range books {
if dlb, ok := localBooksByID[b.ID()]; ok {
b.LocalPath = dlb.LocalPath
if filepath.Ext(dlb.LocalPath) == ".mp4" {
// we're assuming any .mp4 found is completely downloaded
downloadedBooks = append(downloadedBooks, b)
continue
}
// the book may be partially downloaded
}
newBooks = append(newBooks, b)
}
return newBooks, downloadedBooks, nil
}
func (cli *CLI) DownloadLibrary(ctx context.Context, c *audible.Client) error {
activationBytes, err := c.GetActivationBytes(ctx)
if err != nil {
return fmt.Errorf("error getting activation bytes: %s", err)
}
log.Debugf("Activation Bytes: %s\n", string(activationBytes))
books, err := c.GetLibrary(ctx)
if err != nil {
return fmt.Errorf("error reading library: %s", err)
}
cli.DstDir = PromptDownloadDir()
var downloadedBooks []*audible.Book
books, downloadedBooks, err = cli.GetNewBooks(books)
if err != nil {
return fmt.Errorf("error filtering library: %w", err)
}
// write info.txt file for all books already downloaded
for _, b := range downloadedBooks {
dir := filepath.Dir(b.LocalPath)
fi, err := os.Lstat(dir)
if err == nil && fi.IsDir() {
// book exists
if err := common.WriteInfoFile(filepath.Dir(b.LocalPath), b); err != nil {
fmt.Printf("Error writing info file for %q: %s\n", b.Title, err)
}
}
}
if len(books) == 0 {
log.Info("You have downloaded all the books from your Audible library.")
return nil
}
getDstPath := PromptPathTemplate()
for _, b := range books {
p := filepath.Join(cli.DstDir, getDstPath(b))
if b.LocalPath == "" {
b.LocalPath = p
}
}
loop:
for {
answer := strings.ToLower(prompt.String(fmt.Sprintf("Download %d new books from your Audible library? (yes/no/list)", len(books)), prompt.Required))
switch answer {
case "yes":
break loop
case "list":
for i, b := range books {
fmt.Printf("%02d) %s by %s\n", i+1, b.Title, strings.Join(b.Authors, ", "))
}
default:
return fmt.Errorf("download aborted")
}
}
pbgroup := mpb.New()
mainBar := pbgroup.AddBar(int64(len(books)),
mpb.BarPriority(0),
mpb.PrependDecorators(
decor.Name("Books", decor.WCSyncSpaceR),
decor.CountersNoUnit("%d / %d", decor.WCSyncWidth),
),
)
logFile, err := os.OpenFile("output.log", os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return err
}
defer logFile.Close()
dlm, err := downloader.NewDownloader(downloader.OptionLogWriter(logFile))
if err != nil {
return fmt.Errorf("error initializing downloader: %s", err)
}
var wg sync.WaitGroup
wg.Add(len(books))
client := &http.Client{
Jar: c.Jar,
}
var errs []error
var errsMtx sync.Mutex
pushError := func(err error) {
fmt.Fprintln(logFile, err)
errsMtx.Lock()
defer errsMtx.Unlock()
errs = append(errs, err)
}
downloadBook := func(book *audible.Book) {
defer wg.Done()
defer mainBar.Increment()
dir := filepath.Dir(book.LocalPath)
if err := os.MkdirAll(dir, 0755); err != nil {
pushError(fmt.Errorf("error creating dir for %q: %s", book.Title, err))
return
}
if err := common.WriteInfoFile(filepath.Dir(book.LocalPath), book); err != nil {
pushError(fmt.Errorf("error writing info file for %q: %s", book.Title, err))
}
var bookwg sync.WaitGroup
for _, u := range book.DownloadURLs {
bookwg.Add(1)
go func(u string) {
defer bookwg.Done()
var bar *mpb.Bar
// start the download
dlTime := time.Now()
var dl *downloader.Download
dl = downloader.NewDownload(
downloader.DownloadOptionDirname(dir),
downloader.DownloadOptionURL(u),
downloader.DownloadOptionDetectFilename(),
downloader.DownloadOptionHTTPClient(client),
downloader.DownloadOptionProgress(func(totalBytes int64, completedBytes int64) {
if bar == nil {
bar = pbgroup.AddBar(totalBytes,
mpb.BarRemoveOnComplete(),
mpb.PrependDecorators(
decor.Name(filepath.Base(dl.OutputPath()), decor.WCSyncSpaceR),
decor.Name("downloading", decor.WCSyncSpaceR),
decor.Counters(decor.UnitKB, "% .1f / % .1f"),
),
mpb.AppendDecorators(
decor.EwmaETA(decor.ET_STYLE_MMSS, 0, decor.WCSyncWidth),
),
)
}
bar.SetCurrent(completedBytes)
bar.DecoratorEwmaUpdate(time.Since(dlTime))
dlTime = time.Now()
}),
)
dlm.Add(dl)
// wait for it to complete
if err := dl.Wait(); err != nil {
if err == downloader.ErrAbort {
fmt.Fprintf(logFile, "Skipping %s\n", dl.OutputPath())
return
}
pushError(fmt.Errorf("error downloading %s: %s", u, err))
}
outPath := dl.OutputPath()
// decrypt if it's an .aax file
if filepath.Ext(outPath) == ".aax" {
bar = nil
if err := ffmpeg.DecryptAudioBook(
ffmpeg.InputPath(outPath),
ffmpeg.OutputPath(utils.SwapFileExt(outPath, ".mp4")),
ffmpeg.ActivationBytes(string(activationBytes)),
ffmpeg.Progress(func(totalBytes int64, completedBytes int64) {
if bar == nil {
bar = pbgroup.AddBar(totalBytes,
mpb.BarRemoveOnComplete(),
mpb.PrependDecorators(
decor.Name(book.Title, decor.WCSyncSpaceR),
decor.Name("decrypting", decor.WCSyncSpaceR),
),
mpb.AppendDecorators(
decor.Percentage(decor.WC{W: 5}),
),
)
}
bar.SetCurrent(completedBytes)
}),
); err != nil {
pushError(fmt.Errorf("error decrypting %s: %s", u, err))
}
// remove original .aax file
if err := os.Remove(outPath); err != nil {
pushError(fmt.Errorf("error removing .aax file for %q: %s", book.Title, err))
}
}
}(u)
}
bookwg.Wait()
}
dlm.Start()
for _, book := range books {
go downloadBook(book)
}
wg.Wait()
dlm.Wait()
pbgroup.Wait()
errsMtx.Lock()
for _, err := range errs {
fmt.Println(err)
}
errsMtx.Unlock()
return nil
}