summaryrefslogtreecommitdiffstats
path: root/data.go
diff options
context:
space:
mode:
Diffstat (limited to 'data.go')
-rw-r--r--data.go113
1 files changed, 113 insertions, 0 deletions
diff --git a/data.go b/data.go
new file mode 100644
index 0000000..7cdccca
--- /dev/null
+++ b/data.go
@@ -0,0 +1,113 @@
+package main
+
+import (
+ "database/sql"
+ "encoding/xml"
+ "fmt"
+ "time"
+
+ _ "github.com/mattn/go-sqlite3"
+)
+
+type Scrobble struct {
+ Artist string
+ AlbumArtist string
+ TrackName string
+ Album string
+ TrackNumber int
+ Duration int
+ Time int
+ Chosen bool
+ Mbid string
+ Session string
+}
+
+type Session struct {
+ XMLName xml.Name `json:"-" xml:"session"`
+ User string `json:"name" xml:"name"`
+ Key string `json:"key" xml:"key"`
+ Client string
+ Protocol string
+ Created int64
+ Subscriber int64 `json:"subscriber" xml:"subscriber"`
+}
+
+type DataStore interface {
+ PutSession(*Session)
+ GetSession(key string) (*Session, bool)
+ GetPassword(userName string) (string, bool)
+ PutScrobbles([]Scrobble)
+ Api
+}
+
+type SqlStore struct {
+ *sql.DB
+}
+
+func NewSqlStore() *SqlStore {
+ db, err := sql.Open("sqlite3", "./test.db")
+ if err != nil {
+ fmt.Println(err)
+ }
+ err = db.Ping()
+ if err != nil {
+ fmt.Println(err)
+ }
+ return &SqlStore{db}
+}
+
+func NewSession(user string, client string, protocol string) *Session {
+ return &Session{
+ User: user,
+ Key: randomToken(16),
+ Client: client,
+ Protocol: protocol,
+ Created: time.Now().Unix(),
+ }
+}
+
+func (store *SqlStore) PutSession(s *Session) {
+ store.Exec("INSERT INTO sessions VALUES (?, ?, ?, ?, ?)",
+ s.User, s.Key, s.Client, s.Protocol, s.Created)
+}
+
+func (store *SqlStore) GetSession(key string) (*Session, bool) {
+ s := &Session{}
+ row := store.QueryRow("SELECT * FROM sessions WHERE key = ?", key)
+ err := row.Scan(&s.User, &s.Key, &s.Client, &s.Protocol, &s.Created)
+ if err == sql.ErrNoRows {
+ return s, false
+ } else if err != nil {
+ fmt.Println(err)
+ }
+ return s, true
+}
+
+func (store *SqlStore) GetPassword(name string) (string, bool) {
+ var password string
+ row := store.QueryRow("SELECT password FROM users WHERE name = ?", name)
+ err := row.Scan(&password)
+ if err == sql.ErrNoRows {
+ return password, false
+ } else if err != nil {
+ fmt.Println(err)
+ }
+ return password, true
+}
+
+func (store *SqlStore) PutScrobbles(scrobbles []Scrobble) {
+ for _, s := range scrobbles {
+ store.Exec("INSERT INTO scrobbles VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ s.Artist,
+ s.AlbumArtist,
+ s.TrackName,
+ s.Album,
+ s.TrackNumber,
+ s.Duration,
+ s.Time,
+ s.Chosen,
+ s.Mbid,
+ s.Session,
+ )
+ }
+}