This repository has been archived by the owner on Jun 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
383 lines (326 loc) · 10.2 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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package main // import "golang.ssttevee.com/funimation"
import (
"fmt"
"golang.ssttevee.com/funimation/lib"
"net/http/cookiejar"
"log"
"io"
"os"
"time"
"github.com/dustin/go-humanize"
"flag"
"strings"
"strconv"
"github.com/ssttevee/go-downloader"
)
type writerMiddleware struct {
Writer io.Writer
Func func(int)
}
func (w *writerMiddleware) Write(p []byte) (int, error) {
n, err := w.Writer.Write(p)
w.Func(n)
return n, err
}
var funimationClient *funimation.Client
func init() {
downloader.TempDir = os.TempDir() + "/.funimation"
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatal(err.Error())
return
}
funimationClient = funimation.New(jar)
}
func main() {
listCmd := flag.NewFlagSet("list", flag.ExitOnError)
listCmd.Usage = func() {
fmt.Fprintln(os.Stderr, "Usage: funimation list <show>")
fmt.Fprintln(os.Stderr, " OR funimation list <show-url>\n")
fmt.Fprintln(os.Stderr, "Lists all episodes in the given show\n\n")
}
downloadCmd := flag.NewFlagSet("download", flag.ExitOnError)
downloadCmd.String("email", "", "your funimation account email address")
downloadCmd.String("password", "", "your funimation account password")
downloadCmd.String("quality", "max", "quality of the video, `sd, hd, or fhd`")
downloadCmd.String("language", funimation.Subbed, "either `sub or dub`")
downloadCmd.Bool("url-only", false, "get the url instead of downloading")
downloadCmd.Int("threads", 1, "number of threads for multithreaded download")
downloadCmd.Bool("guess", false, "guess urls for non-public videos")
downloadCmd.Usage = func() {
fmt.Fprintln(os.Stderr, "Usage: funimation download [options] <show> <episode> [<episode>...]")
fmt.Fprintln(os.Stderr, " OR funimation download [options] <show> <episode-nums> [<episode-nums>...]")
fmt.Fprintln(os.Stderr, " OR funimation download [options] <show-id> <episode-nums> [<episode-nums>...]")
fmt.Fprintln(os.Stderr, " OR funimation download [options] <episode-url> [<episode-url>...]\n")
fmt.Fprintln(os.Stderr, "Downloads an episode from the given show\n")
fmt.Fprintln(os.Stderr, "Options:")
downloadCmd.PrintDefaults()
}
if len(os.Args) == 1 {
fmt.Println("Usage: funimation <command> [<args>]\n")
fmt.Println("Available commands are: ")
fmt.Println(" list Lists all episodes in the given series")
fmt.Println(" download Downloads an episode from the given series")
return
}
switch os.Args[1] {
case "list":
listCmd.Parse(os.Args[2:])
break
case "download":
downloadCmd.Parse(os.Args[2:])
break
default:
fmt.Printf("%q is not valid command.\n", os.Args[1])
os.Exit(2)
}
switch {
case listCmd.Parsed():
show := listCmd.Arg(0)
if show == "" {
listCmd.Usage()
os.Exit(2)
}
doList(show)
case downloadCmd.Parsed():
doDownload(downloadCmd)
}
}
func doList(show string) {
series, err := funimationClient.GetSeries(show)
if err != nil {
log.Fatal("Failed to get series: ", err)
}
episodes, err := series.GetAllEpisodes()
if err != nil {
log.Fatal("Failed to get episodes: ", err)
}
fmt.Println(series.Title())
fmt.Println(series.Description())
fmt.Println()
fmt.Print(episodes.String())
}
func doDownload(cmd *flag.FlagSet) {
show := cmd.Arg(0)
if show == "" || !strings.HasPrefix(show, "http") && cmd.Arg(1) == "" {
cmd.Usage()
os.Exit(2)
}
if email := cmd.Lookup("email").Value.(flag.Getter).Get().(string); email != "" {
password := cmd.Lookup("password").Value.(flag.Getter).Get().(string)
if password == "" {
log.Fatal("Got `email` flag but missing `password` flag")
}
if err := funimationClient.Login(email, password); err != nil {
log.Fatal("Login failed: ", err)
}
}
episodes := make([]*funimation.Episode, 0)
if strings.HasPrefix(show, "http") {
for _, url := range cmd.Args() {
if !strings.HasPrefix(url[strings.Index(url, "://"):], "://www.funimation.com/shows/") {
log.Println("Only funimation show urls are allowed")
continue
}
episode, err := funimationClient.GetEpisodeFromUrl(url)
if err != nil {
log.Println("Failed to get episode: ", err)
continue
}
episodes = append(episodes, episode)
}
} else {
var series *funimation.Series
if showNum, err := strconv.ParseInt(show, 10, 32); err != nil {
// not a show number, assume it is a show slug
series, err = funimationClient.GetSeries(show)
if err != nil {
log.Fatal("Failed to get series: ", err)
}
} else {
series, err = funimationClient.GetSeriesById(int(showNum))
if err != nil {
log.Fatal("Failed to get series: ", err)
}
}
for i := 1; i < cmd.NArg(); i++ {
arg := cmd.Arg(i)
if arg == "*" {
if eps, err := series.GetAllEpisodes(); err != nil {
log.Println("Failed to get all episodes: ", err)
continue
} else {
episodes = eps
break
}
} else if strings.ContainsRune(arg, '-') {
startEnd := strings.Split(arg, "-")
if len(startEnd) != 2 {
log.Printf("Range value `%s` must contain 1 dash character\n", arg)
continue
}
start, err := strconv.ParseInt(startEnd[0], 10, 32)
if err != nil {
log.Println("Range value must be numeric")
continue
}
end, err := strconv.ParseInt(startEnd[1], 10, 32)
if err != nil {
log.Println("Range value must be numeric")
continue
}
eps, err := series.GetEpisodesRange(int(start), int(end))
if err != nil {
log.Println(err)
continue
}
episodes = append(episodes, eps...)
} else if epNum, err := strconv.ParseInt(arg, 10, 32); err != nil {
episode, err := series.GetEpisodeBySlug(arg)
if err != nil {
log.Println("Failed to get episode: ", err)
continue
}
episodes = append(episodes, episode)
} else {
episode, err := series.GetEpisode(int(epNum))
if err != nil {
log.Println("Failed to get episode: ", err)
continue
}
episodes = append(episodes, episode)
}
}
}
if len(episodes) == 0 {
cmd.Usage()
os.Exit(2)
}
fmt.Printf("Found %d episodes:\n", len(episodes))
quality := cmd.Lookup("quality").Value.(flag.Getter).Get().(string)
language := funimation.EpisodeLanguage(cmd.Lookup("language").Value.(flag.Getter).Get().(string))
urlOnly := cmd.Lookup("url-only").Value.(flag.Getter).Get().(bool)
threads := cmd.Lookup("threads").Value.(flag.Getter).Get().(int)
guessUrls := cmd.Lookup("guess").Value.(flag.Getter).Get().(bool)
// default to subbed
if language != funimation.Subbed && language != funimation.Dubbed {
fmt.Println("Received unknown language mode; defaulting to sub")
language = funimation.Subbed
}
for _, episode := range episodes {
foundLang := false
hasSub := false
for _, l := range episode.Languages() {
if l == funimation.Subbed {
hasSub = true
}
if language == l {
foundLang = true
}
}
// make sure language is available
var el funimation.EpisodeLanguage = language
if !foundLang {
fmt.Printf("Language mode - %s - is unavailable; ", el)
// if subbed is unavailable, something is wrong... just give up...
if !hasSub {
log.Println("skipping...")
continue
}
fmt.Println("defaulting to sub")
el = funimation.Subbed
}
var eq funimation.EpisodeQuality
if quality == "max" {
eq = episode.GetBestQuality(el, !guessUrls)
} else {
eq = funimation.ParseEpisodeQuality(quality)
}
urlFunc := episode.GetVideoUrl
if guessUrls {
urlFunc = episode.GuessVideoUrl
}
url, err := urlFunc(el, eq)
if err != nil {
log.Println("Failed to get url: ", err)
continue
}
if urlOnly {
fmt.Printf("Season %d, %s %v: %s\n", episode.SeasonNumber(), episode.Type(), episode.EpisodeNumber(), url)
continue
}
dl, err := downloader.New(url)
if err != nil {
log.Println("Failed to get downloader: ", err)
continue
}
var epnum interface{}
if episode.EpisodeNumber() == 0 {
epnum = ""
} else {
epnum = episode.EpisodeNumber()
}
fname := fmt.Sprintf("s%d%s%v - %s [%s][%s].mp4", episode.SeasonNumber(), episode.TypeCode(), epnum, episode.Title(), eq.String(), el)
fname = strings.Map(func(r rune) (rune) {
if r == '\\' || r == '/' || r == ':' || r == '*' || r == '?' || r == '"' || r == '<' || r == '>' || r == '|' {
return -1
}
return r
}, fname)
fmt.Printf("\nDownloading %s Season %d - %s %v\n", episode.Title(), episode.SeasonNumber(), episode.Type(), episode.EpisodeNumber())
fmt.Printf("Saving to: %s\n\n", fname)
startTime := time.Now()
bytesStrLen := len(humanize.Comma(dl.Size()))
var lastTime = time.Now()
var rate float64
var bytesSinceLastTime int64
var d *downloader.Download
dl.OnBytesReceived = func(bytes int) {
bytesSinceLastTime += int64(bytes)
percent := d.Percent()
newTime := time.Now()
timeDiff := newTime.Sub(lastTime)
if secs := timeDiff.Seconds(); secs >= 0.5 {
rate = float64(bytesSinceLastTime) / secs
lastTime = newTime
bytesSinceLastTime = 0
}
percentStr := fmt.Sprintf("%.2f", percent * float32(100))
for ; len(percentStr) < 6; {
percentStr = " " + percentStr
}
progBar := "["
progBarLen := 30
for i := 0; i < progBarLen; i++ {
if float32(i) < float32(progBarLen) * percent {
if progBar[len(progBar) - 1] == byte('>') {
progBar = progBar[:len(progBar) - 1] + "="
}
progBar += ">"
} else {
progBar += " "
}
}
progBar += "]"
bytesStr := humanize.Comma(int64(d.Current()))
for ; len(bytesStr) < bytesStrLen; {
bytesStr = " " + bytesStr
}
rateStr := humanize.Bytes(uint64(rate))
for ; len(rateStr) < 10; {
rateStr = " " + rateStr
}
fmt.Printf("\r%s%% %s %s %s/s", percentStr, progBar, bytesStr, rateStr)
}
fmt.Println()
if d, err = dl.Download(fname, threads); err != nil {
log.Println("Failed to start download: ", err)
} else {
if err := d.Wait(); err != nil {
log.Println("\nDownload failed: ", err)
continue
}
fmt.Printf("\nDownloaded %s in %v\n", humanize.Bytes(uint64(dl.Size())), time.Now().Sub(startTime))
}
}
}