internal/episode_url.go

221 lines · 6117 bytes

  1package internal
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"io/ioutil"
  7	"net/http"
  8	"net/url"
  9	"regexp"
 10	"strings"
 11	"unicode"
 12)
 13
 14type config struct {
 15	Agent        string
 16	AllanimeRefr string
 17	AllanimeBase string
 18	AllanimeAPI  string
 19	Mode         string
 20	Quality      string
 21}
 22
 23type allanimeResponse struct {
 24	Data struct {
 25		Episode struct {
 26			SourceUrls []struct {
 27				SourceUrl string `json:"sourceUrl"`
 28			} `json:"sourceUrls"`
 29		} `json:"episode"`
 30	} `json:"data"`
 31}
 32
 33func GetDefaultAllanimeConfig() config {
 34	return config{
 35		Agent:        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0",
 36		AllanimeRefr: "https://allanime.to",
 37		AllanimeBase: "allanime.day",
 38		AllanimeAPI:  "https://api.allanime.day",
 39		Mode:         "sub",
 40		Quality:      "best",
 41	}
 42}
 43
 44func decodeProviderID(encoded string) string {
 45	// Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
 46	re := regexp.MustCompile("..")
 47	pairs := re.FindAllString(encoded, -1)
 48
 49	// Mapping for the replacements
 50	replacements := map[string]string{
 51		"01": "9", "08": "0", "05": "=", "0a": "2", "0b": "3", "0c": "4", "07": "?",
 52		"00": "8", "5c": "d", "0f": "7", "5e": "f", "17": "/", "54": "l", "09": "1",
 53		"48": "p", "4f": "w", "0e": "6", "5b": "c", "5d": "e", "0d": "5", "53": "k",
 54		"1e": "&", "5a": "b", "59": "a", "4a": "r", "4c": "t", "4e": "v", "57": "o",
 55		"51": "i",
 56	}
 57
 58	// Perform the replacement equivalent to sed 's/^../.../'
 59	for i, pair := range pairs {
 60		if val, exists := replacements[pair]; exists {
 61			pairs[i] = val
 62		}
 63	}
 64
 65	// Join the modified pairs back into a single string
 66	result := strings.Join(pairs, "")
 67
 68	// Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
 69	result = strings.ReplaceAll(result, "/clock", "/clock.json")
 70
 71	// Print the final result
 72	return result
 73}
 74
 75func extractLinks(provider_id string) map[string]interface{} {
 76	allanime_base := "https://allanime.day"
 77	url := allanime_base + provider_id
 78	client := &http.Client{}
 79	req, err := http.NewRequest("GET", url, nil)
 80	var videoData map[string]interface{}
 81	if err != nil {
 82		fmt.Println("Error creating request:", err)
 83		return videoData
 84	}
 85
 86	// Add the headers
 87	req.Header.Set("Referer", "https://allanime.to")
 88	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
 89
 90	// Send the request
 91	resp, err := client.Do(req)
 92	if err != nil {
 93		fmt.Println("Error sending request:", err)
 94		return videoData
 95	}
 96	defer resp.Body.Close()
 97
 98	// Read the response body
 99	body, err := ioutil.ReadAll(resp.Body)
100	if err != nil {
101		fmt.Println("Error reading response:", err)
102		return videoData
103	}
104
105	// Parse the JSON response
106	err = json.Unmarshal(body, &videoData)
107	if err != nil {
108		fmt.Println("Error parsing JSON:", err)
109		return videoData
110	}
111
112	// Process the data as needed
113	return videoData
114}
115
116// Get anime episode url respective to given config 
117// If the link is found, it returns a list of links. Otherwise, it returns an error.
118//
119// Parameters:
120// - config: Configuration of the anime search.
121// - id: Allanime id of the anime to search for.
122// - epNo: Anime episode number to get links for.
123//
124// Returns:
125// - []string: a list of links for specified episode.
126// - error: an error if the episode is not found or if there is an issue during the search.
127func GetEpisodeURL(config config, id, epNo string) ([]string, error) {
128	query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
129
130	variables := map[string]string{
131		"showId":          id,
132		"translationType": config.Mode,
133		"episodeString":   epNo,
134	}
135
136	variablesJSON, err := json.Marshal(variables)
137	if err != nil {
138		return nil, err
139	}
140
141	values := url.Values{}
142	values.Set("query", query)
143	values.Set("variables", string(variablesJSON))
144
145	reqURL := fmt.Sprintf("%s/api?%s", config.AllanimeAPI, values.Encode())
146
147	client := &http.Client{}
148	req, err := http.NewRequest("GET", reqURL, nil)
149	if err != nil {
150		return nil, err
151	}
152
153	req.Header.Set("User-Agent", config.Agent)
154	req.Header.Set("Referer", config.AllanimeRefr)
155
156	resp, err := client.Do(req)
157	if err != nil {
158		return nil, err
159	}
160	defer resp.Body.Close()
161
162	body, err := ioutil.ReadAll(resp.Body)
163	if err != nil {
164		return nil, err
165	}
166
167	responseStr := string(body)
168
169	// Unmarshal the JSON data into the struct
170	var response allanimeResponse
171	err = json.Unmarshal([]byte(responseStr), &response)
172	if err != nil {
173		fmt.Println("Error parsing JSON: ", err)
174	}
175
176	var allinks []string // This will be returned
177
178	// Iterate through the SourceUrls and print each URL
179	for _, url := range response.Data.Episode.SourceUrls {
180		if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) { // Source Url 3rd letter is a number (it stars as --32f23k31jk)
181			decodedProviderID := decodeProviderID(url.SourceUrl[2:]) // Decode the source url to get the provider id
182			extractedLinks := extractLinks(decodedProviderID) // Extract the links using provider id
183			if linksInterface, ok := extractedLinks["links"].([]interface{}); ok {
184				for _, linkInterface := range linksInterface {
185					if linkMap, ok := linkInterface.(map[string]interface{}); ok {
186						if link, ok := linkMap["link"].(string); ok {
187							allinks = append(allinks, link) // Add all extracted links into allinks 
188						}
189					}
190				}
191			} else {
192				fmt.Println("Links field is not of the expected type []interface{}")
193			}
194		}
195	}
196
197	return allinks, nil
198}
199
200// func main() {
201// 	config := getDefaultConfig()
202
203// 	id := "ReooPAxPMsHM4KPMY" // One piece
204// 	// id := "RezHft5pjutwWcE3B" // Death note
205// 	epNo := "945"
206
207// 	links, err := getEpisodeURL(config, id, epNo)
208// 	if err != nil {
209// 		fmt.Printf("Error: %v\n", err)
210// 		if strings.Contains(err.Error(), "no source URLs found") {
211// 			fmt.Println("Episode not released!")
212// 		}
213// 		os.Exit(1)
214// 	}
215
216// 	// Print all found links
217// 	// fmt.Println("links:", links)
218// 	for _, link := range links {
219// 		fmt.Println(link)
220// 	}
221// }