internal/episode_url.go

179 lines · 5269 bytes

  1package internal
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"io"
  7	"net/http"
  8	"net/url"
  9	"regexp"
 10	"strings"
 11	"unicode"
 12)
 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), logFile)
 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), logFile)
 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), logFile)
 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), logFile)
 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	responseStr := string(body)
149
150	// Unmarshal the JSON data into the struct
151	var response allanimeResponse
152	err = json.Unmarshal([]byte(responseStr), &response)
153	if err != nil {
154		Log(fmt.Sprint("Error parsing JSON: ", err), logFile)
155	}
156
157	var allinks []string // This will be returned
158
159	// Iterate through the SourceUrls and print each URL
160	for _, url := range response.Data.Episode.SourceUrls {
161		if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) { // Source Url 3rd letter is a number (it stars as --32f23k31jk)
162			decodedProviderID := decodeProviderID(url.SourceUrl[2:]) // Decode the source url to get the provider id
163			extractedLinks := extractLinks(decodedProviderID) // Extract the links using provider id
164			if linksInterface, ok := extractedLinks["links"].([]interface{}); ok {
165				for _, linkInterface := range linksInterface {
166					if linkMap, ok := linkInterface.(map[string]interface{}); ok {
167						if link, ok := linkMap["link"].(string); ok {
168							allinks = append(allinks, link) // Add all extracted links into allinks 
169						}
170					}
171				}
172			} else {
173				Log("Links field is not of the expected type []interface{}", logFile)
174			}
175		}
176	}
177
178	return allinks, nil
179}