internal/providers/allanime/streams_legacy.go

587 lines · 16878 bytes

25 symbols in this file
  1package allanime
  2
  3import (
  4	"bytes"
  5	"crypto/aes"
  6	"crypto/cipher"
  7	"crypto/sha256"
  8	"encoding/base64"
  9	"encoding/binary"
 10	"encoding/hex"
 11	"encoding/json"
 12	"fmt"
 13	"io"
 14	"net/http"
 15	"net/url"
 16	"regexp"
 17	"sort"
 18	"strconv"
 19	"strings"
 20
 21	"github.com/wraient/curd/internal/curdhost"
 22	"github.com/wraient/curd/internal/providers"
 23)
 24
 25type allanimeSource struct {
 26	SourceUrl  string  `json:"sourceUrl"`
 27	SourceName string  `json:"sourceName"`
 28	Priority   float64 `json:"priority"`
 29}
 30
 31type allanimeResponse struct {
 32	Data struct {
 33		M          string `json:"_m"`
 34		Tobeparsed string `json:"tobeparsed"`
 35		Episode    struct {
 36			SourceUrls []allanimeSource `json:"sourceUrls"`
 37		} `json:"episode"`
 38	} `json:"data"`
 39}
 40
 41type allanimeTobeparsedPayload struct {
 42	Episode struct {
 43		SourceUrls []allanimeSource `json:"sourceUrls"`
 44	} `json:"episode"`
 45}
 46
 47type filemoonResponse struct {
 48	IV       string   `json:"iv"`
 49	Payload  string   `json:"payload"`
 50	KeyParts []string `json:"key_parts"`
 51}
 52
 53func decodeTobeparsed(blob string) ([]allanimeSource, error) {
 54	plain, err := decryptTobeparsedPlain(blob)
 55	if err != nil {
 56		return nil, err
 57	}
 58
 59	var payload allanimeTobeparsedPayload
 60	if err := json.Unmarshal(plain, &payload); err != nil {
 61		return nil, fmt.Errorf("failed to parse decrypted tobeparsed payload: %w", err)
 62	}
 63
 64	if len(payload.Episode.SourceUrls) == 0 {
 65		return nil, fmt.Errorf("no source URLs found in decrypted tobeparsed payload")
 66	}
 67
 68	return payload.Episode.SourceUrls, nil
 69}
 70
 71func decryptTobeparsedPlain(blob string) ([]byte, error) {
 72	key := []byte("Xot36i3lK3:v1")
 73	hash := sha256.Sum256(key)
 74
 75	data, err := base64.StdEncoding.DecodeString(blob)
 76	if err != nil {
 77		return nil, fmt.Errorf("error decoding base64: %w", err)
 78	}
 79
 80	if len(data) < 29 {
 81		return nil, fmt.Errorf("data too short to contain tobeparsed payload")
 82	}
 83
 84	iv := data[1:13]
 85	ctLen := len(data) - 13 - 16
 86	if ctLen <= 0 {
 87		return nil, fmt.Errorf("ciphertext length is invalid in tobeparsed payload")
 88	}
 89	ct := data[13 : 13+ctLen]
 90
 91	ctrIV := make([]byte, 16)
 92	copy(ctrIV, iv)
 93	binary.BigEndian.PutUint32(ctrIV[12:], uint32(2))
 94
 95	block, err := aes.NewCipher(hash[:])
 96	if err != nil {
 97		return nil, fmt.Errorf("error creating cipher: %w", err)
 98	}
 99
100	stream := cipher.NewCTR(block, ctrIV)
101	plain := make([]byte, len(ct))
102	stream.XORKeyStream(plain, ct)
103	return plain, nil
104}
105
106func decodeProviderID(encoded string) string {
107	// Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
108	re := regexp.MustCompile("..")
109	pairs := re.FindAllString(encoded, -1)
110
111	// Mapping for the replacements
112	replacements := map[string]string{
113		// Uppercase letters
114		"79": "A", "7a": "B", "7b": "C", "7c": "D", "7d": "E", "7e": "F", "7f": "G",
115		"70": "H", "71": "I", "72": "J", "73": "K", "74": "L", "75": "M", "76": "N", "77": "O",
116		"68": "P", "69": "Q", "6a": "R", "6b": "S", "6c": "T", "6d": "U", "6e": "V", "6f": "W",
117		"60": "X", "61": "Y", "62": "Z",
118		// Lowercase letters
119		"59": "a", "5a": "b", "5b": "c", "5c": "d", "5d": "e", "5e": "f", "5f": "g",
120		"50": "h", "51": "i", "52": "j", "53": "k", "54": "l", "55": "m", "56": "n", "57": "o",
121		"48": "p", "49": "q", "4a": "r", "4b": "s", "4c": "t", "4d": "u", "4e": "v", "4f": "w",
122		"40": "x", "41": "y", "42": "z",
123		// Numbers
124		"08": "0", "09": "1", "0a": "2", "0b": "3", "0c": "4", "0d": "5", "0e": "6", "0f": "7",
125		"00": "8", "01": "9",
126		// Special characters
127		"15": "-", "16": ".", "67": "_", "46": "~", "02": ":", "17": "/", "07": "?", "1b": "#",
128		"63": "[", "65": "]", "78": "@", "19": "!", "1c": "$", "1e": "&", "10": "(", "11": ")",
129		"12": "*", "13": "+", "14": ",", "03": ";", "05": "=", "1d": "%",
130	}
131
132	// Perform the replacement equivalent to sed 's/^../.../'
133	for i, pair := range pairs {
134		if val, exists := replacements[pair]; exists {
135			pairs[i] = val
136		}
137	}
138
139	// Join the modified pairs back into a single string
140	result := strings.Join(pairs, "")
141
142	// Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
143	result = strings.ReplaceAll(result, "/clock", "/clock.json")
144
145	// Print the final result
146	return result
147}
148
149var allanimeNamedProviders = []string{
150	"Default",
151	"Yt-mp4",
152	"S-mp4",
153	"Fm-mp4",
154	"Luf-Mp4",
155}
156
157const (
158	allanimePersistedQueryReferer = "https://youtu-chan.com"
159	allanimeGraphQLReferer        = "https://allanime.to"
160)
161
162func isDirectPlayableAllanimeSource(source allanimeSource) bool {
163	sourceURL := strings.TrimSpace(source.SourceUrl)
164	if sourceURL == "" {
165		return false
166	}
167	if strings.HasPrefix(sourceURL, "--") {
168		return false
169	}
170	if !strings.HasPrefix(sourceURL, "http://") && !strings.HasPrefix(sourceURL, "https://") {
171		return false
172	}
173
174	if isUnreliableAllanimeDirectURL(sourceURL) {
175		return false
176	}
177
178	parsedURL, err := url.Parse(sourceURL)
179	if err != nil {
180		return false
181	}
182
183	path := strings.ToLower(parsedURL.Path)
184	if strings.HasSuffix(path, ".mp4") || strings.HasSuffix(path, ".m3u8") {
185		return true
186	}
187
188	host := strings.ToLower(parsedURL.Host)
189	return strings.Contains(host, "sharepoint.com") || strings.Contains(host, "wixmp.com")
190}
191
192func isUnreliableAllanimeDirectURL(sourceURL string) bool {
193	lowerURL := strings.ToLower(strings.TrimSpace(sourceURL))
194	return strings.Contains(lowerURL, "tools.fast4speed.rsvp/")
195}
196
197func sortAllanimeSourcesByPriority(sourceUrls []allanimeSource) []allanimeSource {
198	if len(sourceUrls) == 0 {
199		return nil
200	}
201
202	sorted := append([]allanimeSource(nil), sourceUrls...)
203	sort.SliceStable(sorted, func(i, j int) bool {
204		return sorted[i].Priority > sorted[j].Priority
205	})
206
207	return sorted
208}
209
210func normalizeAllanimeProviderPath(providerID string) string {
211	const allanimePrefix = "/https://allanime.day"
212
213	if strings.HasPrefix(providerID, allanimePrefix) {
214		trimmed := strings.TrimPrefix(providerID, allanimePrefix)
215		if trimmed == "" {
216			return "/"
217		}
218		if !strings.HasPrefix(trimmed, "/") {
219			return "/" + trimmed
220		}
221		return trimmed
222	}
223
224	return providerID
225}
226
227func decodeBase64URLRaw(input string) ([]byte, error) {
228	if decoded, err := base64.RawURLEncoding.DecodeString(input); err == nil {
229		return decoded, nil
230	}
231	return base64.URLEncoding.DecodeString(input)
232}
233
234func extractFilemoonLinks(videoData map[string]interface{}) []string {
235	raw, err := json.Marshal(videoData)
236	if err != nil {
237		curdhost.Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
238		return nil
239	}
240
241	var payload filemoonResponse
242	if err := json.Unmarshal(raw, &payload); err != nil {
243		curdhost.Log(fmt.Sprintf("Error parsing filemoon payload: %v", err))
244		return nil
245	}
246
247	if payload.IV == "" || payload.Payload == "" || len(payload.KeyParts) < 2 {
248		return nil
249	}
250
251	keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0])
252	if err != nil {
253		curdhost.Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err))
254		return nil
255	}
256
257	keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1])
258	if err != nil {
259		curdhost.Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err))
260		return nil
261	}
262
263	iv, err := decodeBase64URLRaw(payload.IV)
264	if err != nil {
265		curdhost.Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
266		return nil
267	}
268
269	ciphertext, err := decodeBase64URLRaw(payload.Payload)
270	if err != nil {
271		curdhost.Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
272		return nil
273	}
274
275	if len(ciphertext) <= 16 {
276		curdhost.Log("Filemoon ciphertext is too short")
277		return nil
278	}
279
280	// Match jerry.sh behavior: decrypt all bytes except the final 16-byte trailer.
281	ciphertext = ciphertext[:len(ciphertext)-16]
282
283	keyHex := hex.EncodeToString(append(keyPart1, keyPart2...))
284	key, err := hex.DecodeString(keyHex)
285	if err != nil {
286		curdhost.Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err))
287		return nil
288	}
289
290	ctrIVHex := hex.EncodeToString(iv) + "00000002"
291	ctrIV, err := hex.DecodeString(ctrIVHex)
292	if err != nil {
293		curdhost.Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err))
294		return nil
295	}
296
297	if len(ctrIV) != aes.BlockSize {
298		curdhost.Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV)))
299		return nil
300	}
301
302	block, err := aes.NewCipher(key)
303	if err != nil {
304		curdhost.Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
305		return nil
306	}
307
308	plain := make([]byte, len(ciphertext))
309	cipher.NewCTR(block, ctrIV).XORKeyStream(plain, ciphertext)
310
311	decoded := strings.ReplaceAll(string(plain), `\u0026`, "&")
312	decoded = strings.ReplaceAll(decoded, `\u003D`, "=")
313
314	type qualityLink struct {
315		height int
316		link   string
317	}
318
319	collected := make([]qualityLink, 0)
320	seen := make(map[string]struct{})
321
322	reURLFirst := regexp.MustCompile(`"url":"([^"]+)".*?"height":([0-9]+)`)
323	reHeightFirst := regexp.MustCompile(`"height":([0-9]+).*?"url":"([^"]+)"`)
324
325	for _, match := range reURLFirst.FindAllStringSubmatch(decoded, -1) {
326		if len(match) != 3 {
327			continue
328		}
329		height, err := strconv.Atoi(match[2])
330		if err != nil {
331			continue
332		}
333		if _, exists := seen[match[1]]; exists {
334			continue
335		}
336		seen[match[1]] = struct{}{}
337		collected = append(collected, qualityLink{height: height, link: match[1]})
338	}
339
340	for _, match := range reHeightFirst.FindAllStringSubmatch(decoded, -1) {
341		if len(match) != 3 {
342			continue
343		}
344		height, err := strconv.Atoi(match[1])
345		if err != nil {
346			continue
347		}
348		if _, exists := seen[match[2]]; exists {
349			continue
350		}
351		seen[match[2]] = struct{}{}
352		collected = append(collected, qualityLink{height: height, link: match[2]})
353	}
354
355	sort.Slice(collected, func(i, j int) bool {
356		return collected[i].height > collected[j].height
357	})
358
359	links := make([]string, 0, len(collected))
360	for _, entry := range collected {
361		links = append(links, entry.link)
362	}
363
364	if len(links) > 0 {
365		curdhost.Log("Filemoon links fetched")
366	}
367
368	return links
369}
370
371// Get anime episode url respective to given config
372// If the link is found, it returns a list of links. Otherwise, it returns an error.
373//
374// Parameters:
375// - config: Configuration of the anime search.
376// - id: Allanime id of the anime to search for.
377// - epNo: Anime episode number to get links for.
378//
379// Returns:
380// - []string: a list of links for specified episode.
381// - error: an error if the episode is not found or if there is an issue during the search.
382func getAllanimeEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
383	preferredMode := providers.NormalizeTranslationType(config.SubOrDub)
384	return getAllanimeEpisodeURLForMode(id, preferredMode, epNo)
385}
386
387func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
388	return getEpisodeURLForMode(id, providers.NormalizeTranslationType(mode), epNo)
389}
390
391func fetchAllanimeEpisodeSources(id, mode string, epNo int) ([]allanimeSource, error) {
392	return fetchEpisodeSourcesForMode(id, providers.NormalizeTranslationType(mode), epNo)
393}
394
395func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, error) {
396	const (
397		episodeQueryHash = "d405d0edd690624b66baba3068e0edc3ac90f1597d898a1ec8db4e5c43c00fec"
398	)
399
400	episodeEmbedGQL := `query ($showId: String!, $translationType: VaildTranslationTypeEnumType!, $episodeString: String!) { episode( showId: $showId translationType: $translationType episodeString: $episodeString ) { episodeString sourceUrls }}`
401
402	variables := map[string]interface{}{
403		"showId":          id,
404		"translationType": providers.NormalizeTranslationType(mode),
405		"episodeString":   fmt.Sprintf("%d", epNo),
406	}
407
408	extensions := map[string]interface{}{
409		"persistedQuery": map[string]interface{}{
410			"version":    1,
411			"sha256Hash": episodeQueryHash,
412		},
413	}
414
415	variablesJSON, err := json.Marshal(variables)
416	if err != nil {
417		return nil, fmt.Errorf("failed to marshal persisted query variables: %w", err)
418	}
419
420	extensionsJSON, err := json.Marshal(extensions)
421	if err != nil {
422		return nil, fmt.Errorf("failed to marshal persisted query extensions: %w", err)
423	}
424
425	persistedURL := "https://api.allanime.day/api?variables=" + url.QueryEscape(string(variablesJSON)) + "&extensions=" + url.QueryEscape(string(extensionsJSON))
426
427	req, err := http.NewRequest("GET", persistedURL, nil)
428	if err != nil {
429		return nil, fmt.Errorf("failed to create persisted query request: %w", err)
430	}
431	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
432	req.Header.Set("Referer", allanimePersistedQueryReferer)
433	req.Header.Set("Origin", allanimePersistedQueryReferer)
434
435	resp, err := curdhost.HTTPClient().Do(req)
436	if err != nil {
437		return nil, fmt.Errorf("failed to send persisted query request: %w", err)
438	}
439	body, err := io.ReadAll(resp.Body)
440	resp.Body.Close()
441	if err != nil {
442		return nil, fmt.Errorf("failed to read persisted query response: %w", err)
443	}
444	if !curdhost.HTTPStatusOK(resp.StatusCode) {
445		return nil, curdhost.HTTPStatusError("allanime episode persisted query", resp.StatusCode, body)
446	}
447
448	var response allanimeResponse
449	if err := json.Unmarshal(body, &response); err != nil {
450		curdhost.Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
451	}
452
453	useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
454	if !useFallback && response.Data.Tobeparsed == "" && !strings.Contains(string(body), "tobeparsed") {
455		useFallback = true
456	}
457	if useFallback {
458		query := episodeEmbedGQL
459
460		// Build POST request body
461		requestBody, err := json.Marshal(map[string]interface{}{
462			"query":     query,
463			"variables": variables,
464		})
465		if err != nil {
466			return nil, fmt.Errorf("failed to marshal request body: %w", err)
467		}
468
469		req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
470		if err != nil {
471			return nil, fmt.Errorf("failed to create request: %w", err)
472		}
473
474		req.Header.Set("Content-Type", "application/json")
475		req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
476		req.Header.Set("Referer", allanimeGraphQLReferer)
477		req.Header.Set("Origin", allanimeGraphQLReferer)
478
479		resp, err := curdhost.HTTPClient().Do(req)
480		if err != nil {
481			return nil, fmt.Errorf("failed to send request: %w", err)
482		}
483		defer resp.Body.Close()
484
485		body, err := io.ReadAll(resp.Body)
486		if err != nil {
487			return nil, fmt.Errorf("failed to read response body: %w", err)
488		}
489		if !curdhost.HTTPStatusOK(resp.StatusCode) {
490			return nil, curdhost.HTTPStatusError("allanime episode fallback query", resp.StatusCode, body)
491		}
492
493		if err := json.Unmarshal(body, &response); err != nil {
494			curdhost.Log(fmt.Sprint("Error parsing fallback JSON: ", err))
495			return nil, err
496		}
497	}
498
499	if response.Data.Tobeparsed != "" {
500		curdhost.Log("Found tobeparsed field, decoding source URLs")
501		decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed)
502		if err != nil {
503			return nil, err
504		}
505
506		curdhost.Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
507		return decodedSources, nil
508	}
509
510	return response.Data.Episode.SourceUrls, nil
511}
512
513func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
514	links, _, err := getAllanimeEpisodeStreamsForMode(id, mode, epNo)
515	return links, err
516}
517
518func findNamedAllanimeSource(sourceUrls []allanimeSource, providerName string) (allanimeSource, bool) {
519	for _, source := range sourceUrls {
520		if strings.EqualFold(strings.TrimSpace(source.SourceName), providerName) {
521			return source, true
522		}
523	}
524	return allanimeSource{}, false
525}
526
527var wixstaticURLSetPattern = regexp.MustCompile(`^(https://video\.wixstatic\.com/video/[^/,]+/),([^/]*),/mp4/file\.mp4`)
528
529func expandWixmpLinks(link string) []string {
530	normalized := strings.TrimSpace(link)
531	if normalized == "" {
532		return nil
533	}
534
535	if strings.Contains(normalized, "repackager.wixmp.com") {
536		normalized = strings.TrimPrefix(normalized, "https://repackager.wixmp.com/")
537		normalized = strings.TrimPrefix(normalized, "http://repackager.wixmp.com/")
538		if !strings.HasPrefix(normalized, "http") {
539			normalized = "https://" + normalized
540		}
541	}
542
543	if idx := strings.Index(normalized, ".urlset"); idx != -1 {
544		normalized = normalized[:idx]
545	}
546
547	if match := wixstaticURLSetPattern.FindStringSubmatch(normalized); len(match) == 3 {
548		base := match[1]
549		qualities := strings.Split(match[2], ",")
550		expanded := make([]string, 0, len(qualities))
551		for _, quality := range qualities {
552			quality = strings.TrimSpace(quality)
553			if quality == "" {
554				continue
555			}
556			expanded = append(expanded, base+quality+"/mp4/file.mp4")
557		}
558		if len(expanded) > 0 {
559			sort.Slice(expanded, func(i, j int) bool {
560				return wixmpQualityScore(expanded[i]) > wixmpQualityScore(expanded[j])
561			})
562			return expanded
563		}
564	}
565
566	return []string{link}
567}
568
569func wixmpQualityScore(link string) int {
570	for _, quality := range []string{"1080p", "720p", "480p", "360p", "240p"} {
571		if strings.Contains(link, quality) {
572			switch quality {
573			case "1080p":
574				return 1080
575			case "720p":
576				return 720
577			case "480p":
578				return 480
579			case "360p":
580				return 360
581			case "240p":
582				return 240
583			}
584		}
585	}
586	return 0
587}