internal/episode_url.go

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