internal/anime_list.go
163 lines · 4231 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 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
29// func main() {
30// // Get environment variables
31// mode := "sub"
32
33// // Query for the anime (from a file in this example)
34// query := "one piece"
35
36// // Search anime
37// animeList, err := SearchAnime(string(query), mode)
38// if err != nil {
39
40// }
41// fmt.Println(animeList)
42// }
43
44func SearchAnime(query, mode string) ([]SelectionOption, error) {
45 userCurdConfig := GetGlobalConfig()
46 if userCurdConfig == nil {
47 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log")
48 } else {
49 logFile = filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log")
50 }
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 // Prepare the anime list
59 animeList := make([]SelectionOption, 0)
60
61 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
62 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
63 edges {
64 _id
65 name
66 englishName
67 availableEpisodes
68 __typename
69 }
70 }
71 }`
72
73 // Prepare the GraphQL variables
74 variables := map[string]interface{}{
75 "search": map[string]interface{}{
76 "allowAdult": false,
77 "allowUnknown": false,
78 "query": query,
79 },
80 "limit": 40,
81 "page": 1,
82 "translationType": mode,
83 "countryOrigin": "ALL",
84 }
85
86 // Marshal the variables to JSON
87 variablesJSON, err := json.Marshal(variables)
88 if err != nil {
89 Log(fmt.Sprintf("Error encoding variables to JSON: %v", err))
90 return animeList, err
91 }
92
93 // Build the request URL
94 url := fmt.Sprintf("%s?variables=%s&query=%s", allanimeAPI, url.QueryEscape(string(variablesJSON)), url.QueryEscape(searchGql))
95
96 // Make the HTTP request
97 req, err := http.NewRequest("GET", url, nil)
98 if err != nil {
99 Log(fmt.Sprintf("Error creating HTTP request: %v", err))
100 return animeList, err
101 }
102 req.Header.Set("User-Agent", agent)
103 req.Header.Set("Referer", allanimeRef)
104
105 client := &http.Client{}
106 resp, err := client.Do(req)
107 if err != nil {
108 Log(fmt.Sprintf("Error making HTTP request: %v", err))
109 return animeList, err
110 }
111 defer resp.Body.Close()
112
113 // Read the response body
114 body, err := io.ReadAll(resp.Body)
115 if err != nil {
116 Log(fmt.Sprintf("Error reading response body: %v", err))
117 return animeList, err
118 }
119
120 // Debug: Log the response status and first part of the body
121 Log(fmt.Sprintf("Response Status: %s", resp.Status))
122 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
123
124 // Parse the JSON response
125 var response response
126 err = json.Unmarshal(body, &response)
127 if err != nil {
128 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
129 return animeList, err
130 }
131
132 for _, anime := range response.Data.Shows.Edges {
133 var episodesStr string
134 if episodes, ok := anime.AvailableEpisodes.(map[string]interface{}); ok {
135 if subEpisodes, ok := episodes["sub"].(float64); ok {
136 episodesStr = fmt.Sprintf("%d", int(subEpisodes))
137 } else {
138 Log(subEpisodes)
139 episodesStr = "Unknown"
140 }
141 }
142
143 // Use English name if available and configured, otherwise use default name
144 displayName := anime.Name
145 if anime.EnglishName != "" && userCurdConfig.AnimeNameLanguage == "english" {
146 displayName = anime.EnglishName
147 }
148
149 animeList = append(animeList, SelectionOption{
150 Key: anime.ID,
151 Label: fmt.Sprintf("%s (%s episodes)", displayName, episodesStr),
152 })
153 }
154 return animeList, nil
155}
156
157// Helper function
158func min(a, b int) int {
159 if a < b {
160 return a
161 }
162 return b
163}