internal/episode_url.go

390 lines · 11689 bytes

  1package internal
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"io"
  7	"net/http"
  8	"net/url"
  9	"regexp"
 10	"strings"
 11	"time"
 12	"unicode"
 13)
 14
 15type allanimeResponse struct {
 16	Data struct {
 17		Episode struct {
 18			SourceUrls []struct {
 19				SourceUrl string `json:"sourceUrl"`
 20			} `json:"sourceUrls"`
 21		} `json:"episode"`
 22	} `json:"data"`
 23}
 24
 25type result struct {
 26	index int
 27	links []string
 28	err   error
 29}
 30
 31func decodeProviderID(encoded string) string {
 32	// Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
 33	re := regexp.MustCompile("..")
 34	pairs := re.FindAllString(encoded, -1)
 35
 36	// Mapping for the replacements
 37	replacements := map[string]string{
 38		// Uppercase letters
 39		"79": "A", "7a": "B", "7b": "C", "7c": "D", "7d": "E", "7e": "F", "7f": "G",
 40		"70": "H", "71": "I", "72": "J", "73": "K", "74": "L", "75": "M", "76": "N", "77": "O",
 41		"68": "P", "69": "Q", "6a": "R", "6b": "S", "6c": "T", "6d": "U", "6e": "V", "6f": "W",
 42		"60": "X", "61": "Y", "62": "Z",
 43		// Lowercase letters
 44		"59": "a", "5a": "b", "5b": "c", "5c": "d", "5d": "e", "5e": "f", "5f": "g",
 45		"50": "h", "51": "i", "52": "j", "53": "k", "54": "l", "55": "m", "56": "n", "57": "o",
 46		"48": "p", "49": "q", "4a": "r", "4b": "s", "4c": "t", "4d": "u", "4e": "v", "4f": "w",
 47		"40": "x", "41": "y", "42": "z",
 48		// Numbers
 49		"08": "0", "09": "1", "0a": "2", "0b": "3", "0c": "4", "0d": "5", "0e": "6", "0f": "7",
 50		"00": "8", "01": "9",
 51		// Special characters
 52		"15": "-", "16": ".", "67": "_", "46": "~", "02": ":", "17": "/", "07": "?", "1b": "#",
 53		"63": "[", "65": "]", "78": "@", "19": "!", "1c": "$", "1e": "&", "10": "(", "11": ")",
 54		"12": "*", "13": "+", "14": ",", "03": ";", "05": "=", "1d": "%",
 55	}
 56
 57	// Perform the replacement equivalent to sed 's/^../.../'
 58	for i, pair := range pairs {
 59		if val, exists := replacements[pair]; exists {
 60			pairs[i] = val
 61		}
 62	}
 63
 64	// Join the modified pairs back into a single string
 65	result := strings.Join(pairs, "")
 66
 67	// Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
 68	result = strings.ReplaceAll(result, "/clock", "/clock.json")
 69
 70	// Print the final result
 71	return result
 72}
 73
 74func extractLinks(provider_id string) map[string]interface{} {
 75	// Check if provider_id is already a full URL (external link)
 76	if strings.HasPrefix(provider_id, "http://") || strings.HasPrefix(provider_id, "https://") {
 77		// It's an external direct video link, return it as-is
 78		cleanedURL := provider_id
 79		// Clean up any double slashes in the URL (except after protocol)
 80		if strings.Contains(cleanedURL, "://") {
 81			parts := strings.SplitN(cleanedURL, "://", 2)
 82			if len(parts) == 2 {
 83				protocol := parts[0]
 84				rest := parts[1]
 85				// Replace any double slashes in the rest of the URL
 86				rest = strings.ReplaceAll(rest, "//", "/")
 87				cleanedURL = protocol + "://" + rest
 88			}
 89		}
 90		
 91		Log(fmt.Sprintf("Direct external link detected: %s -> %s", provider_id, cleanedURL))
 92		return map[string]interface{}{
 93			"links": []interface{}{
 94				map[string]interface{}{
 95					"link": cleanedURL,
 96				},
 97			},
 98		}
 99	}
100	
101	// It's a relative path for allanime API
102	allanime_base := "https://allanime.day"
103	url := allanime_base + provider_id
104	client := &http.Client{}
105	req, err := http.NewRequest("GET", url, nil)
106	var videoData map[string]interface{}
107	if err != nil {
108		Log(fmt.Sprint("Error creating request:", err))
109		return videoData
110	}
111
112	// Add the headers
113	req.Header.Set("Referer", "https://allanime.to")
114	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
115
116	// Send the request
117	resp, err := client.Do(req)
118	if err != nil {
119		Log(fmt.Sprint("Error sending request:", err))
120		return videoData
121	}
122	defer resp.Body.Close()
123
124	// Read the response body
125	body, err := io.ReadAll(resp.Body)
126	if err != nil {
127		Log(fmt.Sprint("Error reading response:", err))
128		return videoData
129	}
130
131	// Parse the JSON response
132	err = json.Unmarshal(body, &videoData)
133	if err != nil {
134		Log(fmt.Sprint("Error parsing JSON:", err))
135		return videoData
136	}
137
138	// Process the data as needed
139	return videoData
140}
141
142// Get anime episode url respective to given config
143// If the link is found, it returns a list of links. Otherwise, it returns an error.
144//
145// Parameters:
146// - config: Configuration of the anime search.
147// - id: Allanime id of the anime to search for.
148// - epNo: Anime episode number to get links for.
149//
150// Returns:
151// - []string: a list of links for specified episode.
152// - error: an error if the episode is not found or if there is an issue during the search.
153func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
154	query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
155
156	variables := map[string]string{
157		"showId":          id,
158		"translationType": config.SubOrDub,
159		"episodeString":   fmt.Sprintf("%d", epNo),
160	}
161
162	variablesJSON, err := json.Marshal(variables)
163	if err != nil {
164		return nil, err
165	}
166
167	values := url.Values{}
168	values.Set("query", query)
169	values.Set("variables", string(variablesJSON))
170
171	reqURL := fmt.Sprintf("%s/api?%s", "https://api.allanime.day", values.Encode())
172
173	client := &http.Client{}
174	req, err := http.NewRequest("GET", reqURL, nil)
175	if err != nil {
176		return nil, err
177	}
178
179	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
180	req.Header.Set("Referer", "https://allanime.to")
181
182	resp, err := client.Do(req)
183	if err != nil {
184		return nil, err
185	}
186	defer resp.Body.Close()
187
188	body, err := io.ReadAll(resp.Body)
189	if err != nil {
190		return nil, err
191	}
192
193	var response allanimeResponse
194	err = json.Unmarshal(body, &response)
195	if err != nil {
196		Log(fmt.Sprint("Error parsing JSON: ", err))
197		return nil, err
198	}
199
200	// Pre-count valid URLs and create slice to preserve order
201	validURLs := make([]string, 0)
202	highestPriority := -1
203	var highestPriorityURL string
204
205	for _, url := range response.Data.Episode.SourceUrls {
206		if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
207			decodedURL := decodeProviderID(url.SourceUrl[2:])
208			if strings.Contains(decodedURL, LinkPriorities[0]) {
209				priority := int(url.SourceUrl[2] - '0')
210				if priority > highestPriority {
211					highestPriority = priority
212					highestPriorityURL = url.SourceUrl
213				}
214			} else {
215				validURLs = append(validURLs, url.SourceUrl)
216			}
217		}
218	}
219
220	// If we found a highest priority URL, use only that
221	if highestPriorityURL != "" {
222		validURLs = []string{highestPriorityURL}
223	}
224
225	if len(validURLs) == 0 {
226		return nil, fmt.Errorf("no valid source URLs found in response")
227	}
228
229	// Create channels for results and a slice to store ordered results
230	results := make(chan result, len(validURLs))
231	orderedResults := make([][]string, len(validURLs))
232
233	// Add a channel for high priority links
234	highPriorityLink := make(chan []string, 1)
235
236	// Create rate limiter
237	rateLimiter := time.NewTicker(50 * time.Millisecond)
238	defer rateLimiter.Stop()
239
240	// Launch goroutines
241	remainingURLs := len(validURLs)
242	for i, sourceUrl := range validURLs {
243		go func(idx int, url string) {
244			<-rateLimiter.C // Rate limit the requests
245
246			decodedProviderID := decodeProviderID(url[2:])
247			Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
248
249			extractedLinks := extractLinks(decodedProviderID)
250
251			if extractedLinks == nil {
252				results <- result{
253					index: idx,
254					err:   fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
255				}
256				return
257			}
258
259			linksInterface, ok := extractedLinks["links"].([]interface{})
260			if !ok {
261				results <- result{
262					index: idx,
263					err:   fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
264				}
265				return
266			}
267
268			var links []string
269			for _, linkInterface := range linksInterface {
270				linkMap, ok := linkInterface.(map[string]interface{})
271				if !ok {
272					Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
273					continue
274				}
275
276				link, ok := linkMap["link"].(string)
277				if !ok {
278					Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
279					continue
280				}
281
282				links = append(links, link)
283			}
284
285			// Check if any of the extracted links are high priority
286			for _, link := range links {
287				for _, domain := range LinkPriorities[:3] { // Check only top 3 priority domains
288					if strings.Contains(link, domain) {
289						// Found high priority link, send it immediately
290						select {
291						case highPriorityLink <- []string{link}:
292						default:
293							// Channel already has a high priority link
294						}
295						break
296					}
297				}
298			}
299
300			results <- result{
301				index: idx,
302				links: links,
303			}
304		}(i, sourceUrl)
305	}
306
307	// Collect results with timeout
308	timeout := time.After(10 * time.Second)
309	var collectedErrors []error
310	successCount := 0
311
312	// First, try to get a high priority link
313	select {
314	case links := <-highPriorityLink:
315		// Continue extracting other links in background
316		go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs)
317		return links, nil
318	case <-time.After(2 * time.Second): // Wait only briefly for high priority link
319		// No high priority link found quickly, proceed with normal collection
320	}
321
322	// Continue with existing result collection logic
323	// Collect results maintaining order
324	for successCount < len(validURLs) {
325		select {
326		case res := <-results:
327			if res.err != nil {
328				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
329				collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
330			} else {
331				orderedResults[res.index] = res.links
332				successCount++
333				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
334			}
335		case <-timeout:
336			if successCount > 0 {
337				Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
338				// Flatten available results
339				return flattenResults(orderedResults), nil
340			}
341			return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
342		}
343	}
344
345	// If we have any errors but also some successes, log errors but continue
346	if len(collectedErrors) > 0 {
347		Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
348	}
349
350	// Flatten and return results
351	allLinks := flattenResults(orderedResults)
352	if len(allLinks) == 0 {
353		return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
354	}
355
356	return allLinks, nil
357}
358
359// Helper function to collect remaining results in background
360func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) {
361	for *successCount < remainingURLs {
362		select {
363		case res := <-results:
364			if res.err != nil {
365				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
366				*collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
367			} else {
368				orderedResults[res.index] = res.links
369				*successCount++
370				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs))
371			}
372		case <-time.After(10 * time.Second):
373			return
374		}
375	}
376}
377
378// converts the ordered slice of link slices into a single slice
379func flattenResults(results [][]string) []string {
380	var totalLen int
381	for _, r := range results {
382		totalLen += len(r)
383	}
384
385	allLinks := make([]string, 0, totalLen)
386	for _, links := range results {
387		allLinks = append(allLinks, links...)
388	}
389	return allLinks
390}