internal/anime_list.go

221 lines · 5903 bytes

  1package internal
  2
  3import (
  4	"bytes"
  5	"encoding/json"
  6	"fmt"
  7	"io"
  8	"net/http"
  9	"path/filepath"
 10	"strings"
 11)
 12
 13type anime struct {
 14	ID                string      `json:"_id"`
 15	Name              string      `json:"name"`
 16	EnglishName       string      `json:"englishName"`
 17	Thumbnail         string      `json:"thumbnail"`
 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
 29func normalizeTranslationType(mode string) string {
 30	if strings.EqualFold(strings.TrimSpace(mode), "dub") {
 31		return "dub"
 32	}
 33	return "sub"
 34}
 35
 36func alternateTranslationType(mode string) string {
 37	if normalizeTranslationType(mode) == "dub" {
 38		return "sub"
 39	}
 40	return "dub"
 41}
 42
 43// func main() {
 44// 	// Get environment variables
 45// 	mode := "sub"
 46
 47// 	// Query for the anime (from a file in this example)
 48// 	query := "one piece"
 49
 50// 	// Search anime
 51// 	animeList, err := SearchAnime(string(query), mode)
 52// 	if err != nil {
 53
 54// 	}
 55// 	fmt.Println(animeList)
 56// }
 57
 58func searchAllAnime(query, mode string) ([]SelectionOption, error) {
 59	preferredMode := normalizeTranslationType(mode)
 60	alternateMode := alternateTranslationType(preferredMode)
 61
 62	preferredResults, preferredErr := searchAnimeByMode(query, preferredMode, preferredMode)
 63	alternateResults, alternateErr := searchAnimeByMode(query, alternateMode, preferredMode)
 64
 65	if preferredErr != nil {
 66		Log(fmt.Sprintf("Failed searching %s results for %q: %v", preferredMode, query, preferredErr))
 67	}
 68	if alternateErr != nil {
 69		Log(fmt.Sprintf("Failed searching %s results for %q: %v", alternateMode, query, alternateErr))
 70	}
 71
 72	if preferredErr != nil && alternateErr != nil {
 73		return nil, preferredErr
 74	}
 75
 76	animeList := make([]SelectionOption, 0, len(preferredResults)+len(alternateResults))
 77	seen := make(map[string]struct{}, len(preferredResults)+len(alternateResults))
 78
 79	for _, option := range preferredResults {
 80		animeList = append(animeList, option)
 81		seen[option.Key] = struct{}{}
 82	}
 83
 84	for _, option := range alternateResults {
 85		if _, exists := seen[option.Key]; exists {
 86			continue
 87		}
 88		animeList = append(animeList, option)
 89	}
 90
 91	return animeList, nil
 92}
 93
 94func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, error) {
 95	userCurdConfig := GetGlobalConfig()
 96	logFile = filepath.Join(GetStoragePath(), "debug.log")
 97	const (
 98		agent        = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
 99		allanimeRef  = "https://allanime.to"
100		allanimeBase = "allanime.day"
101		allanimeAPI  = "https://api." + allanimeBase + "/api"
102	)
103
104	mode = normalizeTranslationType(mode)
105	preferredMode = normalizeTranslationType(preferredMode)
106
107	animeList := make([]SelectionOption, 0)
108
109	searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
110		shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
111			edges {
112				_id
113				name
114				englishName
115				thumbnail
116				availableEpisodes
117				__typename
118			}
119		}
120	}`
121
122	// Prepare the GraphQL variables
123	variables := map[string]interface{}{
124		"search": map[string]interface{}{
125			"allowAdult":   false,
126			"allowUnknown": false,
127			"query":        query,
128		},
129		"limit":           40,
130		"page":            1,
131		"translationType": mode,
132		"countryOrigin":   "ALL",
133	}
134
135	// Build POST request body
136	requestBody, err := json.Marshal(map[string]interface{}{
137		"query":     searchGql,
138		"variables": variables,
139	})
140	if err != nil {
141		Log(fmt.Sprintf("Error encoding request body to JSON: %v", err))
142		return animeList, err
143	}
144
145	// Make the HTTP POST request
146	req, err := http.NewRequest("POST", allanimeAPI, bytes.NewBuffer(requestBody))
147	if err != nil {
148		Log(fmt.Sprintf("Error creating HTTP request: %v", err))
149		return animeList, err
150	}
151	req.Header.Set("Content-Type", "application/json")
152	req.Header.Set("User-Agent", agent)
153	req.Header.Set("Referer", allanimeRef)
154	req.Header.Set("Origin", allanimeRef)
155
156	resp, err := sharedHTTPClient.Do(req)
157	if err != nil {
158		Log(fmt.Sprintf("Error making HTTP request: %v", err))
159		return animeList, err
160	}
161	defer resp.Body.Close()
162
163	// Read the response body
164	body, err := io.ReadAll(resp.Body)
165	if err != nil {
166		Log(fmt.Sprintf("Error reading response body: %v", err))
167		return animeList, err
168	}
169
170	// Debug: Log the response status and first part of the body
171	Log(fmt.Sprintf("Response Status: %s", resp.Status))
172	Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
173
174	// Parse the JSON response
175	var response response
176	err = json.Unmarshal(body, &response)
177	if err != nil {
178		Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
179		return animeList, err
180	}
181
182	for _, anime := range response.Data.Shows.Edges {
183		var episodesStr string
184		if episodes, ok := anime.AvailableEpisodes.(map[string]interface{}); ok {
185			if modeEpisodes, ok := episodes[mode].(float64); ok {
186				episodesStr = fmt.Sprintf("%d", int(modeEpisodes))
187			} else {
188				episodesStr = "Unknown"
189			}
190		} else {
191			episodesStr = "Unknown"
192		}
193
194		// Use English name if available and configured, otherwise use default name
195		displayName := anime.Name
196		if anime.EnglishName != "" && userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" {
197			displayName = anime.EnglishName
198		}
199
200		label := fmt.Sprintf("%s (%s episodes)", displayName, episodesStr)
201		if mode != preferredMode {
202			label = fmt.Sprintf("%s [%s]", label, mode)
203		}
204
205		animeList = append(animeList, SelectionOption{
206			Title:     displayName,
207			Key:       anime.ID,
208			Label:     label,
209			Thumbnail: anime.Thumbnail,
210		})
211	}
212	return animeList, nil
213}
214
215// Helper function
216func min(a, b int) int {
217	if a < b {
218		return a
219	}
220	return b
221}