internal/episode_url.go
739 lines · 21040 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 if !httpStatusOK(resp.StatusCode) {
228 Log(httpStatusError("allanime source extractor", resp.StatusCode, body))
229 return videoData
230 }
231
232 // Parse the JSON response
233 err = json.Unmarshal(body, &videoData)
234 if err != nil {
235 Log(fmt.Sprint("Error parsing JSON:", err))
236 return videoData
237 }
238
239 // Filemoon extractor payload does not return a top-level "links" field.
240 if _, hasLinks := videoData["links"]; !hasLinks {
241 if filemoonLinks := extractFilemoonLinks(videoData); len(filemoonLinks) > 0 {
242 links := make([]interface{}, 0, len(filemoonLinks))
243 for _, link := range filemoonLinks {
244 links = append(links, map[string]interface{}{"link": link})
245 }
246 videoData["links"] = links
247 }
248 }
249
250 // Process the data as needed
251 return videoData
252}
253
254func normalizeAllanimeProviderPath(providerID string) string {
255 const allanimePrefix = "/https://allanime.day"
256
257 if strings.HasPrefix(providerID, allanimePrefix) {
258 trimmed := strings.TrimPrefix(providerID, allanimePrefix)
259 if trimmed == "" {
260 return "/"
261 }
262 if !strings.HasPrefix(trimmed, "/") {
263 return "/" + trimmed
264 }
265 return trimmed
266 }
267
268 return providerID
269}
270
271func decodeBase64URLRaw(input string) ([]byte, error) {
272 if decoded, err := base64.RawURLEncoding.DecodeString(input); err == nil {
273 return decoded, nil
274 }
275 return base64.URLEncoding.DecodeString(input)
276}
277
278func extractFilemoonLinks(videoData map[string]interface{}) []string {
279 raw, err := json.Marshal(videoData)
280 if err != nil {
281 Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
282 return nil
283 }
284
285 var payload filemoonResponse
286 if err := json.Unmarshal(raw, &payload); err != nil {
287 Log(fmt.Sprintf("Error parsing filemoon payload: %v", err))
288 return nil
289 }
290
291 if payload.IV == "" || payload.Payload == "" || len(payload.KeyParts) < 2 {
292 return nil
293 }
294
295 keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0])
296 if err != nil {
297 Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err))
298 return nil
299 }
300
301 keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1])
302 if err != nil {
303 Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err))
304 return nil
305 }
306
307 iv, err := decodeBase64URLRaw(payload.IV)
308 if err != nil {
309 Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
310 return nil
311 }
312
313 ciphertext, err := decodeBase64URLRaw(payload.Payload)
314 if err != nil {
315 Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
316 return nil
317 }
318
319 if len(ciphertext) <= 16 {
320 Log("Filemoon ciphertext is too short")
321 return nil
322 }
323
324 // Match jerry.sh behavior: decrypt all bytes except the final 16-byte trailer.
325 ciphertext = ciphertext[:len(ciphertext)-16]
326
327 keyHex := hex.EncodeToString(append(keyPart1, keyPart2...))
328 key, err := hex.DecodeString(keyHex)
329 if err != nil {
330 Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err))
331 return nil
332 }
333
334 ctrIVHex := hex.EncodeToString(iv) + "00000002"
335 ctrIV, err := hex.DecodeString(ctrIVHex)
336 if err != nil {
337 Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err))
338 return nil
339 }
340
341 if len(ctrIV) != aes.BlockSize {
342 Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV)))
343 return nil
344 }
345
346 block, err := aes.NewCipher(key)
347 if err != nil {
348 Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
349 return nil
350 }
351
352 plain := make([]byte, len(ciphertext))
353 cipher.NewCTR(block, ctrIV).XORKeyStream(plain, ciphertext)
354
355 decoded := strings.ReplaceAll(string(plain), `\u0026`, "&")
356 decoded = strings.ReplaceAll(decoded, `\u003D`, "=")
357
358 type qualityLink struct {
359 height int
360 link string
361 }
362
363 collected := make([]qualityLink, 0)
364 seen := make(map[string]struct{})
365
366 reURLFirst := regexp.MustCompile(`"url":"([^"]+)".*?"height":([0-9]+)`)
367 reHeightFirst := regexp.MustCompile(`"height":([0-9]+).*?"url":"([^"]+)"`)
368
369 for _, match := range reURLFirst.FindAllStringSubmatch(decoded, -1) {
370 if len(match) != 3 {
371 continue
372 }
373 height, err := strconv.Atoi(match[2])
374 if err != nil {
375 continue
376 }
377 if _, exists := seen[match[1]]; exists {
378 continue
379 }
380 seen[match[1]] = struct{}{}
381 collected = append(collected, qualityLink{height: height, link: match[1]})
382 }
383
384 for _, match := range reHeightFirst.FindAllStringSubmatch(decoded, -1) {
385 if len(match) != 3 {
386 continue
387 }
388 height, err := strconv.Atoi(match[1])
389 if err != nil {
390 continue
391 }
392 if _, exists := seen[match[2]]; exists {
393 continue
394 }
395 seen[match[2]] = struct{}{}
396 collected = append(collected, qualityLink{height: height, link: match[2]})
397 }
398
399 sort.Slice(collected, func(i, j int) bool {
400 return collected[i].height > collected[j].height
401 })
402
403 links := make([]string, 0, len(collected))
404 for _, entry := range collected {
405 links = append(links, entry.link)
406 }
407
408 if len(links) > 0 {
409 Log("Filemoon links fetched")
410 }
411
412 return links
413}
414
415// Get anime episode url respective to given config
416// If the link is found, it returns a list of links. Otherwise, it returns an error.
417//
418// Parameters:
419// - config: Configuration of the anime search.
420// - id: Allanime id of the anime to search for.
421// - epNo: Anime episode number to get links for.
422//
423// Returns:
424// - []string: a list of links for specified episode.
425// - error: an error if the episode is not found or if there is an issue during the search.
426func getAllanimeEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
427 preferredMode := normalizeTranslationType(config.SubOrDub)
428 return getAllanimeEpisodeURLForMode(id, preferredMode, epNo)
429}
430
431func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
432 return getEpisodeURLForMode(id, normalizeTranslationType(mode), epNo)
433}
434
435func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
436 const (
437 episodeQueryHash = "d405d0edd690624b66baba3068e0edc3ac90f1597d898a1ec8db4e5c43c00fec"
438 )
439
440 episodeEmbedGQL := `query ($showId: String!, $translationType: VaildTranslationTypeEnumType!, $episodeString: String!) { episode( showId: $showId translationType: $translationType episodeString: $episodeString ) { episodeString sourceUrls }}`
441
442 variables := map[string]interface{}{
443 "showId": id,
444 "translationType": normalizeTranslationType(mode),
445 "episodeString": fmt.Sprintf("%d", epNo),
446 }
447
448 extensions := map[string]interface{}{
449 "persistedQuery": map[string]interface{}{
450 "version": 1,
451 "sha256Hash": episodeQueryHash,
452 },
453 }
454
455 variablesJSON, err := json.Marshal(variables)
456 if err != nil {
457 return nil, fmt.Errorf("failed to marshal persisted query variables: %w", err)
458 }
459
460 extensionsJSON, err := json.Marshal(extensions)
461 if err != nil {
462 return nil, fmt.Errorf("failed to marshal persisted query extensions: %w", err)
463 }
464
465 persistedURL := "https://api.allanime.day/api?variables=" + url.QueryEscape(string(variablesJSON)) + "&extensions=" + url.QueryEscape(string(extensionsJSON))
466
467 req, err := http.NewRequest("GET", persistedURL, nil)
468 if err != nil {
469 return nil, fmt.Errorf("failed to create persisted query request: %w", err)
470 }
471 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
472 req.Header.Set("Referer", "https://allmanga.to")
473 req.Header.Set("Origin", "https://youtu-chan.com")
474
475 resp, err := sharedHTTPClient.Do(req)
476 if err != nil {
477 return nil, fmt.Errorf("failed to send persisted query request: %w", err)
478 }
479 body, err := io.ReadAll(resp.Body)
480 resp.Body.Close()
481 if err != nil {
482 return nil, fmt.Errorf("failed to read persisted query response: %w", err)
483 }
484 if !httpStatusOK(resp.StatusCode) {
485 return nil, httpStatusError("allanime episode persisted query", resp.StatusCode, body)
486 }
487
488 var response allanimeResponse
489 if err := json.Unmarshal(body, &response); err != nil {
490 Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
491 }
492
493 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
494 if useFallback {
495 query := episodeEmbedGQL
496
497 // Build POST request body
498 requestBody, err := json.Marshal(map[string]interface{}{
499 "query": query,
500 "variables": variables,
501 })
502 if err != nil {
503 return nil, fmt.Errorf("failed to marshal request body: %w", err)
504 }
505
506 req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
507 if err != nil {
508 return nil, fmt.Errorf("failed to create request: %w", err)
509 }
510
511 req.Header.Set("Content-Type", "application/json")
512 req.Header.Set("User-Agent", "Mozilla/5.0")
513 req.Header.Set("Referer", "https://allmanga.to")
514 req.Header.Set("Origin", "https://allanime.to")
515
516 resp, err := sharedHTTPClient.Do(req)
517 if err != nil {
518 return nil, fmt.Errorf("failed to send request: %w", err)
519 }
520 defer resp.Body.Close()
521
522 body, err := io.ReadAll(resp.Body)
523 if err != nil {
524 return nil, fmt.Errorf("failed to read response body: %w", err)
525 }
526 if !httpStatusOK(resp.StatusCode) {
527 return nil, httpStatusError("allanime episode fallback query", resp.StatusCode, body)
528 }
529
530 if err := json.Unmarshal(body, &response); err != nil {
531 Log(fmt.Sprint("Error parsing fallback JSON: ", err))
532 return nil, err
533 }
534 }
535
536 if response.Data.Tobeparsed != "" {
537 Log("Found tobeparsed field, decoding source URLs")
538 decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed)
539 if err != nil {
540 return nil, err
541 }
542
543 Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
544 return getLinksFromSourceUrls(decodedSources)
545 }
546
547 return getLinksFromSourceUrls(response.Data.Episode.SourceUrls)
548}
549
550func getLinksFromSourceUrls(sourceUrls []allanimeSource) ([]string, error) {
551 sourceUrls = sortAllanimeSourcesByPriority(sourceUrls)
552
553 directURLs := make([]string, 0)
554 validURLs := make([]string, 0)
555 highestPriority := -1.0
556 var highestPriorityURL string
557
558 for _, url := range sourceUrls {
559 sourceURL := strings.TrimSpace(url.SourceUrl)
560 if sourceURL == "" {
561 continue
562 }
563
564 if isDirectPlayableAllanimeSource(url) {
565 directURLs = append(directURLs, sourceURL)
566 continue
567 }
568
569 if !strings.HasPrefix(sourceURL, "--") || len(sourceURL) <= 2 {
570 Log(fmt.Sprintf("Skipping unsupported Allanime source %q (%s)", url.SourceName, sourceURL))
571 continue
572 }
573
574 decodedURL := decodeProviderID(sourceURL[2:])
575 if len(LinkPriorities) > 0 && strings.Contains(decodedURL, LinkPriorities[0]) {
576 priority := url.Priority
577 if priority > highestPriority {
578 highestPriority = priority
579 highestPriorityURL = sourceURL
580 }
581 } else {
582 validURLs = append(validURLs, sourceURL)
583 }
584 }
585
586 if len(directURLs) > 0 {
587 Log(fmt.Sprintf("Using %d direct Allanime source URL(s)", len(directURLs)))
588 return directURLs, nil
589 }
590
591 if highestPriorityURL != "" {
592 validURLs = []string{highestPriorityURL}
593 }
594
595 if len(validURLs) == 0 {
596 return nil, fmt.Errorf("no supported source URLs found in response")
597 }
598
599 return getLinksFromURLs(validURLs)
600}
601
602func getLinksFromURLs(validURLs []string) ([]string, error) {
603 results := make(chan result, len(validURLs))
604 orderedResults := make([][]string, len(validURLs))
605
606 highPriorityLink := make(chan []string, 1)
607
608 for i, sourceUrl := range validURLs {
609 go func(idx int, url string) {
610 decodedProviderID := decodeProviderID(url[2:])
611 Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
612
613 extractedLinks := extractLinks(decodedProviderID)
614
615 if extractedLinks == nil {
616 results <- result{
617 index: idx,
618 err: fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
619 }
620 return
621 }
622
623 linksInterface, ok := extractedLinks["links"].([]interface{})
624 if !ok {
625 results <- result{
626 index: idx,
627 err: fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
628 }
629 return
630 }
631
632 var links []string
633 for _, linkInterface := range linksInterface {
634 linkMap, ok := linkInterface.(map[string]interface{})
635 if !ok {
636 Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
637 continue
638 }
639
640 link, ok := linkMap["link"].(string)
641 if !ok {
642 Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
643 continue
644 }
645
646 links = append(links, link)
647 }
648
649 // Check if any of the extracted links are high priority
650 priorityDomains := LinkPriorities
651 if len(priorityDomains) > 3 {
652 priorityDomains = priorityDomains[:3]
653 }
654 for _, link := range links {
655 for _, domain := range priorityDomains {
656 if strings.Contains(link, domain) {
657 // Found high priority link, send it immediately
658 select {
659 case highPriorityLink <- []string{link}:
660 default:
661 // Channel already has a high priority link
662 }
663 break
664 }
665 }
666 }
667
668 results <- result{
669 index: idx,
670 links: links,
671 }
672 }(i, sourceUrl)
673 }
674
675 // Collect results with timeout
676 timeout := time.After(10 * time.Second)
677 var collectedErrors []error
678 successCount := 0
679
680 // First, try to get a high priority link
681 select {
682 case links := <-highPriorityLink:
683 return links, nil
684 case <-time.After(2 * time.Second): // Wait only briefly for high priority link
685 // No high priority link found quickly, proceed with normal collection
686 }
687
688 // Continue with existing result collection logic
689 // Collect results maintaining order
690 completedCount := 0
691 for completedCount < len(validURLs) {
692 select {
693 case res := <-results:
694 completedCount++
695 if res.err != nil {
696 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
697 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
698 } else {
699 orderedResults[res.index] = res.links
700 successCount++
701 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
702 }
703 case <-timeout:
704 if successCount > 0 {
705 Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
706 // Flatten available results
707 return flattenResults(orderedResults), nil
708 }
709 return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
710 }
711 }
712
713 // If we have any errors but also some successes, log errors but continue
714 if len(collectedErrors) > 0 {
715 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
716 }
717
718 // Flatten and return results
719 allLinks := flattenResults(orderedResults)
720 if len(allLinks) == 0 {
721 return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
722 }
723
724 return allLinks, nil
725}
726
727// converts the ordered slice of link slices into a single slice
728func flattenResults(results [][]string) []string {
729 var totalLen int
730 for _, r := range results {
731 totalLen += len(r)
732 }
733
734 allLinks := make([]string, 0, totalLen)
735 for _, links := range results {
736 allLinks = append(allLinks, links...)
737 }
738 return allLinks
739}