-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
296 lines (238 loc) · 7.51 KB
/
config.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
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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/zmb3/spotify"
"golang.org/x/oauth2"
)
type config struct {
duration time.Duration
playlistName string
blacklistedArtists map[string]struct{}
spotifyClientID string
spotifyClientSecret string
auth spotify.Authenticator
}
func (cfg *config) String() string {
var sb strings.Builder
// Yeah, this is kind of ugly. I don't care.
sb.WriteString("{")
sb.WriteString(fmt.Sprintf("duration: %v, ", cfg.duration))
sb.WriteString(fmt.Sprintf("playlistName: %q, ", cfg.playlistName))
blacklistedArtistsLst := make([]string, 0, len(cfg.blacklistedArtists))
for artistName := range cfg.blacklistedArtists {
blacklistedArtistsLst = append(blacklistedArtistsLst, artistName)
}
sb.WriteString(fmt.Sprintf("blacklistedArtists: [%s]", strings.Join(blacklistedArtistsLst, ", ")))
sb.WriteString("}")
return sb.String()
}
const (
redirectURI = "http://localhost:8080/callback"
state = "fangirl"
// Together, maxTries and retryDelay gives us a total wait time of
// around 30 minutes. Sounds crazy, but this is a thing that runs in
// a cronjob once a month and it really sucks if it fails the one
// time it runs per month.
// maxTries is the number of times we should retry a failed Spotify API request.
maxTries = 60
// retryDelay is the amount of time we should wait before retrying a failed Spotify API request.
retryDelay = 30 * time.Second
)
func getTokenPath() (string, bool) {
cacheDir, err := os.UserCacheDir()
if err != nil {
// Better to not just error here, since we can technically still function.
// But this does suck.
return "", false
}
fangirlCacheDir := filepath.Join(cacheDir, "fangirl")
if _, err := os.Stat(fangirlCacheDir); os.IsNotExist(err) {
if err := os.Mkdir(fangirlCacheDir, 0755); err != nil {
return "", false
}
}
return filepath.Join(fangirlCacheDir, "token.txt"), true
}
func (cfg *config) getSpotifyClient() (*SpotifyClient, error) {
if cfg.cacheExists() {
client, err := cfg.getCachedSpotifyClient()
if err != nil {
return nil, err
}
return NewSpotifyClient(client, maxTries, retryDelay), err
}
client, err := cfg.getFreshSpotifyClient()
if err != nil {
return nil, err
}
return NewSpotifyClient(client, maxTries, retryDelay), err
}
func (cfg *config) cacheExists() bool {
cacheDir, ok := getTokenPath()
if !ok {
log.Panicln("failed to find a cache directory for saving the oauth2 token")
return false
}
_, err := os.Stat(cacheDir)
return !os.IsNotExist(err)
}
func (cfg *config) getCachedSpotifyClient() (*spotify.Client, error) {
cacheDir, ok := getTokenPath()
if !ok {
return nil, errors.New("failed to find the cache dir for the oauth2 token")
}
tokenBytes, err := ioutil.ReadFile(cacheDir)
if err != nil {
return nil, fmt.Errorf("failed to read the token file: %w", err)
}
token := oauth2.Token{}
if err := json.Unmarshal(tokenBytes, &token); err != nil {
return nil, fmt.Errorf("failed to unmarshal the token bytes: %w", err)
}
// TODO: Should we be using token.Valid() to determine if we should actually
// re-cache?
client := cfg.auth.NewClient(&token)
return &client, nil
}
func (cfg *config) getFreshSpotifyClient() (*spotify.Client, error) {
var clientChan = make(chan *spotify.Client)
cfg.startHTTPServer(cfg.auth, clientChan)
url := cfg.auth.AuthURL(state)
fmt.Println("Please log in to Spotify by visiting the following page in your browser:", url)
// Wait for the auth flow to complete.
client := <-clientChan
user, err := client.CurrentUser()
if err != nil {
log.Fatal(err)
}
fmt.Println("You are logged in as:", user.ID)
token, err := client.Token()
if err != nil {
return client, fmt.Errorf("failed to retrieve token from the client for saving: %w", err)
}
cfg.saveToken(token)
return client, nil
}
func (cfg *config) saveToken(token *oauth2.Token) error {
tokenBytes, err := json.Marshal(token)
if err != nil {
return fmt.Errorf("failed to marshal the oauth2 token: %w", err)
}
cacheDir, ok := getTokenPath()
if !ok {
return errors.New("failed to find the cache dir for the oauth2 token")
}
if err := ioutil.WriteFile(cacheDir, tokenBytes, 0600); err != nil {
return fmt.Errorf("failed to write the token file: %w", err)
}
return nil
}
// startHTTPServer and surrounding code is taken from the relevant examples
// from zmb3/spotify repository.
func (cfg *config) startHTTPServer(auth spotify.Authenticator, clientChan chan *spotify.Client) {
// Start an HTTP server on our callback URI, so that we can know when the
// OAuth flow has completed.
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
tok, err := auth.Token(state, r)
if err != nil {
http.Error(w, "Couldn't get token", http.StatusForbidden)
log.Fatal(err)
}
if st := r.FormValue("state"); st != state {
http.NotFound(w, r)
log.Fatalf("State mismatch: %s != %s\n", st, state)
}
// Use the token to get an authenticated client
client := auth.NewClient(tok)
fmt.Fprintf(w, "Login to fangirl completed!")
clientChan <- &client
})
go http.ListenAndServe(":8080", nil)
}
// Obviously there is no constant value that can express the length of a month,
// but we assume every month is 31 days. It really doesn'tt matter.
const monthDuration = time.Hour * 24 * 31
func getConfig() (*config, error) {
var playlistName string
flag.StringVar(
&playlistName,
"playlist",
"",
"the name for the playlist containing recent releases",
)
durationPtr := flag.Duration(
"duration",
monthDuration,
"the duration to consider 'recent'; defaults to 1 month",
)
var blacklistFile string
flag.StringVar(
&blacklistFile,
"blacklist",
"",
"a path to a blacklist file containing artists to skip",
)
// Parse the command line arguments.
flag.Parse()
// If not supplied, default the playlist name to 'fangirl'.
if playlistName == "" {
playlistName = "fangirl"
}
var err error
blacklistedArtists := map[string]struct{}{}
if blacklistFile != "" {
blacklistedArtists, err = getBlacklistedArtists(blacklistFile)
if err != nil {
return nil, fmt.Errorf("failed to get blacklisted artists: %w", err)
}
}
auth := spotify.NewAuthenticator(
redirectURI,
spotify.ScopeUserFollowRead,
spotify.ScopeUserLibraryRead,
spotify.ScopePlaylistModifyPrivate,
spotify.ScopePlaylistReadPrivate,
)
spotifyClientID, ok := os.LookupEnv("SPOTIFY_CLIENT_ID")
if !ok {
return nil, errors.New("SPOTIFY_CLIENT_ID environment variable is required to be set")
}
spotifyClientSecret, ok := os.LookupEnv("SPOTIFY_CLIENT_SECRET")
if !ok {
return nil, errors.New("SPOTIFY_CLIENT_SECRET environment variable is required to be set")
}
auth.SetAuthInfo(spotifyClientID, spotifyClientSecret)
return &config{
duration: *durationPtr,
playlistName: playlistName,
blacklistedArtists: blacklistedArtists,
spotifyClientID: spotifyClientID,
spotifyClientSecret: spotifyClientSecret,
auth: auth,
}, nil
}
func getBlacklistedArtists(blacklistFile string) (map[string]struct{}, error) {
fileContents, err := ioutil.ReadFile(blacklistFile)
if err != nil {
return nil, fmt.Errorf("failed to read blacklist file: %w", err)
}
fileContentStr := string(fileContents)
blacklistedArtists := make(map[string]struct{}, 0)
for _, line := range strings.Split(fileContentStr, "\n") {
trimmedLine := strings.Trim(line, "\n\r\t")
if len(trimmedLine) != 0 {
blacklistedArtists[trimmedLine] = struct{}{}
}
}
return blacklistedArtists, nil
}