aboutsummaryrefslogtreecommitdiffstats
path: root/data.go
blob: ba3157bcd12f74551da5191e14cf28c058fb7c0c (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
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package main

import (
	"database/sql"
	"encoding/xml"
	"log"
	"time"
)

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        time.Time   `xml:"timestamp" json:"timestamp,string"`
	Chosen      bool        `xml:"-" json:"-"`
	Mbid        string      `xml:"-" json:"-"`
	SongId      int
	SessionKey  string `xml:"-" json:"-"`
	UserId      int
	Image       string
}

type Session struct {
	XMLName       xml.Name `json:"-" xml:"session"`
	User          string   `json:"name" xml:"name"`
	Key           string   `json:"key" xml:"key"`
	UserId        int
	Client        string
	ClientVersion string
	Protocol      string
	Created       time.Time
	Subscriber    int64 `json:"subscriber" xml:"subscriber"`
}

type Song struct {
	Id          int
	Artist      string
	Album       string
	Name        string
	TrackNumber int
	Duration    int
	Mbid        string
	Image       string
}

type Import struct {
	LfmName   string
	From      time.Time
	To        time.Time
	LastFetch time.Time
	Done      bool
	Count     int
}

type LoveImport struct {
	LfmName string
	Time    time.Time
	Count   int
}

type Client struct {
	Key    string
	Secret string
	Name   string
}

type DataStore interface {
	PutSession(*Session) error
	GetSession(key string) (*Session, error)
	GetClient(key string) (*Client, error)
	PutScrobbles([]Scrobble) error
	PutNowPlaying(s Scrobble) error
	NowPlaying(userId int) *Scrobble
	RecentScrobbles(userId int) []*Scrobble

	GetSongId(s *Song) error
	InsertSong(s *Song) error

	GetScrobblingUser(lfmName string) (int, string, error)
	GetUser(u *User) error
	InsertUser(u *User) error
	SaveUser(u *User) error

	SaveImport(i *Import) error
	InsertImport(i *Import) error
	NewImport(name string) *Import
	ImportStats(name string) (*Import, error)

	InsertLoveImport(i *LoveImport) error
	LoveImportStats(name string) (*LoveImport, error)

	InsertLovedTracks([]LovedTrack, *Session) error

	InsertUserSession(s *UserSession) error
	Api
}

type SqlStore struct {
	*sql.DB
}

func (store *SqlStore) PutSession(s *Session) error {
	query := `
	INSERT INTO scrobbling_sessions (user_id, session_key, client, client_version, protocol)
	VALUES ($1, $2, $3, $4, $5)`
	_, err := store.Exec(query, s.UserId, s.Key, s.Client, s.ClientVersion, s.Protocol)
	return err
}

func (store *SqlStore) GetSession(key string) (*Session, error) {
	query := `
	SELECT user_id, session_key, client, client_version, protocol, created
	FROM scrobbling_sessions WHERE session_key = $1`
	row := store.QueryRow(query, key)
	s := new(Session)
	err := row.Scan(&s.UserId, &s.Key, &s.Client, &s.ClientVersion, &s.Protocol,
		&s.Created)
	return s, err
}

func (store *SqlStore) GetClient(key string) (*Client, error) {
	query := `SELECT secret, name FROM clients WHERE key = $1`
	row := store.QueryRow(query, key)
	c := &Client{Key: key}
	err := row.Scan(&c.Secret, &c.Name)
	return c, err
}

func (store *SqlStore) GetScrobblingUser(lfmName string) (int, string, error) {
	var password string
	var userId int
	row := store.QueryRow("SELECT user_id, lfm_password FROM users WHERE lfm_name = $1",
		lfmName)
	err := row.Scan(&userId, &password)
	return userId, password, err
}

