internal/episode_list.go

117 lines · 3398 bytes

  1package internal
  2
  3import (
  4	"bytes"
  5	"encoding/json"
  6	"fmt"
  7	"io"
  8	"net/http"
  9	"sort"
 10	"strconv"
 11)
 12
 13type episodesResponse struct {
 14	Data struct {
 15		Show struct {
 16			ID                      string                 `json:"_id"`
 17			AvailableEpisodesDetail map[string]interface{} `json:"availableEpisodesDetail"`
 18		} `json:"show"`
 19	} `json:"data"`
 20}
 21
 22// func main() {
 23// 	// Get environment variables
 24// 	// Read the ID from the file
 25// 	id := "ReooPAxPMsHM4KPMY"
 26
 27// 	// Fetch episodes list
 28// 	episodeList := episodesList(string(id), "sub")
 29
 30// 	// Write the episode list to a file
 31// 	fmt.Println(episodeList)
 32// }
 33
 34// episodesList performs the API call and fetches the episodes list
 35func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
 36	preferredMode := normalizeTranslationType(mode)
 37
 38	episodesListGql := `query ($showId String!) { show( _id: $showId ) { _id availableEpisodesDetail }}`
 39
 40	// Build POST request body
 41	requestBody, err := json.Marshal(map[string]interface{}{
 42		"query":     episodesListGql,
 43		"variables": map[string]string{"showId": showID},
 44	})
 45	if err != nil {
 46		return nil, fmt.Errorf("failed to marshal request body: %w", err)
 47	}
 48
 49	// Make the HTTP POST request
 50	req, err := http.NewRequest("POST", "https://api.allanime.day/api", bytes.NewBuffer(requestBody))
 51	if err != nil {
 52		return nil, fmt.Errorf("failed to create request: %w", err)
 53	}
 54	req.Header.Set("Content-Type", "application/json")
 55	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
 56	req.Header.Set("Referer", "https://allanime.to")
 57	req.Header.Set("Origin", "https://allanime.to")
 58
 59	resp, err := sharedHTTPClient.Do(req)
 60	if err != nil {
 61		Log(fmt.Sprint("Error making HTTP request:", err))
 62		return nil, err
 63	}
 64	defer resp.Body.Close()
 65
 66	body, err := io.ReadAll(resp.Body)
 67	if err != nil {
 68		Log(fmt.Sprint("Error reading response body:", err))
 69		return nil, err
 70	}
 71
 72	// Parse the JSON response
 73	var response episodesResponse
 74	err = json.Unmarshal(body, &response)
 75	if err != nil {
 76		Log(fmt.Sprint("Error parsing JSON:", err))
 77		return nil, err
 78	}
 79
 80	// Extract and sort the episodes
 81	episodes := extractEpisodes(response.Data.Show.AvailableEpisodesDetail, preferredMode)
 82	if len(episodes) == 0 {
 83		fallbackMode := alternateTranslationType(preferredMode)
 84		episodes = extractEpisodes(response.Data.Show.AvailableEpisodesDetail, fallbackMode)
 85		if len(episodes) > 0 {
 86			Log(fmt.Sprintf("Falling back to %s episode list for anime %s", fallbackMode, showID))
 87		}
 88	}
 89	if len(episodes) == 0 {
 90		return episodes, fmt.Errorf("no episodes found for anime %s", showID)
 91	}
 92	return episodes, nil
 93}
 94
 95// extractEpisodes extracts the episodes list from the availableEpisodesDetail field
 96func extractEpisodes(availableEpisodesDetail map[string]interface{}, mode string) []string {
 97	var episodes []float64
 98
 99	// Check if the mode (e.g., "sub") exists in the map
100	if eps, ok := availableEpisodesDetail[mode].([]interface{}); ok {
101		for _, ep := range eps {
102			if epNum, err := strconv.ParseFloat(fmt.Sprintf("%v", ep), 64); err == nil {
103				episodes = append(episodes, epNum)
104			}
105		}
106	}
107
108	// Sort episodes numerically
109	sort.Float64s(episodes)
110
111	// Convert to string and return
112	var episodesStr []string
113	for _, ep := range episodes {
114		episodesStr = append(episodesStr, fmt.Sprintf("%v", ep))
115	}
116	return episodesStr
117}