internal/episode_url.go
735 lines · 20877 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 getEpisodeURLForMode(id, preferredMode, epNo)
429}
430
431func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
432 const (
433 episodeQueryHash = "d405d0edd690624b66baba3068e0edc3ac90f1597d898a1ec8db4e5c43c00fec"
434 )
435
436 episodeEmbedGQL := `query ($showId: String!, $translationType: VaildTranslationTypeEnumType!, $episodeString: String!) { episode( showId: $showId translationType: $translationType episodeString: $episodeString ) { episodeString sourceUrls }}`
437
438 variables := map[string]interface{}{
439 "showId": id,
440 "translationType": normalizeTranslationType(mode),
441 "episodeString": fmt.Sprintf("%d", epNo),
442 }
443
444 extensions := map[string]interface{}{
445 "persistedQuery": map[string]interface{}{
446 "version": 1,
447 "sha256Hash": episodeQueryHash,
448 },
449 }
450
451 variablesJSON, err := json.Marshal(variables)
452 if err != nil {
453 return nil, fmt.Errorf("failed to marshal persisted query variables: %w", err)
454 }
455
456 extensionsJSON, err := json.Marshal(extensions)
457 if err != nil {
458 return nil, fmt.Errorf("failed to marshal persisted query extensions: %w", err)
459 }
460
461 persistedURL := "https://api.allanime.day/api?variables=" + url.QueryEscape(string(variablesJSON)) + "&extensions=" + url.QueryEscape(string(extensionsJSON))
462
463 req, err := http.NewRequest("GET", persistedURL, nil)
464 if err != nil {
465 return nil, fmt.Errorf("failed to create persisted query request: %w", err)
466 }
467 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
468 req.Header.Set("Referer", "https://allmanga.to")
469 req.Header.Set("Origin", "https://youtu-chan.com")
470
471 resp, err := sharedHTTPClient.Do(req)
472 if err != nil {
473 return nil, fmt.Errorf("failed to send persisted query request: %w", err)
474 }
475 body, err := io.ReadAll(resp.Body)
476 resp.Body.Close()
477 if err != nil {
478 return nil, fmt.Errorf("failed to read persisted query response: %w", err)
479 }
480 if !httpStatusOK(resp.StatusCode) {
481 return nil, httpStatusError("allanime episode persisted query", resp.StatusCode, body)
482 }
483
484 var response allanimeResponse
485 if err := json.Unmarshal(body, &response); err != nil {
486 Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
487 }
488
489 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
490 if useFallback {
491 query := episodeEmbedGQL
492
493 // Build POST request body
494 requestBody, err := json.Marshal(map[string]interface{}{
495 "query": query,
496 "variables": variables,
497 })
498 if err != nil {
499 return nil, fmt.Errorf("failed to marshal request body: %w", err)
500 }
501
502 req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
503 if err != nil {
504 return nil, fmt.Errorf("failed to create request: %w", err)
505 }
506
507 req.Header.Set("Content-Type", "application/json")
508 req.Header.Set("User-Agent", "Mozilla/5.0")
509 req.Header.Set("Referer", "https://allmanga.to")
510 req.Header.Set("Origin", "https://allanime.to")
511
512 resp, err := sharedHTTPClient.Do(req)
513 if err != nil {
514 return nil, fmt.Errorf("failed to send request: %w", err)
515 }
516 defer resp.Body.Close()
517
518 body, err := io.ReadAll(resp.Body)
519 if err != nil {
520 return nil, fmt.Errorf("failed to read response body: %w", err)
521 }
522 if !httpStatusOK(resp.StatusCode) {
523 return nil, httpStatusError("allanime episode fallback query", resp.StatusCode, body)
524 }
525
526 if err := json.Unmarshal(body, &response); err != nil {
527 Log(fmt.Sprint("Error parsing fallback JSON: ", err))
528 return nil, err
529 }
530 }
531
532 if response.Data.Tobeparsed != "" {
533 Log("Found tobeparsed field, decoding source URLs")
534 decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed)
535 if err != nil {
536 return nil, err
537 }
538
539 Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
540 return getLinksFromSourceUrls(decodedSources)
541 }
542
543 return getLinksFromSourceUrls(response.Data.Episode.SourceUrls)
544}
545
546func getLinksFromSourceUrls(sourceUrls []allanimeSource) ([]string, error) {
547 sourceUrls = sortAllanimeSourcesByPriority(sourceUrls)
548
549 directURLs := make([]string, 0)
550 validURLs := make([]string, 0)
551 highestPriority := -1.0
552 var highestPriorityURL string
553
554 for _, url := range sourceUrls {
555 sourceURL := strings.TrimSpace(url.SourceUrl)
556 if sourceURL == "" {
557 continue
558 }
559
560 if isDirectPlayableAllanimeSource(url) {
561 directURLs = append(directURLs, sourceURL)
562 continue
563 }
564
565 if !strings.HasPrefix(sourceURL, "--") || len(sourceURL) <= 2 {
566 Log(fmt.Sprintf("Skipping unsupported Allanime source %q (%s)", url.SourceName, sourceURL))
567 continue
568 }
569
570 decodedURL := decodeProviderID(sourceURL[2:])
571 if len(LinkPriorities) > 0 && strings.Contains(decodedURL, LinkPriorities[0]) {
572 priority := url.Priority
573 if priority > highestPriority {
574 highestPriority = priority
575 highestPriorityURL = sourceURL
576 }
577 } else {
578 validURLs = append(validURLs, sourceURL)
579 }
580 }
581
582 if len(directURLs) > 0 {
583 Log(fmt.Sprintf("Using %d direct Allanime source URL(s)", len(directURLs)))
584 return directURLs, nil
585 }
586
587 if highestPriorityURL != "" {
588 validURLs = []string{highestPriorityURL}
589 }
590
591 if len(validURLs) == 0 {
592 return nil, fmt.Errorf("no supported source URLs found in response")
593 }
594
595 return getLinksFromURLs(validURLs)
596}
597
598func getLinksFromURLs(validURLs []string) ([]string, error) {
599 results := make(chan result, len(validURLs))
600 orderedResults := make([][]string, len(validURLs))
601
602 highPriorityLink := make(chan []string, 1)
603
604 for i, sourceUrl := range validURLs {
605 go func(idx int, url string) {
606 decodedProviderID := decodeProviderID(url[2:])
607 Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
608
609 extractedLinks := extractLinks(decodedProviderID)
610
611 if extractedLinks == nil {
612 results <- result{
613 index: idx,
614 err: fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
615 }
616 return
617 }
618
619 linksInterface, ok := extractedLinks["links"].([]interface{})
620 if !ok {
621 results <- result{
622 index: idx,
623 err: fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
624 }
625 return
626 }
627
628 var links []string
629 for _, linkInterface := range linksInterface {
630 linkMap, ok := linkInterface.(map[string]interface{})
631 if !ok {
632 Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
633 continue
634 }
635
636 link, ok := linkMap["link"].(string)
637 if !ok {
638 Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
639 continue
640 }
641
642 links = append(links, link)
643 }
644
645 // Check if any of the extracted links are high priority
646 priorityDomains := LinkPriorities
647 if len(priorityDomains) > 3 {
648 priorityDomains = priorityDomains[:3]
649 }
650 for _, link := range links {
651 for _, domain := range priorityDomains {
652 if strings.Contains(link, domain) {
653 // Found high priority link, send it immediately
654 select {
655 case highPriorityLink <- []string{link}:
656 default:
657 // Channel already has a high priority link
658 }
659 break
660 }
661 }
662 }
663
664 results <- result{
665 index: idx,
666 links: links,
667 }
668 }(i, sourceUrl)
669 }
670
671 // Collect results with timeout
672 timeout := time.After(10 * time.Second)
673 var collectedErrors []error
674 successCount := 0
675
676 // First, try to get a high priority link
677 select {
678 case links := <-highPriorityLink:
679 return links, nil
680 case <-time.After(2 * time.Second): // Wait only briefly for high priority link
681 // No high priority link found quickly, proceed with normal collection
682 }
683
684 // Continue with existing result collection logic
685 // Collect results maintaining order
686 completedCount := 0
687 for completedCount < len(validURLs) {
688 select {
689 case res := <-results:
690 completedCount++
691 if res.err != nil {
692 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
693 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
694 } else {
695 orderedResults[res.index] = res.links
696 successCount++
697 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
698 }
699 case <-timeout:
700 if successCount > 0 {
701 Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
702 // Flatten available results
703 return flattenResults(orderedResults), nil
704 }
705 return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
706 }
707 }
708
709 // If we have any errors but also some successes, log errors but continue
710 if len(collectedErrors) > 0 {
711 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
712 }
713
714 // Flatten and return results
715 allLinks := flattenResults(orderedResults)
716 if len(allLinks) == 0 {
717 return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
718 }
719
720 return allLinks, nil
721}
722
723// converts the ordered slice of link slices into a single slice
724func flattenResults(results [][]string) []string {
725 var totalLen int
726 for _, r := range results {
727 totalLen += len(r)
728 }
729
730 allLinks := make([]string, 0, totalLen)
731 for _, links := range results {
732 allLinks = append(allLinks, links...)
733 }
734 return allLinks
735}