func (store *SqlStore) PutScrobbles(scrobbles []Scrobble) error {
	tx, err := store.Begin()
	if err != nil {
		return err
	}
	query := `
	INSERT INTO scrobbles
	(artist, album_artist, track_name, album, track_number, duration, time,
	chosen, mbid, song_id, session_key, user_id)
	VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`
	st, err := tx.Prepare(query)
	if err != nil {
		return err
	}

	for _, s := range scrobbles {
		_, err = st.Exec(s.Artist, s.AlbumArtist, s.TrackName, s.Album,
			s.TrackNumber, s.Duration, s.Time, s.Chosen, s.Mbid, s.SongId,
			s.SessionKey, s.UserId)
		if err != nil {
			tx.Rollback()
			return err
		}
	}
	return tx.Commit()
}

func (store *SqlStore) PutNowPlaying(s Scrobble) error {
	query := `
	INSERT INTO now_playing
	(artist, album_artist, track_name, album, track_number, duration, 
	mbid, song_id, session_key, user_id)
	VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
	ON CONFLICT (user_id) DO UPDATE
	set artist=$1, album_artist=$2, track_name=$3, album=$4, track_number=$5,
	duration=$6, mbid=$7, song_id=$8, session_key=$9, user_id=$10,
	received=current_timestamp`

	_, err := store.Exec(query, s.Artist, s.AlbumArtist, s.TrackName, s.Album,
		s.TrackNumber, s.Duration, s.Mbid, s.SongId, s.SessionKey, s.UserId)
	return err
}

func (store *SqlStore) RecentScrobbles(userId int) []*Scrobble {
	scrobbles := make([]*Scrobble, 0, 10)
	query := `
	SELECT s.artist, s.album, s.track_name, s.time, songs.image
	FROM scrobbles s
	LEFT JOIN songs ON songs.song_id = s.song_id
	WHERE user_id=$1 ORDER BY time DESC LIMIT 10`
	rows, err := store.Query(query, userId)
	if err != nil {
		log.Println(err)
		return scrobbles
	}
	defer rows.Close()

	for rows.Next() {
		scrobble := new(Scrobble)
		rows.Scan(&scrobble.Artist.Name, &scrobble.Album.Name,
			&scrobble.TrackName.Name, &scrobble.Time, &scrobble.Image)
		scrobbles = append(scrobbles, scrobble)
	}
	return scrobbles
}

func (store *SqlStore) NowPlaying(userId int) *Scrobble {
	scrobble := new(Scrobble)
	query := `
	SELECT s.artist, s.album, s.track_name, s.received, songs.image, s.duration
	FROM now_playing s
	LEFT JOIN songs ON songs.song_id = s.song_id
	WHERE user_id=$1`
	row := store.QueryRow(query, userId)
	row.Scan(&scrobble.Artist.Name, &scrobble.Album.Name,
		&scrobble.TrackName.Name, &scrobble.Time, &scrobble.Image,
		&scrobble.Duration)
	return scrobble
}

func (store *SqlStore) GetSongId(s *Song) error {
	var query string
	if s.Mbid != "" {
		query = `SELECT song_id FROM songs WHERE mbid=$1`
		row := store.QueryRow(query, s.Mbid)
		return row.Scan(&s.Id)
	} else {
		query = `
		SELECT song_id FROM songs
		WHERE artist=$1 AND album=$2 AND name=$3`
		row := store.QueryRow(query, s.Artist, s.Album, s.Name)
		return row.Scan(&s.Id)
	}
}

func (store *SqlStore) InsertSong(s *Song) error {
	query := `
	INSERT INTO songs (artist, album, name, track_number, duration, mbid, image)
	VALUES ($1, $2, $3, $4, $5, $6, $7)
	RETURNING song_id`
	row := store.QueryRow(query, s.Artist, s.Album, s.Name, s.TrackNumber,
		s.Duration, s.Mbid, s.Image)
	return row.Scan(&s.Id)
}

func (store *SqlStore) InsertUser(user *User) error {
	query := `
	INSERT into users (type, op_id, name, email)
	VALUES ($1, $2, $3, $4) RETURNING user_id`
	row := store.QueryRow(query, user.Type, user.OpId, user.Name, user.Email)
	return row.Scan(&user.Id)
}

