internal/anime_list.go
225 lines · 6014 bytes
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
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 // Marshal the variables to JSON
141 variablesJSON, err := json.Marshal(variables)
142 if err != nil {
143 Log(fmt.Sprintf("Error encoding variables to JSON: %v", err))
144 return animeList, err
145 }
146
147 // Build the request URL
148 url := fmt.Sprintf("%s?variables=%s&query=%s", allanimeAPI, url.QueryEscape(string(variablesJSON)), url.QueryEscape(searchGql))
149
150 // Make the HTTP request
151 req, err := http.NewRequest("GET", url, nil)
152 if err != nil {
153 Log(fmt.Sprintf("Error creating HTTP request: %v", err))
154 return animeList, err
155 }
156 req.Header.Set("User-Agent", agent)
157 req.Header.Set("Referer", allanimeRef)
158
159 client := &http.Client{}
160 resp, err := client.Do(req)
161 if err != nil {
162 Log(fmt.Sprintf("Error making HTTP request: %v", err))
163 return animeList, err
164 }
165 defer resp.Body.Close()
166
167 // Read the response body
168 body, err := io.ReadAll(resp.Body)
169 if err != nil {
170 Log(fmt.Sprintf("Error reading response body: %v", err))
171 return animeList, err
172 }
173
174 // Debug: Log the response status and first part of the body
175 Log(fmt.Sprintf("Response Status: %s", resp.Status))
176 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
177
178 // Parse the JSON response
179 var response response
180 err = json.Unmarshal(body, &response)
181 if err != nil {
182 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
183 return animeList, err
184 }
185
186 for _, anime := range response.Data.Shows.Edges {
187 var episodesStr string
188 if episodes, ok := anime.AvailableEpisodes.(map[string]interface{}); ok {
189 if modeEpisodes, ok := episodes[mode].(float64); ok {
190 episodesStr = fmt.Sprintf("%d", int(modeEpisodes))
191 } else {
192 episodesStr = "Unknown"
193 }
194 } else {
195 episodesStr = "Unknown"
196 }
197
198 // Use English name if available and configured, otherwise use default name
199 displayName := anime.Name
200 if anime.EnglishName != "" && userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" {
201 displayName = anime.EnglishName
202 }
203
204 label := fmt.Sprintf("%s (%s episodes)", displayName, episodesStr)
205 if mode != preferredMode {
206 label = fmt.Sprintf("%s [%s]", label, mode)
207 }
208
209 animeList = append(animeList, SelectionOption{
210 Title: displayName,
211 Key: anime.ID,
212 Label: label,
213 Thumbnail: anime.Thumbnail,
214 })
215 }
216 return animeList, nil
217}
218
219// Helper function
220func min(a, b int) int {
221 if a < b {
222 return a
223 }
224 return b
225}