internal/anime_list.go

226 lines · 6037 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 searchAllAnime(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	resp, err := sharedHTTPClient.Do(req)
162	if err != nil {
163		Log(fmt.Sprintf("Error making HTTP request: %v", err))
164		return animeList, err
165	}
166	defer resp.Body.Close()
167
168	// Read the response body
169	body, err := io.ReadAll(resp.Body)
170	if err != nil {
171		Log(fmt.Sprintf("Error reading response body: %v", err))
172		return animeList, err
173	}
174
175	// Debug: Log the response status and first part of the body
176	Log(fmt.Sprintf("Response Status: %s", resp.Status))
177	Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
178
179	// Parse the JSON response
180	var response response
181	err = json.Unmarshal(body, &response)
182	if err != nil {
183		Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
184		return animeList, err
185	}
186
187	for _, anime := range response.Data.Shows.Edges {
188		var episodesStr string
189		if episodes, ok := anime.AvailableEpisodes.(map[string]interface{}); ok {
190			if modeEpisodes, ok := episodes[mode].(float64); ok {
191				episodesStr = fmt.Sprintf("%d", int(modeEpisodes))
192			} else {
193				episodesStr = "Unknown"
194			}
195		} else {
196			episodesStr = "Unknown"
197		}
198
199		// Use English name if available and configured, otherwise use default name
200		displayName := anime.Name
201		if anime.EnglishName != "" && userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" {
202			displayName = anime.EnglishName
203		}
204
205		label := fmt.Sprintf("%s (%s episodes)", displayName, episodesStr)
206		if mode != preferredMode {
207			label = fmt.Sprintf("%s [%s]", label, mode)
208		}
209
210		animeList = append(animeList, SelectionOption{
211			Title:     displayName,
212			Key:       anime.ID,
213			Label:     label,
214			Thumbnail: anime.Thumbnail,
215		})
216	}
217	return animeList, nil
218}
219
220// Helper function
221func min(a, b int) int {
222	if a < b {
223		return a
224	}
225	return b
226}