aboutsummaryrefslogtreecommitdiffstats
path: root/data.go
blob: 065e891b4bae8204a98c461b3e7d7c8dc97edd2c (plain)
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
package main

import (
	"database/sql"
	"encoding/xml"
	"fmt"
	"time"

	_ "github.com/mattn/go-sqlite3"
)

type Scrobble struct {
	Artist      Correctable `xml:"artist" json:"artist"`
	AlbumArtist Correctable `xml:"albumArtist" json:"albumArtist"`
	TrackName   Correctable `xml:"track" json:"track"`
	Album       Correctable `xml:"album" json:"album"`
	TrackNumber int         `xml:"-" json:"-"`
	Duration    int         `xml:"-" json:"-"`
	Time        int         `xml:"timestamp" json:"timestamp,string"`
	Chosen      bool        `xml:"-" json:"-"`
	Mbid        string      `xml:"-" json:"-"`
	Session     string      `xml:"-" json:"-"`
}

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, error)
	GetPassword(userName string) (string, error)
	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, error) {
	s := &Session{}
	row := store.QueryRow("SELECT * FROM sessions WHERE key = ?", key)
	err := row.Scan(&s.User, &s.Key, &s.Client, &s.Protocol, &s.Created)
	return s, err
}

func (store *SqlStore) GetPassword(name string) (string, error) {
	var password string
	row := store.QueryRow("SELECT password FROM users WHERE name = ?", name)
	err := row.Scan(&password)
	return password, err
}

func (store *SqlStore) PutScrobbles(scrobbles []Scrobble) {
	for _, s := range scrobbles {
		if _, err := 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,
		); err != nil {
			fmt.Printf("error : %v\n", err)
		}
	}
}