all repos — fixyoutube-go @ 885bf1a0eb716d6fe63a385dc1bc5164564d4cf0

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