internal/providers/senshi/search.go
99 lines · 2262 bytes
1package senshi
2
3import (
4 "fmt"
5 "net/http"
6 "strconv"
7 "strings"
8
9 "github.com/wraient/curd/internal/providers"
10)
11
12func searchAnime(query, mode string) ([]providers.SelectionOption, error) {
13 query = strings.TrimSpace(query)
14 if query == "" {
15 return nil, fmt.Errorf("empty search query")
16 }
17 _ = mode
18
19 var payload filterResponse
20 err := fetchJSON(http.MethodPost, baseURL+"/anime/filter", map[string]any{
21 "searchTerm": query,
22 "page": 1,
23 "limit": 25,
24 }, &payload)
25 if err != nil {
26 return nil, err
27 }
28 if len(payload.Data) == 0 {
29 return nil, fmt.Errorf("no results for %q", query)
30 }
31
32 options := make([]providers.SelectionOption, 0, len(payload.Data))
33 for _, item := range payload.Data {
34 malID := item.ID
35 if malID <= 0 {
36 continue
37 }
38 title := strings.TrimSpace(item.TitleEnglish)
39 if title == "" {
40 title = strings.TrimSpace(item.Title)
41 }
42 label := formatSearchLabel(item)
43 options = append(options, providers.SelectionOption{
44 Key: strconv.Itoa(malID),
45 Label: label,
46 Title: title,
47 Thumbnail: posterURL(malID),
48 ExtraData: toSearchItem(item),
49 })
50 }
51 if len(options) == 0 {
52 return nil, fmt.Errorf("no results for %q", query)
53 }
54 return options, nil
55}
56
57func formatSearchLabel(item animeItem) string {
58 title := strings.TrimSpace(item.TitleEnglish)
59 if title == "" {
60 title = strings.TrimSpace(item.Title)
61 }
62 parts := []string{title}
63 if item.Type != "" {
64 parts = append(parts, item.Type)
65 }
66 if item.AniYear > 0 {
67 parts = append(parts, strconv.Itoa(item.AniYear))
68 }
69 if episodes, ok := parseEpisodeCount(item.AniEpisodes); ok {
70 parts = append(parts, fmt.Sprintf("%d eps", episodes))
71 }
72 return strings.Join(parts, " · ")
73}
74
75func toSearchItem(item animeItem) SearchItem {
76 episodes, _ := parseEpisodeCount(item.AniEpisodes)
77 return SearchItem{
78 MalID: item.ID,
79 PublicID: item.PublicID,
80 Title: item.Title,
81 Type: item.Type,
82 Episodes: episodes,
83 Year: item.AniYear,
84 Score: item.Score,
85 Status: item.AniStatus,
86 }
87}
88
89func parseEpisodeCount(raw string) (int, bool) {
90 raw = strings.TrimSpace(raw)
91 if raw == "" || raw == "?" {
92 return 0, false
93 }
94 count, err := strconv.Atoi(raw)
95 if err != nil || count <= 0 {
96 return 0, false
97 }
98 return count, true
99}