2021-04-01 12:56:08 +00:00
|
|
|
package goscrobble
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
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
|
2021-04-03 00:54:07 +00:00
|
|
|
json := fmt.Sprintf("%s:%s:%s:%s", data.PlayedAt, data.Track, data.Album, userUUID)
|
|
|
|
redisKey := getMd5(json)
|
2021-04-02 13:48:38 +00:00
|
|
|
if getRedisKeyExists(redisKey) {
|
|
|
|
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)
|
|
|
|
}
|
2021-04-04 09:54:53 +00:00
|
|
|
artists = append(artists, artist.UUID)
|
2021-04-02 12:44:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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-04 09:54:53 +00:00
|
|
|
track, err := insertTrack(data.Track, data.Duration, "", "", album.UUID, artists, tx)
|
2021-04-02 12:44:11 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map track")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert scrobble if not exist
|
2021-04-04 09:54:53 +00:00
|
|
|
err = insertScrobble(userUUID, track.UUID, "multiscrobbler", data.PlayedAt, ip, tx)
|
2021-04-02 12:44:11 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map track")
|
|
|
|
}
|
|
|
|
|
2021-04-03 00:54:07 +00:00
|
|
|
ttl := time.Duration(30) * time.Minute
|
2021-04-02 13:48:38 +00:00
|
|
|
setRedisValTtl(redisKey, "1", ttl)
|
|
|
|
|
2021-04-01 12:56:08 +00:00
|
|
|
return nil
|
|
|
|
}
|