-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
248 lines (193 loc) · 5.49 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
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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
_cache "github.com/sweepies/tok-dl/cache"
"github.com/sweepies/tok-dl/tikwm"
"github.com/sweepies/tok-dl/util"
charmLog "github.com/charmbracelet/log"
"github.com/urfave/cli/v3"
)
var (
metadataOnly bool
outDir string
noCache bool
inFile string
debug bool
log *charmLog.Logger
cache *_cache.Cache
urls []string
mimeExts = map[string]string{
"video/mp4": ".mp4",
"audio/mpeg": ".mp3",
"audio/mp3": ".mp3",
}
)
func configure() {
level := charmLog.InfoLevel
if debug {
level = charmLog.DebugLevel
}
log = charmLog.NewWithOptions(os.Stderr, charmLog.Options{
ReportTimestamp: true,
TimeFormat: "15:04:05",
Level: level,
})
cache = _cache.New()
}
func main() {
cmd := &cli.Command{
Name: "tok-dl",
Usage: "A TikTok Downloader that actually works",
Flags: []cli.Flag{
&cli.BoolFlag{Name: "metadata-only", Aliases: []string{"m"}, Usage: "only download metadata", Destination: &metadataOnly},
&cli.StringFlag{Name: "out-dir", Aliases: []string{"o"}, Usage: "output directory", Value: "./tiktok", Destination: &outDir},
&cli.BoolFlag{Name: "no-cache", Usage: "bypass the cache; don't skip alreadty actioned urls", Destination: &noCache},
&cli.BoolFlag{Name: "debug", Usage: "show debug logs", Destination: &debug},
},
ArgsUsage: "INPUT_FILE",
Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
configure()
return ctx, nil
},
Action: func(ctx context.Context, cmd *cli.Command) error {
inFile = cmd.Args().First()
// check if input file is provided
if len(inFile) == 0 {
cli.ShowAppHelpAndExit(cmd, 1)
}
// read input file
data, err := os.ReadFile(inFile)
if err != nil {
log.Fatal("Error opening input file", "err", err.Error())
}
// split by newline, handle carriage returns
lines := strings.Split(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n")
for _, line := range lines {
// skip empty lines
if len(line) == 0 {
continue
}
// ignore comments
exp := regexp.MustCompile("^(#|//|--)")
if exp.FindStringIndex(line) != nil {
continue
}
// skip invalid urls
_, err := url.ParseRequestURI(line)
if err != nil {
continue
}
urls = append(urls, line)
}
log.Info("File loaded", "urls", len(urls))
err = os.MkdirAll(outDir, 0700)
if err != nil {
log.Fatal("Could not create directory", "dir", outDir, "err", err.Error())
}
caller := tikwm.New(cache, log)
for _, url := range urls {
if !noCache && string(cache.Get([]byte(url))) != "" {
log.Debug("URL was found in cache; skipping", "url", url)
continue
}
data, err := caller.FetchMetadata(url)
if err != nil {
if errors.Is(err, tikwm.ErrRateLimit) {
log.Fatal("Exiting", "err", err.Error())
}
log.Warn("Error from API", "err", err.Error(), "url", url)
cache.Set([]byte(url), []byte(err.Error()))
continue
}
dirPath := path.Join(outDir, data.Data.ID)
err = os.MkdirAll(dirPath, 0700)
if err != nil {
log.Fatal("Could not create directory", "dir", dirPath, "err", err.Error())
}
filePath := path.Join(dirPath, fmt.Sprintf("%s.json", data.Data.ID))
file, err := os.Create(filePath)
if err != nil {
log.Fatal("Could not open file", "file", filePath, "err", err.Error())
}
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
encoder.Encode(data.Data)
file.Close()
// download files
if len(data.Data.Images) > 0 {
var imageErrs []error
for _, image := range data.Data.Images {
err := downloadFileInferExt(image, dirPath)
if err != nil {
log.Warn("Error downloading image", "err", err.Error())
imageErrs = append(imageErrs, err)
}
}
if len(imageErrs) > 0 {
log.Warn("Download incomplete", "id", data.Data.ID)
cache.Set([]byte(url), []byte("image(s) had errs"))
}
} else {
downloadUrl := util.StringNotEmptyCoalesce(data.Data.Hdplay, data.Data.Play, data.Data.Wmplay)
err := downloadFileInferExt(downloadUrl, dirPath)
if err != nil {
log.Warn("Error downloading video", "err", err.Error())
cache.Set([]byte(url), []byte(err.Error()))
continue
}
}
// finished
log.Info("Download finished", "id", data.Data.ID)
cache.Set([]byte(url), []byte("satisfied"))
}
log.Info("Finished")
return nil
},
}
if err := cmd.Run(context.Background(), os.Args); err != nil {
log.Fatal(err)
}
}
func downloadFileInferExt(downloadUrl string, destDir string) error {
resp, err := http.Get(downloadUrl)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return errors.New(resp.Status)
}
parsedUrl, _ := url.Parse(downloadUrl)
fileName := util.SanitizeFileName(filepath.Base(parsedUrl.Path))
if filepath.Ext(fileName) == "" {
contentType := resp.Header.Get("Content-Type")
var ext string
if mimeExts[contentType] != "" {
ext = mimeExts[contentType]
} else {
exts, _ := mime.ExtensionsByType(contentType)
ext = exts[0]
}
fileName = fmt.Sprintf("%s%s", fileName, ext)
}
filePath := path.Join(destDir, fileName)
file, err := os.Create(filePath)
if err != nil {
log.Fatal("Could not open file", "file", filePath)
}
defer file.Close()
_, err = io.Copy(file, resp.Body)
return err
}