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