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