internal/provider_animepahe.go

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