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