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