Use memmap to cache json replies from ytdl

Stein Ivar Berghei 2022-11-19 01:58:43 +01:00
parent 17918bf85d
commit c7fca65206
1 changed files with 35 additions and 13 deletions

View File

@ -3,13 +3,24 @@ package ytdl
import (
"errors"
"fmt"
"log"
"os/exec"
"path/filepath"
"time"
"github.com/gohugoio/hugo/cache/filecache"
"github.com/spf13/afero"
"github.com/tidwall/gjson"
)
var cache *filecache.Cache
var yturl = "https://youtu.be/%s"
func init() {
fs := afero.NewMemMapFs()
cache = filecache.NewCache(fs, 6*time.Hour, "")
}
type YTdl struct {
Title string
Url string
@ -17,19 +28,30 @@ type YTdl struct {
Len time.Duration
}
func NewYTdl(uri string) (*YTdl, error) {
ytdl_js, err := exec.Command(
"./bin/yt-dlp_linux",
uri,
"--cookies", "./cookies.txt",
"--no-call-home",
"--no-cache-dir",
"--ignore-errors",
"--newline",
"--restrict-filenames",
"-f", "140",
"-j",
).Output()
func NewYTdl(vid string) (*YTdl, error) {
log.Printf("Loading %s from youtube\n", vid)
_, ytdl_js, err := cache.GetOrCreateBytes(vid+".json", func() ([]byte, error) {
log.Printf("%s not found in cache, downloading info.\n", vid)
js, err := exec.Command(
"./bin/yt-dlp_linux",
fmt.Sprintf(yturl, vid),
"--cookies", "./cookies.txt",
"--no-call-home",
"--no-cache-dir",
"--ignore-errors",
"--newline",
"--restrict-filenames",
"-f", "140",
"-j",
).Output()
if err != nil {
return nil, err
}
log.Printf("%s is now cached.\n", vid)
return js, nil
})
if err != nil {
return nil, err