internal/episode_url.go

531 lines · 15315 bytes

  1package internal
  2
  3import (
  4	"bytes"
  5	"crypto/aes"
  6	"crypto/cipher"
  7	"crypto/sha256"
  8	"encoding/base64"
  9	"encoding/binary"
 10	"encoding/json"
 11	"fmt"
 12	"io"
 13	"net/http"
 14	"regexp"
 15	"strings"
 16	"time"
 17	"unicode"
 18)
 19
 20type allanimeResponse struct {
 21	Data struct {
 22		M          string `json:"_m"`
 23		Tobeparsed string `json:"tobeparsed"`
 24		Episode    struct {
 25			SourceUrls []struct {
 26				SourceUrl  string `json:"sourceUrl"`
 27				SourceName string `json:"sourceName"`
 28			} `json:"sourceUrls"`
 29		} `json:"episode"`
 30	} `json:"data"`
 31}
 32
 33type result struct {
 34	index int
 35	links []string
 36	err   error
 37}
 38
 39func decodeTobeparsed(blob string) string {
 40	key := []byte("Xot36i3lK3:v1")
 41	hash := sha256.Sum256(key)
 42
 43	data, err := base64.StdEncoding.DecodeString(blob)
 44	if err != nil {
 45		Log(fmt.Sprint("Error decoding base64:", err))
 46		return ""
 47	}
 48
 49	if len(data) < 29 {
 50		Log("Data too short to contain tobeparsed payload")
 51		return ""
 52	}
 53
 54	// The payload format is: 1-byte header, 12-byte IV, ciphertext, 16-byte trailer.
 55	iv := data[1:13]
 56	ctLen := len(data) - 13 - 16
 57	if ctLen <= 0 {
 58		Log("Ciphertext length is invalid in tobeparsed payload")
 59		return ""
 60	}
 61	ct := data[13 : 13+ctLen]
 62
 63	ctrIV := make([]byte, 16)
 64	copy(ctrIV, iv)
 65	binary.BigEndian.PutUint32(ctrIV[12:], uint32(2))
 66
 67	block, err := aes.NewCipher(hash[:])
 68	if err != nil {
 69		Log(fmt.Sprint("Error creating cipher:", err))
 70		return ""
 71	}
 72
 73	stream := cipher.NewCTR(block, ctrIV)
 74	plain := make([]byte, len(ct))
 75	stream.XORKeyStream(plain, ct)
 76
 77	result := string(plain)
 78	result = strings.ReplaceAll(result, "{", "\n")
 79	result = strings.ReplaceAll(result, "}", "\n")
 80
 81	re := regexp.MustCompile(`"sourceUrl":"--([^"]+)".*"sourceName":"([^"]+)"`)
 82	matches := re.FindAllStringSubmatch(result, -1)
 83
 84	var sb strings.Builder
 85	for _, match := range matches {
 86		if len(match) == 3 {
 87			sb.WriteString(match[2])
 88			sb.WriteString(" :")
 89			sb.WriteString(match[1])
 90			sb.WriteString("\n")
 91		}
 92	}
 93
 94	return sb.String()
 95}
 96
 97func decodeProviderID(encoded string) string {
 98	// Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
 99	re := regexp.MustCompile("..")
100	pairs := re.FindAllString(encoded, -1)
101
102	// Mapping for the replacements
103	replacements := map[string]string{
104		// Uppercase letters
105		"79": "A", "7a": "B", "7b": "C", "7c": "D", "7d": "E", "7e": "F", "7f": "G",
106		"70": "H", "71": "I", "72": "J", "73": "K", "74": "L", "75": "M", "76": "N", "77": "O",
107		"68": "P", "69": "Q", "6a": "R", "6b": "S", "6c": "T", "6d": "U", "6e": "V", "6f": "W",
108		"60": "X", "61": "Y", "62": "Z",
109		// Lowercase letters
110		"59": "a", "5a": "b", "5b": "c", "5c": "d", "5d": "e", "5e": "f", "5f": "g",
111		"50": "h", "51": "i", "52": "j", "53": "k", "54": "l", "55": "m", "56": "n", "57": "o",
112		"48": "p", "49": "q", "4a": "r", "4b": "s", "4c": "t", "4d": "u", "4e": "v", "4f": "w",
113		"40": "x", "41": "y", "42": "z",
114		// Numbers
115		"08": "0", "09": "1", "0a": "2", "0b": "3", "0c": "4", "0d": "5", "0e": "6", "0f": "7",
116		"00": "8", "01": "9",
117		// Special characters
118		"15": "-", "16": ".", "67": "_", "46": "~", "02": ":", "17": "/", "07": "?", "1b": "#",
119		"63": "[", "65": "]", "78": "@", "19": "!", "1c": "$", "1e": "&", "10": "(", "11": ")",
120		"12": "*", "13": "+", "14": ",", "03": ";", "05": "=", "1d": "%",
121	}
122
123	// Perform the replacement equivalent to sed 's/^../.../'
124	for i, pair := range pairs {
125		if val, exists := replacements[pair]; exists {
126			pairs[i] = val
127		}
128	}
129
130	// Join the modified pairs back into a single string
131	result := strings.Join(pairs, "")
132
133	// Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
134	result = strings.ReplaceAll(result, "/clock", "/clock.json")
135
136	// Print the final result
137	return result
138}
139
140func extractLinks(provider_id string) map[string]interface{} {
141	// Check if provider_id is already a full URL (external link)
142	if strings.HasPrefix(provider_id, "http://") || strings.HasPrefix(provider_id, "https://") {
143		// It's an external direct video link, preserve it exactly as provided.
144		Log(fmt.Sprintf("Direct external link detected: %s", provider_id))
145		return map[string]interface{}{
146			"links": []interface{}{
147				map[string]interface{}{
148					"link": provider_id,
149				},
150			},
151		}
152	}
153
154	// It's a relative path for allanime API
155	allanime_base := "https://allanime.day"
156	url := allanime_base + provider_id
157	req, err := http.NewRequest("GET", url, nil)
158	var videoData map[string]interface{}
159	if err != nil {
160		Log(fmt.Sprint("Error creating request:", err))
161		return videoData
162	}
163
164	// Add the headers
165	req.Header.Set("Referer", "https://allanime.to")
166	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
167
168	// Send the request
169	resp, err := sharedHTTPClient.Do(req)
170	if err != nil {
171		Log(fmt.Sprint("Error sending request:", err))
172		return videoData
173	}
174	defer resp.Body.Close()
175
176	// Read the response body
177	body, err := io.ReadAll(resp.Body)
178	if err != nil {
179		Log(fmt.Sprint("Error reading response:", err))
180		return videoData
181	}
182
183	// Parse the JSON response
184	err = json.Unmarshal(body, &videoData)
185	if err != nil {
186		Log(fmt.Sprint("Error parsing JSON:", err))
187		return videoData
188	}
189
190	// Process the data as needed
191	return videoData
192}
193
194// Get anime episode url respective to given config
195// If the link is found, it returns a list of links. Otherwise, it returns an error.
196//
197// Parameters:
198// - config: Configuration of the anime search.
199// - id: Allanime id of the anime to search for.
200// - epNo: Anime episode number to get links for.
201//
202// Returns:
203// - []string: a list of links for specified episode.
204// - error: an error if the episode is not found or if there is an issue during the search.
205func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
206	preferredMode := normalizeTranslationType(config.SubOrDub)
207	fallbackMode := alternateTranslationType(preferredMode)
208
209	type modeResult struct {
210		mode  string
211		links []string
212		err   error
213	}
214
215	ch := make(chan modeResult, 2)
216
217	go func() {
218		links, err := getEpisodeURLForMode(id, preferredMode, epNo)
219		ch <- modeResult{mode: preferredMode, links: links, err: err}
220	}()
221
222	go func() {
223		links, err := getEpisodeURLForMode(id, fallbackMode, epNo)
224		ch <- modeResult{mode: fallbackMode, links: links, err: err}
225	}()
226
227	var preferredRes, fallbackRes modeResult
228	hasPreferredRes := false
229	hasFallbackRes := false
230	for i := 0; i < 2; i++ {
231		res := <-ch
232
233		if res.mode == preferredMode {
234			preferredRes = res
235			hasPreferredRes = true
236			if res.err == nil && len(res.links) > 0 {
237				return res.links, nil
238			}
239			continue
240		}
241
242		if res.mode == fallbackMode {
243			fallbackRes = res
244			hasFallbackRes = true
245		}
246	}
247
248	if hasPreferredRes && preferredRes.err == nil && len(preferredRes.links) > 0 {
249		return preferredRes.links, nil
250	}
251	if hasFallbackRes && fallbackRes.err == nil && len(fallbackRes.links) > 0 {
252		Log(fmt.Sprintf("Falling back to %s for anime %s episode %d", fallbackMode, id, epNo))
253		return fallbackRes.links, nil
254	}
255
256	if hasPreferredRes && preferredRes.err != nil {
257		return nil, preferredRes.err
258	}
259	if hasFallbackRes && fallbackRes.err != nil {
260		return nil, fallbackRes.err
261	}
262
263	return nil, fmt.Errorf("no valid links found for anime %s episode %d", id, epNo)
264}
265
266func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
267	query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
268
269	variables := map[string]interface{}{
270		"showId":          id,
271		"translationType": normalizeTranslationType(mode),
272		"episodeString":   fmt.Sprintf("%d", epNo),
273	}
274
275	// Build POST request body
276	requestBody, err := json.Marshal(map[string]interface{}{
277		"query":     query,
278		"variables": variables,
279	})
280	if err != nil {
281		return nil, fmt.Errorf("failed to marshal request body: %w", err)
282	}
283
284	req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
285	if err != nil {
286		return nil, fmt.Errorf("failed to create request: %w", err)
287	}
288
289	req.Header.Set("Content-Type", "application/json")
290	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")
291	req.Header.Set("Referer", "https://allanime.to")
292	req.Header.Set("Origin", "https://allanime.to")
293
294	resp, err := sharedHTTPClient.Do(req)
295	if err != nil {
296		return nil, fmt.Errorf("failed to send request: %w", err)
297	}
298	defer resp.Body.Close()
299
300	body, err := io.ReadAll(resp.Body)
301	if err != nil {
302		return nil, fmt.Errorf("failed to read response body: %w", err)
303	}
304
305	var response allanimeResponse
306	err = json.Unmarshal(body, &response)
307	if err != nil {
308		Log(fmt.Sprint("Error parsing JSON: ", err))
309		return nil, err
310	}
311
312	if response.Data.Tobeparsed != "" {
313		Log("Found tobeparsed field, using decoded response")
314		decoded := decodeTobeparsed(response.Data.Tobeparsed)
315		lines := strings.Split(strings.TrimSpace(decoded), "\n")
316		var parsedURLs []struct {
317			SourceName string
318			SourceUrl  string
319		}
320		for _, line := range lines {
321			if parts := strings.Split(line, " :"); len(parts) == 2 {
322				parsedURLs = append(parsedURLs, struct {
323					SourceName string
324					SourceUrl  string
325				}{SourceName: parts[0], SourceUrl: "--" + parts[1]})
326			}
327		}
328
329		validURLs := make([]string, 0)
330		for _, url := range parsedURLs {
331			validURLs = append(validURLs, url.SourceUrl)
332		}
333
334		if len(validURLs) == 0 {
335			return nil, fmt.Errorf("no valid source URLs found in decoded tobeparsed")
336		}
337
338		return getLinksFromURLs(validURLs)
339	}
340
341	return getLinksFromSourceUrls(response.Data.Episode.SourceUrls)
342}
343
344func getLinksFromSourceUrls(sourceUrls []struct {
345	SourceUrl  string `json:"sourceUrl"`
346	SourceName string `json:"sourceName"`
347}) ([]string, error) {
348	validURLs := make([]string, 0)
349	highestPriority := -1
350	var highestPriorityURL string
351
352	for _, url := range sourceUrls {
353		if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
354			decodedURL := decodeProviderID(url.SourceUrl[2:])
355			if strings.Contains(decodedURL, LinkPriorities[0]) {
356				priority := int(url.SourceUrl[2] - '0')
357				if priority > highestPriority {
358					highestPriority = priority
359					highestPriorityURL = url.SourceUrl
360				}
361			} else {
362				validURLs = append(validURLs, url.SourceUrl)
363			}
364		}
365	}
366
367	if highestPriorityURL != "" {
368		validURLs = []string{highestPriorityURL}
369	}
370
371	if len(validURLs) == 0 {
372		return nil, fmt.Errorf("no valid source URLs found in response")
373	}
374
375	return getLinksFromURLs(validURLs)
376}
377
378func getLinksFromURLs(validURLs []string) ([]string, error) {
379	results := make(chan result, len(validURLs))
380	orderedResults := make([][]string, len(validURLs))
381
382	highPriorityLink := make(chan []string, 1)
383
384	remainingURLs := len(validURLs)
385	for i, sourceUrl := range validURLs {
386		go func(idx int, url string) {
387			decodedProviderID := decodeProviderID(url[2:])
388			Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
389
390			extractedLinks := extractLinks(decodedProviderID)
391
392			if extractedLinks == nil {
393				results <- result{
394					index: idx,
395					err:   fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
396				}
397				return
398			}
399
400			linksInterface, ok := extractedLinks["links"].([]interface{})
401			if !ok {
402				results <- result{
403					index: idx,
404					err:   fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
405				}
406				return
407			}
408
409			var links []string
410			for _, linkInterface := range linksInterface {
411				linkMap, ok := linkInterface.(map[string]interface{})
412				if !ok {
413					Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
414					continue
415				}
416
417				link, ok := linkMap["link"].(string)
418				if !ok {
419					Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
420					continue
421				}
422
423				links = append(links, link)
424			}
425
426			// Check if any of the extracted links are high priority
427			for _, link := range links {
428				for _, domain := range LinkPriorities[:3] {
429					if strings.Contains(link, domain) {
430						// Found high priority link, send it immediately
431						select {
432						case highPriorityLink <- []string{link}:
433						default:
434							// Channel already has a high priority link
435						}
436						break
437					}
438				}
439			}
440
441			results <- result{
442				index: idx,
443				links: links,
444			}
445		}(i, sourceUrl)
446	}
447
448	// Collect results with timeout
449	timeout := time.After(10 * time.Second)
450	var collectedErrors []error
451	successCount := 0
452
453	// First, try to get a high priority link
454	select {
455	case links := <-highPriorityLink:
456		// Continue extracting other links in background
457		go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs)
458		return links, nil
459	case <-time.After(2 * time.Second): // Wait only briefly for high priority link
460		// No high priority link found quickly, proceed with normal collection
461	}
462
463	// Continue with existing result collection logic
464	// Collect results maintaining order
465	for successCount < len(validURLs) {
466		select {
467		case res := <-results:
468			if res.err != nil {
469				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
470				collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
471			} else {
472				orderedResults[res.index] = res.links
473				successCount++
474				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
475			}
476		case <-timeout:
477			if successCount > 0 {
478				Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
479				// Flatten available results
480				return flattenResults(orderedResults), nil
481			}
482			return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
483		}
484	}
485
486	// If we have any errors but also some successes, log errors but continue
487	if len(collectedErrors) > 0 {
488		Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
489	}
490
491	// Flatten and return results
492	allLinks := flattenResults(orderedResults)
493	if len(allLinks) == 0 {
494		return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
495	}
496
497	return allLinks, nil
498}
499
500// Helper function to collect remaining results in background
501func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) {
502	for *successCount < remainingURLs {
503		select {
504		case res := <-results:
505			if res.err != nil {
506				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
507				*collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
508			} else {
509				orderedResults[res.index] = res.links
510				*successCount++
511				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs))
512			}
513		case <-time.After(10 * time.Second):
514			return
515		}
516	}
517}
518
519// converts the ordered slice of link slices into a single slice
520func flattenResults(results [][]string) []string {
521	var totalLen int
522	for _, r := range results {
523		totalLen += len(r)
524	}
525
526	allLinks := make([]string, 0, totalLen)
527	for _, links := range results {
528		allLinks = append(allLinks, links...)
529	}
530	return allLinks
531}