all repos — fixyoutube-go @ c9e6e46c2ff2b9496e106388db2f66bef0879330

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}
32
33func CacheVideoDB(v Video) error {
34	db := getDb("rw")
35	defer db.Close()
36
37	cacheVideo, err := db.Prepare(cacheVideoQuery)
38	if err != nil {
39		logger.Error("Could not cache video: ", err)
40		return err
41	}
42	defer cacheVideo.Close()
43
44	_, err = cacheVideo.Exec(v.VideoId, v.Title, v.Description, v.Uploader, v.Duration, v.Url, v.Expire)
45	if err != nil {
46		logger.Error("Could not cache video: ", err)
47		return err
48	}
49
50	return nil
51}
52
53func GetVideoDB(videoId string) (*Video, error) {
54	db := getDb("ro")
55	defer db.Close()
56
57	getVideo, err := db.Prepare(getVideoQuery)
58	if err != nil {
59		logger.Error("Could not get video: ", err)
60		return nil, err
61	}
62	defer getVideo.Close()
63
64	v := &Video{}
65	err = getVideo.QueryRow(videoId).Scan(&v.VideoId, &v.Title, &v.Description, &v.Uploader, &v.Duration, &v.Url, &v.Timestamp, &v.Expire)
66	if err != nil {
67		logger.Debug("Could not get video:", err)
68		return nil, err
69	}
70
71	if v.Timestamp.After(v.Expire) {
72		logger.Info("Video has expired.")
73		return nil, fmt.Errorf("expired")
74	}
75
76	return v, nil
77}
78
79func ClearDB() {
80	db := getDb("rw")
81	defer db.Close()
82
83	stmt, err := db.Prepare(clearQuery)
84	if err != nil {
85		logger.Error("Could not clear DB:", err)
86		return
87	}
88	defer stmt.Close()
89
90	_, err = stmt.Exec()
91	if err != nil {
92		logger.Error("Could not clear DB:", err)
93		return
94	}
95}