internal/episode_url.go

797 lines · 22538 bytes

  1package internal
  2
  3import (
  4	"bytes"
  5	"crypto/aes"
  6	"crypto/cipher"
  7	"crypto/sha256"
  8	"encoding/base64"
  9	"encoding/binary"
 10	"encoding/hex"
 11	"encoding/json"
 12	"fmt"
 13	"io"
 14	"net/http"
 15	"net/url"
 16	"regexp"
 17	"sort"
 18	"strconv"
 19	"strings"
 20	"time"
 21)
 22
 23type allanimeSource struct {
 24	SourceUrl  string  `json:"sourceUrl"`
 25	SourceName string  `json:"sourceName"`
 26	Priority   float64 `json:"priority"`
 27}
 28
 29type allanimeResponse struct {
 30	Data struct {
 31		M          string `json:"_m"`
 32		Tobeparsed string `json:"tobeparsed"`
 33		Episode    struct {
 34			SourceUrls []allanimeSource `json:"sourceUrls"`
 35		} `json:"episode"`
 36	} `json:"data"`
 37}
 38
 39type allanimeTobeparsedPayload struct {
 40	Episode struct {
 41		SourceUrls []allanimeSource `json:"sourceUrls"`
 42	} `json:"episode"`
 43}
 44
 45type result struct {
 46	index int
 47	links []string
 48	err   error
 49}
 50
 51type filemoonResponse struct {
 52	IV       string   `json:"iv"`
 53	Payload  string   `json:"payload"`
 54	KeyParts []string `json:"key_parts"`
 55}
 56
 57func decodeTobeparsed(blob string) ([]allanimeSource, error) {
 58	key := []byte("Xot36i3lK3:v1")
 59	hash := sha256.Sum256(key)
 60
 61	data, err := base64.StdEncoding.DecodeString(blob)
 62	if err != nil {
 63		return nil, fmt.Errorf("error decoding base64: %w", err)
 64	}
 65
 66	if len(data) < 29 {
 67		return nil, fmt.Errorf("data too short to contain tobeparsed payload")
 68	}
 69
 70	// The payload format is: 1-byte header, 12-byte IV, ciphertext, 16-byte trailer.
 71	iv := data[1:13]
 72	ctLen := len(data) - 13 - 16
 73	if ctLen <= 0 {
 74		return nil, fmt.Errorf("ciphertext length is invalid in tobeparsed payload")
 75	}
 76	ct := data[13 : 13+ctLen]
 77
 78	ctrIV := make([]byte, 16)
 79	copy(ctrIV, iv)
 80	binary.BigEndian.PutUint32(ctrIV[12:], uint32(2))
 81
 82	block, err := aes.NewCipher(hash[:])
 83	if err != nil {
 84		return nil, fmt.Errorf("error creating cipher: %w", err)
 85	}
 86
 87	stream := cipher.NewCTR(block, ctrIV)
 88	plain := make([]byte, len(ct))
 89	stream.XORKeyStream(plain, ct)
 90
 91	var payload allanimeTobeparsedPayload
 92	if err := json.Unmarshal(plain, &payload); err != nil {
 93		return nil, fmt.Errorf("failed to parse decrypted tobeparsed payload: %w", err)
 94	}
 95
 96	if len(payload.Episode.SourceUrls) == 0 {
 97		return nil, fmt.Errorf("no source URLs found in decrypted tobeparsed payload")
 98	}
 99
100	return payload.Episode.SourceUrls, nil
101}
102
103func decodeProviderID(encoded string) string {
104	// Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
105	re := regexp.MustCompile("..")
106	pairs := re.FindAllString(encoded, -1)
107
108	// Mapping for the replacements
109	replacements := map[string]string{
110		// Uppercase letters
111		"79": "A", "7a": "B", "7b": "C", "7c": "D", "7d": "E", "7e": "F", "7f": "G",
112		"70": "H", "71": "I", "72": "J", "73": "K", "74": "L", "75": "M", "76": "N", "77": "O",
113		"68": "P", "69": "Q", "6a": "R", "6b": "S", "6c": "T", "6d": "U", "6e": "V", "6f": "W",
114		"60": "X", "61": "Y", "62": "Z",
115		// Lowercase letters
116		"59": "a", "5a": "b", "5b": "c", "5c": "d", "5d": "e", "5e": "f", "5f": "g",
117		"50": "h", "51": "i", "52": "j", "53": "k", "54": "l", "55": "m", "56": "n", "57": "o",
118		"48": "p", "49": "q", "4a": "r", "4b": "s", "4c": "t", "4d": "u", "4e": "v", "4f": "w",
119		"40": "x", "41": "y", "42": "z",
120		// Numbers
121		"08": "0", "09": "1", "0a": "2", "0b": "3", "0c": "4", "0d": "5", "0e": "6", "0f": "7",
122		"00": "8", "01": "9",
123		// Special characters
124		"15": "-", "16": ".", "67": "_", "46": "~", "02": ":", "17": "/", "07": "?", "1b": "#",
125		"63": "[", "65": "]", "78": "@", "19": "!", "1c": "$", "1e": "&", "10": "(", "11": ")",
126		"12": "*", "13": "+", "14": ",", "03": ";", "05": "=", "1d": "%",
127	}
128
129	// Perform the replacement equivalent to sed 's/^../.../'
130	for i, pair := range pairs {
131		if val, exists := replacements[pair]; exists {
132			pairs[i] = val
133		}
134	}
135
136	// Join the modified pairs back into a single string
137	result := strings.Join(pairs, "")
138
139	// Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
140	result = strings.ReplaceAll(result, "/clock", "/clock.json")
141
142	// Print the final result
143	return result
144}
145
146func isDirectPlayableAllanimeSource(source allanimeSource) bool {
147	sourceURL := strings.TrimSpace(source.SourceUrl)
148	if sourceURL == "" {
149		return false
150	}
151
152	if strings.EqualFold(source.SourceName, "Yt-mp4") || strings.EqualFold(source.SourceName, "S-mp4") {
153		return true
154	}
155
156	lowerURL := strings.ToLower(sourceURL)
157	if strings.Contains(lowerURL, "tools.fast4speed.rsvp/") {
158		return true
159	}
160
161	parsedURL, err := url.Parse(sourceURL)
162	if err != nil {
163		return false
164	}
165
166	path := strings.ToLower(parsedURL.Path)
167	return strings.HasSuffix(path, ".mp4") || strings.HasSuffix(path, ".m3u8")
168}
169
170func sortAllanimeSourcesByPriority(sourceUrls []allanimeSource) []allanimeSource {
171	if len(sourceUrls) == 0 {
172		return nil
173	}
174
175	sorted := append([]allanimeSource(nil), sourceUrls...)
176	sort.SliceStable(sorted, func(i, j int) bool {
177		return sorted[i].Priority > sorted[j].Priority
178	})
179
180	return sorted
181}
182
183func extractLinks(provider_id string) map[string]interface{} {
184	provider_id = normalizeAllanimeProviderPath(provider_id)
185
186	// Check if provider_id is already a full URL (external link)
187	if strings.HasPrefix(provider_id, "http://") || strings.HasPrefix(provider_id, "https://") {
188		// It's an external direct video link, preserve it exactly as provided.
189		Log(fmt.Sprintf("Direct external link detected: %s", provider_id))
190		return map[string]interface{}{
191			"links": []interface{}{
192				map[string]interface{}{
193					"link": provider_id,
194				},
195			},
196		}
197	}
198
199	// It's a relative path for allanime API
200	allanime_base := "https://allanime.day"
201	url := allanime_base + provider_id
202	req, err := http.NewRequest("GET", url, nil)
203	var videoData map[string]interface{}
204	if err != nil {
205		Log(fmt.Sprint("Error creating request:", err))
206		return videoData
207	}
208
209	// Add the headers
210	req.Header.Set("Referer", "https://allanime.to")
211	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
212
213	// Send the request
214	resp, err := sharedHTTPClient.Do(req)
215	if err != nil {
216		Log(fmt.Sprint("Error sending request:", err))
217		return videoData
218	}
219	defer resp.Body.Close()
220
221	// Read the response body
222	body, err := io.ReadAll(resp.Body)
223	if err != nil {
224		Log(fmt.Sprint("Error reading response:", err))
225		return videoData
226	}
227
228	// Parse the JSON response
229	err = json.Unmarshal(body, &videoData)
230	if err != nil {
231		Log(fmt.Sprint("Error parsing JSON:", err))
232		return videoData
233	}
234
235	// Filemoon extractor payload does not return a top-level "links" field.
236	if _, hasLinks := videoData["links"]; !hasLinks {
237		if filemoonLinks := extractFilemoonLinks(videoData); len(filemoonLinks) > 0 {
238			links := make([]interface{}, 0, len(filemoonLinks))
239			for _, link := range filemoonLinks {
240				links = append(links, map[string]interface{}{"link": link})
241			}
242			videoData["links"] = links
243		}
244	}
245
246	// Process the data as needed
247	return videoData
248}
249
250func normalizeAllanimeProviderPath(providerID string) string {
251	const allanimePrefix = "/https://allanime.day"
252
253	if strings.HasPrefix(providerID, allanimePrefix) {
254		trimmed := strings.TrimPrefix(providerID, allanimePrefix)
255		if trimmed == "" {
256			return "/"
257		}
258		if !strings.HasPrefix(trimmed, "/") {
259			return "/" + trimmed
260		}
261		return trimmed
262	}
263
264	return providerID
265}
266
267func decodeBase64URLRaw(input string) ([]byte, error) {
268	if decoded, err := base64.RawURLEncoding.DecodeString(input); err == nil {
269		return decoded, nil
270	}
271	return base64.URLEncoding.DecodeString(input)
272}
273
274func extractFilemoonLinks(videoData map[string]interface{}) []string {
275	raw, err := json.Marshal(videoData)
276	if err != nil {
277		Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
278		return nil
279	}
280
281	var payload filemoonResponse
282	if err := json.Unmarshal(raw, &payload); err != nil {
283		Log(fmt.Sprintf("Error parsing filemoon payload: %v", err))
284		return nil
285	}
286
287	if payload.IV == "" || payload.Payload == "" || len(payload.KeyParts) < 2 {
288		return nil
289	}
290
291	keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0])
292	if err != nil {
293		Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err))
294		return nil
295	}
296
297	keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1])
298	if err != nil {
299		Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err))
300		return nil
301	}
302
303	iv, err := decodeBase64URLRaw(payload.IV)
304	if err != nil {
305		Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
306		return nil
307	}
308
309	ciphertext, err := decodeBase64URLRaw(payload.Payload)
310	if err != nil {
311		Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
312		return nil
313	}
314
315	if len(ciphertext) <= 16 {
316		Log("Filemoon ciphertext is too short")
317		return nil
318	}
319
320	// Match jerry.sh behavior: decrypt all bytes except the final 16-byte trailer.
321	ciphertext = ciphertext[:len(ciphertext)-16]
322
323	keyHex := hex.EncodeToString(append(keyPart1, keyPart2...))
324	key, err := hex.DecodeString(keyHex)
325	if err != nil {
326		Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err))
327		return nil
328	}
329
330	ctrIVHex := hex.EncodeToString(iv) + "00000002"
331	ctrIV, err := hex.DecodeString(ctrIVHex)
332	if err != nil {
333		Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err))
334		return nil
335	}
336
337	if len(ctrIV) != aes.BlockSize {
338		Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV)))
339		return nil
340	}
341
342	block, err := aes.NewCipher(key)
343	if err != nil {
344		Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
345		return nil
346	}
347
348	plain := make([]byte, len(ciphertext))
349	cipher.NewCTR(block, ctrIV).XORKeyStream(plain, ciphertext)
350
351	decoded := strings.ReplaceAll(string(plain), `\u0026`, "&")
352	decoded = strings.ReplaceAll(decoded, `\u003D`, "=")
353
354	type qualityLink struct {
355		height int
356		link   string
357	}
358
359	collected := make([]qualityLink, 0)
360	seen := make(map[string]struct{})
361
362	reURLFirst := regexp.MustCompile(`"url":"([^"]+)".*?"height":([0-9]+)`)
363	reHeightFirst := regexp.MustCompile(`"height":([0-9]+).*?"url":"([^"]+)"`)
364
365	for _, match := range reURLFirst.FindAllStringSubmatch(decoded, -1) {
366		if len(match) != 3 {
367			continue
368		}
369		height, err := strconv.Atoi(match[2])
370		if err != nil {
371			continue
372		}
373		if _, exists := seen[match[1]]; exists {
374			continue
375		}
376		seen[match[1]] = struct{}{}
377		collected = append(collected, qualityLink{height: height, link: match[1]})
378	}
379
380	for _, match := range reHeightFirst.FindAllStringSubmatch(decoded, -1) {
381		if len(match) != 3 {
382			continue
383		}
384		height, err := strconv.Atoi(match[1])
385		if err != nil {
386			continue
387		}
388		if _, exists := seen[match[2]]; exists {
389			continue
390		}
391		seen[match[2]] = struct{}{}
392		collected = append(collected, qualityLink{height: height, link: match[2]})
393	}
394
395	sort.Slice(collected, func(i, j int) bool {
396		return collected[i].height > collected[j].height
397	})
398
399	links := make([]string, 0, len(collected))
400	for _, entry := range collected {
401		links = append(links, entry.link)
402	}
403
404	if len(links) > 0 {
405		Log("Filemoon links fetched")
406	}
407
408	return links
409}
410
411// Get anime episode url respective to given config
412// If the link is found, it returns a list of links. Otherwise, it returns an error.
413//
414// Parameters:
415// - config: Configuration of the anime search.
416// - id: Allanime id of the anime to search for.
417// - epNo: Anime episode number to get links for.
418//
419// Returns:
420// - []string: a list of links for specified episode.
421// - error: an error if the episode is not found or if there is an issue during the search.
422func getAllanimeEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
423	preferredMode := normalizeTranslationType(config.SubOrDub)
424	fallbackMode := alternateTranslationType(preferredMode)
425
426	type modeResult struct {
427		mode  string
428		links []string
429		err   error
430	}
431
432	ch := make(chan modeResult, 2)
433
434	go func() {
435		links, err := getEpisodeURLForMode(id, preferredMode, epNo)
436		ch <- modeResult{mode: preferredMode, links: links, err: err}
437	}()
438
439	go func() {
440		links, err := getEpisodeURLForMode(id, fallbackMode, epNo)
441		ch <- modeResult{mode: fallbackMode, links: links, err: err}
442	}()
443
444	var preferredRes, fallbackRes modeResult
445	hasPreferredRes := false
446	hasFallbackRes := false
447	for i := 0; i < 2; i++ {
448		res := <-ch
449
450		if res.mode == preferredMode {
451			preferredRes = res
452			hasPreferredRes = true
453			if res.err == nil && len(res.links) > 0 {
454				return res.links, nil
455			}
456			continue
457		}
458
459		if res.mode == fallbackMode {
460			fallbackRes = res
461			hasFallbackRes = true
462		}
463	}
464
465	if hasPreferredRes && preferredRes.err == nil && len(preferredRes.links) > 0 {
466		return preferredRes.links, nil
467	}
468	if hasFallbackRes && fallbackRes.err == nil && len(fallbackRes.links) > 0 {
469		Log(fmt.Sprintf("Falling back to %s for anime %s episode %d", fallbackMode, id, epNo))
470		return fallbackRes.links, nil
471	}
472
473	if hasPreferredRes && preferredRes.err != nil {
474		return nil, preferredRes.err
475	}
476	if hasFallbackRes && fallbackRes.err != nil {
477		return nil, fallbackRes.err
478	}
479
480	return nil, fmt.Errorf("no valid links found for anime %s episode %d", id, epNo)
481}
482
483func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
484	const (
485		episodeQueryHash = "d405d0edd690624b66baba3068e0edc3ac90f1597d898a1ec8db4e5c43c00fec"
486	)
487
488	episodeEmbedGQL := `query ($showId: String!, $translationType: VaildTranslationTypeEnumType!, $episodeString: String!) { episode( showId: $showId translationType: $translationType episodeString: $episodeString ) { episodeString sourceUrls }}`
489
490	variables := map[string]interface{}{
491		"showId":          id,
492		"translationType": normalizeTranslationType(mode),
493		"episodeString":   fmt.Sprintf("%d", epNo),
494	}
495
496	extensions := map[string]interface{}{
497		"persistedQuery": map[string]interface{}{
498			"version":    1,
499			"sha256Hash": episodeQueryHash,
500		},
501	}
502
503	variablesJSON, err := json.Marshal(variables)
504	if err != nil {
505		return nil, fmt.Errorf("failed to marshal persisted query variables: %w", err)
506	}
507
508	extensionsJSON, err := json.Marshal(extensions)
509	if err != nil {
510		return nil, fmt.Errorf("failed to marshal persisted query extensions: %w", err)
511	}
512
513	persistedURL := "https://api.allanime.day/api?variables=" + url.QueryEscape(string(variablesJSON)) + "&extensions=" + url.QueryEscape(string(extensionsJSON))
514
515	req, err := http.NewRequest("GET", persistedURL, nil)
516	if err != nil {
517		return nil, fmt.Errorf("failed to create persisted query request: %w", err)
518	}
519	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
520	req.Header.Set("Referer", "https://allmanga.to")
521	req.Header.Set("Origin", "https://youtu-chan.com")
522
523	resp, err := sharedHTTPClient.Do(req)
524	if err != nil {
525		return nil, fmt.Errorf("failed to send persisted query request: %w", err)
526	}
527	body, err := io.ReadAll(resp.Body)
528	resp.Body.Close()
529	if err != nil {
530		return nil, fmt.Errorf("failed to read persisted query response: %w", err)
531	}
532
533	var response allanimeResponse
534	if err := json.Unmarshal(body, &response); err != nil {
535		Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
536	}
537
538	useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
539	if useFallback {
540		query := episodeEmbedGQL
541
542		// Build POST request body
543		requestBody, err := json.Marshal(map[string]interface{}{
544			"query":     query,
545			"variables": variables,
546		})
547		if err != nil {
548			return nil, fmt.Errorf("failed to marshal request body: %w", err)
549		}
550
551		req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
552		if err != nil {
553			return nil, fmt.Errorf("failed to create request: %w", err)
554		}
555
556		req.Header.Set("Content-Type", "application/json")
557		req.Header.Set("User-Agent", "Mozilla/5.0")
558		req.Header.Set("Referer", "https://allmanga.to")
559		req.Header.Set("Origin", "https://allanime.to")
560
561		resp, err := sharedHTTPClient.Do(req)
562		if err != nil {
563			return nil, fmt.Errorf("failed to send request: %w", err)
564		}
565		defer resp.Body.Close()
566
567		body, err := io.ReadAll(resp.Body)
568		if err != nil {
569			return nil, fmt.Errorf("failed to read response body: %w", err)
570		}
571
572		if err := json.Unmarshal(body, &response); err != nil {
573			Log(fmt.Sprint("Error parsing fallback JSON: ", err))
574			return nil, err
575		}
576	}
577
578	if response.Data.Tobeparsed != "" {
579		Log("Found tobeparsed field, decoding source URLs")
580		decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed)
581		if err != nil {
582			return nil, err
583		}
584
585		Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
586		return getLinksFromSourceUrls(decodedSources)
587	}
588
589	return getLinksFromSourceUrls(response.Data.Episode.SourceUrls)
590}
591
592func getLinksFromSourceUrls(sourceUrls []allanimeSource) ([]string, error) {
593	sourceUrls = sortAllanimeSourcesByPriority(sourceUrls)
594
595	directURLs := make([]string, 0)
596	validURLs := make([]string, 0)
597	highestPriority := -1.0
598	var highestPriorityURL string
599
600	for _, url := range sourceUrls {
601		sourceURL := strings.TrimSpace(url.SourceUrl)
602		if sourceURL == "" {
603			continue
604		}
605
606		if isDirectPlayableAllanimeSource(url) {
607			directURLs = append(directURLs, sourceURL)
608			continue
609		}
610
611		if !strings.HasPrefix(sourceURL, "--") || len(sourceURL) <= 2 {
612			Log(fmt.Sprintf("Skipping unsupported Allanime source %q (%s)", url.SourceName, sourceURL))
613			continue
614		}
615
616		decodedURL := decodeProviderID(sourceURL[2:])
617		if strings.Contains(decodedURL, LinkPriorities[0]) {
618			priority := url.Priority
619			if priority > highestPriority {
620				highestPriority = priority
621				highestPriorityURL = sourceURL
622			}
623		} else {
624			validURLs = append(validURLs, sourceURL)
625		}
626	}
627
628	if len(directURLs) > 0 {
629		Log(fmt.Sprintf("Using %d direct Allanime source URL(s)", len(directURLs)))
630		return directURLs, nil
631	}
632
633	if highestPriorityURL != "" {
634		validURLs = []string{highestPriorityURL}
635	}
636
637	if len(validURLs) == 0 {
638		return nil, fmt.Errorf("no supported source URLs found in response")
639	}
640
641	return getLinksFromURLs(validURLs)
642}
643
644func getLinksFromURLs(validURLs []string) ([]string, error) {
645	results := make(chan result, len(validURLs))
646	orderedResults := make([][]string, len(validURLs))
647
648	highPriorityLink := make(chan []string, 1)
649
650	remainingURLs := len(validURLs)
651	for i, sourceUrl := range validURLs {
652		go func(idx int, url string) {
653			decodedProviderID := decodeProviderID(url[2:])
654			Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
655
656			extractedLinks := extractLinks(decodedProviderID)
657
658			if extractedLinks == nil {
659				results <- result{
660					index: idx,
661					err:   fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
662				}
663				return
664			}
665
666			linksInterface, ok := extractedLinks["links"].([]interface{})
667			if !ok {
668				results <- result{
669					index: idx,
670					err:   fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
671				}
672				return
673			}
674
675			var links []string
676			for _, linkInterface := range linksInterface {
677				linkMap, ok := linkInterface.(map[string]interface{})
678				if !ok {
679					Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
680					continue
681				}
682
683				link, ok := linkMap["link"].(string)
684				if !ok {
685					Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
686					continue
687				}
688
689				links = append(links, link)
690			}
691
692			// Check if any of the extracted links are high priority
693			for _, link := range links {
694				for _, domain := range LinkPriorities[:3] {
695					if strings.Contains(link, domain) {
696						// Found high priority link, send it immediately
697						select {
698						case highPriorityLink <- []string{link}:
699						default:
700							// Channel already has a high priority link
701						}
702						break
703					}
704				}
705			}
706
707			results <- result{
708				index: idx,
709				links: links,
710			}
711		}(i, sourceUrl)
712	}
713
714	// Collect results with timeout
715	timeout := time.After(10 * time.Second)
716	var collectedErrors []error
717	successCount := 0
718
719	// First, try to get a high priority link
720	select {
721	case links := <-highPriorityLink:
722		// Continue extracting other links in background
723		go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs)
724		return links, nil
725	case <-time.After(2 * time.Second): // Wait only briefly for high priority link
726		// No high priority link found quickly, proceed with normal collection
727	}
728
729	// Continue with existing result collection logic
730	// Collect results maintaining order
731	for successCount < len(validURLs) {
732		select {
733		case res := <-results:
734			if res.err != nil {
735				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
736				collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
737			} else {
738				orderedResults[res.index] = res.links
739				successCount++
740				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
741			}
742		case <-timeout:
743			if successCount > 0 {
744				Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
745				// Flatten available results
746				return flattenResults(orderedResults), nil
747			}
748			return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
749		}
750	}
751
752	// If we have any errors but also some successes, log errors but continue
753	if len(collectedErrors) > 0 {
754		Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
755	}
756
757	// Flatten and return results
758	allLinks := flattenResults(orderedResults)
759	if len(allLinks) == 0 {
760		return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
761	}
762
763	return allLinks, nil
764}
765
766// Helper function to collect remaining results in background
767func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) {
768	for *successCount < remainingURLs {
769		select {
770		case res := <-results:
771			if res.err != nil {
772				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
773				*collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
774			} else {
775				orderedResults[res.index] = res.links
776				*successCount++
777				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs))
778			}
779		case <-time.After(10 * time.Second):
780			return
781		}
782	}
783}
784
785// converts the ordered slice of link slices into a single slice
786func flattenResults(results [][]string) []string {
787	var totalLen int
788	for _, r := range results {
789		totalLen += len(r)
790	}
791
792	allLinks := make([]string, 0, totalLen)
793	for _, links := range results {
794		allLinks = append(allLinks, links...)
795	}
796	return allLinks
797}