internal/providers/anipub/client.go
103 lines · 2427 bytes
10 symbols in this file
1package anipub
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "strings"
10
11 "github.com/wraient/curd/internal/curdhost"
12)
13
14const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
15
16var (
17 baseURL = "https://anipub.xyz"
18 megaplayBaseURL = "https://megaplay.buzz"
19)
20
21func newRequest(method, rawURL, referer string) (*http.Request, error) {
22 req, err := http.NewRequest(method, rawURL, nil)
23 if err != nil {
24 return nil, err
25 }
26 req.Header.Set("User-Agent", userAgent)
27 if referer != "" {
28 req.Header.Set("Referer", referer)
29 }
30 return req, nil
31}
32
33func fetchJSON(rawURL, referer string, dest any) error {
34 req, err := newRequest(http.MethodGet, rawURL, referer)
35 if err != nil {
36 return err
37 }
38 req.Header.Set("Accept", "application/json")
39
40 resp, err := curdhost.HTTPClient().Do(req)
41 if err != nil {
42 return err
43 }
44 defer resp.Body.Close()
45
46 raw, err := io.ReadAll(resp.Body)
47 if err != nil {
48 return err
49 }
50 if !curdhost.HTTPStatusOK(resp.StatusCode) {
51 return curdhost.HTTPStatusError("anipub request", resp.StatusCode, raw)
52 }
53 if dest == nil {
54 return nil
55 }
56 if err := json.Unmarshal(raw, dest); err != nil {
57 return fmt.Errorf("parse anipub response: %w", err)
58 }
59 return nil
60}
61
62func fetchString(rawURL, referer string) (string, error) {
63 req, err := newRequest(http.MethodGet, rawURL, referer)
64 if err != nil {
65 return "", err
66 }
67 resp, err := curdhost.HTTPClient().Do(req)
68 if err != nil {
69 return "", err
70 }
71 defer resp.Body.Close()
72
73 body, err := io.ReadAll(resp.Body)
74 if err != nil {
75 return "", err
76 }
77 if !curdhost.HTTPStatusOK(resp.StatusCode) {
78 return "", curdhost.HTTPStatusError("anipub request", resp.StatusCode, body)
79 }
80 return string(body), nil
81}
82
83func searchURL(query string) string {
84 return fmt.Sprintf("%s/api/search/%s", baseURL, url.PathEscape(strings.TrimSpace(query)))
85}
86
87func infoURL(showID string) string {
88 return fmt.Sprintf("%s/api/info/%s", baseURL, url.PathEscape(strings.TrimSpace(showID)))
89}
90
91func detailsURL(showID string) string {
92 return fmt.Sprintf("%s/v1/api/details/%s", baseURL, url.PathEscape(strings.TrimSpace(showID)))
93}
94
95func thumbnailFromInfo(info infoResponse, fallback string) string {
96 for _, candidate := range []string{info.Image, info.Cover, fallback} {
97 candidate = strings.TrimSpace(candidate)
98 if candidate != "" {
99 return candidate
100 }
101 }
102 return ""
103}