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 (
9 "os" 9 "os"
10 "regexp" 10 "regexp"
11 "strings" 11 "strings"
12 "unicode"
12) 13)
13 14
14type Config struct { 15type Config struct {
@@ -16,40 +17,36 @@ type Config struct {
16 AllanimeRefr string 17 AllanimeRefr string
17 AllanimeBase string 18 AllanimeBase string
18 AllanimeAPI string 19 AllanimeAPI string
19 SubOrDub string
20 Mode string 20 Mode string
21 Quality string 21 Quality string
22} 22}
23 23
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
24func getDefaultConfig() Config { 34func getDefaultConfig() Config {
25 mode := os.Getenv("ANI_CLI_MODE")
26 if mode == "" {
27 mode = "sub"
28 }
29 return Config{ 35 return Config{
30 Agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0", 36 Agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0",
31 AllanimeRefr: "https://allanime.to", 37 AllanimeRefr: "https://allanime.to",
32 AllanimeBase: "allanime.day", 38 AllanimeBase: "allanime.day",
33 AllanimeAPI: "https://api.allanime.day", 39 AllanimeAPI: "https://api.allanime.day",
34 SubOrDub: "sub", 40 Mode: "dub",
35 Mode: mode, 41 Quality: "best",
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
43 } 42 }
44 return defaultValue
45} 43}
46 44
47
48func decodeProviderID(encoded string) string { 45func decodeProviderID(encoded string) string {
49 // Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g') 46 // Split the string into pairs of characters (.. equivalent of 'sed s/../&\n/g')
50 re := regexp.MustCompile("..") 47 re := regexp.MustCompile("..")
51 pairs := re.FindAllString(encoded, -1) 48 pairs := re.FindAllString(encoded, -1)
52 49
53 // Mapping for the replacements 50 // Mapping for the replacements
54 replacements := map[string]string{ 51 replacements := map[string]string{
55 "01": "9", "08": "0", "05": "=", "0a": "2", "0b": "3", "0c": "4", "07": "?", 52 "01": "9", "08": "0", "05": "=", "0a": "2", "0b": "3", "0c": "4", "07": "?",
@@ -58,169 +55,27 @@ func decodeProviderID(encoded string) string {
58 "1e": "&", "5a": "b", "59": "a", "4a": "r", "4c": "t", "4e": "v", "57": "o", 55 "1e": "&", "5a": "b", "59": "a", "4a": "r", "4c": "t", "4e": "v", "57": "o",
59 "51": "i", 56 "51": "i",
60 } 57 }
61 58
62 // Perform the replacement equivalent to sed 's/^../.../' 59 // Perform the replacement equivalent to sed 's/^../.../'
63 for i, pair := range pairs { 60 for i, pair := range pairs {
64 if val, exists := replacements[pair]; exists { 61 if val, exists := replacements[pair]; exists {
65 pairs[i] = val 62 pairs[i] = val
66 } 63 }
67 } 64 }
68 65
69 // Join the modified pairs back into a single string 66 // Join the modified pairs back into a single string
70 result := strings.Join(pairs, "") 67 result := strings.Join(pairs, "")
71 68
72 // Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/" 69 // Replace "/clock" with "/clock.json" equivalent of sed "s/\/clock/\/clock\.json/"
73 result = strings.ReplaceAll(result, "/clock", "/clock.json") 70 result = strings.ReplaceAll(result, "/clock", "/clock.json")
74 71
75 // Print the final result 72 // Print the final result
76 return result 73 return result
77} 74}
78 75
79func getLinks(config Config, providerID string) ([]string, error) { 76func extractLinks(provider_id string) map[string]interface{} {
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{} {
222 allanime_base := "https://allanime.day" 77 allanime_base := "https://allanime.day"
223 url := allanime_base+provider_id 78 url := allanime_base + provider_id
224 client := &http.Client{} 79 client := &http.Client{}
225 req, err := http.NewRequest("GET", url, nil) 80 req, err := http.NewRequest("GET", url, nil)
226 var videoData map[string]interface{} 81 var videoData map[string]interface{}
@@ -257,9 +112,19 @@ func extract_link(provider_id string) map[string]interface{} {
257 112
258 // Process the data as needed 113 // Process the data as needed
259 return videoData 114 return videoData
260
261} 115}
262 116
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.
263func getEpisodeURL(config Config, id, epNo string) ([]string, error) { 128func getEpisodeURL(config Config, id, epNo string) ([]string, error) {
264 query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}` 129 query := `query($showId:String!,$translationType:VaildTranslationTypeEnumType!,$episodeString:String!){episode(showId:$showId,translationType:$translationType,episodeString:$episodeString){episodeString sourceUrls}}`
265 130
@@ -300,39 +165,46 @@ func getEpisodeURL(config Config, id, epNo string) ([]string, error) {
300 return nil, err 165 return nil, err
301 } 166 }
302 167
303 // Transform response similar to the bash script
304 responseStr := string(body) 168 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)
314 169
315 if len(matches) == 0 { 170 // Unmarshal the JSON data into the struct
316 return nil, fmt.Errorf("no source URLs found") 171 var response AllanimeResponse
172 err = json.Unmarshal([]byte(responseStr), &response)
173 if err != nil {
174 fmt.Println("Error parsing JSON: ", err)
317 } 175 }
318 176
319 var allLinks []string 177 var allinks []string // This will be returned
320 for providerType := 1; providerType <= 5; providerType++ { 178
321 links, err := generateLink(config, responseStr, providerType) 179 // Iterate through the SourceUrls and print each URL
322 if err == nil && len(links) > 0 { 180 for _, url := range response.Data.Episode.SourceUrls {
323 allLinks = append(allLinks, links...) 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 }
324 } 195 }
325 } 196 }
326 197
327 return allLinks, nil 198 return allinks, nil
328} 199}
329 200
330func main() { 201func main() {
331 config := getDefaultConfig() 202 config := getDefaultConfig()
332 203
333 id := "RezHft5pjutwWcE3B" 204 id := "ReooPAxPMsHM4KPMY" // One piece
334 epNo := "12" 205 // id := "RezHft5pjutwWcE3B" // Death note
335 206 epNo := "945"
207
336 links, err := getEpisodeURL(config, id, epNo) 208 links, err := getEpisodeURL(config, id, epNo)
337 if err != nil { 209 if err != nil {
338 fmt.Printf("Error: %v\n", err) 210 fmt.Printf("Error: %v\n", err)
@@ -343,7 +215,7 @@ func main() {
343 } 215 }
344 216
345 // Print all found links 217 // Print all found links
346 fmt.Println("links:", links) 218 // fmt.Println("links:", links)
347 for _, link := range links { 219 for _, link := range links {
348 fmt.Println(link) 220 fmt.Println(link)
349 } 221 }