/
web.go
506 lines (433 loc) · 14.1 KB
/
web.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
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
498
499
500
501
502
503
504
505
506
package main
import (
"context"
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
"strconv"
"strings"
"cloud.google.com/go/datastore"
"github.com/nishanths/scrobble/appengine/log"
"github.com/pkg/errors"
)
var (
homeTmpl = template.Must(template.New("").Parse(MustAssetString("appengine/template/home.html")))
dashboardTmpl = template.Must(template.New("").Parse(MustAssetString("appengine/template/dashboard.html")))
uTmpl = template.Must(template.New("").Parse(MustAssetString("appengine/template/u.html")))
)
type BootstrapArgs struct {
Host string `json:"host"`
Email string `json:"email"`
LoginURL string `json:"loginURL"`
LogoutURL string `json:"logoutURL"`
Account Account `json:"account"`
TotalSongs int `json:"totalSongs"` // -1 if failed to compute
LastScrobbleTime int64 `json:"lastScrobbleTime"` // unix seconds; -1 if failed to compute
}
type RootArgs struct {
Title string
Bootstrap BootstrapArgs
AppDomain string
}
func validRootPath(p string) bool {
if p == "/" {
return true
}
c := pathComponents(p)
if len(c) > 0 && c[0] == "dashboard" {
return true
}
return false
}
func (s *server) rootHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
if !validRootPath(r.URL.Path) {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
host := r.Host
dest := r.RequestURI
u, err := s.currentUser(r)
if err != nil {
// either generic error or ErrNoUser
// redirect any "/dashboard/" paths to "/"
if r.URL.Path != "/" {
http.Redirect(w, r, "/", http.StatusFound)
return
}
login := loginURLWithRedirect(dest)
args := RootArgs{
Title: "Apple Music scrobbling — Scrobble",
Bootstrap: BootstrapArgs{
Host: host,
LoginURL: login,
},
AppDomain: AppDomain,
}
if err := homeTmpl.Execute(w, args); err != nil {
log.Errorf("failed to execute template: %v", err.Error())
}
return
}
logout := logoutURLWithRedirect(dest)
a, err := ensureAccount(ctx, u.Email, s.ds)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
lastScrobbled, nSongs, err := songStats(ctx, s.ds, namespaceID(u.Email))
if err != nil {
log.Errorf("failed to count songs (continuing): %v", err.Error())
}
args := RootArgs{
Title: "Dashboard · Scrobble",
Bootstrap: BootstrapArgs{
Host: host,
Email: u.Email,
LogoutURL: logout,
Account: a,
TotalSongs: nSongs,
LastScrobbleTime: lastScrobbled,
},
AppDomain: AppDomain,
}
if err := dashboardTmpl.Execute(w, args); err != nil {
log.Errorf("failed to execute template: %v", err.Error())
}
}
// Returns the last scrobble time and the count of scrobbled songs.
// Partial results may be returned even if the error is non-nil.
// Returns -1 for results that could not be computed.
func songStats(ctx context.Context, ds *datastore.Client, namespace string) (int64, int, error) {
// Get the latest complete parent.
q := datastore.NewQuery(KindSongParent).
Namespace(namespace).
Order("-Created").Filter("Complete=", true).
Limit(1)
var sp []SongParent
parentKeys, err := ds.GetAll(ctx, q, &sp)
if err != nil {
return -1, -1, errors.Wrapf(err, "failed to do SongParent query")
}
if len(parentKeys) == 0 {
// no songs
return 0, 0, nil
}
q = datastore.NewQuery(KindSong).
Namespace(namespace).
Ancestor(parentKeys[0])
count, err := ds.Count(ctx, q)
if err != nil {
return sp[0].Created, -1, errors.Wrapf(err, "failed to count songs")
}
return sp[0].Created, count, nil
}
func ensureAccount(ctx context.Context, accID string, ds *datastore.Client) (Account, error) {
var account Account
_, err := ds.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
aKey := datastore.NameKey(KindAccount, accID, nil)
if err := tx.Get(aKey, &account); err != nil {
if err == datastore.ErrNoSuchEntity {
// account entity does not exists; create new account entity
if _, err := tx.Put(aKey, &account); err != nil {
return errors.Wrapf(err, "failed to put account for %s", accID)
}
return nil
}
// generic error
return errors.Wrapf(err, "failed to get account for %s", accID)
}
// account entity exists
return nil
})
return account, err
}
type UArgs struct {
Title string `json:"title"`
Host string `json:"host"`
ArtworkBaseURL string `json:"artworkBaseURL"`
ProfileUsername string `json:"profileUsername"`
LogoutURL string `json:"logoutURL"`
Account Account `json:"account"`
Self bool `json:"self"`
Private bool `json:"private"`
}
func (s *server) uHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
c := pathComponents(r.URL.Path)
if len(c) < 2 || len(c) > 6 {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
profileUsername := c[1]
acc, _, ok := fetchAccountForUsername(ctx, profileUsername, s.ds, w)
if !ok {
return
}
// If the user is logged in, gather a logout URL and the account info.
var logoutURL string
var account Account
self := false
u, err := s.currentUser(r)
if err == nil {
logoutURL = logoutURLWithRedirect(r.RequestURI)
if err := s.ds.Get(ctx, datastore.NameKey(KindAccount, u.Email, nil), &account); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
self = account.Username != "" && account.Username == profileUsername
}
if err := uTmpl.Execute(w, UArgs{
Title: profileUsername + "'s scrobbles",
Host: r.Host,
ArtworkBaseURL: "https://storage.googleapis.com/" + DefaultBucketName + "/" + artworkStorageDirectory,
ProfileUsername: profileUsername,
LogoutURL: logoutURL,
Account: account,
Self: self,
Private: acc.Private,
}); err != nil {
log.Errorf("failed to execute template: %v", err.Error())
}
}
func pathComponents(path string) []string {
var c []string
parts := strings.Split(path, "/")
for _, p := range parts {
if p != "" {
c = append(c, p)
}
}
return c
}
// Sets the username for the account and initializes the account.
func (s *server) initializeAccountHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
u, err := s.currentUser(r)
if err == ErrNoUser {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
username := r.FormValue("username")
if ok := isAllowedUsername(username); !ok {
http.Error(w, http.StatusText(http.StatusNotAcceptable), http.StatusNotAcceptable) // need a unique code. this is gross, but whatever.
return
}
inUse := false
var account Account
_, err = s.ds.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
// Ensure username uniqueness.
uKey := datastore.NameKey(KindUsername, username, nil)
if err := tx.Get(uKey, ptrStruct()); err != datastore.ErrNoSuchEntity {
if err == nil {
inUse = true
return errors.New("username already in use")
}
return errors.Wrapf(err, "failed to get username")
}
if _, err := tx.Put(uKey, ptrStruct()); err != nil {
return errors.Wrapf(err, "failed to put username")
}
// Ensure API key uniqueness.
gen, err := setAPIKey(tx, generateAPIKey)
if err != nil {
return errors.Wrapf(err, "failed to set API key")
}
// Initialize the account.
aKey := datastore.NameKey(KindAccount, u.Email, nil)
if err := tx.Get(aKey, &account); err != nil {
return errors.Wrapf(err, "failed to get account for %s", u.Email)
}
if account.Username != "" {
return fmt.Errorf("username already set for %s", u.Email)
}
account.Username = username
account.APIKey = gen
account.Private = false
if _, err := tx.Put(aKey, &account); err != nil {
return errors.Wrapf(err, "failed to put account for %s", u.Email)
}
return nil
})
if err != nil {
log.Errorf("%v", err.Error())
if inUse {
http.Error(w, http.StatusText(http.StatusNotAcceptable), http.StatusNotAcceptable) // need a unique code. this is gross, but whatever.
} else {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
return
}
b, err := json.Marshal(account)
if err != nil {
log.Errorf("failed to json-marshal account: %v", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Write(b)
}
func (s *server) newAPIKeyHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
u, err := s.currentUser(r)
if err == ErrNoUser {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var apiKey string
_, err = s.ds.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
k, err := setAPIKey(tx, generateAPIKey)
if err != nil {
return err
}
var account Account
aKey := datastore.NameKey(KindAccount, u.Email, nil)
if err := tx.Get(aKey, &account); err != nil {
return errors.Wrapf(err, "failed to get account for %s", u.Email)
}
account.APIKey = k
if _, err := tx.Put(aKey, &account); err != nil {
return errors.Wrapf(err, "failed to put account for %s", u.Email)
}
apiKey = k
return nil
})
if err != nil {
log.Errorf("%v", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
b, err := json.Marshal(apiKey)
if err != nil {
log.Errorf("%v", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Write(b)
}
func (s *server) setPrivacyHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
u, err := s.currentUser(r)
if err == ErrNoUser {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
privacy, err := strconv.ParseBool(r.FormValue("privacy"))
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
_, err = s.ds.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
var account Account
aKey := datastore.NameKey(KindAccount, u.Email, nil)
if err := tx.Get(aKey, &account); err != nil {
return errors.Wrapf(err, "failed to get account for %s", u.Email)
}
account.Private = privacy
if _, err := tx.Put(aKey, &account); err != nil {
return errors.Wrapf(err, "failed to put account for %s", u.Email)
}
return nil
})
if err != nil {
log.Errorf("%v", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
// Callers provide a transaction.
func setAPIKey(tx *datastore.Transaction, generator func() (string, error)) (string, error) {
const maxTries = 10
tries := 0
for {
tries++
gen, err := generator()
if err != nil {
return "", errors.Wrapf(err, "failed to generate API key")
}
dsKey := datastore.NameKey(KindAPIKey, gen, nil)
if err := tx.Get(dsKey, ptrStruct()); err != datastore.ErrNoSuchEntity {
if err == nil {
if tries == maxTries {
return "", errors.New("API key already assigned")
}
continue
}
return "", errors.Wrapf(err, "failed to get API key")
}
if _, err := tx.Put(dsKey, ptrStruct()); err != nil {
return "", errors.Wrapf(err, "failed to put API key")
}
return gen, nil
}
}
func ptrStruct() *struct{} {
return &struct{}{}
}
const terms = `You are solely responsible for the content of, and for any harm resulting
from, any content that you post, upload, link to or otherwise make available
via the service, regardless of the form of that content. The service copyright
holders, the service authors, or the service contributors are not responsible
for any public display or misuse of your content.
It is possible that any uploaded artwork is not removed upon account deletion.
THE SERVICE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
IN NO EVENT SHALL THE SERVICE COPYRIGHT HOLDERS, THE SERVICE AUTHORS, OR THE
SERVICE CONTRIBUTORS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR
IN CONNECTION WITH THE SERVICE OR THE USE OR OTHER DEALINGS IN THE SERVICE.
`
const privacyPolicy = `For artwork uploaded before 20 Dec 2022, the email address of your account may
be publicly associated with the uploaded image. For artwork uploaded after 20
Dec 2022, the time of the request, the account email address, and the request
IP address are saved in an internal, non-public datastore.
Data in the insights tab may be publicly accessible even if your profile is
set to private.`
func (s *server) termsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
io.WriteString(w, terms)
}
func (s *server) privacyPolicyHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
io.WriteString(w, privacyPolicy)
}