-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathviews.go
More file actions
644 lines (590 loc) · 17.5 KB
/
views.go
File metadata and controls
644 lines (590 loc) · 17.5 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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
package handlers
import (
"context"
"embed"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"path"
"regexp"
"strings"
"time"
"github.com/mtlynch/screenjournal/v2/screenjournal"
"github.com/mtlynch/screenjournal/v2/store"
)
type commonProps struct {
Title string
IsAuthenticated bool
IsAdmin bool
LoggedInUsername screenjournal.Username
CspNonce string
}
func (s Server) indexGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Redirect logged in users to the reviews index instead of the landing
// page.
if isAuthenticated(r.Context()) {
http.Redirect(w, r, "/reviews", http.StatusTemporaryRedirect)
return
}
if err := renderTemplate(w, "index.html", struct {
commonProps
}{
commonProps: makeCommonProps("ScreenJournal", r.Context()),
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) aboutGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := renderTemplate(w, "about.html", struct {
commonProps
}{
commonProps: makeCommonProps("About ScreenJournal", r.Context()),
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) logInGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := renderTemplate(w, "login.html", struct {
commonProps
}{
commonProps: makeCommonProps("Log In", r.Context()),
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) signUpGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
templateFilename := "sign-up.html"
inviteCode, err := inviteCodeFromQueryParams(r)
if err != nil {
log.Printf("invalid invite code: %v", err)
http.Error(w, "Invalid invite code", http.StatusBadRequest)
return
}
var invite screenjournal.SignupInvitation
if !inviteCode.Empty() {
invite, err = s.getDB(r).ReadSignupInvitation(inviteCode)
if err != nil {
log.Printf("invalid invite code: %v", err)
http.Error(w, "Invalid invite code", http.StatusUnauthorized)
return
}
}
uc, err := s.getDB(r).CountUsers()
if err != nil {
log.Printf("failed to count users: %v", err)
http.Error(w, "Failed to load signup template", http.StatusInternalServerError)
return
}
if uc > 0 && invite.Empty() {
templateFilename = "sign-up-by-invitation.html"
}
var suggestedUsername string
if !invite.Empty() {
nonSuggestedCharsPattern := regexp.MustCompile(`(?i)[^a-z0-9]`)
firstPart := strings.SplitN(invite.Invitee.String(), " ", 2)[0]
suggestedUsername = nonSuggestedCharsPattern.ReplaceAllString(strings.ToLower(firstPart), "")
}
if err := renderTemplate(w, templateFilename, struct {
commonProps
Invitee screenjournal.Invitee
SuggestedUsername string
}{
commonProps: makeCommonProps("Sign Up", r.Context()),
Invitee: invite.Invitee,
SuggestedUsername: suggestedUsername,
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) reviewsGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var collectionOwner *screenjournal.Username
queryOptions := []store.ReadReviewsOption{}
if username, err := usernameFromRequestPath(r); err == nil {
collectionOwner = &username
queryOptions = append(queryOptions, store.FilterReviewsByUsername(username))
}
var sortOrder = screenjournal.ByWatchDate
if sort, err := sortOrderFromQueryParams(r); err == nil {
sortOrder = sort
queryOptions = append(queryOptions, store.SortReviews(sort))
}
reviews, err := s.getDB(r).ReadReviews(queryOptions...)
if err != nil {
log.Printf("failed to read reviews: %v", err)
http.Error(w, "Failed to read reviews", http.StatusInternalServerError)
return
}
title := "Ratings"
if collectionOwner != nil {
title = fmt.Sprintf("%s's %s", collectionOwner, title)
}
if err := renderTemplate(w, "reviews-index.html", struct {
commonProps
Reviews []screenjournal.Review
SortOrder screenjournal.SortOrder
CollectionOwner *screenjournal.Username
UserCanAddReview bool
}{
commonProps: makeCommonProps(title, r.Context()),
Reviews: reviews,
SortOrder: sortOrder,
CollectionOwner: collectionOwner,
UserCanAddReview: collectionOwner == nil || collectionOwner.Equal(mustGetUsernameFromContext(r.Context())),
}, template.FuncMap{
"relativeWatchDate": relativeWatchDate,
"formatWatchDate": formatWatchDate,
"iterate": func(n uint8) []uint8 {
var arr []uint8
var i uint8
for i = 0; i < n; i++ {
arr = append(arr, i)
}
return arr
},
"elideBlurb": func(b screenjournal.Blurb) string {
score := 0
var elidedChars []rune
for _, c := range b.String() {
if c == '\n' {
score += 50
} else {
score += 1
}
if score > 350 {
// Add ellipsis.
elidedChars = append(elidedChars, '.', '.', '.')
break
}
elidedChars = append(elidedChars, c)
}
return string(elidedChars)
},
"splitByNewline": func(s string) []string {
return strings.Split(s, "\n")
},
"minus": func(a, b uint8) uint8 {
return a - b
},
"posterPathToURL": posterPathToURL,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) moviesReadGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
mid, err := movieIDFromRequestPath(r)
if err != nil {
http.Error(w, "Invalid movie ID", http.StatusBadRequest)
return
}
movie, err := s.getDB(r).ReadMovie(mid)
if err == store.ErrMovieNotFound {
http.Error(w, "Invalid movie ID", http.StatusNotFound)
return
} else if err != nil {
log.Printf("failed to read movie metadata: %v", err)
http.Error(w, "Failed to retrieve movie information", http.StatusInternalServerError)
return
}
reviews, err := s.getDB(r).ReadReviews(store.FilterReviewsByMovieID(mid))
if err != nil {
log.Printf("failed to read movie reviews: %v", err)
http.Error(w, "Failed to retrieve reviews", http.StatusInternalServerError)
return
}
for i, review := range reviews {
cc, err := s.getDB(r).ReadComments(review.ID)
if err != nil {
log.Printf("failed to read reviews comments: %v", err)
http.Error(w, "Failed to retrieve comments", http.StatusInternalServerError)
return
}
reviews[i].Comments = cc
}
if err := renderTemplate(w, "movies-view.html", struct {
commonProps
Movie screenjournal.Movie
Reviews []screenjournal.Review
}{
commonProps: makeCommonProps(movie.Title.String(), r.Context()),
Movie: movie,
Reviews: reviews,
}, template.FuncMap{
"relativeCommentDate": relativeCommentDate,
"relativeWatchDate": relativeWatchDate,
"formatReleaseDate": func(t screenjournal.ReleaseDate) string {
return t.Time().Format("1/2/2006")
},
"formatWatchDate": formatWatchDate,
"formatCommentTime": formatIso8601Datetime,
"iterate": func(n uint8) []uint8 {
var arr []uint8
var i uint8
for i = 0; i < n; i++ {
arr = append(arr, i)
}
return arr
},
"minus": func(a, b uint8) uint8 {
return a - b
},
"splitByNewline": func(s string) []string {
return strings.Split(s, "\n")
},
"posterPathToURL": posterPathToURL,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) reviewsEditGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, err := reviewIDFromRequestPath(r)
if err != nil {
http.Error(w, "Invalid review ID", http.StatusBadRequest)
return
}
review, err := s.getDB(r).ReadReview(id)
if err == store.ErrReviewNotFound {
http.Error(w, "Invalid review ID", http.StatusNotFound)
return
} else if err != nil {
log.Printf("failed to read review: %v", err)
http.Error(w, "Failed to read review", http.StatusInternalServerError)
return
}
loggedInUsername := mustGetUsernameFromContext(r.Context())
if !review.Owner.Equal(loggedInUsername) {
http.Error(w, "You can't edit another user's review", http.StatusForbidden)
return
}
if err := renderTemplate(w, "reviews-edit.html", struct {
commonProps
RatingOptions []int
Review screenjournal.Review
Today time.Time
}{
commonProps: makeCommonProps("Edit Review", r.Context()),
RatingOptions: []int{1, 2, 3, 4, 5},
Review: review,
Today: time.Now(),
}, template.FuncMap{
"formatWatchDate": formatWatchDate,
"iterate": func(n uint8) []uint8 {
var arr []uint8
var i uint8
for i = 0; i < n; i++ {
arr = append(arr, i)
}
return arr
},
"minus": func(a, b uint8) uint8 {
return a - b
},
"formatDate": func(t time.Time) string {
return t.Format("2006-01-02")
},
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) reviewsDeleteGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, err := reviewIDFromRequestPath(r)
if err != nil {
http.Error(w, "Invalid review ID", http.StatusBadRequest)
return
}
review, err := s.getDB(r).ReadReview(id)
if err == store.ErrReviewNotFound {
http.Error(w, "Invalid review ID", http.StatusNotFound)
return
} else if err != nil {
log.Printf("failed to read review: %v", err)
http.Error(w, "Failed to read review", http.StatusInternalServerError)
return
}
loggedInUsername := mustGetUsernameFromContext(r.Context())
if !review.Owner.Equal(loggedInUsername) {
http.Error(w, "You can't delete another user's review", http.StatusForbidden)
return
}
if err := renderTemplate(w, "reviews-delete.html", struct {
commonProps
Review screenjournal.Review
}{
commonProps: makeCommonProps("Delete Review", r.Context()),
Review: review,
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) reviewsNewGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var mediaTitle string
var tmdbID int32
if mid, err := movieIDFromQueryParams(r); err == nil {
movie, err := s.getDB(r).ReadMovie(mid)
if err == store.ErrMovieNotFound {
http.Error(w, "Invalid movie ID", http.StatusNotFound)
return
} else if err != nil {
log.Printf("failed to read movie metadata: %v", err)
http.Error(w, "Failed to retrieve movie information", http.StatusInternalServerError)
return
}
mediaTitle = movie.Title.String()
tmdbID = movie.TmdbID.Int32()
} else if err == ErrMoveIDNotProvided {
// Movie ID is optional for this view.
} else {
http.Error(w, "Invalid movie ID", http.StatusBadRequest)
return
}
if err := renderTemplate(w, "reviews-new.html", struct {
commonProps
MediaTitle string
TmdbID int32
RatingOptions []int
Today time.Time
}{
commonProps: makeCommonProps("Add Review", r.Context()),
MediaTitle: mediaTitle,
TmdbID: tmdbID,
RatingOptions: []int{1, 2, 3, 4, 5},
Today: time.Now(),
}, template.FuncMap{
"formatDate": func(t time.Time) string {
return t.Format("2006-01-02")
},
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) invitesGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
invites, err := s.getDB(r).ReadSignupInvitations()
if err != nil {
log.Printf("failed to read signup invitations: %v", err)
http.Error(w, "Failed to read signup invitations", http.StatusInternalServerError)
return
}
if err := renderTemplate(w, "invites.html", struct {
commonProps
Invites []screenjournal.SignupInvitation
}{
commonProps: makeCommonProps("Invites", r.Context()),
Invites: invites,
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) invitesNewGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := renderTemplate(w, "invites-new.html", struct {
commonProps
}{
commonProps: makeCommonProps("Create Invite Link", r.Context()),
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) accountChangePasswordGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := renderTemplate(w, "account-change-password.html", struct {
commonProps
}{
commonProps: makeCommonProps("Change Password", r.Context()),
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) accountNotificationsGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
prefs, err := s.getDB(r).ReadNotificationPreferences(mustGetUsernameFromContext(r.Context()))
if err != nil {
log.Printf("failed to read notification preferences: %v", err)
http.Error(w, fmt.Sprintf("failed to read notification preferences: %v", err), http.StatusInternalServerError)
return
}
if err := renderTemplate(w, "account-notifications.html", struct {
commonProps
ReceivesReviewNotices bool
ReceivesAllCommentNotices bool
}{
commonProps: makeCommonProps("Manage Notifications", r.Context()),
ReceivesReviewNotices: prefs.NewReviews,
ReceivesAllCommentNotices: prefs.AllNewComments,
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) accountSecurityGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := renderTemplate(w, "account-security.html", struct {
commonProps
}{
commonProps: makeCommonProps("Account Security", r.Context()),
}, template.FuncMap{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func (s Server) queueGet() http.HandlerFunc {
type entry struct {
Title screenjournal.MediaTitle
PosterPath url.URL
Note string
}
return func(w http.ResponseWriter, r *http.Request) {
reviews, err := s.getDB(r).ReadReviews()
if err != nil {
log.Printf("failed to read queue: %v", err)
http.Error(w, "Failed to read queue", http.StatusInternalServerError)
return
}
entries := make([]entry, len(reviews))
for i, review := range reviews {
entries[i].Title = review.Movie.Title
entries[i].PosterPath = review.Movie.PosterPath
entries[i].Note = "Seems fun!"
}
if err := renderTemplate(w, "queue.html", struct {
commonProps
Entries []entry
}{
commonProps: makeCommonProps("Queue", r.Context()),
Entries: entries,
}, template.FuncMap{
"posterPathToURL": posterPathToURL,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func relativeWatchDate(t screenjournal.WatchDate) string {
daysAgo := int(time.Since(t.Time()).Hours() / 24)
weeksAgo := int(daysAgo / 7)
if daysAgo < 1 {
return "today"
} else if daysAgo == 1 {
return "yesterday"
} else if daysAgo <= 14 {
return fmt.Sprintf("%d days ago", daysAgo)
} else if weeksAgo < 8 {
return fmt.Sprintf("%d weeks ago", weeksAgo)
}
monthsAgo := int(daysAgo / 30)
if monthsAgo == 1 {
return "1 month ago"
}
return fmt.Sprintf("%d months ago", monthsAgo)
}
func formatWatchDate(t screenjournal.WatchDate) string {
return t.Time().Format("2006-01-02")
}
func relativeCommentDate(t time.Time) string {
minutesAgo := int(time.Since(t).Minutes())
if minutesAgo < 1 {
return "just now"
}
if minutesAgo == 1 {
return "a minute ago"
}
hoursAgo := int(time.Since(t).Hours())
if hoursAgo < 1 {
return fmt.Sprintf("%d minutes ago", minutesAgo)
}
if hoursAgo == 1 {
return "an hour ago"
}
if hoursAgo < 24 {
return fmt.Sprintf("%d hours ago", hoursAgo)
}
daysAgo := int(time.Since(t).Hours() / 24)
weeksAgo := int(daysAgo / 7)
if daysAgo == 1 {
return "yesterday"
} else if daysAgo <= 14 {
return fmt.Sprintf("%d days ago", daysAgo)
} else if weeksAgo < 8 {
return fmt.Sprintf("%d weeks ago", weeksAgo)
}
monthsAgo := int(daysAgo / 30)
if monthsAgo == 1 {
return "1 month ago"
}
return fmt.Sprintf("%d months ago", monthsAgo)
}
func formatIso8601Datetime(t time.Time) string {
return t.Format("2006-01-02 3:04 pm")
}
func posterPathToURL(pp url.URL) string {
pp.Scheme = "https"
pp.Host = "image.tmdb.org"
pp.Path = "/t/p/w600_and_h900_bestv2" + pp.Path
return pp.String()
}
func makeCommonProps(title string, ctx context.Context) commonProps {
username, ok := usernameFromContext(ctx)
if !ok {
username = screenjournal.Username("")
}
return commonProps{
Title: title,
IsAuthenticated: isAuthenticated(ctx),
IsAdmin: isAdmin(ctx),
LoggedInUsername: username,
CspNonce: cspNonce(ctx),
}
}
//go:embed templates
var templatesFS embed.FS
func renderTemplate(w http.ResponseWriter, templateFilename string, templateVars interface{}, funcMap template.FuncMap) error {
t := template.New(templateFilename).Funcs(funcMap)
t = template.Must(
t.ParseFS(
templatesFS,
"templates/custom-elements/*.html",
"templates/layouts/*.html",
"templates/partials/*.html",
path.Join("templates/pages", templateFilename)))
if err := t.ExecuteTemplate(w, "base", templateVars); err != nil {
return err
}
return nil
}