invidious/api.go (view raw)
1package invidious
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "strconv"
10 "time"
11)
12
13type Format struct {
14 Name string `json:"qualityLabel"`
15 Url string `json:"url"`
16 Container string `json:"container"`
17 Size string `json:"size"`
18}
19
20func (c *Client) fetchVideo(videoId string) (*Video, int) {
21 endpoint := fmt.Sprintf(videosEndpoint, c.Instance, url.QueryEscape(videoId))
22 resp, err := c.http.Get(endpoint)
23 if err != nil {
24 logger.Error(err)
25 return nil, http.StatusInternalServerError
26 }
27 defer resp.Body.Close()
28
29 if resp.StatusCode == http.StatusNotFound {
30 return nil, http.StatusNotFound
31 }
32
33 if resp.StatusCode != http.StatusOK {
34 logger.Warn("Invidious gave the following status code: ", resp.StatusCode)
35 return nil, resp.StatusCode
36 }
37
38 body, err := io.ReadAll(resp.Body)
39 if err != nil {
40 logger.Error(err)
41 return nil, http.StatusInternalServerError
42 }
43
44 res := &Video{}
45 err = json.Unmarshal(body, res)
46 if err != nil {
47 logger.Error(err)
48 return nil, http.StatusInternalServerError
49 }
50
51 mp4Test := func(f Format) bool { return f.Container == "mp4" }
52 res.Formats = filter(res.Formats, mp4Test)
53
54 expireString := expireRegex.FindStringSubmatch(res.Formats[0].Url)
55 expireTimestamp, err := strconv.ParseInt(expireString[1], 10, 64)
56 if err != nil {
57 logger.Error(err)
58 return nil, http.StatusInternalServerError
59 }
60 res.Expire = time.Unix(expireTimestamp, 0)
61
62 vb, i := c.findCompatibleFormat(res)
63 if i < 0 {
64 logger.Warn("No compatible formats found for video.")
65 res.Url = ""
66 } else {
67 videoBuffer := vb.Clone()
68 c.buffers.Set(videoId, videoBuffer)
69 res.Url = res.Formats[i].Url
70 }
71
72 return res, http.StatusOK
73}
74
75func (c *Client) NewInstance() error {
76 if c.Instance != "" {
77 err := fmt.Errorf("generic error")
78 c.timeouts.Set(c.Instance, &err)
79 }
80
81 resp, err := c.http.Get(instancesEndpoint)
82 if err != nil {
83 return err
84 }
85 defer resp.Body.Close()
86
87 body, err := io.ReadAll(resp.Body)
88 if err != nil {
89 return err
90 }
91
92 if resp.StatusCode != http.StatusOK {
93 return fmt.Errorf("HTTP error: %d", resp.StatusCode)
94 }
95
96 var jsonArray [][]interface{}
97 err = json.Unmarshal(body, &jsonArray)
98 if err != nil {
99 logger.Error("Could not unmarshal JSON response for instances.")
100 return err
101 }
102
103 for i := range jsonArray {
104 instance := jsonArray[i][0].(string)
105 if !c.timeouts.Has(instance) {
106 c.Instance = instance
107 logger.Info("Using new instance: ", c.Instance)
108 return nil
109 }
110 }
111
112 return fmt.Errorf("cannot find a valid instance")
113}