-
Notifications
You must be signed in to change notification settings - Fork 2
/
talks.go
329 lines (289 loc) · 8.19 KB
/
talks.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
package main
import (
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
pathpkg "path"
"sort"
"github.com/shurcooL/home/component"
"github.com/shurcooL/home/httputil"
"github.com/shurcooL/home/internal/exp/service/notification"
"github.com/shurcooL/home/presentdata"
"github.com/shurcooL/htmlg"
"github.com/shurcooL/httperror"
"github.com/shurcooL/httpfs/html/vfstemplate"
"github.com/shurcooL/httpfs/vfsutil"
"github.com/shurcooL/httpgzip"
"github.com/shurcooL/users"
"golang.org/x/net/html"
"golang.org/x/tools/present"
)
var talksHTML = template.Must(template.New("").Parse(`<html>
<head>
{{.AnalyticsHTML}} <title>Dmitri Shuralyov - Talks</title>
<link href="/icon.svg" rel="icon" type="image/svg+xml">
<meta name="viewport" content="width=device-width">
<link href="/assets/fonts/fonts.css" rel="stylesheet" type="text/css">
<link href="/assets/talks/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div style="max-width: 800px; margin: 0 auto 100px auto;">`))
// initTalks registers a talks handler with root as talks content source.
func initTalks(root http.FileSystem, notification notification.Service, users users.Service) {
// Host static files that slides need.
http.Handle("/static/", cookieAuth{httpgzip.FileServer(presentdata.Assets, httpgzip.FileServerOptions{ServeError: detailedForAdmin{Users: users}.ServeError})})
// Create a template for slides.
tmpl := present.Template()
tmpl = tmpl.Funcs(template.FuncMap{"playable": func(present.Code) bool { return false }})
tmpl = template.Must(vfstemplate.ParseFiles(presentdata.Assets, tmpl, "/templates/action.tmpl", "/templates/slides.tmpl"))
talksHandler := http.StripPrefix("/talks", cookieAuth{httputil.ErrorHandler(users, (&talksHandler{
base: "/talks",
fs: root,
slides: tmpl,
notification: notification,
users: users,
}).ServeHTTP)})
http.Handle("/talks", talksHandler)
http.Handle("/talks/", talksHandler)
}
type talksHandler struct {
base string // Base URL to prepend to links.
fs http.FileSystem
slides *template.Template
notification notification.Service
users users.Service
}
func (h *talksHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) error {
if req.Method != "GET" {
return httperror.Method{Allowed: []string{"GET"}}
}
if canonicalURL := pathpkg.Clean(req.RequestURI); canonicalURL != req.RequestURI {
if req.URL.RawQuery != "" {
canonicalURL += "?" + req.URL.RawQuery
}
return httperror.Redirect{URL: canonicalURL}
}
path := pathpkg.Clean("/" + req.URL.Path)
f, err := h.fs.Open(path)
if err != nil {
return err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return err
}
switch dir, ext := fi.IsDir(), pathpkg.Ext(fi.Name()); {
// Serve a directory listing.
case dir:
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := struct{ AnalyticsHTML template.HTML }{analyticsHTML}
err := talksHTML.Execute(w, data)
if err != nil {
return err
}
authenticatedUser, err := h.users.GetAuthenticated(req.Context())
if err != nil {
log.Println(err)
authenticatedUser = users.User{} // THINK: Should it be a fatal error or not? What about on frontend vs backend?
}
var nc uint64
if authenticatedUser.ID != 0 {
nc, err = h.notification.CountNotifications(req.Context())
if err != nil {
return err
}
}
returnURL := req.RequestURI
// Render the header.
header := component.Header{
CurrentUser: authenticatedUser,
NotificationCount: nc,
ReturnURL: returnURL,
}
err = htmlg.RenderComponents(w, header)
if err != nil {
return err
}
err = html.Render(w, htmlg.H1(htmlg.Text("Talks")))
if err != nil {
return err
}
err = html.Render(w, htmlg.H2(htmlg.Text(path)))
if err != nil {
return err
}
// Render the directory listing.
err = h.renderDir(w, path, f)
if err != nil {
return err
}
_, err = io.WriteString(w, `</div>`)
if err != nil {
return err
}
_, err = io.WriteString(w, `</body></html>`)
return err
// Serve a .slide presentation.
case !dir && ext == ".slide":
pctx := present.Context{
ReadFile: func(path string) ([]byte, error) { return vfsutil.ReadFile(h.fs, path) },
}
doc, err := pctx.Parse(f, path, 0)
if err != nil {
return err
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
return doc.Render(w, h.slides)
// Serve regular files (assets).
case !dir && ext != ".slide":
httpgzip.ServeContent(w, req, path, fi.ModTime(), f)
return nil
default:
panic("unreachable")
}
}
// renderDir renders to w the directory listing of d. The path is absolute and clean.
func (h *talksHandler) renderDir(w io.Writer, path string, d dirReader) error {
fis, err := d.Readdir(0)
if err != nil {
return err
}
dl := &dirList{Base: h.base, Path: path}
if path != "/" {
dl.Dirs = append(dl.Dirs, dirEntry{
Path: pathpkg.Join(path, ".."),
Name: "..",
})
}
hasSlides := hasSlides(fis)
for _, fi := range fis {
switch dir, ext := fi.IsDir(), pathpkg.Ext(fi.Name()); {
// Add directories to Dirs, if no slides.
case dir && !hasSlides:
dl.Dirs = append(dl.Dirs, dirEntry{
Path: pathpkg.Join(path, fi.Name()),
Name: fi.Name(),
})
// Add .slide files to Slides.
case !dir && ext == ".slide":
title, err := parseTitle(h.fs, pathpkg.Join(path, fi.Name()))
if err != nil {
log.Println(err)
title = ""
}
dl.Slides = append(dl.Slides, dirEntry{
Path: pathpkg.Join(path, fi.Name()),
Name: fi.Name(),
Title: title,
})
// Add .pdf files to Files.
case !dir && ext == ".pdf":
dl.Files = append(dl.Files, dirEntry{
Path: pathpkg.Join(path, fi.Name()),
Name: fi.Name(),
})
}
}
sort.Sort(dl.Dirs)
sort.Sort(dl.Slides)
sort.Sort(dl.Files)
_, err = io.WriteString(w, htmlg.Render(dl.Render()...))
return err
}
// hasSlides reports if there are any .slide files within fis.
func hasSlides(fis []os.FileInfo) bool {
for _, fi := range fis {
if !fi.IsDir() && pathpkg.Ext(fi.Name()) == ".slide" {
return true
}
}
return false
}
// dirList is a directory listing of slides and directories.
type dirList struct {
Base string // Base URL to prepend to links. E.g., "/talks".
Path string
Dirs, Slides, Files dirEntries
}
// Render renders the directory listing as HTML.
func (dl *dirList) Render() []*html.Node {
var nodes []*html.Node
if len(dl.Dirs) > 0 {
nodes = append(nodes,
htmlg.H4(htmlg.Text("Directories:")),
)
var ns []*html.Node
for _, d := range dl.Dirs {
ns = append(ns,
htmlg.DD(
htmlg.A(d.Name, pathpkg.Join(dl.Base, d.Path)),
),
)
}
nodes = append(nodes, htmlg.DL(ns...))
}
if len(dl.Slides) > 0 {
nodes = append(nodes,
htmlg.H4(htmlg.Text("Slides:")),
)
var ns []*html.Node
for _, s := range dl.Slides {
ns = append(ns,
htmlg.DD(
htmlg.A(s.Name, pathpkg.Join(dl.Base, s.Path)), htmlg.Text(": "+s.Title),
),
)
}
nodes = append(nodes, htmlg.DL(ns...))
}
if len(dl.Files) > 0 {
nodes = append(nodes,
htmlg.H4(htmlg.Text("Files:")),
)
var ns []*html.Node
for _, s := range dl.Files {
ns = append(ns,
htmlg.DD(
htmlg.A(s.Name, pathpkg.Join(dl.Base, s.Path)),
),
)
}
nodes = append(nodes, htmlg.DL(ns...))
}
return nodes
}
// dirEntry is an entry within a directory.
type dirEntry struct {
Path string
Name string
Title string // Slide title.
}
type dirEntries []dirEntry
func (s dirEntries) Len() int { return len(s) }
func (s dirEntries) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s dirEntries) Less(i, j int) bool { return s[i].Name < s[j].Name }
// parseTitle parses the title of .slide presentation at path.
func parseTitle(fs http.FileSystem, path string) (string, error) {
f, err := fs.Open(path)
if err != nil {
return "", err
}
defer f.Close()
doc, err := titlesContext.Parse(f, path, present.TitlesOnly)
if err != nil {
return "", err
}
return doc.Title, nil
}
// titlesContext is used for parsing titles only.
var titlesContext = present.Context{
// ReadFile should not be needed to parse titles.
ReadFile: func(path string) ([]byte, error) { return nil, fmt.Errorf("implementation not provided") },
}
type dirReader interface {
Readdir(count int) ([]os.FileInfo, error)
}