-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmoe.go
524 lines (447 loc) · 12.1 KB
/
moe.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
package main
import (
"flag"
"fmt"
"github.com/fatih/color"
"jaytaylor.com/html2text"
"html"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"strings"
)
// command params
var (
name, AnimeURL, AnimeVideoURL, seasonal, video string
score, rank, synopsis, info, songs, EP, aired, all bool
MALsearch = "https://myanimelist.net/search/all?q="
VIDEOsearch = "https://9anime.is/search?keyword="
)
// results
var (
scoreres, rankres, statres, OPres, EDres, EPres, airedres string
synopsisres, songsres, seasonalres []string
infores = make(map[string]string)
)
//colors
var (
green = color.New(color.FgHiGreen)
boldcyan = color.New(color.FgCyan, color.Bold)
boldred = color.New(color.FgRed, color.Bold)
boldblue = color.New(color.FgHiBlue, color.Bold)
boldyellow = color.New(color.FgYellow, color.Bold)
boldwhite = color.New(color.FgHiWhite, color.Bold)
boldgreen = color.New(color.FgHiGreen, color.Bold)
italicmagenta = color.New(color.FgHiMagenta)
italicblue = color.New(color.FgBlue, color.Italic)
)
// bind flags to params
func bindFlags() {
flag.StringVar(&name, "name", "", "Give Name ex: DeathNode, \"Your Lie In April\"")
flag.StringVar(&seasonal, "seasonal", "", "<SEASON> <YEAR> ex: summer 2017, winter 2016 or Just leave blank for current season")
flag.StringVar(&video, "video", "", "<EPISODE NUMBER> ex: 1, 9 etc or \"all\" to get all the episodes")
flag.BoolVar(&score, "score", false, "Get Score")
flag.BoolVar(&rank, "rank", false, "Get Rank")
flag.BoolVar(&synopsis, "synopsis", false, "Get Synopsis")
flag.BoolVar(&info, "info", false, "Get information")
flag.BoolVar(&songs, "songs", false, "Get all the Opening and Ending song names")
flag.BoolVar(&EP, "EP", false, "Get number of episodes")
flag.BoolVar(&aired, "aired", false, "Get the aired date")
flag.BoolVar(&all, "all", false, "Get All Params")
flag.Parse()
}
// Get HTML page as string
func getContent(URL string) (string, bool) {
resp, err := http.Get(URL)
if err != nil {
fmt.Println("Error fetching page")
return "", true
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
ret := string(body)
if err != nil {
fmt.Println("Error :( Try Again")
return "", true
}
return ret, false
}
// check if ':' exists
func check(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] == ':' {
return true
}
}
return false
}
// replace
func Rep(s *string, rep [][]string) {
var temp string = *s
for i := 0; i < len(rep); i++ {
temp = strings.Replace(temp, rep[i][0], rep[i][1], -1)
}
*s = temp
}
// Print to terminal
func PrintParams() {
if info || all {
boldblue.Printf("Information\n------------\n")
for key, value := range infores {
boldcyan.Printf("%v", key)
for i := 0; i < 9-len(key); i++ {
fmt.Printf(" ")
}
if key == "Score" {
boldgreen.Printf(": %v\n", scoreres)
continue
}
boldwhite.Printf(": %v\n", value)
}
fmt.Printf("\n")
}
if seasonal != "" {
boldblue.Printf("Animes of %v season \n-------------------\n", seasonal)
for index, anime := range seasonalres {
boldwhite.Printf("%v.", index)
fmt.Printf(" %v\n", anime)
}
fmt.Printf("\n")
}
if synopsis || all {
boldblue.Printf("Synopsis\n------------\n")
for i := 0; i < len(synopsisres); i++ {
boldwhite.Printf(synopsisres[i])
}
fmt.Printf("\n\n")
}
if songs || all {
boldblue.Printf("Songs (OP's & EP's)\n----------------\n")
for _, song := range songsres {
italicmagenta.Println(song)
}
fmt.Printf("\n")
}
if score || all {
boldblue.Printf("Score\n------------\n")
boldgreen.Println(scoreres)
fmt.Printf("\n")
}
if rank || all {
boldblue.Printf("Ranked\n------------\n")
boldred.Println(rankres)
fmt.Printf("\n")
}
if aired || all {
boldblue.Printf("Aired\n------------\n")
boldwhite.Println(airedres)
fmt.Printf("\n")
}
if EP || all {
boldblue.Printf("Episodes\n------------\n")
boldwhite.Println(EPres)
fmt.Printf("\n")
}
}
// Check if No results found
func emptyResult(length int, FLAG, query string) bool {
if length == 0 {
boldred.Printf("Could not find any results for %v: %v\n", FLAG, query)
return true
}
return false
}
func fetchVideoURL() {
// Get number of episodes on AnimeVideoURL page and set from and to
var from, to int
var err1, err2 error
if video != "all" {
slicedrange := strings.Split(video, "-")
from, err1 = strconv.Atoi(slicedrange[0])
to, err2 = strconv.Atoi(slicedrange[1])
if err1 != nil || err2 != nil {
boldred.Println("Invalid range in -video", video)
return
}
if from > to {
from, to = to, from
}
}
resp, err := getContent(AnimeVideoURL)
if err {
return
}
htmlcontent, errstr := html2text.FromString(resp)
if errstr != nil {
panic(errstr)
}
htmlcontent = strings.Replace(htmlcontent, " ", "", -1)
regexServerG4 := (`ServerG4[^\*]*|\*(\d+)\(([^\)]*)`)
serverg4re := regexp.MustCompile(regexServerG4)
results := serverg4re.FindAllStringSubmatch(htmlcontent, -1)
episodeURL := make(map[int]string)
videoSite := `https://9anime.is`
totalEpisodes := -1
// map episode number to a url for download
for _, result := range results {
if result[1] == "" {
continue
}
episodeNumber, converror := strconv.Atoi(result[1])
if converror != nil {
fmt.Println("Error downloading ...")
return
}
if episodeURL[episodeNumber] != "" {
break
}
episodeURL[episodeNumber] = videoSite + result[2]
totalEpisodes = episodeNumber
}
if totalEpisodes == -1 {
fmt.Println("Error downloading Anime could'nt find any downloads")
return
}
// set range for all
if video == "all" {
from = 1
to = totalEpisodes
}
// if range is greater than total episode set to max
if to > totalEpisodes {
to = totalEpisodes
}
fmt.Println(from, to)
// show video urls
for i := from; i <= to; i++ {
boldgreen.Println(episodeURL[i], ":Episode", i)
}
}
// fetch seasonl animes
func fetchDetailsSeason(seasonal string) bool {
regexseason := `TV \(New\)(.|\n)*?ONA`
seasonalre := regexp.MustCompile(regexseason)
var seasonURL string
if seasonal == "CURRENT" {
seasonURL = "https://myanimelist.net/anime/season"
} else {
temp := strings.Split(seasonal, " ")
seasonURL = "https://myanimelist.net/anime/season/" + temp[1] + "/" + temp[0]
}
resp, err := getContent(seasonURL)
if err {
return false
}
cleaninfo, errstr := html2text.FromString(resp, html2text.Options{PrettyTables: true})
if errstr != nil {
panic(err)
}
cleaninfo = seasonalre.FindString(cleaninfo)
regex := `https://myanimelist.net/anime/[0-9]*/([^\s]*)`
re := regexp.MustCompile(regex)
animes := re.FindAllString(cleaninfo, -1)
rep := [][]string{{"-", " "}, {"_", " "}}
m := make(map[string]bool)
for _, anime := range animes {
res := strings.Split(anime, "/")
Rep(&res[5], rep)
if !m[res[5]] {
seasonalres = append(seasonalres, res[5])
m[res[5]] = true
}
}
return true
}
// Get anime details from MAL
func fetchDetails() bool {
resp, err := getContent(AnimeURL)
if err {
return false
}
extractregex := regexp.MustCompile(">(.|\n)*?<")
// Extract Synopsis
regexsynopsis := `<span\sitemprop="description">(.|\n)*?</span>`
regexscore := `[0-9]\.[0-9]{2,}`
regexinfo := `<h2[^>]*>(.|\n)*?</h2>(.|\n)*?(<div[^>]*>(.|\n)*?</div>\s*)+`
regexop := `<span\s+class="theme-song">(.|\n)*?</span>`
regexrank := `Ranked[^<]*<strong>(#[\d]+)</strong>`
synopsisre := regexp.MustCompile(regexsynopsis)
infore := regexp.MustCompile(regexinfo)
scorere := regexp.MustCompile(regexscore)
opre := regexp.MustCompile(regexop)
rankre := regexp.MustCompile(regexrank)
// Extract synopsis
result := synopsisre.FindAllString(resp, 1)
synopsisres = extractregex.FindAllString(result[0], -1)
if emptyResult(len(synopsisres), "-synopsis", "true") {
return false
}
synopsisres[0] = synopsisres[0][1 : len(synopsisres[0])-1]
rep := [][]string{{"<", ""}, {">", ""}}
for i := 0; i < len(synopsisres); i++ {
Rep(&synopsisres[i], rep)
synopsisres[i] = html.UnescapeString(synopsisres[i])
}
// Extract score
result = scorere.FindAllString(resp, 1)
if emptyResult(len(result), "-score", "true") {
return false
}
scoreres = result[0]
// Extract info
dirtyinfo := strings.Join(infore.FindAllString(resp, 3), "")
cleaninfo, errstr := html2text.FromString(dirtyinfo)
if errstr != nil {
panic(err)
}
splitcleaninfo := strings.Split(cleaninfo, "\n")
m := make(map[string]string)
for _, str := range splitcleaninfo {
checkres := check(str)
if checkres {
r := strings.Split(str, ":")
m[r[0]] = r[1]
}
}
cleaner := `((\([\d\w/\s_\-]*\))|(\(\s+[\w]+$))`
cleanere := regexp.MustCompile(cleaner)
for k, _ := range m {
infores[k] = cleanere.ReplaceAllString(m[k], "")
}
// Extract OP's and ED's
songsres = opre.FindAllString(resp, -1)
for i := 0; i < len(songsres); i++ {
songsres[i] = html.UnescapeString(extractregex.FindString(songsres[i]))
Rep(&songsres[i], rep)
}
// Extract rank
rankres = extractregex.FindString(html.UnescapeString(rankre.FindString(resp)))
Rep(&rankres, rep)
// Extract number of episodes
EPres = m["Episodes"]
// Extract aired date
airedres = m["Aired"]
// Extract seasonal anime
if seasonal == "CURRENT" {
seasonal = ""
}
return true
}
// Search given a name
// true value indicates matching name found
// shows search results if not found
func Search() bool {
searchURL := MALsearch + name
name = strings.ToLower(name)
//make GET request
resp, err := getContent(searchURL)
if err {
return false
}
regex := `<article>(.|\n)*?</article>`
re := regexp.MustCompile(regex)
results := re.FindString(resp)
regex = `https://myanimelist.net/anime/[0-9]*/([^"/]*)`
re2 := regexp.MustCompile(regex)
results2 := re2.FindAllStringSubmatch(results, -1)
var foundAnime, foundVideoAnime bool
animeUrlMap := make(map[string]bool)
for _, res := range results2 {
res[1] = strings.Replace(res[1], "_", " ", -1)
res[1] = strings.Replace(res[1], " ", " ", -1) // replace double space
res[1] = strings.ToLower(res[1])
if res[1] == name {
// set anime url to fetch results
AnimeURL = res[0]
foundAnime = true
break
}
animeUrlMap[res[1]] = true
}
if !foundAnime && video == "" {
index := 0
boldyellow.Println("Did you mean :")
boldyellow.Println("---------------")
for key := range animeUrlMap {
index += 1
green.Printf("%v.", index)
fmt.Printf(" %v\n", key)
}
}
// if no video parameters set return true if AnimeURL was found
if video == "" {
if foundAnime {
return true
}
return false
}
// Search for episode videos
searchName := strings.Replace(name, " ", "%20", -1)
searchURL = VIDEOsearch + searchName
resp, err = getContent(searchURL)
if err {
return false
}
regex = `https://9anime.is/watch/([^"]*)`
re3 := regexp.MustCompile(regex)
resultsVideo := re3.FindAllStringSubmatch(resp, -1)
if emptyResult(len(resultsVideo), "-video", name) {
return false
}
searchName = strings.Replace(searchName, "%20", "-", -1)
animeVideoUrlMap := make(map[string]bool)
for _, anime := range resultsVideo {
dotpos := 0
if len(anime) < 2 {
continue
}
cleanname := ""
for i := 0; i < len(anime[1]); i++ {
if anime[1][i] == '.' {
dotpos = i
cleanname = strings.Replace(anime[1][:dotpos], "-", " ", -1)
animeVideoUrlMap[cleanname] = true
break
}
}
if cleanname == name {
foundVideoAnime = true
AnimeVideoURL = anime[0]
return true
}
}
if !foundVideoAnime {
index := 0
boldyellow.Println("Video results found for :")
boldyellow.Println("---------------")
for key := range animeVideoUrlMap {
index += 1
green.Printf("%v.", index)
fmt.Printf(" %v\n", key)
}
}
return false
}
func main() {
bindFlags()
if name != "" {
if !synopsis && !score && !rank && !info && !EP && !aired && !songs && !all && len(video) == 0 {
boldred.Println("No params found")
return
}
success := Search()
if success {
if fetchDetails() {
PrintParams()
}
if video != "" {
fetchVideoURL()
}
}
} else if seasonal != "" {
if fetchDetailsSeason(seasonal) {
PrintParams()
}
}
}