internal/anime_list.go

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