-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
108 lines (92 loc) · 2.07 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
)
type Track struct {
Track int `json:"track"`
Name string `json:"name"`
ChapterLink string `json:"chapter_link_dropbox"`
Duration string `json:"duration"`
ChapterID string `json:"chapter_id"`
PostID string `json:"post_id"`
URL string `json:"url"`
}
func main() {
book := os.Getenv("FOLDER_NAME")
if book == "" {
book = "book"
}
trackFile := filepath.Join(book, "tracks.json")
outputFolder := filepath.Join(book, "chapters")
host := os.Getenv("HOST")
if host == "" {
host = "https://files02.tokybook.com/audio/"
}
if err := downloadBook(trackFile, outputFolder, host); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func downloadBook(trackFile, outputFolder, host string) error {
content, err := os.ReadFile(trackFile)
if err != nil {
return err
}
tracks := []Track{}
err = json.Unmarshal(content, &tracks)
if err != nil {
return err
}
fmt.Printf("Found %d tracks\n", len(tracks))
err = os.MkdirAll(outputFolder, os.ModePerm)
if err != nil {
return err
}
wg := sync.WaitGroup{}
for _, track := range tracks {
url := host + track.ChapterLink
name := strings.ReplaceAll(track.Name, " ", "-")
output := outputFolder + "/" + name
go downloadChapter(url, output, &wg)
wg.Add(1)
}
wg.Wait()
return nil
}
func downloadChapter(url, output string, wg *sync.WaitGroup) {
err := func() error {
fmt.Printf("Downloading %s...\n", output)
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if !strings.HasSuffix(output, ".mp3") && !strings.HasSuffix(output, ".mp4") {
output += ".mp3"
}
file, err := os.Create(output)
if err != nil {
return err
}
defer file.Close()
bytesWritten, err := io.Copy(file, resp.Body)
if err != nil {
return err
}
fmt.Printf("Wrote %f MB\n", float64(bytesWritten)/(1<<20))
return nil
}()
if err != nil {
fmt.Println("Error during download: ", err)
} else {
fmt.Printf("Downloaded %s\n", output)
}
wg.Done()
}