internal/provider_animepahe.go
513 lines · 13398 bytes
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "os"
10 "path/filepath"
11 "regexp"
12 "sort"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/go-rod/rod"
18 "github.com/go-rod/rod/lib/launcher"
19)
20
21var animepaheCookiesBypassed bool
22var cookieFilePath = filepath.Join(os.ExpandEnv("$HOME"), ".local", "share", "curd", "animepahe_cookies.json")
23
24func saveCookies(cookies []*http.Cookie) {
25 os.MkdirAll(filepath.Dir(cookieFilePath), 0755)
26 b, _ := json.Marshal(cookies)
27 os.WriteFile(cookieFilePath, b, 0644)
28}
29
30func loadCookies() []*http.Cookie {
31 b, err := os.ReadFile(cookieFilePath)
32 if err != nil {
33 return nil
34 }
35 var cookies []*http.Cookie
36 json.Unmarshal(b, &cookies)
37 return cookies
38}
39
40func checkCookiesValid() bool {
41 req, _ := http.NewRequest("GET", "https://animepahe.pw/api?m=search&q=test", nil)
42 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
43 req.Header.Set("Referer", "https://animepahe.pw/")
44 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
45 req.Header.Set("X-Requested-With", "XMLHttpRequest")
46
47 resp, err := sharedHTTPClient.Do(req)
48 if err != nil {
49 return false
50 }
51 defer resp.Body.Close()
52
53 if resp.StatusCode != 200 {
54 return false
55 }
56
57 contentType := resp.Header.Get("Content-Type")
58 return strings.Contains(contentType, "application/json")
59}
60
61func (p *AnimepaheProvider) ensureBypass() error {
62 if animepaheCookiesBypassed {
63 return nil
64 }
65
66 cookies := loadCookies()
67 if len(cookies) > 0 {
68 u, _ := url.Parse("https://animepahe.pw")
69 SetCookiesForAnimepahe(u, cookies)
70
71 if checkCookiesValid() {
72 animepaheCookiesBypassed = true
73 Log("Successfully restored Animepahe session from cache.")
74 return nil
75 }
76 Log("Cached Animepahe session expired. Requesting new session...")
77 }
78
79 CurdOut("Solving Animepahe DDoS-Guard challenge via headless browser...")
80
81 l := launcher.New().Headless(true)
82 defer l.Cleanup()
83 browser := rod.New().ControlURL(l.MustLaunch()).MustConnect()
84 defer browser.MustClose()
85
86 page := browser.MustPage("https://animepahe.pw/")
87 page.MustWaitLoad()
88
89 for i := 0; i < 30; i++ {
90 info, err := page.Info()
91 if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" {
92 break
93 }
94 time.Sleep(500 * time.Millisecond)
95 }
96
97 rodCookies, err := page.Cookies(nil)
98 if err != nil {
99 return fmt.Errorf("failed to acquire DDoS guard cookies: %v", err)
100 }
101
102 u, _ := url.Parse("https://animepahe.pw")
103 var httpCookies []*http.Cookie
104 for _, cookie := range rodCookies {
105 httpCookies = append(httpCookies, &http.Cookie{
106 Name: cookie.Name,
107 Value: cookie.Value,
108 })
109 }
110 SetCookiesForAnimepahe(u, httpCookies)
111
112 if !checkCookiesValid() {
113 return fmt.Errorf("bypassed cookies are still invalid")
114 }
115
116 saveCookies(httpCookies)
117 animepaheCookiesBypassed = true
118 CurdOut("Successfully bypassed DDoS-Guard.")
119 return nil
120}
121
122type AnimepaheProvider struct{}
123
124func (p *AnimepaheProvider) Name() string {
125 return "animepahe"
126}
127
128type AnimepaheSearchItem struct {
129 ID int `json:"id"`
130 Title string `json:"title"`
131 Type string `json:"type"`
132 Episodes int `json:"episodes"`
133 Status string `json:"status"`
134 Season string `json:"season"`
135 Year int `json:"year"`
136 Score float64 `json:"score"`
137 Poster string `json:"poster"`
138 Session string `json:"session"`
139}
140
141type animepaheSearchResponse struct {
142 Total int `json:"total"`
143 PerPage int `json:"per_page"`
144 CurrentPage int `json:"current_page"`
145 LastPage int `json:"last_page"`
146 Data []AnimepaheSearchItem `json:"data"`
147}
148
149func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
150 if err := p.ensureBypass(); err != nil {
151 return nil, err
152 }
153 // animepahe doesn't distinguish sub/dub at the search level
154 searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query))
155
156 req, _ := http.NewRequest("GET", searchUrl, nil)
157 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
158 req.Header.Set("Referer", "https://animepahe.pw/")
159 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
160 req.Header.Set("X-Requested-With", "XMLHttpRequest")
161
162 resp, err := sharedHTTPClient.Do(req)
163 if err != nil {
164 return nil, err
165 }
166 defer resp.Body.Close()
167
168 body, err := io.ReadAll(resp.Body)
169 if err != nil {
170 return nil, err
171 }
172
173 var searchResp animepaheSearchResponse
174 err = json.Unmarshal(body, &searchResp)
175 if err != nil {
176 return nil, err
177 }
178
179 var result []SelectionOption
180 for _, item := range searchResp.Data {
181 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes)
182 result = append(result, SelectionOption{
183 Title: item.Title,
184 Label: label,
185 Key: item.Session, // Using session as ID
186 Thumbnail: item.Poster,
187 ExtraData: item,
188 })
189 }
190
191 return result, nil
192}
193
194type animepaheEpisodesResponse struct {
195 Total int `json:"total"`
196 PerPage int `json:"per_page"`
197 CurrentPage int `json:"current_page"`
198 LastPage int `json:"last_page"`
199 Data []struct {
200 ID int `json:"id"`
201 AnimeID int `json:"anime_id"`
202 Episode int `json:"episode"`
203 Session string `json:"session"`
204 } `json:"data"`
205}
206
207func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) {
208 if err := p.ensureBypass(); err != nil {
209 return nil, err
210 }
211 // showID here is the session ID for animepahe
212 var allEpisodes []int
213 page := 1
214
215 for {
216 epUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", showID, page)
217 req, _ := http.NewRequest("GET", epUrl, nil)
218 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
219 req.Header.Set("Referer", "https://animepahe.pw/")
220 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
221 req.Header.Set("X-Requested-With", "XMLHttpRequest")
222
223 resp, err := sharedHTTPClient.Do(req)
224 if err != nil {
225 return nil, err
226 }
227
228 body, err := io.ReadAll(resp.Body)
229 resp.Body.Close()
230 if err != nil {
231 return nil, err
232 }
233
234 var epsResp animepaheEpisodesResponse
235 err = json.Unmarshal(body, &epsResp)
236 if err != nil {
237 return nil, err
238 }
239
240 for _, ep := range epsResp.Data {
241 allEpisodes = append(allEpisodes, ep.Episode)
242 }
243
244 if epsResp.CurrentPage >= epsResp.LastPage {
245 break
246 }
247 page++
248 }
249
250 sort.Ints(allEpisodes)
251 var result []string
252 for _, ep := range allEpisodes {
253 result = append(result, strconv.Itoa(ep))
254 }
255
256 return result, nil
257}
258
259func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
260 if err := p.ensureBypass(); err != nil {
261 return nil, err
262 }
263 // 1. Get episode session ID
264 // Map the 1-based Anilist episode number to Animepahe's actual episode number
265 eps, err := p.EpisodesList(id, "")
266 if err != nil {
267 return nil, err
268 }
269 if epNo < 1 || epNo > len(eps) {
270 return nil, fmt.Errorf("episode %d out of bounds (found %d episodes)", epNo, len(eps))
271 }
272
273 mappedEpNo, err := strconv.Atoi(eps[epNo-1])
274 if err != nil {
275 return nil, fmt.Errorf("invalid episode number format in provider: %v", err)
276 }
277
278 // Let's do a simple scan for the episode session:
279 var episodeSession string
280 page := 1
281 for {
282 reqUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", id, page)
283 req, _ := http.NewRequest("GET", reqUrl, nil)
284 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
285 req.Header.Set("Referer", "https://animepahe.pw/")
286 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
287 req.Header.Set("X-Requested-With", "XMLHttpRequest")
288
289 resp, err := sharedHTTPClient.Do(req)
290 if err != nil {
291 return nil, err
292 }
293
294 body, err := io.ReadAll(resp.Body)
295 resp.Body.Close()
296 if err != nil {
297 return nil, err
298 }
299
300 var epsResp animepaheEpisodesResponse
301 err = json.Unmarshal(body, &epsResp)
302 if err != nil {
303 return nil, err
304 }
305
306 for _, item := range epsResp.Data {
307 if item.Episode == mappedEpNo {
308 episodeSession = item.Session
309 break
310 }
311 }
312
313 if episodeSession != "" || epsResp.CurrentPage >= epsResp.LastPage {
314 break
315 }
316 page++
317 }
318
319 if episodeSession == "" {
320 return nil, fmt.Errorf("episode %d (mapped to %d) not found", epNo, mappedEpNo)
321 }
322
323 // player page: https://animepahe.pw/play/<anime_session>/<episode_session>
324 // stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\"
325 playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", id, episodeSession)
326 req, _ := http.NewRequest("GET", playerUrl, nil)
327 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
328 req.Header.Set("Referer", "https://animepahe.pw/")
329 req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
330
331 resp, err := sharedHTTPClient.Do(req)
332 if err != nil {
333 return nil, err
334 }
335 defer resp.Body.Close()
336
337 body, err := io.ReadAll(resp.Body)
338 if err != nil {
339 return nil, err
340 }
341
342 bodyStr := string(body)
343 type streamLink struct {
344 url string
345 res int
346 }
347 var subLinks []streamLink
348 var dubLinks []streamLink
349
350 parts := strings.Split(bodyStr, "<button")
351 for i := 1; i < len(parts); i++ {
352 part := parts[i]
353 srcIdx := strings.Index(part, "data-src=\"")
354 if srcIdx == -1 {
355 continue
356 }
357
358 startIdx := srcIdx + 10
359 endIdx := strings.Index(part[startIdx:], "\"")
360 if endIdx == -1 {
361 continue
362 }
363
364 link := part[startIdx : startIdx+endIdx]
365 if !strings.Contains(link, "kwik.cx") {
366 continue
367 }
368
369 resIdx := strings.Index(part, "data-resolution=\"")
370 res := 0
371 if resIdx != -1 {
372 startRes := resIdx + 17
373 endRes := strings.Index(part[startRes:], "\"")
374 if endRes != -1 {
375 res, _ = strconv.Atoi(part[startRes : startRes+endRes])
376 }
377 }
378
379 sLink := streamLink{url: link, res: res}
380 if strings.Contains(part, "data-audio=\"eng\"") {
381 dubLinks = append(dubLinks, sLink)
382 } else {
383 subLinks = append(subLinks, sLink)
384 }
385 }
386
387 // Sort by resolution descending
388 sortFunc := func(links []streamLink) {
389 sort.Slice(links, func(i, j int) bool {
390 return links[i].res > links[j].res
391 })
392 }
393 sortFunc(subLinks)
394 sortFunc(dubLinks)
395
396 var links []string
397 if config.SubOrDub == "dub" && len(dubLinks) > 0 {
398 for _, l := range dubLinks {
399 links = append(links, l.url)
400 }
401 } else if len(subLinks) > 0 {
402 for _, l := range subLinks {
403 links = append(links, l.url)
404 }
405 } else if len(dubLinks) > 0 {
406 for _, l := range dubLinks {
407 links = append(links, l.url)
408 }
409 }
410
411 var finalLinks []string
412 for _, kwikLink := range links {
413 m3u8, err := p.extractKwikM3u8(kwikLink)
414 if err == nil && m3u8 != "" {
415 finalLinks = append(finalLinks, m3u8)
416 }
417 }
418
419 if len(finalLinks) == 0 {
420 return nil, fmt.Errorf("failed to extract any stream links from kwik")
421 }
422
423 return finalLinks, nil
424}
425
426func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
427 req, _ := http.NewRequest("GET", kwikUrl, nil)
428 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
429 req.Header.Set("Referer", "https://animepahe.pw/")
430 req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
431
432 resp, err := sharedHTTPClient.Do(req)
433 if err != nil {
434 return "", err
435 }
436 defer resp.Body.Close()
437
438 body, err := io.ReadAll(resp.Body)
439 if err != nil {
440 return "", err
441 }
442 bodyStr := string(body)
443
444 re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`)
445 matches := re.FindAllStringSubmatch(bodyStr, -1)
446
447 for _, match := range matches {
448 pStr := match[1]
449 a, _ := strconv.Atoi(match[2])
450 c, _ := strconv.Atoi(match[3])
451 k := strings.Split(match[4], "|")
452
453 pStr = strings.ReplaceAll(pStr, "\\'", "'")
454 unpacked := unpackKwik(pStr, a, c, k)
455
456 if strings.Contains(unpacked, "m3u8") {
457 urlRe := regexp.MustCompile(`(https://[a-zA-Z0-9\-\.\/]+m3u8)`)
458 urlMatch := urlRe.FindStringSubmatch(unpacked)
459 if len(urlMatch) > 1 {
460 return urlMatch[1], nil
461 }
462 }
463 }
464 return "", fmt.Errorf("m3u8 link not found in kwik page")
465}
466
467func unpackKwik(p string, a int, c int, k []string) string {
468 e := func(c int) string {
469 var helper func(c int) string
470 helper = func(c int) string {
471 res := ""
472 if c >= a {
473 res += helper(c / a)
474 }
475 mod := c % a
476 if mod > 35 {
477 res += string(rune(mod + 29))
478 } else {
479 res += strconv.FormatInt(int64(mod), 36)
480 }
481 return res
482 }
483 return helper(c)
484 }
485
486 d := make(map[string]string)
487 for i := c - 1; i >= 0; i-- {
488 val := k[i]
489 if val == "" {
490 val = e(i)
491 }
492 d[e(i)] = val
493 }
494
495 re := regexp.MustCompile(`[a-zA-Z0-9_]+`)
496 unpacked := re.ReplaceAllStringFunc(p, func(match string) string {
497 if val, ok := d[match]; ok && val != "" {
498 return val
499 }
500 return match
501 })
502
503 return unpacked
504}
505
506func contains(slice []string, val string) bool {
507 for _, item := range slice {
508 if item == val {
509 return true
510 }
511 }
512 return false
513}