-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
497 lines (448 loc) · 13.3 KB
/
main.go
File metadata and controls
497 lines (448 loc) · 13.3 KB
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package main
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
_ "github.com/go-sql-driver/mysql"
webPlayer "github.com/mirrorfm/spotify-webplayer-token/app"
api "github.com/mirrorfm/unofficial-spotify-api/app"
"github.com/pkg/errors"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
type App struct {
SQLDriver *sql.DB
}
func getApp() (App, error) {
// MySQL
dbHost := os.Getenv("DB_HOST")
dbUser := os.Getenv("DB_USERNAME")
dbPass := os.Getenv("DB_PASSWORD")
dbName := os.Getenv("DB_NAME")
sqlDriver, err := sql.Open("mysql", dbUser+":"+dbPass+"@tcp("+dbHost+")/"+dbName+"?parseTime=true")
if err != nil {
return App{}, errors.Wrap(err, "failed to set up DB client")
}
return App{
SQLDriver: sqlDriver,
}, nil
}
// getSpotifyOAuthToken fetches an OAuth access token using the refresh token stored in DynamoDB.
func getSpotifyOAuthToken() (string, error) {
clientID := os.Getenv("SPOTIPY_CLIENT_ID")
clientSecret := os.Getenv("SPOTIPY_CLIENT_SECRET")
if clientID == "" || clientSecret == "" {
return "", fmt.Errorf("missing SPOTIPY_CLIENT_ID or SPOTIPY_CLIENT_SECRET")
}
sess := session.Must(session.NewSession(&aws.Config{Region: aws.String("eu-west-1")}))
svc := dynamodb.New(sess)
result, err := svc.GetItem(&dynamodb.GetItemInput{
TableName: aws.String("mirrorfm_cursors"),
Key: map[string]*dynamodb.AttributeValue{"name": {S: aws.String("token")}},
})
if err != nil {
return "", fmt.Errorf("failed to get token from DynamoDB: %w", err)
}
refreshToken := ""
if val, ok := result.Item["value"]; ok && val.M != nil {
if rt, ok := val.M["refresh_token"]; ok && rt.S != nil {
refreshToken = *rt.S
}
}
if refreshToken == "" {
return "", fmt.Errorf("no refresh_token found in DynamoDB")
}
data := url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {refreshToken},
"client_id": {clientID},
"client_secret": {clientSecret},
}
resp, err := http.PostForm("https://accounts.spotify.com/api/token", data)
if err != nil {
return "", fmt.Errorf("token refresh request failed: %w", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return "", fmt.Errorf("token refresh returned %d: %s", resp.StatusCode, body)
}
var tokenResp struct {
AccessToken string `json:"access_token"`
}
if err := json.Unmarshal(body, &tokenResp); err != nil {
return "", fmt.Errorf("failed to parse token response: %w", err)
}
return tokenResp.AccessToken, nil
}
func Handler() error {
app, err := getApp()
if err != nil {
return errors.Wrap(err, "failed to start up app")
}
token, err := webPlayer.GetAccessTokenFromEnv()
if err != nil && token != nil && !token.IsAnonymous {
os.Exit(1)
}
userId, exists := api.GetUserIdFromEnv()
if !exists {
os.Exit(1)
}
// OAuth token for public Spotify API (thumbnails, rename)
oauthToken, err := getSpotifyOAuthToken()
if err != nil {
fmt.Println("Warning: could not get OAuth token:", err)
fmt.Println("Thumbnail repair and archive rename will be skipped")
}
limit := 150
playlistsByFollowers, err := app.GetPlaylistsSortedByTotalFollowers(limit)
if err != nil {
os.Exit(1)
}
playlistsByAddedDatetime, err := app.GetPlaylistsSortedByAddedDatetime(limit)
if err != nil {
os.Exit(1)
}
mixedOrderPlaylist := mergeUnique(playlistsByFollowers, playlistsByAddedDatetime)
if oauthToken != "" {
app.RepairTerminatedThumbnails(oauthToken)
app.RepairDiscogsLabelThumbnails(oauthToken)
app.ArchiveTerminatedPlaylists(oauthToken)
}
rootList := api.RootListResponse{}
for expectedPosition, playlist := range mixedOrderPlaylist {
if rootList.Revision == "" {
// request RootList on first run and after every successful change
res, status, err := api.GetRootList(token.AccessToken, userId)
if err != nil {
os.Exit(1)
}
rootList = *res
fmt.Printf("GET RootList: %d\n", status)
}
sortOperations := GenerateSortOperations(rootList.Contents.Items, playlist, expectedPosition)
if sortOperations != nil {
_, status, err := api.PostRootListChanges([]api.DeltaOps{*sortOperations}, rootList.Revision, token.AccessToken, userId)
if err != nil {
os.Exit(1)
}
fmt.Printf("POST RootListChanges: %d\n", status)
rootList.Revision = ""
}
}
return nil
}
func mergeUnique(pl1, pl2 []string) []string {
check := make(map[string]bool)
var playlists []string
l := min(len(pl1), len(pl2))
for i := 0; i < l; i++ {
appendUnique(pl1[i], check, &playlists)
appendUnique(pl2[i], check, &playlists)
}
return playlists
}
func appendUnique(pl string, check map[string]bool, mixedPl *[]string) {
if _, ok := check[pl]; !ok {
check[pl] = true
*mixedPl = append(*mixedPl, pl)
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func findPlaylistCurrentPosition(playlistId string, contentItems []api.ContentsItem) (int, bool) {
for idx, contentItem := range contentItems {
if strings.Contains(contentItem.Uri, playlistId) {
return idx, true
}
}
return 0, false
}
func GenerateSortOperations(contentItems []api.ContentsItem, playlistId string, expectedPosition int) *api.DeltaOps {
currentPosition, found := findPlaylistCurrentPosition(playlistId, contentItems)
if found && currentPosition != expectedPosition {
return &api.DeltaOps{
Kind: "MOV",
Mov: api.OpsMov{
FromIndex: currentPosition,
Length: 1,
ToIndex: expectedPosition,
},
}
}
return nil
}
func (client *App) RepairTerminatedThumbnails(accessToken string) {
rows, err := client.SQLDriver.Query(`
SELECT e.channel_id, p.spotify_playlist FROM yt_channels e
JOIN yt_playlists p ON e.channel_id = p.channel_id AND p.num = 1
WHERE e.terminated_datetime IS NOT NULL
AND (e.thumbnail_medium LIKE '%yt3.ggpht%' OR e.thumbnail_medium LIKE '%googleusercontent%')
LIMIT 20`)
if err != nil {
fmt.Println("RepairTerminatedThumbnails query error:", err)
return
}
defer rows.Close()
for rows.Next() {
var channelID, playlistID string
if err := rows.Scan(&channelID, &playlistID); err != nil {
continue
}
imageURL, err := getSpotifyPlaylistImage(accessToken, playlistID)
if err != nil || imageURL == "" {
fmt.Printf("[T] Failed to get image for %s: %v\n", channelID, err)
continue
}
_, err = client.SQLDriver.Exec(
"UPDATE yt_channels SET thumbnail_medium = ? WHERE channel_id = ?",
imageURL, channelID)
if err != nil {
fmt.Printf("[T] Failed to update thumbnail for %s: %v\n", channelID, err)
continue
}
fmt.Printf("[T] Repaired thumbnail for %s\n", channelID)
}
}
func (client *App) RepairDiscogsLabelThumbnails(accessToken string) {
// First log how many labels need repair
var count int
err := client.SQLDriver.QueryRow(`
SELECT COUNT(*) FROM dg_labels l
JOIN dg_playlists p ON l.label_id = p.label_id
WHERE l.thumbnail_medium IS NULL
OR l.thumbnail_medium = ''
OR (l.thumbnail_medium NOT LIKE '%spotify%' AND l.thumbnail_medium NOT LIKE '%scdn.co%')`).Scan(&count)
if err != nil {
fmt.Println("[DG] Count query error:", err)
} else {
fmt.Printf("[DG] Labels needing thumbnail repair: %d\n", count)
}
rows, err := client.SQLDriver.Query(`
SELECT l.label_id, MIN(p.spotify_playlist) FROM dg_labels l
JOIN dg_playlists p ON l.label_id = p.label_id
WHERE l.thumbnail_medium IS NULL
OR l.thumbnail_medium = ''
OR (l.thumbnail_medium NOT LIKE '%spotify%' AND l.thumbnail_medium NOT LIKE '%scdn.co%')
GROUP BY l.label_id
LIMIT 20`)
if err != nil {
fmt.Println("RepairDiscogsLabelThumbnails query error:", err)
return
}
defer rows.Close()
for rows.Next() {
var labelID, playlistID string
if err := rows.Scan(&labelID, &playlistID); err != nil {
continue
}
imageURL, err := getSpotifyPlaylistImage(accessToken, playlistID)
if err != nil || imageURL == "" {
fmt.Printf("[DG] No Spotify image for label %s: %v\n", labelID, err)
continue
}
_, err = client.SQLDriver.Exec(
"UPDATE dg_labels SET thumbnail_medium = ? WHERE label_id = ?",
imageURL, labelID)
if err != nil {
fmt.Printf("[DG] Failed to update thumbnail for label %s: %v\n", labelID, err)
continue
}
fmt.Printf("[DG] Repaired thumbnail for label %s\n", labelID)
}
}
func (client *App) ArchiveTerminatedPlaylists(accessToken string) {
rows, err := client.SQLDriver.Query(`
SELECT e.channel_name, p.spotify_playlist FROM yt_channels e
JOIN yt_playlists p ON e.channel_id = p.channel_id
WHERE e.terminated_datetime IS NOT NULL
LIMIT 50`)
if err != nil {
fmt.Println("ArchiveTerminatedPlaylists query error:", err)
return
}
defer rows.Close()
for rows.Next() {
var channelName, playlistID string
if err := rows.Scan(&channelName, &playlistID); err != nil {
continue
}
// Get current playlist name from Spotify
name, err := getSpotifyPlaylistName(accessToken, playlistID)
if err != nil || name == "" {
continue
}
// Skip if already archived
if strings.HasSuffix(name, " (Archive)") {
continue
}
newName := name + " (Archive)"
if err := renameSpotifyPlaylist(accessToken, playlistID, newName); err != nil {
fmt.Printf("[A] Failed to rename %s: %v\n", playlistID, err)
continue
}
fmt.Printf("[A] Archived playlist: %s -> %s\n", name, newName)
}
}
// spotifyDo executes an HTTP request with Spotify 429 rate-limit retry.
func spotifyDo(req *http.Request) (*http.Response, error) {
for i := 0; i < 3; i++ {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != 429 {
return resp, nil
}
resp.Body.Close()
wait := 5
if s := resp.Header.Get("Retry-After"); s != "" {
if v, err := strconv.Atoi(s); err == nil {
wait = v
}
}
fmt.Printf("[Rate limited] waiting %ds\n", wait)
time.Sleep(time.Duration(wait) * time.Second)
}
return nil, fmt.Errorf("rate limited after 3 retries")
}
func getSpotifyPlaylistName(accessToken, playlistID string) (string, error) {
req, _ := http.NewRequest("GET",
"https://api.spotify.com/v1/playlists/"+playlistID+"?fields=name", nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := spotifyDo(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result struct {
Name string `json:"name"`
}
if err := json.Unmarshal(body, &result); err != nil {
return "", err
}
return result.Name, nil
}
func renameSpotifyPlaylist(accessToken, playlistID, newName string) error {
payload, _ := json.Marshal(map[string]string{"name": newName})
req, _ := http.NewRequest("PUT",
"https://api.spotify.com/v1/playlists/"+playlistID,
strings.NewReader(string(payload)))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := spotifyDo(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("status %d: %s", resp.StatusCode, body)
}
return nil
}
func getSpotifyPlaylistImage(accessToken, playlistID string) (string, error) {
req, _ := http.NewRequest("GET",
"https://api.spotify.com/v1/playlists/"+playlistID+"?fields=images", nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := spotifyDo(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result struct {
Images []struct {
URL string `json:"url"`
} `json:"images"`
}
if err := json.Unmarshal(body, &result); err != nil {
return "", err
}
if len(result.Images) > 0 {
return result.Images[0].URL, nil
}
return "", nil
}
func (client *App) GetPlaylistsSortedByAddedDatetime(limit int) ([]string, error) {
var playlists []string
db, err := client.SQLDriver.Query(fmt.Sprintf(`
SELECT spotify_playlist FROM
(
SELECT
yt_playlists.spotify_playlist as spotify_playlist,
yt_channels.added_datetime as added_datetime
FROM yt_playlists JOIN yt_channels on yt_playlists.channel_id = yt_channels.channel_id
UNION ALL
SELECT
dg_playlists.spotify_playlist as spotify_playlist,
dg_labels.added_datetime as added_datetime
FROM dg_playlists JOIN dg_labels on dg_playlists.label_id = dg_labels.label_id
) T1
ORDER BY added_datetime DESC
LIMIT ?
`), limit)
if err != nil {
fmt.Println(err.Error())
return playlists, err
}
var playlistId string
for db.Next() {
err = db.Scan(&playlistId)
if err != nil {
return playlists, err
}
playlists = append(playlists, playlistId)
}
return playlists, nil
}
func (client *App) GetPlaylistsSortedByTotalFollowers(limit int) ([]string, error) {
var playlists []string
db, err := client.SQLDriver.Query(fmt.Sprintf(`
SELECT spotify_playlist FROM
(
SELECT spotify_playlist, count_followers FROM yt_playlists
UNION ALL
SELECT spotify_playlist, count_followers FROM dg_playlists
) T1
ORDER BY count_followers DESC
LIMIT ?
`), limit)
if err != nil {
fmt.Println(err.Error())
return playlists, err
}
var playlistId string
for db.Next() {
err = db.Scan(&playlistId)
if err != nil {
return playlists, err
}
playlists = append(playlists, playlistId)
}
return playlists, nil
}
func main() {
if os.Getenv("AWS_LAMBDA_FUNCTION_NAME") != "" {
lambda.Start(Handler)
} else {
err := Handler()
if err != nil {
fmt.Println(err.Error())
}
}
}