-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
349 lines (310 loc) · 7.74 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
package main
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
"google.golang.org/api/sheets/v4"
"html/template"
"io"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
ctx, cancel := gracefulCtx()
defer cancel()
s, err := newStorage(ctx)
if err != nil {
panic(err)
}
h, err := newHandler(s)
if err != nil {
panic(err)
}
r := mux.NewRouter()
r.PathPrefix("/").Methods(http.MethodGet).HandlerFunc(h.handleGet)
r.PathPrefix("/").Methods(http.MethodPost).HandlerFunc(h.handlePost)
srv := &http.Server{
Handler: r,
Addr: fmt.Sprintf(":%d", 1999),
WriteTimeout: 5 * time.Second,
ReadTimeout: 5 * time.Second,
}
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
defer wg.Done()
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Println(err)
}
}()
fmt.Println("server listening")
<-ctx.Done()
fmt.Println("context done")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer shutdownCancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
fmt.Println(err)
}
wg.Wait()
fmt.Println("successful shutdown")
}
//go:embed index.html.tpl
var indexHtml string
type handler struct {
s *storage
tpl *template.Template
pool *sync.Pool
}
func newHandler(s *storage) (*handler, error) {
tpl, err := template.New("index.html").Parse(indexHtml)
if err != nil {
return nil, err
}
return &handler{
s: s,
tpl: tpl,
pool: new(sync.Pool),
}, nil
}
// FIXME: mpavlicek - move parsing and marshaling to the update part of this script
func (h *handler) handleGet(w http.ResponseWriter, r *http.Request) {
jsonTimeline, err := json.Marshal(h.s.timeline)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "marshal error: %v", err)
return
}
buf := new(bytes.Buffer)
if err := h.tpl.ExecuteTemplate(buf, "index.html", struct {
Timeline string
}{
Timeline: string(jsonTimeline),
}); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "execute template error: %v", err)
return
}
w.WriteHeader(http.StatusOK)
io.Copy(w, buf)
}
func (h *handler) handlePost(w http.ResponseWriter, r *http.Request) {
if err := h.s.update(r.Context()); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "fetch error: %v", err)
return
}
http.Redirect(w, r, "/", http.StatusMovedPermanently)
}
type storage struct {
timeline Timeline
mut *sync.Mutex
}
func newStorage(ctx context.Context) (*storage, error) {
t, err := fetch(ctx)
if err != nil {
return nil, err
}
return &storage{
timeline: t,
mut: new(sync.Mutex),
}, nil
}
func (r *storage) update(ctx context.Context) error {
t, err := fetch(ctx)
if err != nil {
return err
}
r.mut.Lock()
defer r.mut.Unlock()
r.timeline = t
return nil
}
func (r *storage) get() Timeline {
r.mut.Lock()
defer r.mut.Unlock()
return r.timeline
}
const (
fieldStart = iota
fieldEnd
fieldTitle
fieldDescription
fieldGroup
)
func fetch(ctx context.Context) (Timeline, error) {
var creds *google.Credentials
if raw, has := os.LookupEnv("GOOGLE_JSON_CREDENTIALS"); has {
var err error
creds, err = google.CredentialsFromJSON(ctx, []byte(raw), sheets.SpreadsheetsReadonlyScope)
if err != nil {
return Timeline{}, fmt.Errorf("error getting credentials: %v", err)
}
} else {
return Timeline{}, fmt.Errorf("GOOGLE_JSON_CREDENTIALS not found")
}
srv, err := sheets.NewService(ctx, option.WithCredentials(creds))
if err != nil {
return Timeline{}, err
}
var t Timeline
events, err := srv.Spreadsheets.Values.Get(os.Getenv("SPREADSHEET_ID"), "events!A2:E").Do()
if err != nil {
return Timeline{}, err
}
for i, line := range events.Values {
lineIndex := i + 2
var e Event
if start, ok := line[fieldStart].(string); ok && start != "" {
var startTime time.Time
if start == "now" {
startTime = time.Now()
} else {
startTime, err = time.Parse("2006-1", start)
if err != nil {
return Timeline{}, fmt.Errorf("line %d: error parsing start date: %v", lineIndex, err)
}
}
e.Start = Date{
Year: startTime.Year(),
Month: int(startTime.Month()),
}
} else {
return Timeline{}, fmt.Errorf("line %d: start date missing or corrupt", lineIndex)
}
if end, ok := line[fieldEnd].(string); ok && end != "" {
var endTime time.Time
if end == "now" {
endTime = time.Now()
} else {
endTime, err = time.Parse("2006-1", end)
if err != nil {
return Timeline{}, fmt.Errorf("line %d: error parsing end date: %v", lineIndex, err)
}
}
e.End = &Date{
Year: endTime.Year(),
Month: int(endTime.Month()),
}
}
if title, ok := line[fieldTitle].(string); ok && title != "" {
e.Text.Title = title
} else {
return Timeline{}, fmt.Errorf("line %d: title missing or corrupt", lineIndex)
}
if len(line) >= 4 {
if description, ok := line[fieldDescription].(string); ok && description != "" {
e.Text.Description = &description
}
}
if len(line) >= 5 {
if group, ok := line[fieldGroup].(string); ok && group != "" {
e.Group = &group
}
}
t.Events = append(t.Events, e)
}
eras, err := srv.Spreadsheets.Values.Get(os.Getenv("SPREADSHEET_ID"), "eras!A2:C").Do()
if err != nil {
return Timeline{}, err
}
for i, line := range eras.Values {
lineIndex := i + 2
var e Era
if start, ok := line[fieldStart].(string); ok && start != "" {
var startTime time.Time
if start == "now" {
startTime = time.Now()
} else {
startTime, err = time.Parse("2006-1", start)
if err != nil {
return Timeline{}, fmt.Errorf("line %d: error parsing start date: %v", lineIndex, err)
}
}
e.Start = Date{
Year: startTime.Year(),
Month: int(startTime.Month()),
}
} else {
return Timeline{}, fmt.Errorf("line %d: start date missing or corrupt", lineIndex)
}
if end, ok := line[fieldEnd].(string); ok && end != "" {
var endTime time.Time
if end == "now" {
endTime = time.Now()
} else {
endTime, err = time.Parse("2006-1", end)
if err != nil {
return Timeline{}, fmt.Errorf("line %d: error parsing end date: %v", lineIndex, err)
}
}
e.End = Date{
Year: endTime.Year(),
Month: int(endTime.Month()),
}
} else {
return Timeline{}, fmt.Errorf("line %d: end date missing or corrupt", lineIndex)
}
if title, ok := line[fieldTitle].(string); ok && title != "" {
e.Text.Title = title
} else {
return Timeline{}, fmt.Errorf("line %d: title missing or corrupt", lineIndex)
}
t.Eras = append(t.Eras, e)
}
return t, nil
}
type Timeline struct {
Events []Event `json:"events"`
Eras []Era `json:"eras"`
}
type Date struct {
Year int `json:"year"`
Month int `json:"month"`
}
type Text struct {
Title string `json:"headline"` // can be HTML
Description *string `json:"text,omitempty"` // can be HTML
}
type Event struct {
Start Date `json:"start_date"`
End *Date `json:"end_date,omitempty"`
Text Text `json:"text"`
Group *string `json:"group,omitempty"`
}
type Era struct {
Start Date `json:"start_date"`
End Date `json:"end_date"`
Text Text `json:"text"`
}
func gracefulCtx() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
signals := make(chan os.Signal)
signal.Notify(signals, terminationSignals()...)
go func() {
select {
case <-ctx.Done():
case <-signals:
cancel()
}
}()
return ctx, cancel
}
// terminationSignals from https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html
func terminationSignals() []os.Signal {
return []os.Signal{
syscall.SIGTERM,
syscall.SIGINT,
syscall.SIGQUIT,
syscall.SIGKILL,
syscall.SIGHUP,
}
}