internal/filler_list.go

91 lines · 2245 bytes

5 symbols in this file
 1package internal
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"net/http"
 7	"time"
 8)
 9
10type AnimeFillerListEpisode struct {
11	EpisodeID int  `json:"mal_id"`
12	IsFiller  bool `json:"filler"`
13}
14
15type EpisodesResponse struct {
16	Data       []AnimeFillerListEpisode `json:"data"`
17	Pagination struct {
18		HasNextPage bool `json:"has_next_page"`
19	} `json:"pagination"`
20}
21
22func FetchFillerEpisodes(malID int) ([]int, error) {
23	baseURL := fmt.Sprintf("https://api.jikan.moe/v4/anime/%d/episodes", malID)
24	var fillerEpisodes []int
25	page := 1
26	rateLimiter := time.NewTicker(334 * time.Millisecond) // ~3 requests per second
27	defer rateLimiter.Stop()
28
29	for {
30		<-rateLimiter.C // Wait for rate limit
31		url := fmt.Sprintf("%s?page=%d", baseURL, page)
32		resp, err := sharedHTTPClient.Get(url)
33		if err != nil {
34			return nil, fmt.Errorf("error fetching episodes: %v", err)
35		}
36
37		if resp.StatusCode == http.StatusTooManyRequests {
38			resp.Body.Close()
39			// Wait for 2 seconds and retry
40			time.Sleep(2 * time.Second)
41			continue
42		}
43
44		if resp.StatusCode != http.StatusOK {
45			resp.Body.Close()
46			return nil, fmt.Errorf("received non-200 response: %d", resp.StatusCode)
47		}
48
49		var episodesResp EpisodesResponse
50		if err := json.NewDecoder(resp.Body).Decode(&episodesResp); err != nil {
51			resp.Body.Close()
52			return nil, fmt.Errorf("error decoding response: %v", err)
53		}
54		resp.Body.Close()
55
56		for _, episode := range episodesResp.Data {
57			if episode.IsFiller {
58				fillerEpisodes = append(fillerEpisodes, episode.EpisodeID)
59			}
60		}
61
62		if !episodesResp.Pagination.HasNextPage {
63			break
64		}
65		page++
66	}
67
68	return fillerEpisodes, nil
69}
70
71// IsEpisodeFiller checks if a given episode number is in the filler episodes list
72func IsEpisodeFiller(fillerEpisodes []int, episodeNumber int) bool {
73	for _, fillerEp := range fillerEpisodes {
74		if fillerEp == episodeNumber {
75			return true
76		}
77	}
78	return false
79}
80
81// GetNextCanonEpisode returns the next non-filler episode number after the current episode
82func GetNextCanonEpisode(fillerEpisodes []int, currentEpisode int) int {
83	nextEpisode := currentEpisode + 1
84
85	// Keep incrementing episode number until we find a non-filler episode
86	for IsEpisodeFiller(fillerEpisodes, nextEpisode) {
87		nextEpisode++
88	}
89
90	return nextEpisode
91}