all repos — fixyoutube-go @ 97e64504cf0957b9ef32a87404415a6697900a5d

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

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.Fatal("Error opening database")
31	}
32	db.SetMaxOpenConns(1)
33	return db
34}
35
36func InitDB() {
37	db := getDb("rwc")
38	defer db.Close()
39
40	_, err := db.Exec(createQuery)
41	if err != nil {
42		log.Printf("%q: %s\n", err, createQuery)
43		return
44	}
45}
46
47func CacheVideoDB(v Video) {
48	db := getDb("rw")
49	defer db.Close()
50
51	stmt, err := db.Prepare(cacheVideoQuery)
52	if err != nil {
53		log.Fatal(err)
54	}
55	defer stmt.Close()
56
57	_, err = stmt.Exec(v.VideoId, v.Title, v.Description, v.Uploader, v.Duration, v.Height, v.Width, v.Url)
58	if err != nil {
59		log.Printf("%q: %s\n", err, cacheVideoQuery)
60		return
61	}
62}
63
64func GetVideoDB(videoId string) (*Video, error) {
65	db := getDb("ro")
66	defer db.Close()
67
68	stmt, err := db.Prepare(getVideoQuery)
69	if err != nil {
70		log.Fatal(err)
71	}
72	defer stmt.Close()
73
74	t := &Video{}
75	err = stmt.QueryRow(videoId).Scan(&t.VideoId, &t.Title, &t.Description, &t.Uploader, &t.Duration, &t.Height, &t.Width, &t.Url, &t.Timestamp)
76	if err != nil {
77		//log.Printf("%q: %s\n", err, getVideoQuery)
78		return &Video{}, err
79	}
80	return t, nil
81}
82
83func ClearDB() {
84	db := getDb("rw")
85	defer db.Close()
86
87	stmt, err := db.Prepare(clearQuery)
88	if err != nil {
89		log.Fatal(err)
90	}
91	defer stmt.Close()
92
93	_, err = stmt.Exec()
94	if err != nil {
95		log.Printf("%q: %s\n", err, cacheVideoQuery)
96		return
97	}
98}