internal/provider_animepahe.go

623 lines · 16360 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 animepaheAnimeRef struct {
147	ReleaseID string
148	Session   string
149}
150
151func (r animepaheAnimeRef) apiID() string {
152	if r.Session != "" {
153		return r.Session
154	}
155	return r.ReleaseID
156}
157
158func formatAnimepaheProviderID(item AnimepaheSearchItem) string {
159	if item.ID > 0 && item.Session != "" {
160		return fmt.Sprintf("%d:%s", item.ID, item.Session)
161	}
162	if item.Session != "" {
163		return item.Session
164	}
165	if item.ID > 0 {
166		return strconv.Itoa(item.ID)
167	}
168	return ""
169}
170
171func parseAnimepaheProviderID(providerID string) animepaheAnimeRef {
172	providerID = strings.TrimSpace(providerID)
173	if providerID == "" {
174		return animepaheAnimeRef{}
175	}
176
177	parts := strings.SplitN(providerID, ":", 2)
178	if len(parts) == 2 && parts[0] != "" && parts[1] != "" {
179		if _, err := strconv.Atoi(parts[0]); err == nil {
180			return animepaheAnimeRef{ReleaseID: parts[0], Session: parts[1]}
181		}
182	}
183
184	if _, err := strconv.Atoi(providerID); err == nil {
185		return animepaheAnimeRef{ReleaseID: providerID}
186	}
187
188	return animepaheAnimeRef{Session: providerID}
189}
190
191func stableAnimepaheProviderID(providerID string) string {
192	animeRef := parseAnimepaheProviderID(providerID)
193	if animeRef.ReleaseID != "" {
194		return animeRef.ReleaseID
195	}
196	return providerID
197}
198
199func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string, error) {
200	animeRef := parseAnimepaheProviderID(providerID)
201	query = strings.TrimSpace(query)
202	if query == "" {
203		if animeRef.Session != "" {
204			return providerID, nil
205		}
206		return "", fmt.Errorf("cannot resolve animepahe provider id %q without an anime title", providerID)
207	}
208
209	options, err := p.SearchAnime(query, "")
210	if err != nil {
211		if animeRef.Session != "" {
212			Log(fmt.Sprintf("Animepahe provider id refresh failed for %q, using existing session: %v", providerID, err))
213			return providerID, nil
214		}
215		return "", err
216	}
217
218	for _, option := range options {
219		item, ok := option.ExtraData.(AnimepaheSearchItem)
220		if !ok {
221			continue
222		}
223
224		if animeRef.ReleaseID != "" && strconv.Itoa(item.ID) == animeRef.ReleaseID {
225			return formatAnimepaheProviderID(item), nil
226		}
227		if animeRef.Session != "" && item.Session == animeRef.Session {
228			return formatAnimepaheProviderID(item), nil
229		}
230	}
231
232	if animeRef.Session != "" {
233		Log(fmt.Sprintf("Animepahe provider id %q was not found in search results for %q, using existing session", providerID, query))
234		return providerID, nil
235	}
236
237	return "", fmt.Errorf("animepahe id %q was not found in search results for %q", providerID, query)
238}
239
240type animepaheSearchResponse struct {
241	Total       int                   `json:"total"`
242	PerPage     int                   `json:"per_page"`
243	CurrentPage int                   `json:"current_page"`
244	LastPage    int                   `json:"last_page"`
245	Data        []AnimepaheSearchItem `json:"data"`
246}
247
248func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
249	if err := p.ensureBypass(); err != nil {
250		return nil, err
251	}
252	// animepahe doesn't distinguish sub/dub at the search level
253	searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query))
254
255	req, _ := http.NewRequest("GET", searchUrl, nil)
256	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")
257	req.Header.Set("Referer", "https://animepahe.pw/")
258	req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
259	req.Header.Set("X-Requested-With", "XMLHttpRequest")
260
261	resp, err := sharedHTTPClient.Do(req)
262	if err != nil {
263		return nil, err
264	}
265	defer resp.Body.Close()
266
267	body, err := io.ReadAll(resp.Body)
268	if err != nil {
269		return nil, err
270	}
271
272	var searchResp animepaheSearchResponse
273	err = json.Unmarshal(body, &searchResp)
274	if err != nil {
275		return nil, err
276	}
277
278	var result []SelectionOption
279	for _, item := range searchResp.Data {
280		label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes)
281		result = append(result, SelectionOption{
282			Title:     item.Title,
283			Label:     label,
284			Key:       formatAnimepaheProviderID(item),
285			Thumbnail: item.Poster,
286			ExtraData: item,
287		})
288	}
289
290	return result, nil
291}
292
293type animepaheEpisodesResponse struct {
294	Total       int `json:"total"`
295	PerPage     int `json:"per_page"`
296	CurrentPage int `json:"current_page"`
297	LastPage    int `json:"last_page"`
298	Data        []struct {
299		ID      int    `json:"id"`
300		AnimeID int    `json:"anime_id"`
301		Episode int    `json:"episode"`
302		Session string `json:"session"`
303	} `json:"data"`
304}
305
306func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) {
307	if err := p.ensureBypass(); err != nil {
308		return nil, err
309	}
310	animeRef := parseAnimepaheProviderID(showID)
311	apiID := animeRef.apiID()
312	if apiID == "" {
313		return nil, fmt.Errorf("animepahe provider id %q is invalid; please reselect this anime", showID)
314	}
315
316	var allEpisodes []int
317	page := 1
318
319	for {
320		epUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page)
321		req, _ := http.NewRequest("GET", epUrl, nil)
322		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")
323		req.Header.Set("Referer", "https://animepahe.pw/")
324		req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
325		req.Header.Set("X-Requested-With", "XMLHttpRequest")
326
327		resp, err := sharedHTTPClient.Do(req)
328		if err != nil {
329			return nil, err
330		}
331
332		body, err := io.ReadAll(resp.Body)
333		resp.Body.Close()
334		if err != nil {
335			return nil, err
336		}
337
338		var epsResp animepaheEpisodesResponse
339		err = json.Unmarshal(body, &epsResp)
340		if err != nil {
341			return nil, err
342		}
343
344		for _, ep := range epsResp.Data {
345			allEpisodes = append(allEpisodes, ep.Episode)
346		}
347
348		if epsResp.CurrentPage >= epsResp.LastPage {
349			break
350		}
351		page++
352	}
353
354	sort.Ints(allEpisodes)
355	var result []string
356	for _, ep := range allEpisodes {
357		result = append(result, strconv.Itoa(ep))
358	}
359
360	return result, nil
361}
362
363func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
364	if err := p.ensureBypass(); err != nil {
365		return nil, err
366	}
367	animeRef := parseAnimepaheProviderID(id)
368	if animeRef.Session == "" {
369		return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id)
370	}
371	apiID := animeRef.apiID()
372
373	// 1. Get episode session ID
374	// Map the 1-based Anilist episode number to Animepahe's actual episode number
375	eps, err := p.EpisodesList(id, "")
376	if err != nil {
377		return nil, err
378	}
379	if epNo < 1 || epNo > len(eps) {
380		return nil, fmt.Errorf("episode %d out of bounds (found %d episodes)", epNo, len(eps))
381	}
382
383	mappedEpNo, err := strconv.Atoi(eps[epNo-1])
384	if err != nil {
385		return nil, fmt.Errorf("invalid episode number format in provider: %v", err)
386	}
387
388	// Let's do a simple scan for the episode session:
389	var episodeSession string
390	page := 1
391	for {
392		reqUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page)
393		req, _ := http.NewRequest("GET", reqUrl, nil)
394		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")
395		req.Header.Set("Referer", "https://animepahe.pw/")
396		req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
397		req.Header.Set("X-Requested-With", "XMLHttpRequest")
398
399		resp, err := sharedHTTPClient.Do(req)
400		if err != nil {
401			return nil, err
402		}
403
404		body, err := io.ReadAll(resp.Body)
405		resp.Body.Close()
406		if err != nil {
407			return nil, err
408		}
409
410		var epsResp animepaheEpisodesResponse
411		err = json.Unmarshal(body, &epsResp)
412		if err != nil {
413			return nil, err
414		}
415
416		for _, item := range epsResp.Data {
417			if item.Episode == mappedEpNo {
418				episodeSession = item.Session
419				break
420			}
421		}
422
423		if episodeSession != "" || epsResp.CurrentPage >= epsResp.LastPage {
424			break
425		}
426		page++
427	}
428
429	if episodeSession == "" {
430		return nil, fmt.Errorf("episode %d (mapped to %d) not found", epNo, mappedEpNo)
431	}
432
433	// player page: https://animepahe.pw/play/<anime_session>/<episode_session>
434	// stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\"
435	playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", animeRef.Session, episodeSession)
436	req, _ := http.NewRequest("GET", playerUrl, nil)
437	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")
438	req.Header.Set("Referer", "https://animepahe.pw/")
439	req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
440
441	resp, err := sharedHTTPClient.Do(req)
442	if err != nil {
443		return nil, err
444	}
445	defer resp.Body.Close()
446
447	body, err := io.ReadAll(resp.Body)
448	if err != nil {
449		return nil, err
450	}
451
452	bodyStr := string(body)
453	type streamLink struct {
454		url string
455		res int
456	}
457	var subLinks []streamLink
458	var dubLinks []streamLink
459
460	parts := strings.Split(bodyStr, "<button")
461	for i := 1; i < len(parts); i++ {
462		part := parts[i]
463		srcIdx := strings.Index(part, "data-src=\"")
464		if srcIdx == -1 {
465			continue
466		}
467
468		startIdx := srcIdx + 10
469		endIdx := strings.Index(part[startIdx:], "\"")
470		if endIdx == -1 {
471			continue
472		}
473
474		link := part[startIdx : startIdx+endIdx]
475		if !strings.Contains(link, "kwik.cx") {
476			continue
477		}
478
479		resIdx := strings.Index(part, "data-resolution=\"")
480		res := 0
481		if resIdx != -1 {
482			startRes := resIdx + 17
483			endRes := strings.Index(part[startRes:], "\"")
484			if endRes != -1 {
485				res, _ = strconv.Atoi(part[startRes : startRes+endRes])
486			}
487		}
488
489		sLink := streamLink{url: link, res: res}
490		if strings.Contains(part, "data-audio=\"eng\"") {
491			dubLinks = append(dubLinks, sLink)
492		} else {
493			subLinks = append(subLinks, sLink)
494		}
495	}
496
497	// Sort by resolution descending
498	sortFunc := func(links []streamLink) {
499		sort.Slice(links, func(i, j int) bool {
500			return links[i].res > links[j].res
501		})
502	}
503	sortFunc(subLinks)
504	sortFunc(dubLinks)
505
506	var links []string
507	if config.SubOrDub == "dub" && len(dubLinks) > 0 {
508		for _, l := range dubLinks {
509			links = append(links, l.url)
510		}
511	} else if len(subLinks) > 0 {
512		for _, l := range subLinks {
513			links = append(links, l.url)
514		}
515	} else if len(dubLinks) > 0 {
516		for _, l := range dubLinks {
517			links = append(links, l.url)
518		}
519	}
520
521	var finalLinks []string
522	for _, kwikLink := range links {
523		m3u8, err := p.extractKwikM3u8(kwikLink)
524		if err == nil && m3u8 != "" {
525			finalLinks = append(finalLinks, m3u8)
526		}
527	}
528
529	if len(finalLinks) == 0 {
530		return nil, fmt.Errorf("failed to extract any stream links from kwik")
531	}
532
533	return finalLinks, nil
534}
535
536func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
537	req, _ := http.NewRequest("GET", kwikUrl, nil)
538	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")
539	req.Header.Set("Referer", "https://animepahe.pw/")
540	req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
541
542	resp, err := sharedHTTPClient.Do(req)
543	if err != nil {
544		return "", err
545	}
546	defer resp.Body.Close()
547
548	body, err := io.ReadAll(resp.Body)
549	if err != nil {
550		return "", err
551	}
552	bodyStr := string(body)
553
554	re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`)
555	matches := re.FindAllStringSubmatch(bodyStr, -1)
556
557	for _, match := range matches {
558		pStr := match[1]
559		a, _ := strconv.Atoi(match[2])
560		c, _ := strconv.Atoi(match[3])
561		k := strings.Split(match[4], "|")
562
563		pStr = strings.ReplaceAll(pStr, "\\'", "'")
564		unpacked := unpackKwik(pStr, a, c, k)
565
566		if strings.Contains(unpacked, "m3u8") {
567			urlRe := regexp.MustCompile(`(https://[a-zA-Z0-9\-\.\/]+m3u8)`)
568			urlMatch := urlRe.FindStringSubmatch(unpacked)
569			if len(urlMatch) > 1 {
570				return urlMatch[1], nil
571			}
572		}
573	}
574	return "", fmt.Errorf("m3u8 link not found in kwik page")
575}
576
577func unpackKwik(p string, a int, c int, k []string) string {
578	e := func(c int) string {
579		var helper func(c int) string
580		helper = func(c int) string {
581			res := ""
582			if c >= a {
583				res += helper(c / a)
584			}
585			mod := c % a
586			if mod > 35 {
587				res += string(rune(mod + 29))
588			} else {
589				res += strconv.FormatInt(int64(mod), 36)
590			}
591			return res
592		}
593		return helper(c)
594	}
595
596	d := make(map[string]string)
597	for i := c - 1; i >= 0; i-- {
598		val := k[i]
599		if val == "" {
600			val = e(i)
601		}
602		d[e(i)] = val
603	}
604
605	re := regexp.MustCompile(`[a-zA-Z0-9_]+`)
606	unpacked := re.ReplaceAllStringFunc(p, func(match string) string {
607		if val, ok := d[match]; ok && val != "" {
608			return val
609		}
610		return match
611	})
612
613	return unpacked
614}
615
616func contains(slice []string, val string) bool {
617	for _, item := range slice {
618		if item == val {
619			return true
620		}
621	}
622	return false
623}