invidious/cache.go (view raw)
1package invidious
2
3import (
4 "database/sql"
5 "log"
6
7 _ "github.com/mattn/go-sqlite3"
8)
9
10var dbConnectionString = "file:cache.sqlite?cache=shared&mode="
11var createQuery = `
12CREATE TABLE IF NOT EXISTS videos (
13 videoId TEXT PRIMARY KEY,
14 title TEXT NOT NULL,
15 description TEXT NOT NULL,
16 uploader TEXT NOT NULL,
17 duration int NOT NULL,
18 height TEXT NOT NULL,
19 width TEXT NOT NULL,
20 url TEXT,
21 timestamp DATETIME DEFAULT (datetime('now'))
22);`
23var getVideoQuery = "SELECT * FROM videos WHERE videoId = (?);"
24var cacheVideoQuery = "INSERT OR REPLACE INTO videos (videoId, title, description, uploader, duration, height, width, url) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"
25var clearQuery = "DELETE FROM videos;"
26
27func getDb(mode string) *sql.DB {
28 db, err := sql.Open("sqlite3", dbConnectionString+mode)
29 if err != nil {
30 log.Println("Could not open DB:", err)
31 return nil
32 }
33 db.SetMaxOpenConns(1)
34 return db
35}
36
37func InitDB() {
38 db := getDb("rwc")
39 defer db.Close()
40
41 _, err := db.Exec(createQuery)
42 if err != nil {
43 log.Printf("%q: %s\n", err, createQuery)
44 return
45 }
46}
47
48func CacheVideoDB(v Video) {
49 db := getDb("rw")
50 defer db.Close()
51
52 stmt, err := db.Prepare(cacheVideoQuery)
53 if err != nil {
54 log.Println("Could not cache video:", err)
55 return
56 }
57 defer stmt.Close()
58
59 _, err = stmt.Exec(v.VideoId, v.Title, v.Description, v.Uploader, v.Duration, v.Height, v.Width, v.Url)
60 if err != nil {
61 log.Println("Could not cache video:", err)
62 return
63 }
64}
65
66func GetVideoDB(videoId string) (*Video, error) {
67 db := getDb("ro")
68 defer db.Close()
69
70 stmt, err := db.Prepare(getVideoQuery)
71 if err != nil {
72 log.Println("Could not get video:", err)
73 return nil, err
74 }
75 defer stmt.Close()
76
77 t := &Video{}
78 err = stmt.QueryRow(videoId).Scan(&t.VideoId, &t.Title, &t.Description, &t.Uploader, &t.Duration, &t.Height, &t.Width, &t.Url, &t.Timestamp)
79 if err != nil {
80 log.Println("Could not get video:", err)
81 return nil, err
82 }
83 return t, nil
84}
85
86func ClearDB() {
87 db := getDb("rw")
88 defer db.Close()
89
90 stmt, err := db.Prepare(clearQuery)
91 if err != nil {
92 log.Println("Could not clear DB:", err)
93 return
94 }
95 defer stmt.Close()
96
97 _, err = stmt.Exec()
98 if err != nil {
99 log.Println("Could not clear DB:", err)
100 return
101 }
102}