internal/providers/anineko/client.go

92 lines · 2067 bytes

 1package anineko
 2
 3import (
 4	"fmt"
 5	"io"
 6	"net/http"
 7	"strings"
 8
 9	"github.com/wraient/curd/internal/curdhost"
10)
11
12const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
13
14var baseURL = "https://anineko.to"
15
16func newRequest(method, rawURL, referer string) (*http.Request, error) {
17	req, err := http.NewRequest(method, rawURL, nil)
18	if err != nil {
19		return nil, err
20	}
21	req.Header.Set("User-Agent", userAgent)
22	if referer != "" {
23		req.Header.Set("Referer", referer)
24	}
25	return req, nil
26}
27
28func fetchString(rawURL, referer string) (string, error) {
29	req, err := newRequest(http.MethodGet, rawURL, referer)
30	if err != nil {
31		return "", err
32	}
33	resp, err := curdhost.HTTPClient().Do(req)
34	if err != nil {
35		return "", err
36	}
37	defer resp.Body.Close()
38
39	body, err := io.ReadAll(resp.Body)
40	if err != nil {
41		return "", err
42	}
43	if !curdhost.HTTPStatusOK(resp.StatusCode) {
44		return "", curdhost.HTTPStatusError("anineko request", resp.StatusCode, body)
45	}
46	return string(body), nil
47}
48
49func fetchBytes(rawURL, referer string) ([]byte, error) {
50	req, err := newRequest(http.MethodGet, rawURL, referer)
51	if err != nil {
52		return nil, err
53	}
54	resp, err := curdhost.HTTPClient().Do(req)
55	if err != nil {
56		return nil, err
57	}
58	defer resp.Body.Close()
59
60	body, err := io.ReadAll(resp.Body)
61	if err != nil {
62		return nil, err
63	}
64	if !curdhost.HTTPStatusOK(resp.StatusCode) {
65		return nil, curdhost.HTTPStatusError("anineko request", resp.StatusCode, body)
66	}
67	return body, nil
68}
69
70func absoluteURL(path string) string {
71	path = strings.TrimSpace(path)
72	if path == "" {
73		return ""
74	}
75	if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
76		return path
77	}
78	if strings.HasPrefix(path, "//") {
79		return "https:" + path
80	}
81	if !strings.HasPrefix(path, "/") {
82		path = "/" + path
83	}
84	return baseURL + path
85}
86
87func watchURL(slug string, epNo int) string {
88	if epNo > 0 {
89		return fmt.Sprintf("%s/watch/%s/ep-%d", baseURL, slug, epNo)
90	}
91	return fmt.Sprintf("%s/watch/%s", baseURL, slug)
92}