-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
362 lines (299 loc) · 7.27 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
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-gorp/gorp/v3"
"github.com/google/uuid"
"github.com/jessevdk/go-flags"
"github.com/minor-industries/rtgraph"
"github.com/minor-industries/rtgraph/schema"
"github.com/pkg/errors"
"html/template"
"net/http"
"sort"
"strconv"
"strings"
"time"
"weight-tracker/assets"
"weight-tracker/db"
)
const (
dbHost = "127.0.0.1"
location = "America/Los_Angeles"
day = 24 * time.Hour
defaultStartDate = "2011-01-01"
)
var opts struct {
Listen string `long:"listen" default:"0.0.0.0:8000" env:"LISTEN"`
DisableTLS bool `long:"disable-tls" env:"DISABLE_TLS"`
TLSCert string `long:"tls-cert" env:"TLS_CERT" default:"/var/lib/tls/certs/server.pem"`
TLSKey string `long:"tls-key" env:"TLS_KEY" default:"/var/lib/tls/private/server-key.pem"`
}
type StorageBackend struct {
db *gorp.DbMap
}
func (s *StorageBackend) LoadDataBetween(seriesName string, start time.Time, end time.Time) (schema.Series, error) {
//TODO implement me
panic("implement me")
}
func (s *StorageBackend) AllSeriesNames() ([]string, error) {
//TODO implement me
panic("implement me")
}
func (s *StorageBackend) LoadDataAfter(
seriesName string,
start time.Time,
) (schema.Series, error) {
var values []schema.Value
switch seriesName {
case "weight":
rows, err := getDataAfter(s.db, start)
if err != nil {
return schema.Series{}, errors.Wrap(err, "get data after")
}
values = make([]schema.Value, len(rows))
for idx, row := range rows {
values[idx] = schema.Value{
Timestamp: row.T,
Value: row.Weight,
}
}
default:
return schema.Series{}, errors.New("unknown series")
}
return schema.Series{
SeriesName: seriesName,
Values: values,
}, nil
}
func (s *StorageBackend) CreateSeries(seriesNames []string) error {
return nil
}
func (s *StorageBackend) InsertValue(seriesName string, timestamp time.Time, value float64) error {
//TODO implement me
panic("implement me")
}
func run() error {
_, err := flags.Parse(&opts)
if err != nil {
return errors.Wrap(err, "parse flags")
}
dbmap, err := db.Get(dbHost)
if err != nil {
return errors.Wrap(err, "get db")
}
backend := &StorageBackend{
db: dbmap,
}
errCh := make(chan error)
graph, err := rtgraph.New(
backend,
errCh,
rtgraph.Opts{},
)
if err != nil {
return errors.Wrap(err, "new rtgraph")
}
funcs := map[string]any{
"Localtime": func(w db.Weight) string {
loc, err := time.LoadLocation(w.Location)
if err != nil {
return "~location error~"
}
return w.T.In(loc).Format("2006-01-02 15:04:05")
},
"FmtWeight": func(w float64) string {
return fmt.Sprintf("%.02f", w)
},
"Delta": func(w []db.Weight, i0 int) string {
i1 := i0 + 1
if i1 >= len(w) {
return "-"
}
delta := w[i0].Weight - w[i1].Weight
return fmt.Sprintf("%+0.02f", delta)
},
"DateOfWeek": func(w db.Weight) string {
loc, err := time.LoadLocation(w.Location)
if err != nil {
return "~location error~"
}
return w.T.In(loc).Format("Mon")
},
"DaysMissing": func(w []db.Weight, i0 int) string {
i1 := i0 + 1
if i1 >= len(w) {
return ""
}
loc0, err := time.LoadLocation(w[i0].Location)
if err != nil {
return "~location error~"
}
loc1, err := time.LoadLocation(w[i1].Location)
if err != nil {
return "~location error~"
}
t0 := w[i0].T.In(loc0)
t1 := w[i1].T.In(loc1)
day0 := time.Date(t0.Year(), t0.Month(), t0.Day(), 0, 0, 0, 0, time.UTC)
day1 := time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.UTC)
delta := day0.Sub(day1)
days := int(delta.Hours() / 24)
switch days {
case 0, 1:
return ""
case 2:
return "1 day missing"
default:
return fmt.Sprintf("%d days missing", days)
}
},
}
gin.SetMode(gin.ReleaseMode)
router := gin.New()
templ := template.Must(template.New("").Funcs(funcs).ParseFS(assets.FS, "*.html"))
router.SetHTMLTemplate(templ)
router.GET("/favicon.ico", func(c *gin.Context) {
c.Status(204)
})
graph.SetupServer(router.Group("/rtgraph"))
router.GET("/ios-icon.png", func(c *gin.Context) {
c.FileFromFS("/ios-icon.png", http.FS(assets.FS))
})
router.GET("/", func(c *gin.Context) {
after, err := time.Parse("2006-01-02", c.DefaultQuery("after", defaultStartDate))
if err != nil {
c.AbortWithError(400, errors.Wrap(err, "parse time"))
return
}
data, err := getDataAfter(dbmap, after)
if err != nil {
_ = c.Error(err)
return
}
sort.Slice(data, func(i, j int) bool {
return data[i].T.After(data[j].T)
})
c.HTML(http.StatusOK, "index.html", map[string]any{
"date": time.Now().String(),
"action": "form-handler",
"id": uuid.New().String(),
"data": data,
})
})
router.POST("/form-handler", func(c *gin.Context) {
res, err := writeWeightToDB(
dbmap,
c.PostForm("weight"),
c.PostForm("unit"),
c.PostForm("id"),
)
if err != nil {
c.HTML(400, "error.html", map[string]any{
"message": err.Error(),
})
return
}
c.HTML(http.StatusOK, "form-handler.html", res)
})
router.GET("/commit-and-push.html", func(c *gin.Context) {
commit, err := db.CommitAndPush(dbmap)
args := map[string]any{
"err": err,
}
if commit.Valid {
args["commit"] = commit.String
}
c.HTML(200, "commit-and-push.html", args)
})
router.GET("/data.csv", func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/plain")
c.Status(200)
after, err := time.Parse("2006-01-02", c.DefaultQuery("after", defaultStartDate))
if err != nil {
c.AbortWithError(400, errors.Wrap(err, "parse time"))
return
}
data, err := getDataAfter(dbmap, after)
if err != nil {
_ = c.Error(err)
return
}
lines := []string{"date,weight"}
for i, d := range data {
if i > 0 {
d0 := data[i-1]
dt := d.T.Sub(d0.T)
if dt > 7*day {
lines = append(lines, fmt.Sprintf("%s,NaN",
d0.T.Format("2006/01/02 15:04:05"),
))
}
}
lines = append(lines, fmt.Sprintf("%s,%f",
d.T.Format("2006/01/02 15:04:05"),
d.Weight,
))
}
content := []byte(strings.Join(lines, "\n"))
_, _ = c.Writer.Write(content)
})
if opts.DisableTLS {
if err := router.Run(opts.Listen); err != nil {
return errors.Wrap(err, "run")
}
} else {
if err := router.RunTLS(opts.Listen, opts.TLSCert, opts.TLSKey); err != nil {
return errors.Wrap(err, "run")
}
}
return nil
}
func writeWeightToDB(
dbmap *gorp.DbMap,
weightParam string,
unitParam string,
idParam string,
) (map[string]any, error) {
switch unitParam {
case "kg", "lbs":
//pass
default:
return nil, errors.New("invalid unit")
}
weight, err := strconv.ParseFloat(weightParam, 64)
if err != nil {
return nil, errors.Wrap(err, "parse weight")
}
now := time.Now()
id, err := uuid.Parse(idParam)
if err != nil {
return nil, errors.Wrap(err, "parse id")
}
idBytes, err := id.MarshalBinary()
if err != nil {
return nil, errors.Wrap(err, "marshal id")
}
w := &db.Weight{
Id: idBytes,
T: now.UTC(),
Location: location,
Weight: weight,
Unit: unitParam,
}
err = dbmap.Insert(w)
if err != nil {
return nil, errors.Wrap(err, "insert")
}
return map[string]any{
"weight": weight,
"unit": unitParam,
"t": now,
"id": idParam,
}, nil
}
func main() {
if err := run(); err != nil {
panic(err)
}
}