internal/episode_url.go

517 lines · 14823 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		links []string
211		err   error
212	}
213
214	ch := make(chan modeResult, 2)
215
216	go func() {
217		links, err := getEpisodeURLForMode(id, preferredMode, epNo)
218		ch <- modeResult{links: links, err: err}
219	}()
220
221	go func() {
222		links, err := getEpisodeURLForMode(id, fallbackMode, epNo)
223		ch <- modeResult{links: links, err: err}
224	}()
225
226	var preferredRes, fallbackRes modeResult
227	for i := 0; i < 2; i++ {
228		res := <-ch
229		if res.err == nil {
230			if res.links != nil {
231				return res.links, nil
232			}
233		}
234		if res.err == nil || res.links != nil {
235			preferredRes = res
236		} else {
237			fallbackRes = res
238		}
239	}
240
241	if preferredRes.links != nil {
242		return preferredRes.links, nil
243	}
244	if fallbackRes.links != nil {
245		Log(fmt.Sprintf("Falling back to %s for anime %s episode %d", fallbackMode, id, epNo))
246		return fallbackRes.links, nil
247	}
248
249	return nil, preferredRes.err
250}
251
252func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
253	query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
254
255	variables := map[string]interface{}{
256		"showId":          id,
257		"translationType": normalizeTranslationType(mode),
258		"episodeString":   fmt.Sprintf("%d", epNo),
259	}
260
261	// Build POST request body
262	requestBody, err := json.Marshal(map[string]interface{}{
263		"query":     query,
264		"variables": variables,
265	})
266	if err != nil {
267		return nil, fmt.Errorf("failed to marshal request body: %w", err)
268	}
269
270	req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
271	if err != nil {
272		return nil, fmt.Errorf("failed to create request: %w", err)
273	}
274
275	req.Header.Set("Content-Type", "application/json")
276	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")
277	req.Header.Set("Referer", "https://allanime.to")
278	req.Header.Set("Origin", "https://allanime.to")
279
280	resp, err := sharedHTTPClient.Do(req)
281	if err != nil {
282		return nil, fmt.Errorf("failed to send request: %w", err)
283	}
284	defer resp.Body.Close()
285
286	body, err := io.ReadAll(resp.Body)
287	if err != nil {
288		return nil, fmt.Errorf("failed to read response body: %w", err)
289	}
290
291	var response allanimeResponse
292	err = json.Unmarshal(body, &response)
293	if err != nil {
294		Log(fmt.Sprint("Error parsing JSON: ", err))
295		return nil, err
296	}
297
298	if response.Data.Tobeparsed != "" {
299		Log("Found tobeparsed field, using decoded response")
300		decoded := decodeTobeparsed(response.Data.Tobeparsed)
301		lines := strings.Split(strings.TrimSpace(decoded), "\n")
302		var parsedURLs []struct {
303			SourceName string
304			SourceUrl  string
305		}
306		for _, line := range lines {
307			if parts := strings.Split(line, " :"); len(parts) == 2 {
308				parsedURLs = append(parsedURLs, struct {
309					SourceName string
310					SourceUrl  string
311				}{SourceName: parts[0], SourceUrl: "--" + parts[1]})
312			}
313		}
314
315		validURLs := make([]string, 0)
316		for _, url := range parsedURLs {
317			validURLs = append(validURLs, url.SourceUrl)
318		}
319
320		if len(validURLs) == 0 {
321			return nil, fmt.Errorf("no valid source URLs found in decoded tobeparsed")
322		}
323
324		return getLinksFromURLs(validURLs)
325	}
326
327	return getLinksFromSourceUrls(response.Data.Episode.SourceUrls)
328}
329
330func getLinksFromSourceUrls(sourceUrls []struct {
331	SourceUrl  string `json:"sourceUrl"`
332	SourceName string `json:"sourceName"`
333}) ([]string, error) {
334	validURLs := make([]string, 0)
335	highestPriority := -1
336	var highestPriorityURL string
337
338	for _, url := range sourceUrls {
339		if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
340			decodedURL := decodeProviderID(url.SourceUrl[2:])
341			if strings.Contains(decodedURL, LinkPriorities[0]) {
342				priority := int(url.SourceUrl[2] - '0')
343				if priority > highestPriority {
344					highestPriority = priority
345					highestPriorityURL = url.SourceUrl
346				}
347			} else {
348				validURLs = append(validURLs, url.SourceUrl)
349			}
350		}
351	}
352
353	if highestPriorityURL != "" {
354		validURLs = []string{highestPriorityURL}
355	}
356
357	if len(validURLs) == 0 {
358		return nil, fmt.Errorf("no valid source URLs found in response")
359	}
360
361	return getLinksFromURLs(validURLs)
362}
363
364func getLinksFromURLs(validURLs []string) ([]string, error) {
365	results := make(chan result, len(validURLs))
366	orderedResults := make([][]string, len(validURLs))
367
368	highPriorityLink := make(chan []string, 1)
369
370	remainingURLs := len(validURLs)
371	for i, sourceUrl := range validURLs {
372		go func(idx int, url string) {
373			decodedProviderID := decodeProviderID(url[2:])
374			Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
375
376			extractedLinks := extractLinks(decodedProviderID)
377
378			if extractedLinks == nil {
379				results <- result{
380					index: idx,
381					err:   fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
382				}
383				return
384			}
385
386			linksInterface, ok := extractedLinks["links"].([]interface{})
387			if !ok {
388				results <- result{
389					index: idx,
390					err:   fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
391				}
392				return
393			}
394
395			var links []string
396			for _, linkInterface := range linksInterface {
397				linkMap, ok := linkInterface.(map[string]interface{})
398				if !ok {
399					Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
400					continue
401				}
402
403				link, ok := linkMap["link"].(string)
404				if !ok {
405					Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
406					continue
407				}
408
409				links = append(links, link)
410			}
411
412			// Check if any of the extracted links are high priority
413			for _, link := range links {
414				for _, domain := range LinkPriorities[:3] {
415					if strings.Contains(link, domain) {
416						// Found high priority link, send it immediately
417						select {
418						case highPriorityLink <- []string{link}:
419						default:
420							// Channel already has a high priority link
421						}
422						break
423					}
424				}
425			}
426
427			results <- result{
428				index: idx,
429				links: links,
430			}
431		}(i, sourceUrl)
432	}
433
434	// Collect results with timeout
435	timeout := time.After(10 * time.Second)
436	var collectedErrors []error
437	successCount := 0
438
439	// First, try to get a high priority link
440	select {
441	case links := <-highPriorityLink:
442		// Continue extracting other links in background
443		go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs)
444		return links, nil
445	case <-time.After(2 * time.Second): // Wait only briefly for high priority link
446		// No high priority link found quickly, proceed with normal collection
447	}
448
449	// Continue with existing result collection logic
450	// Collect results maintaining order
451	for successCount < len(validURLs) {
452		select {
453		case res := <-results:
454			if res.err != nil {
455				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
456				collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
457			} else {
458				orderedResults[res.index] = res.links
459				successCount++
460				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
461			}
462		case <-timeout:
463			if successCount > 0 {
464				Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
465				// Flatten available results
466				return flattenResults(orderedResults), nil
467			}
468			return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
469		}
470	}
471
472	// If we have any errors but also some successes, log errors but continue
473	if len(collectedErrors) > 0 {
474		Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
475	}
476
477	// Flatten and return results
478	allLinks := flattenResults(orderedResults)
479	if len(allLinks) == 0 {
480		return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
481	}
482
483	return allLinks, nil
484}
485
486// Helper function to collect remaining results in background
487func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) {
488	for *successCount < remainingURLs {
489		select {
490		case res := <-results:
491			if res.err != nil {
492				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
493				*collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
494			} else {
495				orderedResults[res.index] = res.links
496				*successCount++
497				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs))
498			}
499		case <-time.After(10 * time.Second):
500			return
501		}
502	}
503}
504
505// converts the ordered slice of link slices into a single slice
506func flattenResults(results [][]string) []string {
507	var totalLen int
508	for _, r := range results {
509		totalLen += len(r)
510	}
511
512	allLinks := make([]string, 0, totalLen)
513	for _, links := range results {
514		allLinks = append(allLinks, links...)
515	}
516	return allLinks
517}