/
marshaller.go
212 lines (168 loc) · 5.25 KB
/
marshaller.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package main
import (
_ "github.com/mattn/go-sqlite3"
"log"
"os"
"io/ioutil"
"fmt"
"github.com/jmoiron/sqlx"
"encoding/json"
"errors"
)
type SongJSON map[string]interface{}
type Room struct {
// capitalized variables so they are exported https://golang.org/ref/spec#Exported_identifiers
Id int `json:"id" db:"id"`
Name string `json:"name" db:"name"`
CurrentIndex int `json:"currentIndex" db:"current_index"`
Queue []SongJSON `json:"queue"`
Current SongJSON `json:"current"`
}
type Song struct {
VideoData string `db:"videoData"`
}
var schema = `
CREATE TABLE rooms (
id integer not null primary key,
name text unique,
current_index integer not null default 0
);
CREATE TABLE songs (
songId text,
roomId integer not null,
videoData text
)`
/*
Method definitions:
room->getSongQueue() []Song
room->DeleteSong(videoLink)
room->AddSong(videoLink)
*/
// keep a versioning scheme for the db so we can know when to recreate the sqlite file
const dbVersion string = "1.5";
const dbFile string = "./rooms.db"
// TODO (ajafri): we perform a file read on each one of these calls so use it sparingly or change the pattern
func createNewDB() (*sqlx.DB, error) {
var version string = "dbVersion"
b, err := ioutil.ReadFile("bridgdDBVersion.txt")
if err != nil {
b = []byte("") // simulate a version mismatch if reading the file throws an error
}
version = string(b)
_, err = os.Stat(dbFile)
if version != dbVersion || os.IsNotExist(err) {
log.Println ("Version difference detected - recreating database")
os.Remove(dbFile) // clear the db if it is not versioned to the current version
// let's create a new db and instantiate the structure
db, err := sqlx.Open("sqlite3", "./rooms.db")
if err != nil {
return db,err
}
/* TABLE CREATION */
_, err = db.Exec(schema)
if err != nil {
log.Printf("%q: %s\n", err, schema)
return db, err
}
room := Room{Id:1, Name:"no-yolo-zone"}
// TODO (ajafri): testing code to initialize table with data. Take out.
_, err = db.NamedExec("insert into rooms(id, name) values(:id, :name)",room )
if err != nil {
log.Printf("%q: %s\n", err)
return db, err
}
// TODO (ajafri): testing code to initialize table with data. Take out.
song := Song{VideoData: "{ \"id\": { \"kind\": \"youtube#video\", \"videoId\": \"IDKMKBmpwrg\" }, \"snippet\": { \"title\": \"Tinashe - Player (Audio) ft. Chris Brown\", \"description\": \"\\\"Player\\\" feat. Chris Brown from Tinashe's forthcoming new album, Joyride. Apple Music: http://smarturl.it/PlayerCBa?IQid=yt Spotify: http://smarturl.it/PlayerCBs?\", \"thumbnails\": { \"default\": { \"url\": \"https://i.ytimg.com/vi/IDKMKBmpwrg/default.jpg\" } }, \"channelTitle\": \"TinasheOfficialVEVO\" } }"}
_, err = db.NamedExec("insert into songs(songId, roomId, videoData) values(:songId, :id, :videoData)", map[string]interface{}{ "songId":"IDKMKBmpwrg", "id":room.Id, "videoData":song.VideoData })
if err != nil {
log.Printf("%q: %s\n", err)
return db, err
}
err = ioutil.WriteFile("bridgdDBVersion.txt", []byte(dbVersion), 0644)
if err != nil {
return db, err
}
}
return sqlx.Open("sqlite3", "./rooms.db")
}
func getRooms() ([]Room) {
db, err := createNewDB()
if err != nil {
log.Fatal(err)
}
defer db.Close()
var rooms []Room
rows, err := db.Queryx("select id, name from rooms")
defer rows.Close()
for rows.Next() {
var room Room
err := rows.StructScan(&room)
if err != nil {
log.Fatalln(err)
}
room.Queue = getSongsForRoom(room)
room.Current = room.Queue[0]
rooms = append(rooms, room)
}
return rooms
}
func getRoom(roomName string) (Room, error) {
db, err := createNewDB()
if err != nil {
log.Fatal(err)
}
defer db.Close()
var room Room
err = db.Get(&room, "select * from rooms where name=$1", roomName)
if err != nil {
return room, err
}
room.Queue = getSongsForRoom(room)
room.Current = room.Queue[room.CurrentIndex]
if err != nil {
return room, err
}
return room, nil
}
func addSongToRoom(songJSONStr string, room Room) (Room, error) {
db, err := createNewDB()
var songJSON SongJSON
err = json.Unmarshal([]byte(songJSONStr), &songJSON)
if err != nil {
return room, err
}
songIdMap,ok := songJSON["id"].(map[string]interface{}) // type assertion
if !ok {
return room, errors.New("song json is not formatted properly")
}
_, err = db.NamedExec("insert into songs(songId, roomId, videoData) values(:songId, :id, :videoData)", map[string]interface{}{ "songId": songIdMap["videoId"] , "id":room.Id, "videoData":songJSONStr })
if err != nil {
return room, err
}
room.Queue = append(room.Queue, songJSON)
return room, nil
}
func getSongsForRoom(room Room) ([]SongJSON) {
db, err := createNewDB()
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query(fmt.Sprintf("select videoData from songs where roomId=%d",room.Id))
if err != nil {
log.Fatal(err)
}
var songs []SongJSON
defer rows.Close()
for rows.Next() {
var song Song
rows.Scan(&song.VideoData)
var songJSON SongJSON
err := json.Unmarshal([]byte(song.VideoData), &songJSON)
if err != nil {
log.Fatal(err)
}
songs = append(songs, songJSON)
}
return songs
}