2021-04-02 09:24:00 +00:00
|
|
|
package goscrobble
|
|
|
|
|
|
|
|
import (
|
2022-01-05 08:52:36 +00:00
|
|
|
"context"
|
2021-04-02 09:24:00 +00:00
|
|
|
"database/sql"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
2022-01-05 08:52:36 +00:00
|
|
|
"github.com/zmb3/spotify/v2"
|
|
|
|
spotifyauth "github.com/zmb3/spotify/v2/auth"
|
2021-04-02 09:24:00 +00:00
|
|
|
"golang.org/x/oauth2"
|
|
|
|
)
|
|
|
|
|
|
|
|
// updateSpotifyData - Pull data for all users
|
|
|
|
func updateSpotifyData() {
|
|
|
|
// Lets ignore if not configured
|
2022-01-05 08:08:39 +00:00
|
|
|
val, _ := getConfigValue("SPOTIFY_API_SECRET")
|
2021-04-02 09:24:00 +00:00
|
|
|
if val == "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get all active users with a spotify token
|
|
|
|
users, err := getAllSpotifyUsers()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to fetch spotify users")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, user := range users {
|
|
|
|
user.updateSpotifyPlaydata()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-05 08:52:36 +00:00
|
|
|
// setSpotifyEnvVars - Temp fix for V2 Spotify SDK
|
|
|
|
func setSpotifyEnvVars() {
|
2022-01-05 08:08:39 +00:00
|
|
|
appId, _ := getConfigValue("SPOTIFY_API_ID")
|
|
|
|
appSecret, _ := getConfigValue("SPOTIFY_API_SECRET")
|
2022-01-05 08:52:36 +00:00
|
|
|
os.Setenv("SPOTIFY_ID", appId)
|
|
|
|
os.Setenv("SPOTIFY_SECRET", appSecret)
|
|
|
|
}
|
2021-04-02 09:24:00 +00:00
|
|
|
|
2022-01-05 08:52:36 +00:00
|
|
|
func getSpotifyAuthHandler() spotifyauth.Authenticator {
|
|
|
|
setSpotifyEnvVars()
|
2021-04-02 09:24:00 +00:00
|
|
|
redirectUrl := os.Getenv("GOSCROBBLE_DOMAIN") + "/api/v1/link/spotify"
|
|
|
|
if redirectUrl == "http://localhost:3000/api/v1/link/spotify" {
|
|
|
|
// Handle backend on a different port
|
|
|
|
redirectUrl = "http://localhost:42069/api/v1/link/spotify"
|
|
|
|
}
|
|
|
|
|
2022-01-05 08:52:36 +00:00
|
|
|
// the redirect URL must be an exact match of a URL you've registered for your application
|
|
|
|
// scopes determine which permissions the user is prompted to authorize
|
|
|
|
auth := spotifyauth.New(
|
|
|
|
spotifyauth.WithRedirectURL(redirectUrl),
|
|
|
|
spotifyauth.WithScopes(spotifyauth.ScopeUserReadRecentlyPlayed, spotifyauth.ScopeUserReadCurrentlyPlaying),
|
|
|
|
)
|
2021-04-02 09:24:00 +00:00
|
|
|
|
2022-01-05 08:52:36 +00:00
|
|
|
return *auth
|
2021-04-02 09:24:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func connectSpotifyResponse(r *http.Request) error {
|
|
|
|
urlParams := r.URL.Query()
|
|
|
|
userUuid := urlParams["state"][0]
|
|
|
|
|
|
|
|
// TODO: Add validation user exists here
|
|
|
|
auth := getSpotifyAuthHandler()
|
2022-01-05 08:52:36 +00:00
|
|
|
token, err := auth.Token(r.Context(), userUuid, r)
|
2021-04-02 09:24:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get displayName
|
2022-01-05 08:52:36 +00:00
|
|
|
client := spotify.New(auth.Client(r.Context(), token))
|
|
|
|
spotifyUser, err := client.CurrentUser(r.Context())
|
2021-04-02 09:24:00 +00:00
|
|
|
|
|
|
|
// Lets pull in last 30 minutes
|
|
|
|
time := time.Now().UTC().Add(-(time.Duration(30) * time.Minute))
|
2021-04-09 21:49:32 +00:00
|
|
|
err = insertOauthToken(userUuid, "spotify", token.AccessToken, token.RefreshToken, token.Expiry, spotifyUser.DisplayName, time, "")
|
2021-04-02 09:24:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) updateSpotifyPlaydata() {
|
|
|
|
dbToken, err := user.getSpotifyTokens()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("No spotify token for user: %+v %+v", user.Username, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
token := new(oauth2.Token)
|
|
|
|
token.AccessToken = dbToken.AccessToken
|
|
|
|
token.RefreshToken = dbToken.RefreshToken
|
|
|
|
token.Expiry = dbToken.Expiry
|
|
|
|
token.TokenType = "Bearer"
|
|
|
|
|
|
|
|
auth := getSpotifyAuthHandler()
|
2022-01-05 08:52:36 +00:00
|
|
|
ctx := context.Background()
|
|
|
|
client := spotify.New(auth.Client(ctx, token))
|
2021-04-02 09:24:00 +00:00
|
|
|
|
|
|
|
// Only fetch tracks since last sync
|
|
|
|
opts := spotify.RecentlyPlayedOptions{
|
|
|
|
AfterEpochMs: dbToken.LastSynced.UnixNano() / int64(time.Millisecond),
|
|
|
|
}
|
|
|
|
|
|
|
|
// We want the next sync timestamp from before we call
|
|
|
|
// so we don't end up with a few seconds gap
|
|
|
|
currTime := time.Now()
|
2022-01-05 08:52:36 +00:00
|
|
|
items, err := client.PlayerRecentlyPlayedOpt(ctx, &opts)
|
2021-04-02 09:24:00 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
fmt.Printf("Unable to get recently played tracks for user: %+v", user.Username)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, v := range items {
|
|
|
|
if !checkIfSpotifyAlreadyScrobbled(user.UUID, v) {
|
|
|
|
tx, _ := db.Begin()
|
2022-01-05 08:52:36 +00:00
|
|
|
err := ParseSpotifyInput(ctx, user.UUID, v, client, tx)
|
2021-04-02 09:24:00 +00:00
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to insert Spotify scrobble: %+v", err)
|
|
|
|
tx.Rollback()
|
|
|
|
break
|
|
|
|
}
|
|
|
|
tx.Commit()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if token has changed.. if so, save it to db
|
|
|
|
currToken, err := client.Token()
|
2021-04-09 21:49:32 +00:00
|
|
|
err = insertOauthToken(user.UUID, "spotify", currToken.AccessToken, currToken.RefreshToken, currToken.Expiry, dbToken.Username, currTime, "")
|
2021-04-02 09:24:00 +00:00
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to update spotify token in database")
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func checkIfSpotifyAlreadyScrobbled(userUuid string, data spotify.RecentlyPlayedItem) bool {
|
|
|
|
return checkIfScrobbleExists(userUuid, data.PlayedAt, "spotify")
|
|
|
|
}
|
|
|
|
|
|
|
|
// ParseSpotifyInput - Transform API data
|
2022-01-05 08:52:36 +00:00
|
|
|
func ParseSpotifyInput(ctx context.Context, userUUID string, data spotify.RecentlyPlayedItem, client *spotify.Client, tx *sql.Tx) error {
|
2021-04-02 09:24:00 +00:00
|
|
|
artists := make([]string, 0)
|
|
|
|
albumartists := make([]string, 0)
|
|
|
|
|
|
|
|
// Insert track artists
|
|
|
|
for _, artist := range data.Track.Artists {
|
2022-01-05 08:52:36 +00:00
|
|
|
fullArtist, err := client.GetArtist(ctx, artist.ID)
|
2021-04-08 07:50:43 +00:00
|
|
|
img := ""
|
|
|
|
if len(fullArtist.Images) > 0 {
|
|
|
|
img = fullArtist.Images[0].URL
|
|
|
|
}
|
|
|
|
|
|
|
|
artist, err := insertArtist(artist.Name, "", artist.ID.String(), img, tx)
|
2021-04-02 09:24:00 +00:00
|
|
|
|
|
|
|
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 09:24:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get full track data (album / track info)
|
2022-01-05 08:52:36 +00:00
|
|
|
fulltrack, err := client.GetTrack(ctx, data.Track.ID)
|
2021-04-02 09:24:00 +00:00
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to get full track info from spotify: %+v", data.Track.Name)
|
|
|
|
return errors.New("Failed to get full track info from spotify: " + data.Track.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert album artists
|
|
|
|
for _, artist := range fulltrack.Album.Artists {
|
2022-01-05 08:52:36 +00:00
|
|
|
fullArtist, err := client.GetArtist(ctx, artist.ID)
|
2021-04-08 07:50:43 +00:00
|
|
|
img := ""
|
|
|
|
if len(fullArtist.Images) > 0 {
|
|
|
|
img = fullArtist.Images[0].URL
|
|
|
|
}
|
|
|
|
|
|
|
|
albumartist, err := insertArtist(artist.Name, "", artist.ID.String(), img, tx)
|
2021-04-02 09:24:00 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map album: " + artist.Name)
|
|
|
|
}
|
2021-04-04 09:54:53 +00:00
|
|
|
albumartists = append(albumartists, albumartist.UUID)
|
2021-04-02 09:24:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Insert album if not exist
|
2021-04-08 07:50:43 +00:00
|
|
|
albumImage := ""
|
|
|
|
if len(fulltrack.Album.Images) > 0 {
|
|
|
|
albumImage = fulltrack.Album.Images[0].URL
|
|
|
|
}
|
|
|
|
album, err := insertAlbum(fulltrack.Album.Name, "", fulltrack.Album.ID.String(), albumartists, albumImage, tx)
|
2021-04-02 09:24:00 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map album")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert track if not exist
|
2021-04-02 13:53:54 +00:00
|
|
|
length := int(fulltrack.Duration / 1000)
|
2021-04-04 09:54:53 +00:00
|
|
|
track, err := insertTrack(fulltrack.Name, length, "", fulltrack.ID.String(), album.UUID, artists, tx)
|
2021-04-02 09:24:00 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map track")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert scrobble if not exist
|
|
|
|
ip := net.ParseIP("0.0.0.0")
|
2021-04-04 09:54:53 +00:00
|
|
|
err = insertScrobble(userUUID, track.UUID, "spotify", data.PlayedAt, ip, tx)
|
2021-04-02 09:24:00 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("%+v", err)
|
|
|
|
return errors.New("Failed to map track")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2021-04-08 07:50:43 +00:00
|
|
|
|
2021-04-08 08:46:31 +00:00
|
|
|
// updateImageDataFromSpotify update artist/album images from spotify ;D
|
|
|
|
func (user *User) updateImageDataFromSpotify() error {
|
|
|
|
// Check that data is set before we attempt to pull
|
2022-01-05 08:08:39 +00:00
|
|
|
val, _ := getConfigValue("SPOTIFY_API_SECRET")
|
2021-04-08 08:46:31 +00:00
|
|
|
if val == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// TO BE REWORKED TO NOT USE A DAMN USER ARGHHH
|
|
|
|
dbToken, err := user.getSpotifyTokens()
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
token := new(oauth2.Token)
|
|
|
|
token.AccessToken = dbToken.AccessToken
|
|
|
|
token.RefreshToken = dbToken.RefreshToken
|
|
|
|
token.Expiry = dbToken.Expiry
|
|
|
|
token.TokenType = "Bearer"
|
|
|
|
|
|
|
|
auth := getSpotifyAuthHandler()
|
2022-01-05 08:52:36 +00:00
|
|
|
client := spotify.New(auth.Client(ctx, token))
|
2021-04-08 08:46:31 +00:00
|
|
|
|
2021-04-16 23:34:53 +00:00
|
|
|
rows, err := db.Query("SELECT BIN_TO_UUID(`uuid`, true), `name` FROM `artists` WHERE IFNULL(`img`,'') NOT IN ('pending', 'complete') LIMIT 100")
|
2021-04-08 08:46:31 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to fetch config: %+v", err)
|
|
|
|
return errors.New("Failed to fetch artists")
|
|
|
|
}
|
|
|
|
|
|
|
|
toUpdate := make(map[string]string)
|
|
|
|
for rows.Next() {
|
|
|
|
var uuid string
|
|
|
|
var name string
|
|
|
|
err := rows.Scan(&uuid, &name)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to fetch artists: %+v", err)
|
|
|
|
rows.Close()
|
|
|
|
return errors.New("Failed to fetch artist")
|
|
|
|
}
|
2022-01-05 08:52:36 +00:00
|
|
|
res, err := client.Search(ctx, name, spotify.SearchTypeArtist)
|
2021-04-08 08:46:31 +00:00
|
|
|
if len(res.Artists.Artists) > 0 {
|
|
|
|
if len(res.Artists.Artists[0].Images) > 0 {
|
|
|
|
toUpdate[uuid] = res.Artists.Artists[0].Images[0].URL
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
rows.Close()
|
|
|
|
|
|
|
|
var artist Artist
|
|
|
|
tx, _ := db.Begin()
|
|
|
|
for uuid, img := range toUpdate {
|
|
|
|
artist, err = getArtistByUUID(uuid)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2021-04-11 08:10:52 +00:00
|
|
|
|
|
|
|
err = importImage(uuid, img)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to import image: %+v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
_ = artist.updateArtist("img", "pending", tx)
|
2021-04-08 08:46:31 +00:00
|
|
|
}
|
|
|
|
tx.Commit()
|
|
|
|
|
2021-04-16 23:34:53 +00:00
|
|
|
rows, err = db.Query("SELECT BIN_TO_UUID(`uuid`, true), `name` FROM `albums` WHERE IFNULL(`img`,'') NOT IN ('pending', 'complete') LIMIT 100")
|
2021-04-08 08:46:31 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to fetch config: %+v", err)
|
|
|
|
return errors.New("Failed to fetch artists")
|
|
|
|
}
|
|
|
|
|
|
|
|
toUpdate = make(map[string]string)
|
|
|
|
for rows.Next() {
|
|
|
|
var uuid string
|
|
|
|
var name string
|
|
|
|
err := rows.Scan(&uuid, &name)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to fetch albums: %+v", err)
|
|
|
|
rows.Close()
|
|
|
|
return errors.New("Failed to fetch album")
|
|
|
|
}
|
2022-01-05 08:52:36 +00:00
|
|
|
res, err := client.Search(ctx, name, spotify.SearchTypeAlbum)
|
2021-04-08 08:46:31 +00:00
|
|
|
if len(res.Albums.Albums) > 0 {
|
|
|
|
if len(res.Albums.Albums[0].Images) > 0 {
|
|
|
|
toUpdate[uuid] = res.Albums.Albums[0].Images[0].URL
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
rows.Close()
|
|
|
|
|
|
|
|
var album Album
|
|
|
|
tx, _ = db.Begin()
|
|
|
|
for uuid, img := range toUpdate {
|
|
|
|
album, err = getAlbumByUUID(uuid)
|
2021-04-11 08:10:52 +00:00
|
|
|
err = importImage(uuid, img)
|
|
|
|
|
2021-04-08 08:46:31 +00:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2021-04-11 08:10:52 +00:00
|
|
|
_ = album.updateAlbum("img", "pending", tx)
|
2021-04-08 08:46:31 +00:00
|
|
|
}
|
|
|
|
tx.Commit()
|
2021-04-08 07:50:43 +00:00
|
|
|
return nil
|
|
|
|
}
|