-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
603 lines (534 loc) · 17.3 KB
/
main.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
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
package main
import (
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"math"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"slices"
"strings"
"time"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/gorilla/mux"
"github.com/lucasb-eyer/go-colorful"
)
// FatalIf removes the boilerplate for cases where errors are fatal.
func FatalIf(err error) {
if err != nil {
log.Fatalln(err)
}
}
var staticHP = NewHostedPath("static/", "/static/")
/// HTML templates.
// Need to be functions that return template.HTML rather than separate types
// with a custom String() function because html/template assumes all `string`s
// to be plaintext in need of HTML escaping.
/// --------------
func htmlFormattedTime(t time.Time, format string) template.HTML {
utctime := t.UTC()
str := utctime.Format(format)
// Adding the `datetime` attribute in case we ever want to have some
// JavaScript for conversion into different time zones…
dt := utctime.Format(time.RFC3339)
return template.HTML(fmt.Sprintf(`<time datetime="%s">%s</time>`, dt, str))
}
// HTMLTime outputs t in a nice HTML format.
func HTMLTime(t time.Time) template.HTML {
return htmlFormattedTime(t, "2006-01-02 15:04 UTC")
}
// HTMLDate outputs the date part of t in ISO 8601 format.
func HTMLDate(t time.Time) template.HTML {
return htmlFormattedTime(t, "2006-01-02")
}
// HTMLEmoji returns HTML markup for the given custom emoji.
func HTMLEmoji(emoji string) template.HTML {
fn := emoji
style := ""
ext := ".png"
switch emoji {
case "onricdennat":
fn = "tannedcirno"
style = `transform: scaleX(-1);`
// SVG icons
case "opencollective":
fallthrough
case "paypal":
fallthrough
case "stripe":
ext = ".svg"
}
if len(style) > 0 {
style = `style="` + style + `" `
}
url := staticHP.VersionURLFor("emoji-" + fn + ext)
return template.HTML(fmt.Sprintf(
// Calculated from the default `font-size` times `--icon-width` or
// `--icon-height`.
`<img src="%s" alt=":%s:" width="24" height="24" align="top" %s/>`,
url, emoji, style,
))
}
// HTMLFloatMaxPrec prints the most compact representation of v, with at
// most n decimal places.
func HTMLFloatMaxPrec(val float64, n int) string {
pow := math.Pow10(n)
return fmt.Sprintf("%v", math.Round(val*pow)/pow)
}
// HTMLPercentage formats the given value as a percentage.
func HTMLPercentage(val float64) template.HTML {
if math.IsNaN(val) {
return "n/a"
} else if val == 100.0 {
return "100 %"
}
return template.HTML(fmt.Sprintf("%.2f %%", val))
}
// HTMLCurrency formats the given amount of cents as a currency value.
func HTMLCurrency(cents float64) template.HTML {
return template.HTML(
fmt.Sprintf(
"<script>formatCurrency(%.0f)</script>"+
"<noscript>%.2f €</noscript>", cents, cents/100.0,
),
)
}
// HTMLPushPrice returns the current push price, rendered as HTML.
func HTMLPushPrice() template.HTML {
return HTMLCurrency(prices.Current().Push)
}
// HTMLDownload returns a file download link for basename, hosted at hp.
func HTMLDownload(hp *HostedPath, basename string) template.HTML {
localFN := hp.LocalPath + basename
fi, err := os.Stat(localFN)
FatalIf(err)
return template.HTML(
fmt.Sprintf(
`<a class="download" href="%s" data-kb="%.1f">%s </a>`,
hp.VersionURLFor(basename), (float64(fi.Size()) / 1024.0), basename,
),
)
}
func HTMLPC98Y(class string, title string, v int) template.HTML {
return template.HTML(fmt.Sprintf(
`<span class="y %s" title="%s">%v</span>`, class, title, v,
))
}
// HTMLScreenY formats v as a Y coordinate in the PC-98 640×400 screen space.
func HTMLScreenY(v int) template.HTML {
return HTMLPC98Y("screen", "Y coordinate in on-screen 640×400 space", v)
}
// HTML200Y formats v as a Y coordinate in the PC-98 VRAM space, in
// line-doubled 640×200 mode.
func HTML200Y(v int) template.HTML {
return HTMLPC98Y("vram200", "Y coordinate in 640×200 VRAM space", v)
}
// HTMLPerfBar creates a performance bar showing a minimum and maximum value with a relative length.
func HTMLPerfBar(min, max, rel float64) template.HTML {
minFrac := (rel * (min / max))
return template.HTML(fmt.Sprintf(`<span
class="perfbar" style="%v width: max(%v%%, 2ch);">%v</span><span
class="perfbar" style="%v width: %v%%;">%v</span>`,
CSSMeter(rel), minFrac, min, CSSMeter(rel), (rel - minFrac), max,
))
}
type eNoDescription struct {
Tag string
}
func (e eNoDescription) Error() string {
return fmt.Sprintf("no description for tag \"%s\"", e.Tag)
}
type htmlTagLinkData struct {
url string
title string
body string
}
// HTMLTagData bundles all strings of a HTML-rendered tag that are constant
// between rendering methods.
type HTMLTagData struct {
class string
links []htmlTagLinkData
}
// NewHTMLTagData generates all strings to render a blog tag as HTML with the
// given filters, and with additional links to manipulate the filters.
func NewHTMLTagData(tag string, filters []string) (ret HTMLTagData, err error) {
link := func(allTags []string, title string, text string) htmlTagLinkData {
url := "/blog/tag"
if len(allTags) >= 1 {
url += `/` + strings.Join(allTags, "/")
}
return htmlTagLinkData{url, template.HTMLEscapeString(title), text}
}
desc, ok := tagDescriptions.Map[tag]
if !ok {
// Nope, no log.Fatalf() here, don't want a mistyped or outdated tag
// filter URL to crash the entire server process.
return HTMLTagData{}, eNoDescription{tag}
}
ret.links = []htmlTagLinkData{link([]string{tag}, desc, tag)}
ret.class = "tag"
// Any append() call that involves filters, or any sub-slice of it, will
// modify the underlying array!
if indexInFilters := slices.Index(filters, tag); indexInFilters != -1 {
ret.class += " active"
filterMod := append([]string{}, filters[:indexInFilters]...)
filterMod = append(filterMod, filters[indexInFilters+1:]...)
ret.links = append(
ret.links, link(filterMod, "Remove from filters", "-"),
)
} else if len(filters) >= 1 {
filterMod := append([]string{}, filters...)
filterMod = append(filterMod, tag)
ret.links = append(ret.links, link(filterMod, "Add to filters", "+"))
}
return ret, nil
}
// HTMLTagInline renders a tag using inline elements, using GET request-sending
// <a> elements for links.
func HTMLTagInline(tag string) (template.HTML, error) {
data, err := NewHTMLTagData(tag, nil)
if err != nil {
return "", err
}
ret := `<span class="` + data.class + `">`
for _, l := range data.links {
ret += `<a href="` + l.url + `" title="` + l.title + `">`
ret += l.body
ret += `</a>`
}
ret += `</span>`
return template.HTML(ret), nil
}
// HTMLTagBlock renders a tag using block elements, using POST request-sending
// form buttons for links
func HTMLTagBlock(tag string, filters []string) (template.HTML, error) {
data, err := NewHTMLTagData(tag, filters)
if err != nil {
return "", err
}
ret := `<span class="` + data.class + `">`
for _, l := range data.links {
ret += `<form action="` + l.url + `" method="POST">`
ret += `<button type="submit" title="` + l.title + `">` + l.body
ret += `</button></form>`
}
ret += `</span>`
return template.HTML(ret), nil
}
var meterGradient = GradientTable{
{MustParseHex("#d73414"), 0},
{MustParseHex("#d7b614"), 50},
{MustParseHex("#75b635"), 100},
}
// CSSMeter generates a CSS background gradient for the given meter percentage.
func CSSMeter(val float64) template.CSS {
var middle, edge, highlight string
h, s, l := meterGradient.GetInterpolatedColorFor(val).Hsl()
// go-colorful does not clamp these themselves.
s = Min(s, 1/1.2)
l = Min(l, 1/1.6)
middle = colorful.Hsl(h, s, l).Hex()
edge = colorful.Hsl(h, (s * 1.1), (l * 1.3)).Hex()
highlight = colorful.Hsl(h, (s * 1.2), (l * 1.6)).Hex()
return template.CSS(fmt.Sprintf(
`background: linear-gradient(%v, %v 20%%, %v 45%%, %v 55%%, %v);`,
edge, highlight, middle, middle, edge,
))
}
var pages = template.New("").Funcs(map[string]interface{}{
// Arithmetic, safe
"pct": func(f float64) float64 { return (f * 100.0) },
"inc": func(i int) int { return i + 1 },
// Control flow, safe
"loop": func(from int, to int) chan int {
ret := make(chan int)
go func() {
for i := from; i < to; i++ {
ret <- i
}
close(ret)
}()
return ret
},
// String munging, safe
"hasprefix": strings.HasPrefix,
// Markup, safe
"HTML_Date": HTMLDate,
"HTML_Time": HTMLTime,
"HTML_Emoji": HTMLEmoji,
"HTML_FloatMaxPrec": HTMLFloatMaxPrec,
"HTML_Percentage": HTMLPercentage,
"HTML_Currency": HTMLCurrency,
"HTML_PushPrice": HTMLPushPrice,
"HTML_Download": HTMLDownload,
"HTML_TagBlock": HTMLTagBlock,
"HTML_TagInline": HTMLTagInline,
"HTML_Screen_Y": HTMLScreenY,
"HTML_200_Y": HTML200Y,
"HTML_PerfBar": HTMLPerfBar,
"CSS_Meter": CSSMeter,
// ReC98, safe
"ReC98_REProgressAtTree": REProgressAtTree,
"ReC98_REBaselineRev": REBaselineRev,
})
// pagesExecute wraps template execution on [pages], logging any errors
// using the facilities from package log.
func pagesExecute(wr io.Writer, name string, data interface{}) {
if err := pages.ExecuteTemplate(wr, name, data); err != nil {
log.Println(wr, err)
}
}
func respondWithError(wr http.ResponseWriter, err error) {
wr.WriteHeader(500)
fmt.Fprintln(wr, err)
}
// PageDot bundles all data handed to a page template via dot.
type PageDot struct {
*http.Request
Vars map[string]string // from gorilla/mux
TemplateName string
StaticFileURL func(string) string
}
// NewPageDot builds a new PageDot structure.
func NewPageDot(req *http.Request, templateName string) PageDot {
return PageDot{req, mux.Vars(req), templateName, func(fn string) string {
return staticHP.VersionURLFor(fn)
}}
}
// pagesHandler returns a handler that executes the given template of [pages],
// with a map of the request variables as the value of dot.
func pagesHandler(template string) http.Handler {
header := pages.Lookup("header.html")
footer := pages.Lookup("footer.html")
tmpl := pages.Lookup(template)
if tmpl == nil {
log.Fatalf("couldn't find template %s", template)
}
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
errorIf := func(err error) {
if err != nil {
respondWithError(wr, err)
}
}
dot := NewPageDot(req, strings.TrimSuffix(template, path.Ext(template)))
errorIf(header.Execute(wr, dot))
errorIf(tmpl.Execute(wr, dot))
errorIf(footer.Execute(wr, dot))
})
}
type ProviderHandler = func(http.ResponseWriter, *http.Request, *Incoming)
// incomingHandler wraps the given provider-specific payment processing handler
// with common request validation and transaction parsing code.
func incomingHandler(handler ProviderHandler) http.Handler {
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
var in Incoming
err := json.NewDecoder(req.Body).Decode(&in)
if err != nil {
respondWithError(wr, err)
return
}
handler(wr, req, &in)
})
}
/// --------------
func measureRequestTime(next http.Handler) http.Handler {
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
start := time.Now()
next.ServeHTTP(wr, req)
log.Printf("%s %s: %v\n", req.Method, req.URL.Path, time.Since(start))
})
}
func main() {
domainString := os.Getenv("DOMAIN")
if len(os.Args) < 2 || domainString == "" {
log.Fatalf(
"Usage: DOMAIN=<public URL> %s <ReC98 repository path/URL>\n",
os.Args[0],
)
}
domain, err := url.ParseRequestURI(domainString)
FatalIf(err)
// Concurrent initialization
// -------------------------
paypalClient := Concurrent(NewPaypalClient)
videoRoot := Concurrent(func() *VideoRoot {
return NewVideoRoot(SymmetricPath{
LocalPath: filepath.Join(blogHP.LocalPath, "video"),
URLPrefix: "video/", // blogHP contains the remaining prefix
})
})
// -------------------------
repo := NewRepository(os.Args[1])
master, err := repo.GetCommit("master")
if err != nil {
log.Fatal(err)
}
pages.Funcs(map[string]interface{}{
// Can fail
"git_getCommit": repo.GetCommit,
"git_getLogAt": repo.GetLogAt,
// Safe
"git_commits": commits,
"git_makeCommitInfo": makeCommitInfo,
"git_CommitLink": CommitLink,
"git_MasterCommit": func() *object.Commit { return master },
})
// Late database initialization
// ----------------------------
pushes := NewPushes(transactions, tsvPushes, &repo)
pages.Funcs(map[string]interface{}{
"DB_CustomerByID": func(id CustomerID) template.HTML {
return customers.HTMLByID(id)
},
"DB_DiscountOffers": func() []DiscountOfferView {
return DiscountOffers(prices.Current().Push)
},
"DB_TransactionBacklog": TransactionBacklog,
"DB_Pushes": pushes.All,
"DB_CapCurrent": CapCurrent,
})
// ----------------------------
// Calculate the baseline for reverse-engineering progress
// -------------------------------------------------------
baselineFunc, err := REProgressBaseline(&repo)
if err != nil {
log.Fatalln("Error retrieving the baseline for reverse-engineering progress:", err)
}
log.Printf("That worked!")
sppFunc := RESpeedPerPushFrom(pushes.DiffsForEstimate())
estimateFunc := REProgressEstimateAtTree(baselineFunc())
pages.Funcs(map[string]interface{}{
"ReC98_REProgressBaseline": baselineFunc,
"ReC98_RESpeedPerPush": sppFunc,
"ReC98_REProgressEstimateAtTree": estimateFunc,
})
// -------------------------------------------------------
// Blog
// ----
blog := NewBlog(pages, pushes, blogTags, <-videoRoot, func(blog *Blog) map[string]interface{} {
return map[string]interface{}{
"Blog_Posts": func(filters []string) chan *Post {
return blog.Posts(blog.Render, filters)
},
"Blog_TOC": func() chan *Post {
return blog.Posts(blog.PostHeader, nil)
},
"Blog_PostLink": blog.PostLink,
"Blog_FindEntryForPush": blog.FindEntryForPush,
"Blog_GetPost": blog.GetPost,
"Blog_ParseTags": func(t string) []string {
return strings.FieldsFunc(t, func(c rune) bool {
return c == '/'
})
},
"Blog_TagDescriptions": func() []*TagDescription {
return tagDescriptions.Ordered
},
}
}).AutogenerateTags(&repo)
feedHandler := FeedHandler{
Blog: blog,
SiteURL: domain.String(),
BlogPath: "/blog",
}
feedFormats := feedHandler.Formats()
pages.Funcs((map[string]interface{}{
"Blog_FeedFormats": func() []*FeedFormat { return feedFormats },
}))
// ----
// Payment providers
// -----------------
paypal := <-paypalClient
if paypal != nil {
pages.Funcs(map[string]interface{}{
"PayPal_ClientID": func() string { return paypal.ClientID },
})
}
stripe := NewStripeClient(domain, "/api/stripe", "/customer/stripe")
if stripe != nil {
pages.Funcs(map[string]interface{}{
"Stripe_Session": stripe.Session,
"Stripe_SubVerify": stripe.Sub,
"Stripe_RouteAPICancel": func() string {
return stripe.RouteAPICancel
},
})
}
// -----------------
pages = template.Must(pages.ParseGlob("*.html"))
// Badge data
// ----------
masterTree, err := master.Tree()
FatalIf(err)
badger := Badger{
Done: REProgressAtTree(masterTree).Pct(baselineFunc()),
Fallback: pagesHandler("badges.html"),
}
// ----------
log.Printf("Got everything, starting the server.")
r := mux.NewRouter()
r.Use(measureRequestTime)
r.Handle(
blogHP.URLPrefix+"{stem}-vp8.webm", blog.OldVideoRedirectHandler(&VP8),
)
r.Handle(blogHP.URLPrefix+"{stem}.webm", blog.OldVideoRedirectHandler(&VP9))
staticHP.RegisterFileServer(r)
blogHP.RegisterFileServer(r)
r.Handle("/robots.txt", staticHP.Server())
r.Handle("/favicon.ico", staticHP.Server())
r.Handle("/", pagesHandler("index.html"))
r.Handle("/faq", pagesHandler("faq.html"))
r.Handle("/fundlog", pagesHandler("fundlog.html"))
r.Handle(blogURLPrefix, pagesHandler("blog_toc.html"))
r.Handle(blogURLPrefix+"/all", pagesHandler("blog_all.html"))
for _, feedFormat := range feedFormats {
r.Handle(feedFormat.Path, feedFormat.Handler)
}
r.Handle(blogURLPrefix+"/tag", pagesHandler("blog_taglist.html"))
r.Handle(blogURLPrefix+"/{date}", pagesHandler("blog_single.html"))
r.Handle(
blogURLPrefix+"/tag/{tags:(?:.+/?)+}", pagesHandler("blog_tagged.html"),
)
r.Handle("/progress", pagesHandler("progress.html"))
r.Handle("/progress/{rev}", pagesHandler("progress_for.html"))
if len(providerAuth) > 0 {
r.Handle("/order", pagesHandler("order.html"))
r.Handle("/thankyou", pagesHandler("thankyou.html"))
if paypal != nil {
r.Methods("POST").Path("/api/paypal/incoming").
Handler(incomingHandler(PaypalIncomingHandler(paypal)))
}
if stripe != nil {
r.Methods("POST").Path(stripe.RouteAPIIncoming).
Handler(incomingHandler(stripe.HandleIncoming))
// Yup, Stripe does in fact send a GET request to an endpoint that
// is highly likely to change a server's database…
r.Handle(
stripe.RouteAPISuccess, http.HandlerFunc(stripe.HandleSuccess),
)
r.Methods("POST").Path(stripe.RouteAPICancel).
Handler(http.HandlerFunc(stripe.HandleCancel))
r.Handle(
stripe.RoutePageThankYou+"/{stripeSession}/{salt}",
pagesHandler("thankyou.html"),
)
r.Handle(
stripe.RoutePageManage+"/{salt}",
pagesHandler("customer_stripe.html"),
)
}
} else {
log.Println("`provider_auth` table is empty, disabling order pages.")
}
r.Handle("/donate", pagesHandler("donate.html"))
r.Handle("/badges", badger.Fallback)
r.Handle("/badge/{type}", badger)
r.Handle("/badge/{type}/{game}", badger)
r.Handle("/legal", pagesHandler("legal.html"))
log.Fatal(http.ListenAndServe(":8098", r))
}