internal/episode_url.go

285 lines · 7901 bytes

  1package internal
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"io"
  7	"net/http"
  8	"net/url"
  9	"regexp"
 10	"strings"
 11	"time"
 12	"unicode"
 13)
 14
 15type allanimeResponse struct {
 16	Data struct {
 17		Episode struct {
 18			SourceUrls []struct {
 19				SourceUrl string `json:"sourceUrl"`
 20			} `json:"sourceUrls"`
 21		} `json:"episode"`
 22	} `json:"data"`
 23}
 24
 25func decodeProviderID(encoded string) string {
 26	// Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
 27	re := regexp.MustCompile("..")
 28	pairs := re.FindAllString(encoded, -1)
 29
 30	// Mapping for the replacements
 31	replacements := map[string]string{
 32		"01": "9", "08": "0", "05": "=", "0a": "2", "0b": "3", "0c": "4", "07": "?",
 33		"00": "8", "5c": "d", "0f": "7", "5e": "f", "17": "/", "54": "l", "09": "1",
 34		"48": "p", "4f": "w", "0e": "6", "5b": "c", "5d": "e", "0d": "5", "53": "k",
 35		"1e": "&", "5a": "b", "59": "a", "4a": "r", "4c": "t", "4e": "v", "57": "o",
 36		"51": "i",
 37	}
 38
 39	// Perform the replacement equivalent to sed 's/^../.../'
 40	for i, pair := range pairs {
 41		if val, exists := replacements[pair]; exists {
 42			pairs[i] = val
 43		}
 44	}
 45
 46	// Join the modified pairs back into a single string
 47	result := strings.Join(pairs, "")
 48
 49	// Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
 50	result = strings.ReplaceAll(result, "/clock", "/clock.json")
 51
 52	// Print the final result
 53	return result
 54}
 55
 56func extractLinks(provider_id string) map[string]interface{} {
 57	allanime_base := "https://allanime.day"
 58	url := allanime_base + provider_id
 59	client := &http.Client{}
 60	req, err := http.NewRequest("GET", url, nil)
 61	var videoData map[string]interface{}
 62	if err != nil {
 63		Log(fmt.Sprint("Error creating request:", err))
 64		return videoData
 65	}
 66
 67	// Add the headers
 68	req.Header.Set("Referer", "https://allanime.to")
 69	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
 70
 71	// Send the request
 72	resp, err := client.Do(req)
 73	if err != nil {
 74		Log(fmt.Sprint("Error sending request:", err))
 75		return videoData
 76	}
 77	defer resp.Body.Close()
 78
 79	// Read the response body
 80	body, err := io.ReadAll(resp.Body)
 81	if err != nil {
 82		Log(fmt.Sprint("Error reading response:", err))
 83		return videoData
 84	}
 85
 86	// Parse the JSON response
 87	err = json.Unmarshal(body, &videoData)
 88	if err != nil {
 89		Log(fmt.Sprint("Error parsing JSON:", err))
 90		return videoData
 91	}
 92
 93	// Process the data as needed
 94	return videoData
 95}
 96
 97// Get anime episode url respective to given config
 98// If the link is found, it returns a list of links. Otherwise, it returns an error.
 99//
