internal/anime_list.go

133 lines · 3930 bytes

  1package internal
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"io"
  7	"net/http"
  8	"os"
  9	"path/filepath"
 10	// "strings"
 11)
 12
 13type anime struct {
 14	ID               string      `json:"_id"`
 15	Name             string      `json:"name"`
 16	AvailableEpisodes interface{} `json:"availableEpisodes"`
 17}
 18
 19type response struct {
 20	Data struct {
 21		Shows struct {
 22			Edges []anime `json:"edges"`
 23		} `json:"shows"`
 24	} `json:"data"`
 25}
 26
 27// func main() {
 28// 	// Get environment variables
 29// 	mode := "sub"
 30
 31// 	// Query for the anime (from a file in this example)
 32// 	query := "one piece"
 33
 34// 	// Search anime
 35// 	animeList, err := SearchAnime(string(query), mode)
 36// 	if err != nil {
 37
 38// 	}
 39// 	fmt.Println(animeList)
 40// }
 41
 42// searchAnime performs the API call and fetches anime information
 43func SearchAnime(query, mode string) (map[string]string, error) {
 44	userCurdConfig := GetGlobalConfig()
 45	if userCurdConfig == nil {
 46		logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log")
 47	} else {
 48		logFile = filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log")
 49	}
 50	const (
 51		agent         = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
 52		allanimeRef   = "https://allanime.to"
 53		allanimeBase  = "allanime.day"
 54		allanimeAPI   = "https://api." + allanimeBase + "/api"
 55	)
 56
 57	// Format and return the anime list
 58	animeList := make(map[string]string)
 59	
 60	searchGql := `query( $search: SearchInput $limit: Int $page: Int $translationType: VaildTranslationTypeEnumType $countryOrigin: VaildCountryOriginEnumType ) { shows( search: $search limit: $limit page: $page translationType: $translationType countryOrigin: $countryOrigin ) { edges { _id name availableEpisodes __typename } } }`
 61
 62	// Build the request URL
 63	url := fmt.Sprintf("%s?variables={\"search\":{\"allowAdult\":false,\"allowUnknown\":false,\"query\":\"%s\"},\"limit\":40,\"page\":1,\"translationType\":\"%s\",\"countryOrigin\":\"ALL\"}&query=%s", allanimeAPI, query, mode, searchGql)
 64
 65	// Make the HTTP request
 66	req, err := http.NewRequest("GET", url, nil)
 67	if err != nil {
 68		Log(fmt.Sprint("Error creating HTTP request:", err), logFile)
 69		return animeList, err
 70	}
 71	req.Header.Set("User-Agent", agent)
 72	req.Header.Set("Referer", allanimeRef)
 73
 74	client := &http.Client{}
 75	resp, err := client.Do(req)
 76	if err != nil {
 77		Log(fmt.Sprint("Error making HTTP request:", err), logFile)
 78		return animeList, err
 79	}
 80	defer resp.Body.Close()
 81
 82	// Read the response body
 83	body, err := io.ReadAll(resp.Body)
 84	if err != nil {
 85		Log(fmt.Sprint("Error reading response body:", err), logFile)
 86		return animeList, err
 87	}
 88
 89	// Debug: Log the response status and first part of body
 90	Log(fmt.Sprintf("Response Status: %s", resp.Status), logFile)
 91	Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])), logFile)
 92
 93	// Parse the JSON response
 94	var response response
 95	err = json.Unmarshal(body, &response)
 96	if err != nil {
 97		Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)), logFile)
 98		return animeList, err
 99	}
100
101	for _, anime := range response.Data.Shows.Edges {
102		// availableEpisodes, _ := anime.AvailableEpisodes.Int64() // Converts json.Number to int64
103
104		var episodesStr string
105
106		// Log(anime.AvailableEpisodes, logFile)
107		// episodesStr = anime.AvailableEpisodes.sub
108
109		//anime = {"dub":0,"raw":0,"sub":4}
110
111		if episodes, ok := anime.AvailableEpisodes.(map[string]interface{}); ok {
112			// Log(episodes, logFile)
113			if subEpisodes, ok := episodes["sub"].(float64); ok {
114				episodesStr = fmt.Sprintf("%d", int(subEpisodes))
115			} else {
116				Log(subEpisodes, logFile)
117				episodesStr = "Unknown"
118			}
119		}
120
121		animeList[anime.ID] = fmt.Sprintf("%s (%s episodes)", anime.Name, episodesStr)
122		// animeList.WriteString(fmt.Sprintf("%s\t%s (%s episodes)\n", anime.ID, anime.Name, episodesStr))
123	}
124	return animeList, nil
125}
126
127// Helper function
128func min(a, b int) int {
129	if a < b {
130		return a
131	}
132	return b
133}