-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd.go
61 lines (51 loc) · 1.07 KB
/
cmd.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
package main
import (
"io/ioutil"
"math/rand"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
)
func fetchCmd(link string) tea.Cmd {
return func() tea.Msg {
song, err := GetSong(&client, link)
if err != nil {
return errorMsg(err)
}
return fetchMsg(song)
}
}
func downloadCmd(song *Song, index int) tea.Cmd {
return func() tea.Msg {
max, min := 5, 1
delay := rand.Intn(max-min) + min
err := retry(5, time.Duration(delay)*time.Second, func() error {
return song.Save(output)
})
if err != nil {
return errorMsg(err)
}
return downloadMsg(index)
}
}
func retry(attempts int, sleep time.Duration, f func() error) error {
if err := f(); err != nil {
if attempts--; attempts > 0 {
time.Sleep(sleep)
return retry(attempts, 4*sleep, f)
}
return err
}
return nil
}
func saveCmd(skipped []string) tea.Cmd {
return func() tea.Msg {
path := output + "failed.txt"
b := []byte(strings.Join(skipped, "\n"))
err := ioutil.WriteFile(path, b, 0644)
if err != nil {
return errorMsg(err)
}
return saveMsg(len(skipped))
}
}