allow getting the best format
Marco Andronaco andronacomarco@gmail.com
Wed, 16 Oct 2024 11:31:25 +0200
2 files changed,
15 insertions(+),
19 deletions(-)
M
src/app/proxy.go
→
src/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.go
→
src/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 }