2021-04-01 12:56:08 +00:00
|
|
|
package goscrobble
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2021-04-02 13:48:38 +00:00
|
|
|
"encoding/json"
|
2021-04-02 12:44:11 +00:00
|
|
|
"errors"
|
2021-04-02 13:48:38 +00:00
|
|
|
"fmt"
|
2021-04-02 12:44:11 +00:00
|
|
|
"log"
|
2021-04-01 12:56:08 +00:00
|
|
|
"net"
|
2021-04-02 12:11:05 +00:00
|
|
|
"time"
|
2021-04-01 12:56:08 +00:00
|
|
|
)
|
|
|
|
|
2021-04-02 13:48:38 +00:00
|
|
|
type MultiScrobblerRequest struct {
|
2021-04-02 12:11:05 +00:00
|
|
|
Artists []string `json:"artists"`
|
|
|
|
Album string `json:"album"`
|
|
|
|
Track string `json:"track"`
|
|
|
|
PlayedAt time.Time `json:"playDate"`
|
2021-04-02 12:44:11 +00:00
|
|
|
Duration int `json:"duration"`
|
2021-04-02 12:11:05 +00:00
|
|
|
}
|
|
|
|
|
2021-04-01 12:56:08 +00:00
|
|
|
// ParseMultiScrobblerInput - Transform API data
|
2021-04-02 13:48:38 +00:00
|
|
|
func ParseMultiScrobblerInput(userUUID string, data MultiScrobblerRequest, ip net.IP, tx *sql.Tx) error {
|
|
|
|
// Cache key
|
|
|
|
json, _ := json.Marshal(data)
|
|
|
|
redisKey := getMd5(string(json) + userUUID)
|
|
|
|
if getRedisKeyExists(redisKey) {
|
|
|
|
fmt.Printf("Prevented duplicate entry!")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-04-02 12:44:11 +00:00
|
|
|
artists := make([]string, 0)
|
|
|
|
albumartists := make([]string, 0)
|
|
|
|
|
|
|
|
// Insert track artists
|
|
|
|
for _, artist := range data.Artists {
|
|
|
|
artist, err := insertArtist(artist, "", "", tx)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map artist: " + artist.Name)
|
|
|
|
}
|
|
|
|
artists = append(artists, artist.Uuid)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert album if not exist
|
|
|
|
album, err := insertAlbum(data.Album, "", "", albumartists, tx)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map album")
|
|
|
|
}
|
2021-04-01 12:56:08 +00:00
|
|
|
|
|
|
|
// Insert track if not exist
|
2021-04-02 12:44:11 +00:00
|
|
|
track, err := insertTrack(data.Track, data.Duration, "", "", album.Uuid, artists, tx)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map track")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert scrobble if not exist
|
|
|
|
err = insertScrobble(userUUID, track.Uuid, "multiscrobbler", data.PlayedAt, ip, tx)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map track")
|
|
|
|
}
|
|
|
|
|
2021-04-02 13:48:38 +00:00
|
|
|
// Add cache key for the duration of the song *2 since we're caching the start time too
|
|
|
|
ttl := time.Duration(data.Duration*2) * time.Second
|
|
|
|
setRedisValTtl(redisKey, "1", ttl)
|
|
|
|
|
2021-04-01 12:56:08 +00:00
|
|
|
return nil
|
|
|
|
}
|