func (store *SqlStore) GetUser(user *User) error {
	var query string
	var row *sql.Row
	if user.Id == 0 {
		query = `
		SELECT user_id, name, email, lfm_name
		FROM users WHERE type=$1 AND op_id=$2`
		row = store.QueryRow(query, user.Type, user.OpId)
	} else {
		query = `
		SELECT user_id, name, email, lfm_name
		FROM users WHERE user_id=$1`
		row = store.QueryRow(query, user.Id)
	}
	return row.Scan(&user.Id, &user.Name, &user.Email, &user.LfmName)
}

func (store *SqlStore) SaveUser(user *User) error {
	var err error
	var query string
	if user.LfmPassword != "" {
		query = `
		UPDATE users SET name=$1, email=$2, lfm_name=$3, lfm_password=$4
		WHERE  user_id=$5`
		_, err = store.Exec(query, user.Name, user.Email, user.LfmName,
			user.LfmPassword, user.Id)
	} else {
		query = `
		UPDATE users SET name=$1, email=$2, lfm_name=$3 WHERE  user_id=$5`
		_, err = store.Exec(query, user.Name, user.Email, user.LfmName, user.Id)

	}
	return err
}

func (store *SqlStore) InsertUserSession(s *UserSession) error {
	query := `INSERT into user_sessions values ($1, $2)`
	_, err := store.Exec(query, &s.Id, &s.UserId)
	return err
}

func (store *SqlStore) SaveImport(i *Import) error {
	query := `UPDATE scrobble_import SET last_fetch=$1, done=$5, count=$6
	WHERE "from"=$2 and "to"=$3 and lfm_name=$4`
	_, err := store.Exec(query, i.LastFetch, i.From, i.To, i.LfmName, i.Done, i.Count)
	return err
}

func (store *SqlStore) InsertImport(i *Import) error {
	query := `
	INSERT into scrobble_import (lfm_name, "from", "to", last_fetch, done, count)
	VALUES ($1, $2, $3, $4, $5, $6)`
	_, err := store.Exec(query, i.LfmName, i.From, i.To, i.LastFetch, i.Done, i.Count)
	return err
}

func (store *SqlStore) NewImport(name string) *Import {
	i := &Import{
		LfmName: name,
		To:      time.Now(),
	}
	query := `SELECT max("to") FROM scrobble_import WHERE lfm_name=$1`
	row := store.QueryRow(query, i.LfmName)
	row.Scan(&i.From)
	if err := store.InsertImport(i); err != nil {
		log.Println(err)
	}
	return i
}

func (store *SqlStore) ImportStats(name string) (*Import, error) {
	query := `
	SELECT max("to"), sum(count)
	FROM scrobble_import
	WHERE lfm_name=$1
	GROUP BY lfm_name`
	i := new(Import)
	row := store.QueryRow(query, name)
	err := row.Scan(&i.To, &i.Count)
	return i, err
}

func (store *SqlStore) InsertLoveImport(i *LoveImport) error {
	query := `
	INSERT INTO love_import (lfm_name, count) VALUES ($1, $2)`
	_, err := store.Exec(query, i.LfmName, i.Count)
	return err
}

func (store *SqlStore) InsertLovedTracks(lt []LovedTrack, se *Session) error {
	tx, err := store.Begin()
	if err != nil {
		return err
	}
	query := `
	INSERT INTO love
	(artist, name, mbid, time, session, "user")
	VALUES ($1, $2, $3, $4, $5, $6)`
	st, err := tx.Prepare(query)
	if err != nil {
		return err
	}

	for _, t := range lt {
		_, err = st.Exec(t.Artist.Name, t.Name, t.Mbid, t.Date.ToTime(),
			se.Key, se.UserId)
		if err != nil {
			tx.Rollback()
			return err
		}
	}
	return tx.Commit()
}
func (store *SqlStore) LoveImportStats(name string) (*LoveImport, error) {
	query := `
	SELECT max(time), sum(count) FROM love_import
	WHERE lfm_name = $1 GROUP BY lfm_name`
	li := new(LoveImport)
	row := store.QueryRow(query, name)
	err := row.Scan(&li.Time, &li.Count)
	return li, err
}