-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
240 lines (193 loc) · 5.9 KB
/
utils.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
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
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"math/rand"
"net/http"
"net/url"
"time"
"github.com/BrianMwangi21/anti-discover.git/templates/pages"
"github.com/a-h/templ"
gowebly "github.com/gowebly/helpers"
"github.com/valyala/fasthttp"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
"golang.org/x/oauth2"
)
var (
scopes = [...]string{
spotifyauth.ScopePlaylistReadPrivate, spotifyauth.ScopePlaylistModifyPublic, spotifyauth.ScopePlaylistModifyPrivate,
spotifyauth.ScopePlaylistReadCollaborative, spotifyauth.ScopeUserReadEmail, spotifyauth.ScopeUserReadPrivate,
spotifyauth.ScopeUserReadCurrentlyPlaying, spotifyauth.ScopeUserReadRecentlyPlayed, spotifyauth.ScopeUserTopRead,
}
)
func convertRequest(req *fasthttp.Request) (*http.Request, error) {
httpReq, err := http.NewRequest(
string(req.Header.Method()),
string(req.Header.RequestURI()),
bytes.NewReader(req.Body()),
)
if err != nil {
return nil, err
}
req.Header.VisitAll(func(key, value []byte) {
httpReq.Header.Set(string(key), string(value))
})
return httpReq, nil
}
func getAuth() *spotifyauth.Authenticator {
redirectURI := gowebly.Getenv("REDIRECT_URI", "")
if redirectURI == "" {
redirectURI = "http://localhost:8080/anti"
}
return spotifyauth.New(spotifyauth.WithRedirectURL(redirectURI), spotifyauth.WithScopes(scopes[:]...))
}
func getMetaTags() templ.Component {
return pages.MetaTags(
"Anti-Discover",
"Spotify's discover weekly rogue twin",
)
}
func saveToken(request *http.Request, token *oauth2.Token) error {
ctx := context.Background()
values := request.URL.Query()
code := values.Get("code")
tokenData, err := json.Marshal(token)
if err != nil {
return errors.New("Error marshalling struct to JSON")
}
tokenString := string(tokenData)
err = redisClient.Set(ctx, code, tokenString, time.Hour).Err()
if err != nil {
return errors.New("Error saving token to Redis")
}
return nil
}
func retrieveToken(request *http.Request) (*oauth2.Token, error) {
ctx := context.Background()
values := request.URL.Query()
code := values.Get("code")
val, err := redisClient.Get(ctx, code).Result()
if err != nil {
return nil, errors.New("Error getting token from Redis")
}
var token oauth2.Token
err = json.Unmarshal([]byte(val), &token)
if err != nil {
return nil, errors.New("Error unmarshalling to struct")
}
return &token, nil
}
func getSpotifyLink() (templ.SafeURL, error) {
auth := getAuth()
spotifyID := gowebly.Getenv("SPOTIFY_ID", "")
if spotifyID == "" {
return "", errors.New("SPOTIFY_ID not set")
}
authURL := auth.AuthURL(state)
parsedURL, err := url.Parse(authURL)
if err != nil {
return "", errors.New("Parsing error failed")
}
query := parsedURL.Query()
query.Set("client_id", spotifyID)
parsedURL.RawQuery = query.Encode()
updatedURL := parsedURL.String()
return templ.URL(updatedURL), nil
}
func getRecommendationAndCreatePlaylist(client *spotify.Client, userID string) ([]spotify.SimpleTrack, *spotify.FullPlaylist, error) {
ctx := context.Background()
topTracks, err := client.CurrentUsersTopTracks(ctx)
if err != nil {
return nil, nil, err
}
rand.NewSource(time.Now().UnixNano())
randomIndex := rand.Intn(len(topTracks.Tracks))
seeds := spotify.Seeds{
Tracks: []spotify.ID{
topTracks.Tracks[randomIndex].ID,
},
}
var trackIDs []spotify.ID
for _, track := range topTracks.Tracks {
trackIDs = append(trackIDs, track.ID)
}
audioFeatures, err := client.GetAudioFeatures(ctx, trackIDs...)
if err != nil {
return nil, nil, err
}
trackAttributes := calculateAntiFeatures(audioFeatures)
recommendations, err := client.GetRecommendations(ctx, seeds, trackAttributes)
if err != nil {
return nil, nil, err
}
playlist, err := createPlaylist(client, recommendations.Tracks, userID)
if err != nil {
return nil, nil, err
}
return recommendations.Tracks, playlist, nil
}
func calculateAntiFeatures(features []*spotify.AudioFeatures) *spotify.TrackAttributes {
var (
acousticness float64
danceability float64
energy float64
instrumentalness float64
liveness float64
valence float64
)
for _, f := range features {
acousticness += float64(f.Acousticness)
danceability += float64(f.Danceability)
energy += float64(f.Energy)
instrumentalness += float64(f.Instrumentalness)
liveness += float64(f.Liveness)
valence += float64(f.Valence)
}
count := float64(len(features))
return spotify.NewTrackAttributes().
TargetAcousticness(superSecretTakeItToExtremeAlgo(acousticness, count)).
TargetDanceability(superSecretTakeItToExtremeAlgo(danceability, count)).
TargetEnergy(superSecretTakeItToExtremeAlgo(energy, count)).
TargetInstrumentalness(superSecretTakeItToExtremeAlgo(instrumentalness, count)).
TargetLiveness(superSecretTakeItToExtremeAlgo(liveness, count)).
TargetValence(superSecretTakeItToExtremeAlgo(valence, count))
}
func superSecretTakeItToExtremeAlgo(feature, count float64) float64 {
target := 1 - feature/count
if target > 0.5 {
return 0.9
}
return 0.1
}
func createPlaylist(client *spotify.Client, recommendations []spotify.SimpleTrack, userID string) (*spotify.FullPlaylist, error) {
ctx := context.Background()
playlists, err := client.GetPlaylistsForUser(ctx, userID)
if err != nil {
return nil, err
}
for _, playlist := range playlists.Playlists {
if playlist.Name == "Anti-Discover" {
err = client.UnfollowPlaylist(ctx, playlist.ID)
if err != nil {
return nil, err
}
break
}
}
playlist, err := client.CreatePlaylistForUser(ctx, userID, "Anti-Discover", "Playlist created from Spotify's evil twin - Anti-Discover", true, false)
if err != nil {
return nil, err
}
var trackIDs []spotify.ID
for _, recommendation := range recommendations {
trackIDs = append(trackIDs, recommendation.ID)
}
_, err = client.AddTracksToPlaylist(ctx, playlist.ID, trackIDs...)
if err != nil {
return nil, err
}
return playlist, nil
}