internal/episode_url.go

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