internal/episode_url.go

352 lines · 10093 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
162	// Pre-count valid URLs and create slice to preserve order
163	validURLs := make([]string, 0)
164	highestPriority := -1
165	var highestPriorityURL string
166
167	for _, url := range response.Data.Episode.SourceUrls {
168		if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
169			decodedURL := decodeProviderID(url.SourceUrl[2:])
170			if strings.Contains(decodedURL, LinkPriorities[0]) {
171				priority := int(url.SourceUrl[2] - '0')
172				if priority > highestPriority {
173					highestPriority = priority
174					highestPriorityURL = url.SourceUrl
175				}
176			} else {
177				validURLs = append(validURLs, url.SourceUrl)
178			}
179		}
180	}
181
182	// If we found a highest priority URL, use only that
183	if highestPriorityURL != "" {
184		validURLs = []string{highestPriorityURL}
185	}
186
187	if len(validURLs) == 0 {
188		return nil, fmt.Errorf("no valid source URLs found in response")
189	}
190
191	// Create channels for results and a slice to store ordered results
192	results := make(chan result, len(validURLs))
193	orderedResults := make([][]string, len(validURLs))
194
195	// Add a channel for high priority links
196	highPriorityLink := make(chan []string, 1)
197
198	// Create rate limiter
199	rateLimiter := time.NewTicker(50 * time.Millisecond)
200	defer rateLimiter.Stop()
201
202	// Launch goroutines
203	remainingURLs := len(validURLs)
204	for i, sourceUrl := range validURLs {
205		go func(idx int, url string) {
206			<-rateLimiter.C // Rate limit the requests
207
208			decodedProviderID := decodeProviderID(url[2:])
209			Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
210
211			extractedLinks := extractLinks(decodedProviderID)
212
213			if extractedLinks == nil {
214				results <- result{
215					index: idx,
216					err:   fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
217				}
218				return
219			}
220
221			linksInterface, ok := extractedLinks["links"].([]interface{})
222			if !ok {
223				results <- result{
224					index: idx,
225					err:   fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
226				}
227				return
228			}
229
230			var links []string
231			for _, linkInterface := range linksInterface {
232				linkMap, ok := linkInterface.(map[string]interface{})
233				if !ok {
234					Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
235					continue
236				}
237
238				link, ok := linkMap["link"].(string)
239				if !ok {
240					Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
241					continue
242				}
243
244				links = append(links, link)
245			}
246
247			// Check if any of the extracted links are high priority
248			for _, link := range links {
249				for _, domain := range LinkPriorities[:3] { // Check only top 3 priority domains
250					if strings.Contains(link, domain) {
251						// Found high priority link, send it immediately
252						select {
253						case highPriorityLink <- []string{link}:
254						default:
255							// Channel already has a high priority link
256						}
257						break
258					}
259				}
260			}
261
262			results <- result{
263				index: idx,
264				links: links,
265			}
266		}(i, sourceUrl)
267	}
268
269	// Collect results with timeout
270	timeout := time.After(10 * time.Second)
271	var collectedErrors []error
272	successCount := 0
273
274	// First, try to get a high priority link
275	select {
276	case links := <-highPriorityLink:
277		// Continue extracting other links in background
278		go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs)
279		return links, nil
280	case <-time.After(2 * time.Second): // Wait only briefly for high priority link
281		// No high priority link found quickly, proceed with normal collection
282	}
283
284	// Continue with existing result collection logic
285	// Collect results maintaining order
286	for successCount < len(validURLs) {
287		select {
288		case res := <-results:
289			if res.err != nil {
290				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
291				collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
292			} else {
293				orderedResults[res.index] = res.links
294				successCount++
295				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
296			}
297		case <-timeout:
298			if successCount > 0 {
299				Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
300				// Flatten available results
301				return flattenResults(orderedResults), nil
302			}
303			return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
304		}
305	}
306
307	// If we have any errors but also some successes, log errors but continue
308	if len(collectedErrors) > 0 {
309		Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
310	}
311
312	// Flatten and return results
313	allLinks := flattenResults(orderedResults)
314	if len(allLinks) == 0 {
315		return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
316	}
317
318	return allLinks, nil
319}
320
321// Helper function to collect remaining results in background
322func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) {
323	for *successCount < remainingURLs {
324		select {
325		case res := <-results:
326			if res.err != nil {
327				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
328				*collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
329			} else {
330				orderedResults[res.index] = res.links
331				*successCount++
332				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs))
333			}
334		case <-time.After(10 * time.Second):
335			return
336		}
337	}
338}
339
340// converts the ordered slice of link slices into a single slice
341func flattenResults(results [][]string) []string {
342	var totalLen int
343	for _, r := range results {
344		totalLen += len(r)
345	}
346
347	allLinks := make([]string, 0, totalLen)
348	for _, links := range results {
349		allLinks = append(allLinks, links...)
350	}
351	return allLinks
352}