internal/episode_url.go
530 lines · 15236 bytes
1package internal
2
3import (
4 "bytes"
5 "crypto/aes"
6 "crypto/cipher"
7 "crypto/sha256"
8 "encoding/base64"
9 "encoding/binary"
10 "encoding/json"
11 "fmt"
12 "io"
13 "net/http"
14 "regexp"
15 "strings"
16 "time"
17 "unicode"
18)
19
20type allanimeResponse struct {
21 Data struct {
22 M string `json:"_m"`
23 Tobeparsed string `json:"tobeparsed"`
24 Episode struct {
25 SourceUrls []struct {
26 SourceUrl string `json:"sourceUrl"`
27 SourceName string `json:"sourceName"`
28 } `json:"sourceUrls"`
29 } `json:"episode"`
30 } `json:"data"`
31}
32
33type result struct {
34 index int
35 links []string
36 err error
37}
38
39func decodeTobeparsed(blob string) string {
40 key := []byte("Xot36i3lK3:v1")
41 hash := sha256.Sum256(key)
42
43 data, err := base64.StdEncoding.DecodeString(blob)
44 if err != nil {
45 Log(fmt.Sprint("Error decoding base64:", err))
46 return ""
47 }
48
49 if len(data) < 29 {
50 Log("Data too short to contain tobeparsed payload")
51 return ""
52 }
53
54 // The payload format is: 1-byte header, 12-byte IV, ciphertext, 16-byte trailer.
55 iv := data[1:13]
56 ctLen := len(data) - 13 - 16
57 if ctLen <= 0 {
58 Log("Ciphertext length is invalid in tobeparsed payload")
59 return ""
60 }
61 ct := data[13 : 13+ctLen]
62
63 ctrIV := make([]byte, 16)
64 copy(ctrIV, iv)
65 binary.BigEndian.PutUint32(ctrIV[12:], uint32(2))
66
67 block, err := aes.NewCipher(hash[:])
68 if err != nil {
69 Log(fmt.Sprint("Error creating cipher:", err))
70 return ""
71 }
72
73 stream := cipher.NewCTR(block, ctrIV)
74 plain := make([]byte, len(ct))
75 stream.XORKeyStream(plain, ct)
76
77 result := string(plain)
78 result = strings.ReplaceAll(result, "{", "\n")
79 result = strings.ReplaceAll(result, "}", "\n")
80
81 re := regexp.MustCompile(`"sourceUrl":"--([^"]+)".*"sourceName":"([^"]+)"`)
82 matches := re.FindAllStringSubmatch(result, -1)
83
84 var sb strings.Builder
85 for _, match := range matches {
86 if len(match) == 3 {
87 sb.WriteString(match[2])
88 sb.WriteString(" :")
89 sb.WriteString(match[1])
90 sb.WriteString("\n")
91 }
92 }
93
94 return sb.String()
95}
96
97func decodeProviderID(encoded string) string {
98 // Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
99 re := regexp.MustCompile("..")
100 pairs := re.FindAllString(encoded, -1)
101
102 // Mapping for the replacements
103 replacements := map[string]string{
104 // Uppercase letters
105 "79": "A", "7a": "B", "7b": "C", "7c": "D", "7d": "E", "7e": "F", "7f": "G",
106 "70": "H", "71": "I", "72": "J", "73": "K", "74": "L", "75": "M", "76": "N", "77": "O",
107 "68": "P", "69": "Q", "6a": "R", "6b": "S", "6c": "T", "6d": "U", "6e": "V", "6f": "W",
108 "60": "X", "61": "Y", "62": "Z",
109 // Lowercase letters
110 "59": "a", "5a": "b", "5b": "c", "5c": "d", "5d": "e", "5e": "f", "5f": "g",
111 "50": "h", "51": "i", "52": "j", "53": "k", "54": "l", "55": "m", "56": "n", "57": "o",
112 "48": "p", "49": "q", "4a": "r", "4b": "s", "4c": "t", "4d": "u", "4e": "v", "4f": "w",
113 "40": "x", "41": "y", "42": "z",
114 // Numbers
115 "08": "0", "09": "1", "0a": "2", "0b": "3", "0c": "4", "0d": "5", "0e": "6", "0f": "7",
116 "00": "8", "01": "9",
117 // Special characters
118 "15": "-", "16": ".", "67": "_", "46": "~", "02": ":", "17": "/", "07": "?", "1b": "#",
119 "63": "[", "65": "]", "78": "@", "19": "!", "1c": "$", "1e": "&", "10": "(", "11": ")",
120 "12": "*", "13": "+", "14": ",", "03": ";", "05": "=", "1d": "%",
121 }
122
123 // Perform the replacement equivalent to sed 's/^../.../'
124 for i, pair := range pairs {
125 if val, exists := replacements[pair]; exists {
126 pairs[i] = val
127 }
128 }
129
130 // Join the modified pairs back into a single string
131 result := strings.Join(pairs, "")
132
133 // Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
134 result = strings.ReplaceAll(result, "/clock", "/clock.json")
135
136 // Print the final result
137 return result
138}
139
140func extractLinks(provider_id string) map[string]interface{} {
141 // Check if provider_id is already a full URL (external link)
142 if strings.HasPrefix(provider_id, "http://") || strings.HasPrefix(provider_id, "https://") {
143 // It's an external direct video link, return it as-is
144 cleanedURL := provider_id
145 // Clean up any double slashes in the URL (except after protocol)
146 if strings.Contains(cleanedURL, "://") {
147 parts := strings.SplitN(cleanedURL, "://", 2)
148 if len(parts) == 2 {
149 protocol := parts[0]
150 rest := parts[1]
151 // Replace any double slashes in the rest of the URL
152 rest = strings.ReplaceAll(rest, "//", "/")
153 cleanedURL = protocol + "://" + rest
154 }
155 }
156
157 Log(fmt.Sprintf("Direct external link detected: %s -> %s", provider_id, cleanedURL))
158 return map[string]interface{}{
159 "links": []interface{}{
160 map[string]interface{}{
161 "link": cleanedURL,
162 },
163 },
164 }
165 }
166
167 // It's a relative path for allanime API
168 allanime_base := "https://allanime.day"
169 url := allanime_base + provider_id
170 req, err := http.NewRequest("GET", url, nil)
171 var videoData map[string]interface{}
172 if err != nil {
173 Log(fmt.Sprint("Error creating request:", err))
174 return videoData
175 }
176
177 // Add the headers
178 req.Header.Set("Referer", "https://allanime.to")
179 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
180
181 // Send the request
182 resp, err := sharedHTTPClient.Do(req)
183 if err != nil {
184 Log(fmt.Sprint("Error sending request:", err))
185 return videoData
186 }
187 defer resp.Body.Close()
188
189 // Read the response body
190 body, err := io.ReadAll(resp.Body)
191 if err != nil {
192 Log(fmt.Sprint("Error reading response:", err))
193 return videoData
194 }
195
196 // Parse the JSON response
197 err = json.Unmarshal(body, &videoData)
198 if err != nil {
199 Log(fmt.Sprint("Error parsing JSON:", err))
200 return videoData
201 }
202
203 // Process the data as needed
204 return videoData
205}
206
207// Get anime episode url respective to given config
208// If the link is found, it returns a list of links. Otherwise, it returns an error.
209//
210// Parameters:
211// - config: Configuration of the anime search.
212// - id: Allanime id of the anime to search for.
213// - epNo: Anime episode number to get links for.
214//
215// Returns:
216// - []string: a list of links for specified episode.
217// - error: an error if the episode is not found or if there is an issue during the search.
218func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
219 preferredMode := normalizeTranslationType(config.SubOrDub)
220 fallbackMode := alternateTranslationType(preferredMode)
221
222 type modeResult struct {
223 links []string
224 err error
225 }
226
227 ch := make(chan modeResult, 2)
228
229 go func() {
230 links, err := getEpisodeURLForMode(id, preferredMode, epNo)
231 ch <- modeResult{links: links, err: err}
232 }()
233
234 go func() {
235 links, err := getEpisodeURLForMode(id, fallbackMode, epNo)
236 ch <- modeResult{links: links, err: err}
237 }()
238
239 var preferredRes, fallbackRes modeResult
240 for i := 0; i < 2; i++ {
241 res := <-ch
242 if res.err == nil {
243 if res.links != nil {
244 return res.links, nil
245 }
246 }
247 if res.err == nil || res.links != nil {
248 preferredRes = res
249 } else {
250 fallbackRes = res
251 }
252 }
253
254 if preferredRes.links != nil {
255 return preferredRes.links, nil
256 }
257 if fallbackRes.links != nil {
258 Log(fmt.Sprintf("Falling back to %s for anime %s episode %d", fallbackMode, id, epNo))
259 return fallbackRes.links, nil
260 }
261
262 return nil, preferredRes.err
263}
264
265func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
266 query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
267
268 variables := map[string]interface{}{
269 "showId": id,
270 "translationType": normalizeTranslationType(mode),
271 "episodeString": fmt.Sprintf("%d", epNo),
272 }
273
274 // Build POST request body
275 requestBody, err := json.Marshal(map[string]interface{}{
276 "query": query,
277 "variables": variables,
278 })
279 if err != nil {
280 return nil, fmt.Errorf("failed to marshal request body: %w", err)
281 }
282
283 req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
284 if err != nil {
285 return nil, fmt.Errorf("failed to create request: %w", err)
286 }
287
288 req.Header.Set("Content-Type", "application/json")
289 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")
290 req.Header.Set("Referer", "https://allanime.to")
291 req.Header.Set("Origin", "https://allanime.to")
292
293 resp, err := sharedHTTPClient.Do(req)
294 if err != nil {
295 return nil, fmt.Errorf("failed to send request: %w", err)
296 }
297 defer resp.Body.Close()
298
299 body, err := io.ReadAll(resp.Body)
300 if err != nil {
301 return nil, fmt.Errorf("failed to read response body: %w", err)
302 }
303
304 var response allanimeResponse
305 err = json.Unmarshal(body, &response)
306 if err != nil {
307 Log(fmt.Sprint("Error parsing JSON: ", err))
308 return nil, err
309 }
310
311 if response.Data.Tobeparsed != "" {
312 Log("Found tobeparsed field, using decoded response")
313 decoded := decodeTobeparsed(response.Data.Tobeparsed)
314 lines := strings.Split(strings.TrimSpace(decoded), "\n")
315 var parsedURLs []struct {
316 SourceName string
317 SourceUrl string
318 }
319 for _, line := range lines {
320 if parts := strings.Split(line, " :"); len(parts) == 2 {
321 parsedURLs = append(parsedURLs, struct {
322 SourceName string
323 SourceUrl string
324 }{SourceName: parts[0], SourceUrl: "--" + parts[1]})
325 }
326 }
327
328 validURLs := make([]string, 0)
329 for _, url := range parsedURLs {
330 validURLs = append(validURLs, url.SourceUrl)
331 }
332
333 if len(validURLs) == 0 {
334 return nil, fmt.Errorf("no valid source URLs found in decoded tobeparsed")
335 }
336
337 return getLinksFromURLs(validURLs)
338 }
339
340 return getLinksFromSourceUrls(response.Data.Episode.SourceUrls)
341}
342
343func getLinksFromSourceUrls(sourceUrls []struct {
344 SourceUrl string `json:"sourceUrl"`
345 SourceName string `json:"sourceName"`
346}) ([]string, error) {
347 validURLs := make([]string, 0)
348 highestPriority := -1
349 var highestPriorityURL string
350
351 for _, url := range sourceUrls {
352 if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
353 decodedURL := decodeProviderID(url.SourceUrl[2:])
354 if strings.Contains(decodedURL, LinkPriorities[0]) {
355 priority := int(url.SourceUrl[2] - '0')
356 if priority > highestPriority {
357 highestPriority = priority
358 highestPriorityURL = url.SourceUrl
359 }
360 } else {
361 validURLs = append(validURLs, url.SourceUrl)
362 }
363 }
364 }
365
366 if highestPriorityURL != "" {
367 validURLs = []string{highestPriorityURL}
368 }
369
370 if len(validURLs) == 0 {
371 return nil, fmt.Errorf("no valid source URLs found in response")
372 }
373
374 return getLinksFromURLs(validURLs)
375}
376
377func getLinksFromURLs(validURLs []string) ([]string, error) {
378 results := make(chan result, len(validURLs))
379 orderedResults := make([][]string, len(validURLs))
380
381 highPriorityLink := make(chan []string, 1)
382
383 remainingURLs := len(validURLs)
384 for i, sourceUrl := range validURLs {
385 go func(idx int, url string) {
386 decodedProviderID := decodeProviderID(url[2:])
387 Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
388
389 extractedLinks := extractLinks(decodedProviderID)
390
391 if extractedLinks == nil {
392 results <- result{
393 index: idx,
394 err: fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
395 }
396 return
397 }
398
399 linksInterface, ok := extractedLinks["links"].([]interface{})
400 if !ok {
401 results <- result{
402 index: idx,
403 err: fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
404 }
405 return
406 }
407
408 var links []string
409 for _, linkInterface := range linksInterface {
410 linkMap, ok := linkInterface.(map[string]interface{})
411 if !ok {
412 Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
413 continue
414 }
415
416 link, ok := linkMap["link"].(string)
417 if !ok {
418 Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
419 continue
420 }
421
422 links = append(links, link)
423 }
424
425 // Check if any of the extracted links are high priority
426 for _, link := range links {
427 for _, domain := range LinkPriorities[:3] {
428 if strings.Contains(link, domain) {
429 // Found high priority link, send it immediately
430 select {
431 case highPriorityLink <- []string{link}:
432 default:
433 // Channel already has a high priority link
434 }
435 break
436 }
437 }
438 }
439
440 results <- result{
441 index: idx,
442 links: links,
443 }
444 }(i, sourceUrl)
445 }
446
447 // Collect results with timeout
448 timeout := time.After(10 * time.Second)
449 var collectedErrors []error
450 successCount := 0
451
452 // First, try to get a high priority link
453 select {
454 case links := <-highPriorityLink:
455 // Continue extracting other links in background
456 go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs)
457 return links, nil
458 case <-time.After(2 * time.Second): // Wait only briefly for high priority link
459 // No high priority link found quickly, proceed with normal collection
460 }
461
462 // Continue with existing result collection logic
463 // Collect results maintaining order
464 for successCount < len(validURLs) {
465 select {
466 case res := <-results:
467 if res.err != nil {
468 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
469 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
470 } else {
471 orderedResults[res.index] = res.links
472 successCount++
473 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
474 }
475 case <-timeout:
476 if successCount > 0 {
477 Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
478 // Flatten available results
479 return flattenResults(orderedResults), nil
480 }
481 return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
482 }
483 }
484
485 // If we have any errors but also some successes, log errors but continue
486 if len(collectedErrors) > 0 {
487 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
488 }
489
490 // Flatten and return results
491 allLinks := flattenResults(orderedResults)
492 if len(allLinks) == 0 {
493 return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
494 }
495
496 return allLinks, nil
497}
498
499// Helper function to collect remaining results in background
500func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) {
501 for *successCount < remainingURLs {
502 select {
503 case res := <-results:
504 if res.err != nil {
505 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
506 *collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
507 } else {
508 orderedResults[res.index] = res.links
509 *successCount++
510 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs))
511 }
512 case <-time.After(10 * time.Second):
513 return
514 }
515 }
516}
517
518// converts the ordered slice of link slices into a single slice
519func flattenResults(results [][]string) []string {
520 var totalLen int
521 for _, r := range results {
522 totalLen += len(r)
523 }
524
525 allLinks := make([]string, 0, totalLen)
526 for _, links := range results {
527 allLinks = append(allLinks, links...)
528 }
529 return allLinks
530}