internal/providers/anineko/episodes.go

50 lines · 992 bytes

 1package anineko
 2
 3import (
 4	"fmt"
 5	"regexp"
 6	"sort"
 7	"strconv"
 8	"strings"
 9)
10
11var episodePathRE = regexp.MustCompile(`/ep-(\d+)`)
12
13func episodesList(showID, mode string) ([]string, error) {
14	slug := strings.TrimSpace(showID)
15	if slug == "" {
16		return nil, fmt.Errorf("empty show id")
17	}
18
19	html, err := fetchString(watchURL(slug, 0), baseURL+"/")
20	if err != nil {
21		return nil, err
22	}
23
24	seen := map[int]struct{}{}
25	for _, match := range episodePathRE.FindAllStringSubmatch(html, -1) {
26		if len(match) < 2 {
27			continue
28		}
29		epNo, err := strconv.Atoi(match[1])
30		if err != nil || epNo <= 0 {
31			continue
32		}
33		seen[epNo] = struct{}{}
34	}
35	if len(seen) == 0 {
36		return nil, fmt.Errorf("no episodes found for %q", slug)
37	}
38
39	episodes := make([]int, 0, len(seen))
40	for epNo := range seen {
41		episodes = append(episodes, epNo)
42	}
43	sort.Ints(episodes)
44
45	result := make([]string, 0, len(episodes))
46	for _, epNo := range episodes {
47		result = append(result, strconv.Itoa(epNo))
48	}
49	return result, nil
50}