-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
483 lines (401 loc) · 10.9 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
package main
import (
"bytes"
"database/sql"
"encoding/csv"
"fmt"
"github.com/badoux/checkmail"
"github.com/fridgecow/smartalarm-server/sleepdata"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/wcharczuk/go-chart"
gomail "gopkg.in/mail.v2"
"html/template"
"io"
"log"
"math"
"math/rand"
"net/http"
"os"
"strings"
"time"
)
var db *sql.DB
var templates *template.Template
type EmailInfo struct {
Id int
RegisterDate time.Time
Email string
Status string
Token string
Uses int
LastUse time.Time
}
type ConfirmData struct {
Email string
Token string
}
type SummaryEmail struct {
Statistics sleepdata.SleepStatistics
Email string
Token string
}
var Err = fmt.Errorf
func generateToken() string {
const letters = "0123456789abcdef"
b := make([]byte, 64)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func validateEmail(email string) bool {
log.Println("Validating email", email)
err := checkmail.ValidateFormat(email)
if err != nil {
return false
}
err = checkmail.ValidateHost(email)
if err != nil {
return false
}
err = checkmail.ValidateHost(email)
if _, ok := err.(checkmail.SmtpError); ok && err != nil {
return false
}
return true
}
type AttachmentContainer struct {
name string
reader io.Reader
}
func handlerNoLog(f func(*http.Request) (string, error)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
out, err := f(r)
if err != nil {
w.Write([]byte("Error: " + err.Error()))
log.Println("Error:", err.Error())
return
}
w.Write([]byte(out))
}
}
func handler(f func(*http.Request) (string, error)) func(http.ResponseWriter, *http.Request) {
handlerF := handlerNoLog(f)
return func(w http.ResponseWriter, r *http.Request) {
log.Println("Handling", r.Method, r.URL)
handlerF(w, r)
}
}
func sendEmail(to string, subject string, f func(io.Writer) error, files ...AttachmentContainer) error {
msg := gomail.NewMessage()
msg.SetAddressHeader("From", os.Getenv("SMARTALARM_EMAILADDR"), "Smart Alarm")
msg.SetHeader("To", to)
msg.SetHeader("ReplyTo", os.Getenv("SMARTALARM_EMAILREPLY"))
msg.SetHeader("Subject", subject)
msg.SetBody("text/plain", "Thank you for using Smart Alarm. Please switch to an HTML-capable client to view this email.")
msg.AddAlternativeWriter("text/html", f)
for _, file := range files {
msg.EmbedReader(file.name, file.reader)
}
// Send on seperate channel
emailChan <- msg
return nil
}
func getEmailInfo(email string) (emailInfo EmailInfo, e error) {
// DB query
err := db.QueryRow(
"SELECT id, register_date, email, type, token, uses, last_use FROM smartalarm_emails WHERE email = ?",
email,
).Scan(&emailInfo.Id, &emailInfo.RegisterDate, &emailInfo.Email, &emailInfo.Status, &emailInfo.Token, &emailInfo.Uses, &emailInfo.LastUse)
if err != nil {
return emailInfo, err
}
return emailInfo, nil
}
func addEmail(r *http.Request) (string, error) {
params := mux.Vars(r)
email := params["email"]
info, err := getEmailInfo(email)
if err == nil && info.Status == "CONFIRMED" {
return "", Err("email already confirmed")
}
token := generateToken()
if err != nil {
// No results - add email to DB
if !validateEmail(email) {
return "", Err("email not valid")
}
log.Println("Registering", email)
_, err := db.Exec(
"INSERT INTO smartalarm_emails (email, token) VALUES (?, ?)",
email,
token,
)
if err != nil {
return "", err
}
} else if info.Status == "UNSUBSCRIBED" || info.Status == "REGISTERED" {
// Update token
_, err := db.Exec(
"UPDATE `smartalarm_emails` SET `token` = ? WHERE `email` = ?",
token,
email,
)
if err != nil {
return "", err
}
}
err = sendEmail(email, "Smart Alarm Email Confirmation", func(w io.Writer) error {
return templates.Lookup("emailconfirm.tmpl").ExecuteTemplate(w, "confirmation", ConfirmData{Email: email, Token: token})
})
if err != nil {
return "", err
}
return "Confirmation sent - check your email", nil
}
func confirmEmail(r *http.Request) (string, error) {
params := mux.Vars(r)
email := params["email"]
token := params["token"]
info, err := getEmailInfo(email)
if err != nil {
return "", Err("email not registered")
}
if info.Status == "CONFIRMED" {
return "", Err("email already confirmed")
}
if info.Token != token {
return "", Err("token doesn't match")
}
_, err = db.Exec(
"UPDATE `smartalarm_emails` SET `type`='CONFIRMED', `token` = '' WHERE `email` = ?",
email,
)
if err != nil {
return "", err
}
log.Println("Confirmed", email)
return "Email confirmed - you can now export your data.", nil
}
func unsubEmail(r *http.Request) (string, error) {
params := mux.Vars(r)
email := params["email"]
token := params["token"]
info, err := getEmailInfo(email)
if err != nil {
return "", Err("email not registered")
}
if info.Status != "CONFIRMED" {
return "", Err("email not subscribed")
}
if info.Token != token {
return "", Err("token doesn't match. Use most recent email.")
}
_, err = db.Exec(
"UPDATE `smartalarm_emails` SET `type`='UNSUBSCRIBED', `token` = '' WHERE `email` = ?",
email,
)
if err != nil {
return "", err
}
log.Println("Unsubscribed", email)
return "Email unsubscribed. To re-subscribe, send a new confirmation from your watch.", nil
}
func sendCSV(r *http.Request) (string, error) {
params := mux.Vars(r)
email := params["email"]
tz := r.FormValue("tz")
// Validate email and regenerate token before doing any other work
info, err := getEmailInfo(email)
if err != nil {
return "", Err("email not registered")
}
if info.Status != "CONFIRMED" {
return "", Err("email not subscribed")
}
info.Token = generateToken()
_, err = db.Exec(
"UPDATE `smartalarm_emails` SET `token` = ? WHERE `email` = ?",
info.Token,
email,
)
if err != nil {
return "", Err(err.Error() + " db")
}
location, err := time.LoadLocation(tz)
if err != nil {
return "", Err(err.Error() + " tz")
}
csvData := csv.NewReader(strings.NewReader(r.FormValue("csv")))
csvData.FieldsPerRecord = -1
header, err := csvData.Read()
if err != nil {
return "", Err("can not read CSV: " + err.Error())
}
csvBody, err := csvData.ReadAll()
if err != nil {
return "", Err("can not read CSV body: " + err.Error())
}
var sleepSummary sleepdata.SleepSummary
fullExport := header[0] != "Region Type"
if fullExport {
// Full Export - load sleep data then summarise it
sleepData, err := sleepdata.MakeSleepData(csvBody, *location)
if err != nil {
return "", Err(err.Error() + " sd")
}
sleepSummary, err = sleepdata.SummariseData(sleepData)
if err != nil {
return "", Err(err.Error() + " ss")
}
log.Println("Full summary export")
} else {
// Summary export - parse sleep regions
sleepSummary, err = sleepdata.ParseRegions(csvBody, location)
if err != nil {
return "", Err(err.Error() + " ss reg")
}
}
graph := chart.Chart{
Title: sleepSummary.Title,
TitleStyle: chart.StyleShow(),
Width: 1200,
Background: chart.Style{
Padding: chart.Box{
Left: 50,
},
},
XAxis: chart.XAxis{
Name: "Time",
NameStyle: chart.StyleShow(),
Style: chart.StyleShow(),
ValueFormatter: chart.TimeValueFormatterWithFormat("15:04"),
},
YAxis: chart.YAxis{
Name: "Motion (m/s²)",
NameStyle: chart.StyleShow(),
Style: chart.StyleShow(),
},
YAxisSecondary: chart.YAxis{
Name: "Heart Rate (bpm)",
NameStyle: chart.StyleShow(),
Style: chart.StyleShow(),
},
}
if !fullExport {
graph.YAxis.Range = &chart.ContinuousRange{
Min: 0,
Max: 1000,
}
graph.YAxis.Style.Show = false
graph.YAxisSecondary.Style.Show = false
graph.Series = sleepSummary.GetChartBands()
} else {
graph.Series = append(
sleepSummary.GetChartBands(),
sleepSummary.Data.GetMotionSeries(),
sleepSummary.Data.GetHeartRateSeries(),
)
}
if !sleepSummary.Statistics.HeartRateEnabled {
graph.YAxisSecondary.Style.Show = false
}
graph.Elements = []chart.Renderable{
chart.Legend(&graph),
}
buffer := bytes.NewBuffer([]byte{})
err = graph.Render(chart.PNG, buffer)
if err != nil {
return "", Err("could not render graph: " + err.Error())
}
emailData := SummaryEmail{
Token: info.Token,
Email: info.Email,
Statistics: sleepSummary.Statistics,
}
sendEmail(
email,
sleepSummary.Title,
func(w io.Writer) error {
return templates.Lookup("emailhtml.tmpl").ExecuteTemplate(w, "export", emailData)
},
AttachmentContainer{
"image.png",
buffer,
},
AttachmentContainer{
"data.csv",
bytes.NewBufferString(r.FormValue("csv")),
},
)
return "Export success", nil
}
func main() {
var err error
// Database Connection
db, err = sql.Open(
"mysql",
os.Getenv("SMARTALARM_DBUSER")+":"+os.Getenv("SMARTALARM_DBPASS")+"@"+os.Getenv("SMARTALARM_DBHOST")+"/"+os.Getenv("SMARTALARM_DBNAME")+"?parseTime=true",
)
if err != nil {
log.Fatalf("Error on initializing database connection: %s", err.Error())
}
err = db.Ping()
if err != nil {
log.Fatalf("Error on opening database connection: %s", err.Error())
}
// Load templates
templates, err = template.New("").Funcs(template.FuncMap{
"dict": func(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, Err("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
return nil, Err("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
},
"percent": func(value float64) string {
return fmt.Sprintf("%.1f", value*100)
},
"time": func(value time.Time) string {
return value.Format("15:04")
},
"duration": func(value time.Duration) string {
d := value.Round(time.Minute)
h := d / time.Hour
d -= h * time.Hour
m := d / time.Minute
return fmt.Sprintf("%d hours %d minutes", h, m)
},
"multDuration": func(a float64, b time.Duration) string {
duration := fmt.Sprintf("%v", time.Duration(math.Round(a*float64(b))))
return duration[:len(duration)-2] // Remove "0s" from end
},
}).ParseGlob("templates/*.tmpl")
if err != nil {
log.Fatalf("Could not parse templates: %s", err.Error())
}
log.Println("Initialisation complete")
r := mux.NewRouter()
r.HandleFunc("/v1/add/{email}", handler(addEmail))
r.HandleFunc("/v1/confirm/{email}/{token:[0-9a-f]{64,}}", handler(confirmEmail))
r.HandleFunc("/v1/unsub/{email}/{token:[0-9a-f]{64,}}", handler(unsubEmail))
r.HandleFunc("/v1/csv/{email}", handler(sendCSV))
r.HandleFunc("/ping", handlerNoLog(func(r *http.Request) (string, error) { return "☑", nil }))
srv := &http.Server{
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
Handler: r,
Addr: ":6662",
}
log.Println("Starting server...")
log.Fatal(srv.ListenAndServe())
}