internal/episode_url.go

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