internal/anime_list.go
195 lines · 5078 bytes
1package internal
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "path/filepath"
10 "strings"
11)
12
13type anime struct {
14 ID string `json:"_id"`
15 Name string `json:"name"`
16 EnglishName string `json:"englishName"`
17 Thumbnail string `json:"thumbnail"`
18 AvailableEpisodes interface{} `json:"availableEpisodes"`
19}
20
21type response struct {
22 Data struct {
23 Shows struct {
24 Edges []anime `json:"edges"`
25 } `json:"shows"`
26 } `json:"data"`
27}
28
29func normalizeTranslationType(mode string) string {
30 if strings.EqualFold(strings.TrimSpace(mode), "dub") {
31 return "dub"
32 }
33 return "sub"
34}
35
36func alternateTranslationType(mode string) string {
37 if normalizeTranslationType(mode) == "dub" {
38 return "sub"
39 }
40 return "dub"
41}
42
43// func main() {
44// // Get environment variables
45// mode := "sub"
46
47// // Query for the anime (from a file in this example)
48// query := "one piece"
49
50// // Search anime
51// animeList, err := SearchAnime(string(query), mode)
52// if err != nil {
53
54// }
55// fmt.Println(animeList)
56// }
57
58func searchAllAnime(query, mode string) ([]SelectionOption, error) {
59 preferredMode := normalizeTranslationType(mode)
60 return searchAnimeByMode(query, preferredMode, preferredMode)
61}
62
63func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, error) {
64 userCurdConfig := GetGlobalConfig()
65 logFile = filepath.Join(GetStoragePath(), "debug.log")
66 const (
67 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
68 allanimeRef = "https://allanime.to"
69 allanimeBase = "allanime.day"
70 allanimeAPI = "https://api." + allanimeBase + "/api"
71 )
72
73 mode = normalizeTranslationType(mode)
74 preferredMode = normalizeTranslationType(preferredMode)
75
76 animeList := make([]SelectionOption, 0)
77
78 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
79 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
80 edges {
81 _id
82 name
83 englishName
84 thumbnail
85 availableEpisodes
86 __typename
87 }
88 }
89 }`
90
91 // Prepare the GraphQL variables
92 variables := map[string]interface{}{
93 "search": map[string]interface{}{
94 "allowAdult": false,
95 "allowUnknown": false,
96 "query": query,
97 },
98 "limit": 40,
99 "page": 1,
100 "translationType": mode,
101 "countryOrigin": "ALL",
102 }
103
104 // Build POST request body
105 requestBody, err := json.Marshal(map[string]interface{}{
106 "query": searchGql,
107 "variables": variables,
108 })
109 if err != nil {
110 Log(fmt.Sprintf("Error encoding request body to JSON: %v", err))
111 return animeList, err
112 }
113
114 // Make the HTTP POST request
115 req, err := http.NewRequest("POST", allanimeAPI, bytes.NewBuffer(requestBody))
116 if err != nil {
117 Log(fmt.Sprintf("Error creating HTTP request: %v", err))
118 return animeList, err
119 }
120 req.Header.Set("Content-Type", "application/json")
121 req.Header.Set("User-Agent", agent)
122 req.Header.Set("Referer", allanimeRef)
123 req.Header.Set("Origin", allanimeRef)
124
125 resp, err := sharedHTTPClient.Do(req)
126 if err != nil {
127 Log(fmt.Sprintf("Error making HTTP request: %v", err))
128 return animeList, err
129 }
130 defer resp.Body.Close()
131
132 // Read the response body
133 body, err := io.ReadAll(resp.Body)
134 if err != nil {
135 Log(fmt.Sprintf("Error reading response body: %v", err))
136 return animeList, err
137 }
138
139 // Debug: Log the response status and first part of the body
140 Log(fmt.Sprintf("Response Status: %s", resp.Status))
141 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
142 if !httpStatusOK(resp.StatusCode) {
143 err := httpStatusError("allanime search", resp.StatusCode, body)
144 Log(err)
145 return animeList, err
146 }
147
148 // Parse the JSON response
149 var response response
150 err = json.Unmarshal(body, &response)
151 if err != nil {
152 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
153 return animeList, err
154 }
155
156 for _, anime := range response.Data.Shows.Edges {
157 var episodesStr string
158 if episodes, ok := anime.AvailableEpisodes.(map[string]interface{}); ok {
159 if modeEpisodes, ok := episodes[mode].(float64); ok {
160 episodesStr = fmt.Sprintf("%d", int(modeEpisodes))
161 } else {
162 episodesStr = "Unknown"
163 }
164 } else {
165 episodesStr = "Unknown"
166 }
167
168 // Use English name if available and configured, otherwise use default name
169 displayName := anime.Name
170 if anime.EnglishName != "" && userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" {
171 displayName = anime.EnglishName
172 }
173
174 label := fmt.Sprintf("%s (%s episodes)", displayName, episodesStr)
175 if mode != preferredMode {
176 label = fmt.Sprintf("%s [%s]", label, mode)
177 }
178
179 animeList = append(animeList, SelectionOption{
180 Title: displayName,
181 Key: anime.ID,
182 Label: label,
183 Thumbnail: anime.Thumbnail,
184 })
185 }
186 return animeList, nil
187}
188
189// Helper function
190func min(a, b int) int {
191 if a < b {
192 return a
193 }
194 return b
195}