internal/episode_list.go
113 lines · 3243 bytes
1package internal
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "sort"
10 "strconv"
11)
12
13type episodesResponse struct {
14 Data struct {
15 Show struct {
16 ID string `json:"_id"`
17 AvailableEpisodesDetail map[string]interface{} `json:"availableEpisodesDetail"`
18 } `json:"show"`
19 } `json:"data"`
20}
21
22// func main() {
23// // Get environment variables
24// // Read the ID from the file
25// id := "ReooPAxPMsHM4KPMY"
26
27// // Fetch episodes list
28// episodeList := episodesList(string(id), "sub")
29
30// // Write the episode list to a file
31// fmt.Println(episodeList)
32// }
33
34// episodesList performs the API call and fetches the episodes list
35func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
36 preferredMode := normalizeTranslationType(mode)
37
38 episodesListGql := `query ($showId: String!) { show( _id: $showId ) { _id availableEpisodesDetail }}`
39
40 // Build POST request body
41 requestBody, err := json.Marshal(map[string]interface{}{
42 "query": episodesListGql,
43 "variables": map[string]string{"showId": showID},
44 })
45 if err != nil {
46 return nil, fmt.Errorf("failed to marshal request body: %w", err)
47 }
48
49 // Make the HTTP POST request
50 req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
51 if err != nil {
52 return nil, fmt.Errorf("failed to create request: %w", err)
53 }
54 req.Header.Set("Content-Type", "application/json")
55 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
56 req.Header.Set("Referer", "https://allanime.to")
57 req.Header.Set("Origin", "https://allanime.to")
58
59 resp, err := sharedHTTPClient.Do(req)
60 if err != nil {
61 Log(fmt.Sprint("Error making HTTP request:", err))
62 return nil, err
63 }
64 defer resp.Body.Close()
65
66 body, err := io.ReadAll(resp.Body)
67 if err != nil {
68 Log(fmt.Sprint("Error reading response body:", err))
69 return nil, err
70 }
71 if !httpStatusOK(resp.StatusCode) {
72 return nil, httpStatusError("allanime episode list", resp.StatusCode, body)
73 }
74
75 // Parse the JSON response
76 var response episodesResponse
77 err = json.Unmarshal(body, &response)
78 if err != nil {
79 Log(fmt.Sprint("Error parsing JSON:", err))
80 return nil, err
81 }
82
83 // Extract and sort the episodes
84 episodes := extractEpisodes(response.Data.Show.AvailableEpisodesDetail, preferredMode)
85 if len(episodes) == 0 {
86 return episodes, fmt.Errorf("no %s episodes found for anime %s", preferredMode, showID)
87 }
88 return episodes, nil
89}
90
91// extractEpisodes extracts the episodes list from the availableEpisodesDetail field
92func extractEpisodes(availableEpisodesDetail map[string]interface{}, mode string) []string {
93 var episodes []float64
94
95 // Check if the mode (e.g., "sub") exists in the map
96 if eps, ok := availableEpisodesDetail[mode].([]interface{}); ok {
97 for _, ep := range eps {
98 if epNum, err := strconv.ParseFloat(fmt.Sprintf("%v", ep), 64); err == nil {
99 episodes = append(episodes, epNum)
100 }
101 }
102 }
103
104 // Sort episodes numerically
105 sort.Float64s(episodes)
106
107 // Convert to string and return
108 var episodesStr []string
109 for _, ep := range episodes {
110 episodesStr = append(episodesStr, fmt.Sprintf("%v", ep))
111 }
112 return episodesStr
113}