invidious/invidious.go (view raw)
1package invidious
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "regexp"
10 "strconv"
11 "time"
12
13 "github.com/sirupsen/logrus"
14)
15
16const timeoutDuration = 10 * time.Minute
17const maxSizeBytes = 30000000 // 30 MB
18const instancesEndpoint = "https://api.invidious.io/instances.json?sort_by=api,type"
19const videosEndpoint = "https://%s/api/v1/videos/%s?fields=videoId,title,description,author,lengthSeconds,size,formatStreams"
20
21var expireRegex = regexp.MustCompile(`(?i)expire=(\d+)`)
22var logger = logrus.New()
23
24type Timeout struct {
25 Instance string
26 Timestamp time.Time
27}
28
29type Client struct {
30 http *http.Client
31 timeouts []Timeout
32 Instance string
33}
34
35type Format struct {
36 VideoId string
37 Name string `json:"qualityLabel"`
38 Height int
39 Width int
40 Url string `json:"url"`
41 Container string `json:"container"`
42 Size string `json:"size"`
43}
44
45type Video struct {
46 VideoId string `json:"videoId"`
47 Title string `json:"title"`
48 Description string `json:"description"`
49 Uploader string `json:"author"`
50 Duration int `json:"lengthSeconds"`
51 Formats []Format `json:"formatStreams"`
52 Timestamp time.Time
53 Expire time.Time
54 FormatIndex int
55}
56
57func filter[T any](ss []T, test func(T) bool) (ret []T) {
58 for _, s := range ss {
59 if test(s) {
60 ret = append(ret, s)
61 }
62 }
63 return
64}
65
66func parseOrZero(number string) int {
67 res, err := strconv.Atoi(number)
68 if err != nil {
69 return 0
70 }
71 return res
72}
73
74type HTTPError struct {
75 StatusCode int
76}
77
78func (e HTTPError) Error() string {
79 return fmt.Sprintf("HTTP error: %d", e.StatusCode)
80}
81
82func (c *Client) fetchVideo(videoId string) (*Video, error) {
83 if c.Instance == "" {
84 err := c.NewInstance()
85 if err != nil {
86 logger.Fatal(err, "Could not get a new instance.")
87 }
88 }
89 endpoint := fmt.Sprintf(videosEndpoint, c.Instance, url.QueryEscape(videoId))
90 resp, err := c.http.Get(endpoint)
91 if err != nil {
92 return nil, err
93 }
94 defer resp.Body.Close()
95
96 body, err := io.ReadAll(resp.Body)
97 if err != nil {
98 return nil, err
99 }
100
101 if resp.StatusCode != http.StatusOK {
102 return nil, HTTPError{resp.StatusCode}
103 }
104
105 res := &Video{}
106 err = json.Unmarshal(body, res)
107 if err != nil {
108 return nil, err
109 }
110
111 mp4Test := func(f Format) bool { return f.Container == "mp4" }
112 res.Formats = filter(res.Formats, mp4Test)
113
114 expireString := expireRegex.FindStringSubmatch(res.Formats[0].Url)
115 expireTimestamp, err := strconv.ParseInt(expireString[1], 10, 64)
116 if err != nil {
117 fmt.Println("Error:", err)
118 return nil, err
119 }
120 res.Expire = time.Unix(expireTimestamp, 0)
121
122 return res, err
123}
124
125func (c *Client) GetVideo(videoId string) (*Video, error) {
126 logger.Info("Video https://youtu.be/", videoId, " was requested.")
127
128 video, err := GetVideoDB(videoId)
129 if err == nil {
130 logger.Info("Found a valid cache entry.")
131 return video, nil
132 }
133
134 video, err = c.fetchVideo(videoId)
135
136 if err != nil {
137 if httpErr, ok := err.(HTTPError); ok {
138 // handle HTTPError
139 s := httpErr.StatusCode
140 if s == http.StatusNotFound || s == http.StatusInternalServerError {
141 logger.Debug("Video does not exist.")
142 return nil, err
143 }
144 logger.Debug("Invidious HTTP error: ", httpErr.StatusCode)
145 }
146 // handle generic error
147 logger.Error(err)
148 err = c.NewInstance()
149 if err != nil {
150 logger.Error("Could not get a new instance: ", err)
151 time.Sleep(10 * time.Second)
152 }
153 return c.GetVideo(videoId)
154 }
155 logger.Info("Retrieved by API.")
156
157 err = CacheVideoDB(*video)
158 if err != nil {
159 logger.Warn("Could not cache video id: ", videoId)
160 logger.Warn(err)
161 }
162 return video, nil
163}
164
165func (c *Client) isNotTimedOut(instance string) bool {
166 for i := range c.timeouts {
167 cur := c.timeouts[i]
168 if instance == cur.Instance {
169 return false
170 }
171 }
172 return true
173}
174
175func (c *Client) NewInstance() error {
176 now := time.Now()
177
178 timeoutsTest := func(t Timeout) bool { return now.Sub(t.Timestamp) < timeoutDuration }
179 c.timeouts = filter(c.timeouts, timeoutsTest)
180
181 timeout := Timeout{c.Instance, now}
182 c.timeouts = append(c.timeouts, timeout)
183
184 resp, err := c.http.Get(instancesEndpoint)
185 if err != nil {
186 return err
187 }
188 defer resp.Body.Close()
189
190 body, err := io.ReadAll(resp.Body)
191 if err != nil {
192 return err
193 }
194
195 if resp.StatusCode != http.StatusOK {
196 return HTTPError{resp.StatusCode}
197 }
198
199 var jsonArray [][]interface{}
200 err = json.Unmarshal(body, &jsonArray)
201 if err != nil {
202 logger.Error("Could not unmarshal JSON response for instances.")
203 return err
204 }
205
206 for i := range jsonArray {
207 instance := jsonArray[i][0].(string)
208 instanceTest := func(t Timeout) bool { return t.Instance == instance }
209 result := filter(c.timeouts, instanceTest)
210 if len(result) == 0 {
211 c.Instance = instance
212 logger.Info("Using new instance: ", c.Instance)
213 return nil
214 }
215 }
216 logger.Error("Cannot find a valid instance.")
217 return err
218}
219
220func (c *Client) ProxyVideo(w http.ResponseWriter, r *http.Request, videoId string, formatIndex int) int {
221 video, err := GetVideoDB(videoId)
222 if err != nil {
223 logger.Warn("Cannot proxy a video that is not cached: https://youtu.be/", videoId)
224 return http.StatusBadRequest
225 }
226
227 fmtAmount := len(video.Formats)
228 idx := formatIndex % fmtAmount
229 url := video.Formats[fmtAmount-1-idx].Url
230 req, err := http.NewRequest(http.MethodGet, url, nil)
231 if err != nil {
232 logger.Error(err)
233 new_video, err := c.fetchVideo(videoId)
234 if err != nil {
235 logger.Error("Url for", videoId, "expired:", err)
236 return http.StatusGone
237 }
238 return c.ProxyVideo(w, r, new_video.VideoId, formatIndex)
239 }
240
241 resp, err := c.http.Do(req) // send video request
242 if err != nil {
243 logger.Error(err)
244 return http.StatusInternalServerError
245 }
246
247 if resp.ContentLength > maxSizeBytes {
248 newIndex := formatIndex + 1
249 if newIndex < fmtAmount {
250 logger.Debug("Format ", newIndex, ": Content-Length exceeds max size. Trying another format.")
251 return c.ProxyVideo(w, r, videoId, newIndex)
252 }
253 logger.Error("Could not find a suitable format.")
254 return http.StatusBadRequest
255 }
256 defer resp.Body.Close()
257
258 w.Header().Set("Content-Type", "video/mp4")
259 w.Header().Set("Status", "200")
260 _, err = io.Copy(w, resp.Body)
261 return http.StatusOK
262}
263
264func NewClient(httpClient *http.Client) *Client {
265 InitDB()
266 return &Client{
267 http: httpClient,
268 timeouts: []Timeout{},
269 Instance: "",
270 }
271}