internal/episode_url.go
407 lines · 12507 bytes
1package internal
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
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 preferredMode := normalizeTranslationType(config.SubOrDub)
155 links, err := getEpisodeURLForMode(id, preferredMode, epNo)
156 if err == nil {
157 return links, nil
158 }
159
160 fallbackMode := alternateTranslationType(preferredMode)
161 fallbackLinks, fallbackErr := getEpisodeURLForMode(id, fallbackMode, epNo)
162 if fallbackErr == nil {
163 Log(fmt.Sprintf("Falling back to %s for anime %s episode %d", fallbackMode, id, epNo))
164 return fallbackLinks, nil
165 }
166
167 return nil, err
168}
169
170func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
171 query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
172
173 variables := map[string]interface{}{
174 "showId": id,
175 "translationType": normalizeTranslationType(mode),
176 "episodeString": fmt.Sprintf("%d", epNo),
177 }
178
179 // Build POST request body
180 requestBody, err := json.Marshal(map[string]interface{}{
181 "query": query,
182 "variables": variables,
183 })
184 if err != nil {
185 return nil, fmt.Errorf("failed to marshal request body: %w", err)
186 }
187
188 client := &http.Client{}
189 req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
190 if err != nil {
191 return nil, fmt.Errorf("failed to create request: %w", err)
192 }
193
194 req.Header.Set("Content-Type", "application/json")
195 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")
196 req.Header.Set("Referer", "https://allanime.to")
197 req.Header.Set("Origin", "https://allanime.to")
198
199 resp, err := client.Do(req)
200 if err != nil {
201 return nil, fmt.Errorf("failed to send request: %w", err)
202 }
203 defer resp.Body.Close()
204
205 body, err := io.ReadAll(resp.Body)
206 if err != nil {
207 return nil, fmt.Errorf("failed to read response: %w", err)
208 }
209
210 var response allanimeResponse
211 err = json.Unmarshal(body, &response)
212 if err != nil {
213 Log(fmt.Sprint("Error parsing JSON: ", err))
214 return nil, err
215 }
216
217 // Pre-count valid URLs and create slice to preserve order
218 validURLs := make([]string, 0)
219 highestPriority := -1
220 var highestPriorityURL string
221
222 for _, url := range response.Data.Episode.SourceUrls {
223 if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
224 decodedURL := decodeProviderID(url.SourceUrl[2:])
225 if strings.Contains(decodedURL, LinkPriorities[0]) {
226 priority := int(url.SourceUrl[2] - '0')
227 if priority > highestPriority {
228 highestPriority = priority
229 highestPriorityURL = url.SourceUrl
230 }
231 } else {
232 validURLs = append(validURLs, url.SourceUrl)
233 }
234 }
235 }
236
237 // If we found a highest priority URL, use only that
238 if highestPriorityURL != "" {
239 validURLs = []string{highestPriorityURL}
240 }
241
242 if len(validURLs) == 0 {
243 return nil, fmt.Errorf("no valid source URLs found in response")
244 }
245
246 // Create channels for results and a slice to store ordered results
247 results := make(chan result, len(validURLs))
248 orderedResults := make([][]string, len(validURLs))
249
250 // Add a channel for high priority links
251 highPriorityLink := make(chan []string, 1)
252
253 // Create rate limiter
254 rateLimiter := time.NewTicker(50 * time.Millisecond)
255 defer rateLimiter.Stop()
256
257 // Launch goroutines
258 remainingURLs := len(validURLs)
259 for i, sourceUrl := range validURLs {
260 go func(idx int, url string) {
261 <-rateLimiter.C // Rate limit the requests
262
263 decodedProviderID := decodeProviderID(url[2:])
264 Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
265
266 extractedLinks := extractLinks(decodedProviderID)
267
268 if extractedLinks == nil {
269 results <- result{
270 index: idx,
271 err: fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
272 }
273 return
274 }
275
276 linksInterface, ok := extractedLinks["links"].([]interface{})
277 if !ok {
278 results <- result{
279 index: idx,
280 err: fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
281 }
282 return
283 }
284
285 var links []string
286 for _, linkInterface := range linksInterface {
287 linkMap, ok := linkInterface.(map[string]interface{})
288 if !ok {
289 Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
290 continue
291 }
292
293 link, ok := linkMap["link"].(string)
294 if !ok {
295 Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
296 continue
297 }
298
299 links = append(links, link)
300 }
301
302 // Check if any of the extracted links are high priority
303 for _, link := range links {
304 for _, domain := range LinkPriorities[:3] { // Check only top 3 priority domains
305 if strings.Contains(link, domain) {
306 // Found high priority link, send it immediately
307 select {
308 case highPriorityLink <- []string{link}:
309 default:
310 // Channel already has a high priority link
311 }
312 break
313 }
314 }
315 }
316
317 results <- result{
318 index: idx,
319 links: links,
320 }
321 }(i, sourceUrl)
322 }
323
324 // Collect results with timeout
325 timeout := time.After(10 * time.Second)
326 var collectedErrors []error
327 successCount := 0
328
329 // First, try to get a high priority link
330 select {
331 case links := <-highPriorityLink:
332 // Continue extracting other links in background
333 go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs)
334 return links, nil
335 case <-time.After(2 * time.Second): // Wait only briefly for high priority link
336 // No high priority link found quickly, proceed with normal collection
337 }
338
339 // Continue with existing result collection logic
340 // Collect results maintaining order
341 for successCount < len(validURLs) {
342 select {
343 case res := <-results:
344 if res.err != nil {
345 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
346 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
347 } else {
348 orderedResults[res.index] = res.links
349 successCount++
350 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
351 }
352 case <-timeout:
353 if successCount > 0 {
354 Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
355 // Flatten available results
356 return flattenResults(orderedResults), nil
357 }
358 return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
359 }
360 }
361
362 // If we have any errors but also some successes, log errors but continue
363 if len(collectedErrors) > 0 {
364 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
365 }
366
367 // Flatten and return results
368 allLinks := flattenResults(orderedResults)
369 if len(allLinks) == 0 {
370 return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
371 }
372
373 return allLinks, nil
374}
375
376// Helper function to collect remaining results in background
377func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) {
378 for *successCount < remainingURLs {
379 select {
380 case res := <-results:
381 if res.err != nil {
382 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
383 *collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
384 } else {
385 orderedResults[res.index] = res.links
386 *successCount++
387 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs))
388 }
389 case <-time.After(10 * time.Second):
390 return
391 }
392 }
393}
394
395// converts the ordered slice of link slices into a single slice
396func flattenResults(results [][]string) []string {
397 var totalLen int
398 for _, r := range results {
399 totalLen += len(r)
400 }
401
402 allLinks := make([]string, 0, totalLen)
403 for _, links := range results {
404 allLinks = append(allLinks, links...)
405 }
406 return allLinks
407}