-
Notifications
You must be signed in to change notification settings - Fork 0
/
playlist_maker.go
79 lines (69 loc) · 2.24 KB
/
playlist_maker.go
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
package main
import (
"fmt"
"log"
"time"
"github.com/zmb3/spotify"
)
func makePlaylist(client *SpotifyClient, cfg *config, d *data) error {
// So we're ready to potentially make, and append to a target playlist.
currentUser, err := client.CurrentUser()
if err != nil {
return fmt.Errorf("failed to get the current user: %w", err)
}
sinceTime := time.Now().Add(-1 * cfg.duration)
playlistSuffixFormat := "Jan _2, 2006"
playlistTimeSuffix := fmt.Sprintf(
"%s - %s",
sinceTime.Format(playlistSuffixFormat),
time.Now().Format(playlistSuffixFormat),
)
descriptionFormat := "Mon Jan _2, 3:04PM 2006"
playlist, err := client.CreatePlaylistForUser(
currentUser.ID,
fmt.Sprintf("%s (%s)", cfg.playlistName, playlistTimeSuffix),
fmt.Sprintf(
"Generated by fangirl - releases from %v to %v.",
sinceTime.Format(descriptionFormat),
time.Now().Format(descriptionFormat),
),
false,
)
if err != nil {
return fmt.Errorf("failed to create the playlist: %w", err)
}
for i, album := range d.albums {
albumTracksPage, err := client.GetAlbumTracks(album.ID)
if err != nil {
return fmt.Errorf("failed to get album tracks: %w", err)
}
for {
batch := make([]spotify.ID, 0, 100)
for _, track := range albumTracksPage.Tracks {
batch = append(batch, track.ID)
if len(batch) == 100 {
if _, err := client.AddTracksToPlaylist(playlist.ID, batch...); err != nil {
return fmt.Errorf("failed to add tracks to the playlist: %w", err)
}
batch = batch[:0]
}
}
if len(batch) != 0 {
// If this happens, it means that we finished the batching loop above
// and had some tracks leftover. So let's not forget to add this to the
// playlist before we go to the next page of tracks.
if _, err := client.AddTracksToPlaylist(playlist.ID, batch...); err != nil {
return fmt.Errorf("failed to add tracks to the playlist: %w", err)
}
}
if err := client.NextSimpleTrackPage(albumTracksPage); err == spotify.ErrNoMorePages {
break
} else if err != nil {
return fmt.Errorf("failed to iterate to the next album track page: %w", err)
}
}
percentageDone := 100 * (float64(i+1) / float64(len(d.albums)))
log.Printf("\t(%f%% done) Importing into playlist", percentageDone)
}
return nil
}