all repos — gopipe @ e52ebbb0058a735dc63d53c92024f696a6c3de34

Embed YouTube videos on Telegram, Discord and more!

allow getting the best format
Marco Andronaco andronacomarco@gmail.com
Wed, 16 Oct 2024 11:31:25 +0200
commit

e52ebbb0058a735dc63d53c92024f696a6c3de34

parent

cec307a9e07ec65951325dcc377f9c24c25ac94b

2 files changed, 15 insertions(+), 19 deletions(-)

jump to
M src/app/proxy.gosrc/app/proxy.go

@@ -27,11 +27,6 @@ http.Error(w, err404, http.StatusNotFound)

return } - if video.ID == emptyVideo.ID { - http.Error(w, err500, http.StatusInternalServerError) - return - } - format := getFormat(*video, formatID) if format == nil { http.Error(w, err500, http.StatusInternalServerError)
M src/app/video.gosrc/app/video.go

@@ -20,7 +20,6 @@ defaultCacheDuration = 6 * time.Hour

) var ( - emptyVideo = youtube.Video{} expireRegex = regexp.MustCompile(`(?i)expire=(\d+)`) )

@@ -36,19 +35,28 @@ return time.Until(time.Unix(expireTimestamp, 0))

} func getFormat(video youtube.Video, formatID int) *youtube.Format { - formats := video.Formats.Select(formatsSelectFn) - l := len(formats) + selectFn := formatsSelectFn + if formatID == 0 { + selectFn = formatsSelectFnBest + formatID = 1 + } + + f := video.Formats.Select(selectFn) + l := len(f) if l == 0 { return nil } - - return &formats[formatID%l] + return &f[(formatID-1)%l] } func formatsSelectFn(f youtube.Format) bool { return f.AudioChannels > 1 && f.ContentLength < maxContentLength && strings.HasPrefix(f.MimeType, "video/mp4") } +func formatsSelectFnBest(f youtube.Format) bool { + return f.AudioChannels > 1 && strings.HasPrefix(f.MimeType, "video/mp4") +} + func getURL(videoID string) string { return fmt.Sprintf(fmtYouTubeURL, videoID) }

@@ -64,11 +72,6 @@ err = errors.New("video should not be nil")

return } - if video.ID == emptyVideo.ID { - err = errors.New("no formats for this video") - return - } - format = getFormat(*video, formatID) return }

@@ -78,19 +81,17 @@ url := getURL(videoID)

log.Println("Requesting video ", url) video, err = g.YT.GetVideo(url) - if err != nil { + if err != nil || video == nil { return } format = getFormat(*video, formatID) duration := defaultCacheDuration - v := emptyVideo if format != nil { - v = *video duration = parseExpiration(format.URL) } - g.KS.Set(videoID, v, duration) + g.KS.Set(videoID, *video, duration) return }