all repos — fixyoutube-go @ f33a2e3dc414259fae3738ea558b32ec1731ba99

A better way to embed YouTube videos everywhere (inspired by FixTweet).

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	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 HTTPError{resp.StatusCode}
193	}
194
195	var jsonArray [][]interface{}
196	err = json.Unmarshal(body, &jsonArray)
197	if err != nil {
198		logger.Error("Could not unmarshal JSON response for instances.")
199		return err
200	}
201
202	for i := range jsonArray {
203		instance := jsonArray[i][0].(string)
204		instanceTest := func(t Timeout) bool { return t.Instance == instance }
205		result := filter(c.timeouts, instanceTest)
206		if len(result) == 0 {
207			c.Instance = instance
208			logger.Info("Using new instance: ", c.Instance)
209			return nil
210		}
211	}
212	logger.Error("Cannot find a valid instance.")
213	return err
214}
215
216func (c *Client) ProxyVideo(w http.ResponseWriter, r *http.Request, videoId string, formatIndex int) int {
217	video, err := GetVideoDB(videoId)
218	if err != nil {
219		logger.Warn("Cannot proxy a video that is not cached: https://youtu.be/", videoId)
220		return http.StatusBadRequest
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 http.StatusGone
233		}
234		return c.ProxyVideo(w, r, new_video.VideoId, formatIndex)
235	}
236
237	resp, err := c.http.Do(req) // send video request
238	if err != nil {
239		logger.Error(err)
240		return http.StatusInternalServerError
241	}
242
243	if resp.ContentLength > maxSizeBytes {
244		newIndex := formatIndex + 1
245		if newIndex < fmtAmount {
246			logger.Debug("Format ", newIndex, ": Content-Length exceeds max size. Trying another format.")
247			return c.ProxyVideo(w, r, videoId, newIndex)
248		}
249		logger.Error("Could not find a suitable format.")
250		return http.StatusBadRequest
251	}
252	defer resp.Body.Close()
253
254	w.Header().Set("Content-Type", "video/mp4")
255	w.Header().Set("Status", "200")
256	_, err = io.Copy(w, resp.Body)
257	return http.StatusOK
258}
259
260func NewClient(httpClient *http.Client) *Client {
261	InitDB()
262	return &Client{
263		http:     httpClient,
264		timeouts: []Timeout{},
265		Instance: "",
266	}
267}