internal/episode_url.go

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