Commit b08e4daf8f

b08e4daf8f39ae39d3731e62a8194b0036e1e9c1

parent: 1f81a2763a

Unsigned

Wraient <wraient.911@gmail.com> · 2024-10-17 23:26 UTC

working episode url thing

Layout: unified · split

internal/episode_url.go +61 −189
@@ -9,6 +9,7 @@ import (
99 "os"
1010 "regexp"
1111 "strings"
12 "unicode"
1213)
1314
1415type Config struct {
@@ -16,40 +17,36 @@ type Config struct {
1617 AllanimeRefr string
1718 AllanimeBase string
1819 AllanimeAPI string
19 SubOrDub string
2020 Mode string
2121 Quality string
2222}
2323
24type AllanimeResponse struct {
25 Data struct {
26 Episode struct {
27 SourceUrls []struct {
28 SourceUrl string `json:"sourceUrl"`
29 } `json:"sourceUrls"`
30 } `json:"episode"`
31 } `json:"data"`
32}
33
2434func getDefaultConfig() Config {
25 mode := os.Getenv("ANI_CLI_MODE")
26 if mode == "" {
27 mode = "sub"
28 }
2935 return Config{
3036 Agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0",
3137 AllanimeRefr: "https://allanime.to",
3238 AllanimeBase: "allanime.day",
3339 AllanimeAPI: "https://api.allanime.day",
34 SubOrDub: "sub",
35 Mode: mode,
36 Quality: getEnvOrDefault("ANI_CLI_QUALITY", "best"),
37 }
38}
39
40func getEnvOrDefault(key, defaultValue string) string {
41 if value := os.Getenv(key); value != "" {
42 return value
40 Mode: "dub",
41 Quality: "best",
4342 }
44 return defaultValue
4543}
4644
47
4845func decodeProviderID(encoded string) string {
4946 // Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
5047 re := regexp.MustCompile("..")
5148 pairs := re.FindAllString(encoded, -1)
52
49
5350 // Mapping for the replacements
5451 replacements := map[string]string{
5552 "01": "9", "08": "0", "05": "=", "0a": "2", "0b": "3", "0c": "4", "07": "?",
@@ -58,169 +55,27 @@ func decodeProviderID(encoded string) string {
5855 "1e": "&", "5a": "b", "59": "a", "4a": "r", "4c": "t", "4e": "v", "57": "o",
5956 "51": "i",
6057 }
61
58
6259 // Perform the replacement equivalent to sed 's/^../.../'
6360 for i, pair := range pairs {
6461 if val, exists := replacements[pair]; exists {
6562 pairs[i] = val
6663 }
6764 }
68
65
6966 // Join the modified pairs back into a single string
7067 result := strings.Join(pairs, "")
71
68
7269 // Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
7370 result = strings.ReplaceAll(result, "/clock", "/clock.json")
74
71
7572 // Print the final result
7673 return result
7774}
7875
79func getLinks(config Config, providerID string) ([]string, error) {
80 url := fmt.Sprintf("https://%s%s", config.AllanimeBase, providerID)
81 req, err := http.NewRequest("GET", url, nil)
82 if err != nil {
83 return nil, err
84 }
85
86 req.Header.Set("User-Agent", config.Agent)
87 req.Header.Set("Referer", config.AllanimeRefr)
88
89 client := &http.Client{}
90 resp, err := client.Do(req)
91 if err != nil {
92 return nil, err
93 }
94 defer resp.Body.Close()
95
96 body, err := ioutil.ReadAll(resp.Body)
97 if err != nil {
98 return nil, err
99 }
100
101 bodyStr := string(body)
102 var links []string
103
104 // Extract links with their qualities
105 re := regexp.MustCompile(`link":"([^"]*)".*?"resolutionStr":"([^"]*)"`)
106 matches := re.FindAllStringSubmatch(bodyStr, -1)
107 for _, match := range matches {
108 if len(match) >= 3 {
109 link := fmt.Sprintf("%s>%s", match[2], match[1])
110 links = append(links, link)
111 }
112 }
113
114 // Extract m3u8 links
115 re = regexp.MustCompile(`hls","url":"([^"]*)".*?"hardsub_lang":"en-US"`)
116 matches = re.FindAllStringSubmatch(bodyStr, -1)
117 for _, match := range matches {
118 if len(match) >= 2 {
119 links = append(links, match[1])
120 }
121 }
122
123 // Process links based on provider type
124 var processedLinks []string
125 for _, link := range links {
126 if strings.Contains(link, "repackager.wixmp.com") {
127 parts := strings.Split(link, ">")
128 if len(parts) == 2 {
129 extractLink := parts[1]
130 extractLink = strings.ReplaceAll(extractLink, "repackager.wixmp.com/", "")
131 extractLink = regexp.MustCompile(`\.urlset.*`).ReplaceAllString(extractLink, "")
132
133 re = regexp.MustCompile(`/,([^/]*),/mp4`)
134 matches = re.FindAllStringSubmatch(link, -1)
135 for _, match := range matches {
136 if len(match) >= 2 {
137 quality := match[1]
138 newLink := fmt.Sprintf("%s>%s", quality, extractLink)
139 newLink = strings.ReplaceAll(newLink, ","+quality, quality)
140 processedLinks = append(processedLinks, newLink)
141 }
142 }
143 }
144 } else if strings.Contains(link, "vipanicdn") || strings.Contains(link, "anifastcdn") {
145 if strings.Contains(link, "original.m3u") {
146 processedLinks = append(processedLinks, link)
147 } else {
148 parts := strings.Split(link, ">")
149 if len(parts) > 0 {
150 extractLink := parts[0]
151 relativeLink := regexp.MustCompile(`[^/]*$`).ReplaceAllString(extractLink, "")
152
153 // Fetch m3u8 content
154 req, err := http.NewRequest("GET", extractLink, nil)
155 if err != nil {
156 continue
157 }
158 req.Header.Set("User-Agent", config.Agent)
159 req.Header.Set("Referer", config.AllanimeRefr)
160
161 resp, err := client.Do(req)
162 if err != nil {
163 continue
164 }
165 m3u8Content, err := ioutil.ReadAll(resp.Body)
166 resp.Body.Close()
167 if err != nil {
168 continue
169 }
170
171 lines := strings.Split(string(m3u8Content), "\n")
172 for i := 0; i < len(lines); i++ {
173 line := lines[i]
174 if strings.HasPrefix(line, "#") {
175 continue
176 }
177 quality := regexp.MustCompile(`x(\d+)`).ReplaceAllString(line, "$1")
178 if quality != "" {
179 processedLinks = append(processedLinks, fmt.Sprintf("%sp>%s%s", quality, relativeLink, line))
180 }
181 }
182 }
183 }
184 } else if link != "" {
185 processedLinks = append(processedLinks, link)
186 }
187 }
188
189 return processedLinks, nil
190}
191
192func generateLink(config Config, resp string, providerType int) ([]string, error) {
193 var pattern string
194 switch providerType {
195 case 1:
196 pattern = `/Default :([^\n]+)`
197 case 2:
198 pattern = `/Sak :([^\n]+)`
199 case 3:
200 pattern = `/Kir :([^\n]+)`
201 case 4:
202 pattern = `/S-mp4 :([^\n]+)`
203 default:
204 pattern = `/Luf-mp4 :([^\n]+)`
205 }
206
207 re := regexp.MustCompile(pattern)
208 matches := re.FindStringSubmatch(resp)
209 if len(matches) < 2 {
210 return nil, fmt.Errorf("no provider ID found")
211 }
212
213 providerID := decodeProviderID(matches[1])
214 if strings.Contains(providerID, "/clock") {
215 providerID = strings.Replace(providerID, "/clock", "/clock.json", 1)
216 }
217
218 return getLinks(config, providerID)
219}
220
221func extract_link(provider_id string) map[string]interface{} {
76func extractLinks(provider_id string) map[string]interface{} {
22277 allanime_base := "https://allanime.day"
223 url := allanime_base+provider_id
78 url := allanime_base + provider_id
22479 client := &http.Client{}
22580 req, err := http.NewRequest("GET", url, nil)
22681 var videoData map[string]interface{}
@@ -257,9 +112,19 @@ func extract_link(provider_id string) map[string]interface{} {
257112
258113 // Process the data as needed
259114 return videoData
260
261115}
262116
117// Get anime episode url respective to given config
118// If the link is found, it returns a list of links. Otherwise, it returns an error.
119//
120// Parameters:
121// - config: Configuration of the anime search.
122// - id: Allanime id of the anime to search for.
123// - epNo: Anime episode number to get links for.
124//
125// Returns:
126// - []string: a list of links for specified episode.
127// - error: an error if the episode is not found or if there is an issue during the search.
263128func getEpisodeURL(config Config, id, epNo string) ([]string, error) {
264129 query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
265130
@@ -300,39 +165,46 @@ func getEpisodeURL(config Config, id, epNo string) ([]string, error) {
300165 return nil, err
301166 }
302167
303 // Transform response similar to the bash script
304168 responseStr := string(body)
305 responseStr = strings.ReplaceAll(responseStr, "\\u002F", "/")
306 responseStr = strings.ReplaceAll(responseStr, "\\", "")
307 responseStr = strings.ReplaceAll(responseStr, "{", "\n")
308 responseStr = strings.ReplaceAll(responseStr, "}", "\n")
309
310 // fmt.Println(responseStr)
311
312 re := regexp.MustCompile(`sourceUrl":"--([^"]*)".*?sourceName":"([^"]*)"`)
313 matches := re.FindAllStringSubmatch(responseStr, -1)
314169
315 if len(matches) == 0 {
316 return nil, fmt.Errorf("no source URLs found")
170 // Unmarshal the JSON data into the struct
171 var response AllanimeResponse
172 err = json.Unmarshal([]byte(responseStr), &response)
173 if err != nil {
174 fmt.Println("Error parsing JSON: ", err)
317175 }
318176
319 var allLinks []string
320 for providerType := 1; providerType <= 5; providerType++ {
321 links, err := generateLink(config, responseStr, providerType)
322 if err == nil && len(links) > 0 {
323 allLinks = append(allLinks, links...)
177 var allinks []string // This will be returned
178
179 // Iterate through the SourceUrls and print each URL
180 for _, url := range response.Data.Episode.SourceUrls {
181 if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) { // Source Url 3rd letter is a number (it stars as --32f23k31jk)
182 decodedProviderID := decodeProviderID(url.SourceUrl[2:]) // Decode the source url to get the provider id
183 extractedLinks := extractLinks(decodedProviderID) // Extract the links using provider id
184 if linksInterface, ok := extractedLinks["links"].([]interface{}); ok {
185 for _, linkInterface := range linksInterface {
186 if linkMap, ok := linkInterface.(map[string]interface{}); ok {
187 if link, ok := linkMap["link"].(string); ok {
188 allinks = append(allinks, link) // Add all extracted links into allinks
189 }
190 }
191 }
192 } else {
193 fmt.Println("Links field is not of the expected type []interface{}")
194 }
324195 }
325196 }
326197
327 return allLinks, nil
198 return allinks, nil
328199}
329200
330201func main() {
331202 config := getDefaultConfig()
332
333 id := "RezHft5pjutwWcE3B"
334 epNo := "12"
335
203
204 id := "ReooPAxPMsHM4KPMY" // One piece
205 // id := "RezHft5pjutwWcE3B" // Death note
206 epNo := "945"
207
336208 links, err := getEpisodeURL(config, id, epNo)
337209 if err != nil {
338210 fmt.Printf("Error: %v\n", err)
@@ -343,7 +215,7 @@ func main() {
343215 }
344216
345217 // Print all found links
346 fmt.Println("links:", links)
218 // fmt.Println("links:", links)
347219 for _, link := range links {
348220 fmt.Println(link)
349221 }