all repos — gopipe @ 8223ef17cd00edc14c764e8f9874a05ee2073d0b

Embed YouTube videos on Telegram, Discord and more!

src/app/video.go (view raw)

  1package app
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"log"
  7	"regexp"
  8	"strconv"
  9	"strings"
 10	"time"
 11
 12	g "github.com/birabittoh/gopipe/src/globals"
 13	"github.com/kkdai/youtube/v2"
 14)
 15
 16const (
 17	maxMB                = 20
 18	maxContentLength     = maxMB * 1048576
 19	defaultCacheDuration = 6 * time.Hour
 20)
 21
 22var (
 23	expireRegex = regexp.MustCompile(`(?i)expire=(\d+)`)
 24)
 25
 26func parseExpiration(url string) time.Duration {
 27	expireString := expireRegex.FindStringSubmatch(url)
 28	expireTimestamp, err := strconv.ParseInt(expireString[1], 10, 64)
 29	if err != nil {
 30		log.Println("parseExpiration ERROR: ", err)
 31		return defaultCacheDuration
 32	}
 33
 34	return time.Until(time.Unix(expireTimestamp, 0))
 35}
 36
 37func getFormat(video youtube.Video, formatID int) *youtube.Format {
 38	if formatID != 0 {
 39		f := video.Formats.Select(formatsSelectFn)
 40		l := len(f)
 41		if l > 0 {
 42			return &f[(formatID-1)%l]
 43		}
 44	}
 45
 46	f := video.Formats.Select(formatsSelectFnBest)
 47	if len(f) > 0 {
 48		return &f[0]
 49	}
 50
 51	return nil
 52}
 53
 54func formatsSelectFn(f youtube.Format) bool {
 55	return f.AudioChannels > 1 && f.ContentLength < maxContentLength && strings.HasPrefix(f.MimeType, "video/mp4")
 56}
 57
 58func formatsSelectFnBest(f youtube.Format) bool {
 59	return f.AudioChannels > 1 && strings.HasPrefix(f.MimeType, "video/mp4")
 60}
 61
 62func getURL(videoID string) string {
 63	return fmt.Sprintf(fmtYouTubeURL, videoID)
 64}
 65
 66func getFromCache(videoID string, formatID int) (video *youtube.Video, format *youtube.Format, err error) {
 67	video, err = g.KS.Get(videoID)
 68	if err != nil {
 69		return
 70	}
 71
 72	if video == nil {
 73		err = errors.New("video should not be nil")
 74		return
 75	}
 76
 77	format = getFormat(*video, formatID)
 78	return
 79}
 80
 81func getFromYT(videoID string, formatID int) (video *youtube.Video, format *youtube.Format, err error) {
 82	url := getURL(videoID)
 83
 84	log.Println("Requesting video ", url)
 85	video, err = g.YT.GetVideo(url)
 86	if err != nil || video == nil {
 87		return
 88	}
 89
 90	format = getFormat(*video, formatID)
 91	duration := defaultCacheDuration
 92	if format != nil {
 93		duration = parseExpiration(format.URL)
 94	}
 95
 96	g.KS.Set(videoID, *video, duration)
 97	return
 98}
 99
100func getVideo(videoID string, formatID int) (video *youtube.Video, format *youtube.Format, err error) {
101	video, format, err = getFromCache(videoID, formatID)
102	if err != nil {
103		video, format, err = getFromYT(videoID, formatID)
104	}
105	return
106}