-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
214 lines (181 loc) · 5.68 KB
/
sync.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main
import (
"errors"
"github.com/sirupsen/logrus"
"github.com/thechubbypanda/syncify/model"
"github.com/thechubbypanda/syncify/views"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
"golang.org/x/oauth2"
"net/http"
"time"
)
func getLikedTrackIds(r *http.Request, s *spotify.Client) ([]spotify.ID, error) {
var trackIds []spotify.ID
tracks, err := s.CurrentUsersTracks(r.Context(), spotify.Limit(50))
if err != nil {
return nil, err
}
for _, t := range tracks.Tracks {
trackIds = append(trackIds, t.SimpleTrack.ID)
}
for page := 1; ; page++ {
err = s.NextPage(r.Context(), tracks)
if errors.Is(err, spotify.ErrNoMorePages) {
break
}
if err != nil {
return nil, err
}
for _, t := range tracks.Tracks {
trackIds = append(trackIds, t.SimpleTrack.ID)
}
}
return trackIds, nil
}
func getPlaylist(r *http.Request, s *spotify.Client, user *spotify.PrivateUser) (*spotify.SimplePlaylist, error) {
playlists, err := s.GetPlaylistsForUser(r.Context(), user.ID)
if err != nil {
return nil, err
}
logrus.Traceln(user.ID, ":", "reading page", 0, " of liked songs")
for _, p := range playlists.Playlists {
if p.Name == "Syncify" {
return &p, nil
}
}
for page := 1; ; page++ {
err = s.NextPage(r.Context(), playlists)
if errors.Is(err, spotify.ErrNoMorePages) {
break
}
if err != nil {
return nil, err
}
logrus.Traceln(user.ID, ":", "reading page", page, " of liked songs")
for _, p := range playlists.Playlists {
if p.Name == "Syncify" {
return &p, nil
}
}
}
playlist, err := s.CreatePlaylistForUser(r.Context(), user.ID, "Syncify", "A copy of your 'Liked Songs' playlist by Syncify", false, false)
if err != nil {
return nil, err
}
logrus.Debugln(user.ID, ":", "created playlist", playlist.ID)
return &playlist.SimplePlaylist, nil
}
func truncatePlaylist(r *http.Request, s *spotify.Client, user *spotify.PrivateUser, playlist *spotify.SimplePlaylist) error {
var trackIds []spotify.ID
// TODO (wasteful) https://github.com/zmb3/spotify/issues/262
tracks, err := s.GetPlaylistItems(r.Context(), playlist.ID /*spotify.Fields("items(track(id))"),*/, spotify.Limit(50))
if err != nil {
return err
}
logrus.Traceln(user.ID, ":", "reading page", 0, " of tracks from playlist", playlist.ID)
for _, t := range tracks.Items {
trackIds = append(trackIds, t.Track.Track.ID)
}
for page := 1; ; page++ {
err = s.NextPage(r.Context(), tracks)
if errors.Is(err, spotify.ErrNoMorePages) {
break
}
if err != nil {
return err
}
logrus.Traceln(user.ID, ":", "reading page", page, " of tracks from playlist", playlist.ID)
for _, t := range tracks.Items {
trackIds = append(trackIds, t.Track.Track.ID)
}
}
if len(trackIds) > 0 {
for i := 0; i <= len(trackIds)/100; i++ {
logrus.Traceln(user.ID, ":", "removing tracks", i*100, "-", min((i+1)*100, len(trackIds))-1, "from", playlist.ID)
_, err := s.RemoveTracksFromPlaylist(r.Context(), playlist.ID, trackIds[i*100:min((i+1)*100, len(trackIds))]...)
if err != nil {
return err
}
}
}
return nil
}
func truncateWrapper(r *http.Request, s *spotify.Client, user *spotify.PrivateUser, playlist *spotify.SimplePlaylist, c chan error) {
c <- truncatePlaylist(r, s, user, playlist)
}
type LikedTrackIdsResult struct {
Tracks []spotify.ID
Err error
}
func getLikedTrackIdsWrapper(r *http.Request, s *spotify.Client, c chan LikedTrackIdsResult) {
tracks, err := getLikedTrackIds(r, s)
c <- LikedTrackIdsResult{
tracks,
err,
}
}
func sync(r *http.Request, token *oauth2.Token) model.SyncResponse {
s := spotify.New(spotifyauth.New().Client(r.Context(), token))
user, err := s.CurrentUser(r.Context())
if err != nil {
logrus.Errorln("failed to fetch user: ", err)
return model.SyncResponse{Err: err}
}
logrus.Debugln(user.ID, ":", "starting sync")
playlist, err := getPlaylist(r, s, user)
if err != nil {
logrus.Errorln(user.ID, ":", err)
return model.SyncResponse{Err: err}
}
logrus.Debugln(user.ID, ":", "using playlist", playlist.ID)
truncateChannel := make(chan error)
go truncateWrapper(r, s, user, playlist, truncateChannel)
likedIdsChannel := make(chan LikedTrackIdsResult)
go getLikedTrackIdsWrapper(r, s, likedIdsChannel)
likedResult := <- likedIdsChannel
if likedResult.Err != nil {
logrus.Errorln(user.ID, ":", err)
return model.SyncResponse{Err: err}
}
trackIds := likedResult.Tracks
logrus.Debugln(user.ID, ":", "found", len(trackIds), "liked songs")
if <-truncateChannel != nil {
logrus.Errorln(user.ID, ":", err)
return model.SyncResponse{Err: err}
}
logrus.Debugln(user.ID, ":", "truncated playlist", playlist.ID)
if len(trackIds) > 0 {
for i := 0; i <= len(trackIds)/100; i++ {
logrus.Traceln(user.ID, ":", "adding tracks", i*100, "-", min((i+1)*100, len(trackIds))-1, "to", playlist.ID)
_, err := s.AddTracksToPlaylist(r.Context(), playlist.ID, trackIds[i*100:min((i+1)*100, len(trackIds))]...)
if err != nil {
logrus.Errorln(user.ID, ":", err)
return model.SyncResponse{Err: err}
}
}
}
logrus.Infoln(user.ID, ":", "sync complete for", len(trackIds), "songs")
return model.SyncResponse{
Count: len(trackIds),
PlaylistUrl: playlist.ExternalURLs["spotify"],
}
}
func Sync(w http.ResponseWriter, r *http.Request) {
token, ok := sm.Get(r.Context(), "token").(oauth2.Token)
if !ok || token.Expiry.Before(time.Now()) {
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
logrus.Traceln("no token or expired")
return
}
syncResponse := sync(r, &token)
err := views.Outcome(model.Model{
Plausible: nil,
User: nil,
SyncOutcome: &syncResponse,
}).Render(w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}