forked from XiovV/Golty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideos_database_handlers.go
72 lines (57 loc) · 1.69 KB
/
videos_database_handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
func (v DownloadVideoPayload) AddToDatabase() error {
b, err := ioutil.ReadFile(filepath.Join(CONFIG_ROOT, "videos.json"))
if err != nil {
return fmt.Errorf("v.AddToDatabase: %s", err)
}
var videos []DownloadVideoPayload
json.Unmarshal(b, &videos)
log.Info("adding video to DB")
videos = append(videos, v)
err = writeToVideosDb(videos, CONFIG_ROOT+"videos.json")
if err != nil {
return fmt.Errorf("v.AddToDatabase: %s", err)
}
return nil
}
func GetVideos() ([]DownloadVideoPayload, error) {
log.Info("getting all videos from videos.json")
jsonFile, err := os.Open(CONFIG_ROOT + "videos.json")
if err != nil {
log.Error("From GetChannels()", err)
return []DownloadVideoPayload{}, fmt.Errorf("From GetVideos(): %v", err)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var videos []DownloadVideoPayload
err = json.Unmarshal(byteValue, &videos)
if err != nil {
log.Error("From GetChannels()", err)
return []DownloadVideoPayload{}, fmt.Errorf("From GetChannels(): %v", err)
}
log.Info("successfully read all channels")
return reverseVideos(videos), nil
}
func writeToVideosDb(db []DownloadVideoPayload, dbName string) error {
result, err := json.Marshal(db)
if err != nil {
log.Error("There was an error writing to database: ", err)
return fmt.Errorf("writeToVideosDb: %s", err)
}
json.Unmarshal(result, &db)
file, _ := json.MarshalIndent(db, "", " ")
err = ioutil.WriteFile(dbName, file, 0644)
if err != nil {
log.Error("There was an error writing to database: ", err)
return fmt.Errorf("writeToVideosDb: %s", err)
}
return nil
}