internal/anime_list.go
152 lines · 3967 bytes
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "os"
9 "path/filepath"
10 "net/url"
11 // "strings"
12)
13
14type anime struct {
15 ID string `json:"_id"`
16 Name string `json:"name"`
17 AvailableEpisodes interface{} `json:"availableEpisodes"`
18}
19
20type response struct {
21 Data struct {
22 Shows struct {
23 Edges []anime `json:"edges"`
24 } `json:"shows"`
25 } `json:"data"`
26}
27
28// func main() {
29// // Get environment variables
30// mode := "sub"
31
32// // Query for the anime (from a file in this example)
33// query := "one piece"
34
35// // Search anime
36// animeList, err := SearchAnime(string(query), mode)
37// if err != nil {
38
39// }
40// fmt.Println(animeList)
41// }
42
43func SearchAnime(query, mode string) (map[string]string, error) {
44 userCurdConfig := GetGlobalConfig()
45 var logFile string
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(map[string]string)
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 availableEpisodes
67 __typename
68 }
69 }
70 }`
71
72 // Prepare the GraphQL variables
73 variables := map[string]interface{}{
74 "search": map[string]interface{}{
75 "allowAdult": false,
76 "allowUnknown": false,
77 "query": query,
78 },
79 "limit": 40,
80 "page": 1,
81 "translationType": mode,
82 "countryOrigin": "ALL",
83 }
84
85 // Marshal the variables to JSON
86 variablesJSON, err := json.Marshal(variables)
87 if err != nil {
88 Log(fmt.Sprintf("Error encoding variables to JSON: %v", err), logFile)
89 return animeList, err
90 }
91
92 // Build the request URL
93 url := fmt.Sprintf("%s?variables=%s&query=%s", allanimeAPI, url.QueryEscape(string(variablesJSON)), url.QueryEscape(searchGql))
94
95 // Make the HTTP request
96 req, err := http.NewRequest("GET", url, nil)
97 if err != nil {
98 Log(fmt.Sprintf("Error creating HTTP request: %v", err), logFile)
99 return animeList, err
100 }
101 req.Header.Set("User-Agent", agent)
102 req.Header.Set("Referer", allanimeRef)
103
104 client := &http.Client{}
105 resp, err := client.Do(req)
106 if err != nil {
107 Log(fmt.Sprintf("Error making HTTP request: %v", err), logFile)
108 return animeList, err
109 }
110 defer resp.Body.Close()
111
112 // Read the response body
113 body, err := io.ReadAll(resp.Body)
114 if err != nil {
115 Log(fmt.Sprintf("Error reading response body: %v", err), logFile)
116 return animeList, err
117 }
118
119 // Debug: Log the response status and first part of the body
120 Log(fmt.Sprintf("Response Status: %s", resp.Status), logFile)
121 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])), logFile)
122
123 // Parse the JSON response
124 var response response
125 err = json.Unmarshal(body, &response)
126 if err != nil {
127 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)), logFile)
128 return animeList, err
129 }
130
131 for _, anime := range response.Data.Shows.Edges {
132 var episodesStr string
133 if episodes, ok := anime.AvailableEpisodes.(map[string]interface{}); ok {
134 if subEpisodes, ok := episodes["sub"].(float64); ok {
135 episodesStr = fmt.Sprintf("%d", int(subEpisodes))
136 } else {
137 Log(subEpisodes, logFile)
138 episodesStr = "Unknown"
139 }
140 }
141 animeList[anime.ID] = fmt.Sprintf("%s (%s episodes)", anime.Name, episodesStr)
142 }
143 return animeList, nil
144}
145
146// Helper function
147func min(a, b int) int {
148 if a < b {
149 return a
150 }
151 return b
152}