You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

145 lines
2.5 KiB
Go

package lists
import (
"context"
"fmt"
"time"
"gitea.ravianand.me/Dan6erbond/listy/core"
"gitea.ravianand.me/Dan6erbond/listy/internal"
"gitea.ravianand.me/Dan6erbond/listy/models"
"gitea.ravianand.me/Dan6erbond/listy/users"
"github.com/zmb3/spotify/v2"
)
func SyncMonthlyList(ctx context.Context, app *core.App, user *models.User) (int, error) {
client, err := users.GetSpotifyClient(ctx, app, user)
if err != nil {
return 0, err
}
beginningOfMonth := internal.BeginningOfMonth()
playlistName := fmt.Sprintf("%d %d", beginningOfMonth.Year(), beginningOfMonth.Month())
fmt.Println(playlistName)
var playlist *spotify.SimplePlaylist
playlists, err := client.CurrentUsersPlaylists(ctx)
if err != nil {
return 0, err
}
PLAYLISTS:
for page := 1; ; page++ {
for _, pl := range playlists.Playlists {
if pl.Name == playlistName {
playlist = &pl
break PLAYLISTS
}
}
err := client.NextPage(ctx, playlists)
if err == spotify.ErrNoMorePages {
break
}
if err != nil {
return 0, err
}
}
if playlist == nil {
fullPlaylist, err := client.CreatePlaylistForUser(ctx, user.SpotifyID, playlistName, "", false, false)
if err != nil {
return 0, err
}
playlist = &fullPlaylist.SimplePlaylist
}
var playlistTracks []spotify.PlaylistItemTrack
items, err := client.GetPlaylistItems(ctx, playlist.ID)
if err != nil {
return 0, err
}
for page := 1; ; page++ {
for _, item := range items.Items {
playlistTracks = append(playlistTracks, item.Track)
}
err := client.NextPage(ctx, items)
if err == spotify.ErrNoMorePages {
break
}
if err != nil {
return 0, err
}
}
tracks, err := client.CurrentUsersTracks(ctx)
if err != nil {
return 0, err
}
var trackIDs []spotify.ID
TRACKS:
for page := 1; ; page++ {
TRACK:
for _, track := range tracks.Tracks {
for _, t := range playlistTracks {
if t.Track.ID == track.ID {
continue TRACK
}
}
addedAt, err := time.Parse(time.RFC3339, track.AddedAt)
if err != nil {
return 0, err
}
if addedAt.Before(beginningOfMonth) {
break TRACKS
}
fmt.Println("Adding", track.Name, "(added at", track.AddedAt+")")
trackIDs = append(trackIDs, track.ID)
}
err := client.NextPage(ctx, tracks)
if err == spotify.ErrNoMorePages {
break
}
if err != nil {
return 0, err
}
}
if len(trackIDs) > 0 {
_, err = client.AddTracksToPlaylist(ctx, playlist.ID, trackIDs...)
if err != nil {
return 0, err
}
return len(trackIDs), nil
}
return 0, nil
}