internal/anime_list.go

161 lines · 4266 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	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) (map[string]string, error) {
 45	userCurdConfig := GetGlobalConfig()
 46	var logFile string
 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(map[string]string)
 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				availableEpisodes
 69				__typename
 70			}
 71		}
 72	}`
 73
 74	// Prepare the GraphQL variables
 75	variables := map[string]interface{}{
 76		"search": map[string]interface{}{
 77			"allowAdult":    false,
 78			"allowUnknown":  false,
 79			"query":         query,
 80		},
 81		"limit":          40,
 82		"page":           1,
 83		"translationType": mode,
 84		"countryOrigin":   "ALL",
 85	}
 86
 87	// Marshal the variables to JSON
 88	variablesJSON, err := json.Marshal(variables)
 89	if err != nil {
 90		Log(fmt.Sprintf("Error encoding variables to JSON: %v", err), logFile)
 91		return animeList, err
 92	}
 93
 94	// Build the request URL
 95	url := fmt.Sprintf("%s?variables=%s&query=%s", allanimeAPI, url.QueryEscape(string(variablesJSON)), url.QueryEscape(searchGql))
 96
 97	// Make the HTTP request
 98	req, err := http.NewRequest("GET", url, nil)
 99	if err != nil {
100		Log(fmt.Sprintf("Error creating HTTP request: %v", err), logFile)
101		return animeList, err
102	}
103	req.Header.Set("User-Agent", agent)
104	req.Header.Set("Referer", allanimeRef)
105
106	client := &http.Client{}
107	resp, err := client.Do(req)
108	if err != nil {
109		Log(fmt.Sprintf("Error making HTTP request: %v", err), logFile)
110		return animeList, err
111	}
112	defer resp.Body.Close()
113
114	// Read the response body
115	body, err := io.ReadAll(resp.Body)
116	if err != nil {
117		Log(fmt.Sprintf("Error reading response body: %v", err), logFile)
118		return animeList, err
119	}
120
121	// Debug: Log the response status and first part of the body
122	Log(fmt.Sprintf("Response Status: %s", resp.Status), logFile)
123	Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])), logFile)
124
125	// Parse the JSON response
126	var response response
127	err = json.Unmarshal(body, &response)
128	if err != nil {
129		Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)), logFile)
130		return animeList, err
131	}
132
133	for _, anime := range response.Data.Shows.Edges {
134		var episodesStr string
135		if episodes, ok := anime.AvailableEpisodes.(map[string]interface{}); ok {
136			if subEpisodes, ok := episodes["sub"].(float64); ok {
137				episodesStr = fmt.Sprintf("%d", int(subEpisodes))
138			} else {
139				Log(subEpisodes, logFile)
140				episodesStr = "Unknown"
141			}
142		}
143		
144		// Use English name if available and configured, otherwise use default name
145		displayName := anime.Name
146		if anime.EnglishName != "" && userCurdConfig.AnimeNameLanguage == "english" {
147			displayName = anime.EnglishName
148		}
149		
150		animeList[anime.ID] = fmt.Sprintf("%s (%s episodes)", displayName, episodesStr)
151	}
152	return animeList, nil
153}
154
155// Helper function
156func min(a, b int) int {
157	if a < b {
158		return a
159	}
160	return b
161}