all repos — fixyoutube-go @ 5dacd81acbedefff9ee292127e188e1052e7e540

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

invidious/cache.go (view raw)

  1package invidious
  2
  3import (
  4	"database/sql"
  5	"fmt"
  6
  7	_ "github.com/mattn/go-sqlite3"
  8)
  9
 10const dbConnectionString = "file:cache.sqlite?cache=shared&mode="
 11
 12func getDb(mode string) *sql.DB {
 13	db, err := sql.Open("sqlite3", dbConnectionString+mode)
 14	if err != nil {
 15		logger.Error("Could not open DB:", err)
 16		return nil
 17	}
 18	db.SetMaxOpenConns(1)
 19	return db
 20}
 21
 22func InitDB() {
 23	db := getDb("rwc")
 24	defer db.Close()
 25
 26	_, err := db.Exec(createQueryVideos)
 27	if err != nil {
 28		logger.Errorf("%q: %s\n", err, createQueryVideos)
 29		return
 30	}
 31	_, err = db.Exec(createQueryFormats)
 32	if err != nil {
 33		logger.Errorf("%q: %s\n", err, createQueryFormats)
 34		return
 35	}
 36}
 37
 38func CacheVideoDB(v Video) error {
 39	db := getDb("rw")
 40	defer db.Close()
 41
 42	cacheVideo, err := db.Prepare(cacheVideoQuery)
 43	if err != nil {
 44		logger.Error("Could not cache video: ", err)
 45		return err
 46	}
 47	defer cacheVideo.Close()
 48
 49	_, err = cacheVideo.Exec(v.VideoId, v.Title, v.Description, v.Uploader, v.Duration, v.Url, v.Expire)
 50	if err != nil {
 51		logger.Error("Could not cache video: ", err)
 52		return err
 53	}
 54
 55	return nil
 56}
 57
 58func GetVideoDB(videoId string) (*Video, error) {
 59	db := getDb("ro")
 60	defer db.Close()
 61
 62	getVideo, err := db.Prepare(getVideoQuery)
 63	if err != nil {
 64		logger.Error("Could not get video: ", err)
 65		return nil, err
 66	}
 67	defer getVideo.Close()
 68
 69	v := &Video{}
 70	err = getVideo.QueryRow(videoId).Scan(&v.VideoId, &v.Title, &v.Description, &v.Uploader, &v.Duration, &v.Url, &v.Timestamp, &v.Expire)
 71	if err != nil {
 72		logger.Debug("Could not get video:", err)
 73		return nil, err
 74	}
 75
 76	if v.Timestamp.After(v.Expire) {
 77		logger.Info("Video has expired.")
 78		return nil, fmt.Errorf("expired")
 79	}
 80
 81	return v, nil
 82}
 83
 84func ClearDB() {
 85	db := getDb("rw")
 86	defer db.Close()
 87
 88	stmt, err := db.Prepare(clearQuery)
 89	if err != nil {
 90		logger.Error("Could not clear DB:", err)
 91		return
 92	}
 93	defer stmt.Close()
 94
 95	_, err = stmt.Exec()
 96	if err != nil {
 97		logger.Error("Could not clear DB:", err)
 98		return
 99	}
100}