100// Parameters:
101// - config: Configuration of the anime search.
102// - id: Allanime id of the anime to search for.
103// - epNo: Anime episode number to get links for.
104//
105// Returns:
106// - []string: a list of links for specified episode.
107// - error: an error if the episode is not found or if there is an issue during the search.
108func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
109	query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
110
111	variables := map[string]string{
112		"showId":          id,
113		"translationType": config.SubOrDub,
114		"episodeString":   fmt.Sprintf("%d", epNo),
115	}
116
117	variablesJSON, err := json.Marshal(variables)
118	if err != nil {
119		return nil, err
120	}
121
122	values := url.Values{}
123	values.Set("query", query)
124	values.Set("variables", string(variablesJSON))
125
126	reqURL := fmt.Sprintf("%s/api?%s", "https://api.allanime.day", values.Encode())
127
128	client := &http.Client{}
129	req, err := http.NewRequest("GET", reqURL, nil)
130	if err != nil {
131		return nil, err
132	}
133
134	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
135	req.Header.Set("Referer", "https://allanime.to")
136
137	resp, err := client.Do(req)
138	if err != nil {
139		return nil, err
140	}
141	defer resp.Body.Close()
142
143	body, err := io.ReadAll(resp.Body)
144	if err != nil {
145		return nil, err
146	}
147
148	var response allanimeResponse
149	err = json.Unmarshal(body, &response)
150	if err != nil {
151		Log(fmt.Sprint("Error parsing JSON: ", err))
152		return nil, err
153	}
154
155	type result struct {
156		index int
157		links []string
158		err   error
159	}
160
161	// Pre-count valid URLs and create slice to preserve order
162	validURLs := make([]string, 0)
163	for _, url := range response.Data.Episode.SourceUrls {
164		if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
165			validURLs = append(validURLs, url.SourceUrl)
166		}
167	}
168
169	if len(validURLs) == 0 {
170		return nil, fmt.Errorf("no valid source URLs found in response")
171	}
172
173	// Create channels for results and a slice to store ordered results
174	results := make(chan result, len(validURLs))
175	orderedResults := make([][]string, len(validURLs))
176
177	// Create rate limiter
178	rateLimiter := time.NewTicker(50 * time.Millisecond)
179	defer rateLimiter.Stop()
180
181	// Launch goroutines
182	for i, sourceUrl := range validURLs {
183		go func(idx int, url string) {
184			<-rateLimiter.C // Rate limit the requests
185
186			decodedProviderID := decodeProviderID(url[2:])
187			Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
188
189			extractedLinks := extractLinks(decodedProviderID)
190
191			if extractedLinks == nil {
192				results <- result{
193					index: idx,
194					err:   fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
195				}
196				return
197			}
198
199			linksInterface, ok := extractedLinks["links"].([]interface{})
200			if !ok {
201				results <- result{
202					index: idx,
203					err:   fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
204				}
205				return
206			}
207
208			var links []string
209			for _, linkInterface := range linksInterface {
210				linkMap, ok := linkInterface.(map[string]interface{})
211				if !ok {
212					Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
213					continue
214				}
215
216				link, ok := linkMap["link"].(string)
217				if !ok {
218					Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
219					continue
220				}
221
222				links = append(links, link)
223			}
224
225			results <- result{
226				index: idx,
227				links: links,
228			}
229		}(i, sourceUrl)
230	}
231
232	// Collect results with timeout
233	timeout := time.After(10 * time.Second)
234	var collectedErrors []error
235	successCount := 0
236
237	// Collect results maintaining order
238	for successCount < len(validURLs) {
239		select {
240		case res := <-results:
241			if res.err != nil {
242				Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
243				collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
244			} else {
245				orderedResults[res.index] = res.links
246				successCount++
247				Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
248			}
249		case <-timeout:
250			if successCount > 0 {
251				Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
252				// Flatten available results
253				return flattenResults(orderedResults), nil
254			}
255			return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
256		}
257	}
258
259	// If we have any errors but also some successes, log errors but continue
260	if len(collectedErrors) > 0 {
261		Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
262	}
263
264	// Flatten and return results
265	allLinks := flattenResults(orderedResults)
266	if len(allLinks) == 0 {
267		return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
268	}
269
270	return allLinks, nil
271}
272
273// converts the ordered slice of link slices into a single slice
274func flattenResults(results [][]string) []string {
275	var totalLen int
276	for _, r := range results {
277		totalLen += len(r)
278	}
279
280	allLinks := make([]string, 0, totalLen)
281	for _, links := range results {
282		allLinks = append(allLinks, links...)
283	}
284	return allLinks
285}