-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfitplot.go
631 lines (590 loc) · 18.8 KB
/
fitplot.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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//
// Fitplot provides a webserver used to process .fit and .tcx files.
//
package main
import (
//"database/sql"
"encoding/json"
"fmt"
// "github.com/cprevallet/fitplot/desktop"
"github.com/cprevallet/fitplot/persist"
"github.com/cprevallet/fitplot/strutil"
"github.com/cprevallet/fitplot/tcx"
"github.com/jezard/fit"
"github.com/mitchellh/go-homedir"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"time"
)
// Buildstamp represents a build timestamp for use in technical support. It is
// created using the linker option -X we can set a value for a symbol that can
// be accessed from within the binary.
// go build -ldflags "-X main.Buildstamp=`date -u '+%Y-%m-%d_%I:%M:%S%p'` -X main.Githash=`git rev-parse HEAD`" fitplot.go
var Buildstamp = "No build timestamp provided"
// Githash represents a hash from the version control system for use in
// technical support. It is created using the linker option -X we can
// set a value for a symbol that can be accessed from within the binary.
// go build -ldflags "-X main.Buildstamp=`date -u '+%Y-%m-%d_%I:%M:%S%p'` -X main.Githash=`git rev-parse HEAD`" fitplot.go
var Githash = "No git hash provided"
var tmpFname = ""
var timeStamp time.Time
var workingDirPath = ""
// Compile templates on start for better performance.
// Display the named template.
func display(w http.ResponseWriter, tmpl string, data interface{}) {
var templates = template.Must(template.ParseFiles("tmpl/fitplot.html"))
templates.ExecuteTemplate(w, tmpl+".html", data)
}
// Handle requests to "/".
func pageloadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
// Load page.
//fmt.Println("pageloadHandler Received Request")
display(w, "fitplot", nil)
}
if r.Method == "POST" {
// File load request
//fmt.Println("pageloadHandler POST Received Request")
uploadHandler(w, r)
//display(w, "fitplot", nil)
}
}
//Upload a copy the fit file to a temporary local directory.
func uploadHandler(w http.ResponseWriter, r *http.Request) {
//fmt.Println("uploadHandler Received Request")
// Do some low-level stuff to retrieve the file name and byte array.
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// fBytes is an in-memory array of bytes read from the file.
fBytes, err := ioutil.ReadAll(file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fName := handler.Filename
fType, fitStruct, tcxdb, _, _, err := parseInputBytes(fBytes)
switch {
case fType == "FIT":
timeStamp = time.Unix(fitStruct.Records[0].Timestamp, 0)
case fType == "TCX":
timeStamp = time.Unix(tcxdb.Acts.Act[0].Laps[0].Trk.Pt[0].Time.Unix(), 0)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Persist the in-memory array of bytes to the database.
dbRecord := persist.Record{FName: fName, FType: fType, FContent: fBytes, TimeStamp: timeStamp}
db, err := persist.ConnectDatabase("fitplot", workingDirPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = persist.InsertNewRecord(db, dbRecord)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
db.Close()
return
}
db.Close()
}
// getDistance retrieves a run's total distance in the appropriate unit system.
func getOtherVals(fBytes []byte) (totalDistance float64, movingTime float64, totalPace string) {
dummyTimeStamp := []int64{0}
lapCal := []float64{0.0}
_, _, _, _, runLaps, _ := parseInputBytes(fBytes)
_, _, _, _, totalDistance, movingTime = processFitLap(runLaps, toEnglish)
_, totalPace, _, _, _, _,_ = createStats(toEnglish, totalDistance, movingTime, dummyTimeStamp, lapCal)
return totalDistance, movingTime, totalPace
}
// Return information about entries in the database between two dates.
func dbGetRecs(w http.ResponseWriter, r *http.Request) (recs []persist.Record, err error) {
type DBDateStrings struct {
DBStart string
DBEnd string
}
decoder := json.NewDecoder(r.Body)
var dbQuery DBDateStrings //string
err = decoder.Decode(&dbQuery)
if err != nil {
return nil, err
}
// Connect to database and retrieve. Be sure we bracket the entirety of
// the selected day.
db, err := persist.ConnectDatabase("fitplot", workingDirPath)
if err != nil {
return nil, err
}
startTime, _ := time.Parse("2006-01-02 15:04:05", dbQuery.DBStart+" 00:00:00")
endTime, _ := time.Parse("2006-01-02 15:04:05", dbQuery.DBEnd+" 23:59:59")
recs = persist.GetRecsByTime(db, startTime, endTime)
db.Close()
return recs, nil
}
type RunInfoStruct struct {
FName string
FType string
TimeStamp string
Date string
Time string
TimeZone string
Weekday string
MovingTime string
Pace string
Distance string
}
// worker handles the task of making the database results presentable.
func worker(id int, jobs <-chan persist.Record, results chan<- RunInfoStruct) {
for rec := range jobs {
var rs RunInfoStruct
rs.FName = rec.FName
rs.FType = rec.FType
rs.TimeStamp = rec.TimeStamp.Format(time.RFC1123)
rs.Date = rec.TimeStamp.Format(time.RFC3339)[0:10]
rs.Time = rec.TimeStamp.Format(time.RFC3339)[11:19]
rs.TimeZone = rec.TimeStamp.Format(time.RFC3339)[19:25]
rs.Weekday = rec.TimeStamp.Format(time.RFC1123)[0:3]
totalDistance, movingTime,totalPace := getOtherVals(rec.FContent)
rs.Distance = strconv.FormatFloat(totalDistance, 'f', 2, 64)
rs.MovingTime = strutil.DecimalTimetoHourMinSec(movingTime)
rs.Pace = totalPace
results <- rs
}
}
// Return information about entries in the database.
func dbHandler(w http.ResponseWriter, r *http.Request) {
var DBFileList []RunInfoStruct
// Structure element names MUST be uppercase or decoder can't access them.
type RtnStruct struct {
DBFileList []RunInfoStruct
Totals map[string]float64
Units map[string]string
}
returnData := RtnStruct{
DBFileList: nil,
Totals: nil,
Units: nil,
}
totals := map[string]float64 {"Distance": 0.0}
recs, err := dbGetRecs(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Do a bit of fancy footwork to speed up the reads with goroutines.
jobs := make(chan persist.Record, 10000) //make this buffered
results := make(chan RunInfoStruct, 10000) //make this buffered
for i, _ := range recs {
go worker(i, jobs, results) // initially blocked
}
for _, rec := range recs {
jobs <- rec // start processing
}
close(jobs) //indicate this is all the work we have
for range recs {
presentableRec := <- results //get presentableRec from channel
f, _ := strconv.ParseFloat(presentableRec.Distance, 64)
totals["Distance"] += f
DBFileList = append(DBFileList, presentableRec)
}
var units map[string]string
units = make(map[string]string)
if toEnglish {
units["Distance"] = "miles"
} else {
units["Distance"] = "kilometers"
}
returnData.DBFileList = DBFileList
returnData.Totals = totals
returnData.Units = units
//Convert to json.
js, err := json.Marshal(returnData)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
//Send
w.Write(js)
}
// Set an individually record in the the database as the one to process via
// the timeStamp global variable.
func dbSelectHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
type DateStrings struct {
DateStr string
TimeStr string
TimeZoneStr string
}
var ds DateStrings
var ts string
err := decoder.Decode(&ds)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
ts = ds.DateStr + "T"+ ds.TimeStr + ds.TimeZoneStr
timeStamp, err = time.Parse(time.RFC3339, ts)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Export file(s) to disk.
func dbExportHandler(w http.ResponseWriter, r *http.Request) {
recs,err := dbGetRecs(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//slash := string(filepath.Separator)
// path := "." + slash + "export" + slash
//_ = "breakpoint"
for _, rec := range recs {
ioutil.WriteFile(filepath.Join(workingDirPath, rec.FName), rec.FContent, 0644)
}
}
// Return information about the runtime environment.
func envHandler(w http.ResponseWriter, r *http.Request) {
type Environ struct {
Buildstamp string
Githash string
CPUArchitecture string
OperatingSystem string
}
e := Environ{
Buildstamp: Buildstamp,
Githash: Githash,
CPUArchitecture: runtime.GOARCH,
OperatingSystem: runtime.GOOS,
}
//Convert to json.
js, err := json.Marshal(e)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//fmt.Println("plotHandler Received Request")
w.Header().Set("Content-Type", "text/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
//Send
w.Write(js)
}
// Parse the input bytes into structures more conducive for additional
// processing by routines in graphdata.go.
func parseInputBytes(fBytes []byte) (fType string, fitStruct fit.FitFile, tcxdb *tcx.TCXDB, runRecs []fit.Record, runLaps []fit.Lap, err error) {
// Make a copy in a temporary folder for use with fit and tcx
// libraries.
tmpFile, err := persist.CreateTempFile(fBytes)
if err != nil {
return "", fit.FitFile{}, nil, nil, nil, err
}
err = nil
tmpFname = tmpFile.Name()
// Determine what type of file we're looking at.
rslt := http.DetectContentType(fBytes)
switch {
case rslt == "application/octet-stream":
// Filetype is FIT, or at least it could be?
fType = "FIT"
fitStruct = fit.Parse(tmpFname, false)
tcxdb = nil
runRecs = fitStruct.Records
runLaps = fitStruct.Laps
case rslt == "text/xml; charset=utf-8":
// Filetype is TCX or at least it could be?
fType = "TCX"
fitStruct = fit.FitFile{}
tcxdb, err = tcx.ReadTCXFile(tmpFname)
// We cleverly convert the values of interest into a structures we already
// can handle.
if err == nil {
runRecs = tcx.CvtToFitRecs(tcxdb)
runLaps = tcx.CvtToFitLaps(tcxdb)
}
}
persist.DeleteTempFile(tmpFile)
return fType, fitStruct, tcxdb, runRecs, runLaps, err
}
// Parse the uploaded file, parse it and return run information suitable
// to construct the user interface.
func plotHandler(w http.ResponseWriter, r *http.Request) {
type Plotvals struct {
Titletext string
XName string
Y0Name string
Y1Name string
Y2Name string
DispDistance []float64
DispPace []float64
DispAltitude []float64
DispCadence []float64
TimeStamps []int64
Latlongs []map[string]float64
LapDist []float64
LapTime []string
LapCal []float64
LapPace []string
C0Str string
C1Str string
C2Str string
C3Str string
C4Str string
TotalDistance float64
MovingTime float64
DispTotalDistance string
DispMovingTime string
TotalPace string
ElapsedTime string
TotalCal string
AvgPower string
StartDateStamp string
EndDateStamp string
Device string
PredictedTimes map[string]string
TrainingPaces map[string]string
VDOT float64
DeviceName string
DeviceUnitID string
DeviceProdID string
RunScore float64
VO2max float64
Buildstamp string
Githash string
}
// Note extra space on following assignments.
var xStr = "Distance "
var y0Str = "Pace "
var y1Str = "Elevation "
var y2Str = "Cadence "
var c0Str, c1Str, c2Str, c3Str, c4Str string
// User hasn't selected a file yet? Avoid a panic.
if timeStamp.IsZero() {
http.Error(w, "No file selected.", http.StatusConflict)
return
}
// Structure element names MUST be uppercase or decoder can't access them.
type UIData struct {
UseEnglish bool
Racedist float64
Racehours int64
Racemins int64
Racesecs int64
UseSegment bool
Splitdist float64
Splithours int64
Splitmins int64
Splitsecs int64
}
decoder := json.NewDecoder(r.Body)
var UI UIData
err := decoder.Decode(&UI)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
toEnglish = UI.UseEnglish
// Retrieve the file from the database by timeStamp global
// variable. Make the search criteria just outside the
// expected run start time.
db, err := persist.ConnectDatabase("fitplot", workingDirPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
slightlyOlder := timeStamp.Add(-1 * time.Second)
slightlyNewer := timeStamp.Add(1 * time.Second)
recs := persist.GetRecsByTime(db, slightlyOlder, slightlyNewer)
db.Close()
fBytes := recs[0].FContent
// Parse the input bytes into structures more conducive for additional
// processing by routines in graphdata.go.
fType, fitStruct, tcxdb, runRecs, runLaps, err := parseInputBytes(fBytes)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Build the variable strings based on unit system.
if toEnglish {
xStr = xStr + "(mi)"
y0Str = y0Str + "(min/mi)"
y1Str = y1Str + "(ft)"
y2Str = y2Str + "(steps/min)"
c0Str = "Lap"
c1Str = "Distance" + "(mi)"
c2Str = "Pace" + "(min/mi)"
c3Str = "Time" + "(min)"
c4Str = "Calories" + "(kcal)"
} else {
xStr = xStr + "(km)"
y0Str = y0Str + "(min/km)"
y1Str = y1Str + "(m)"
y2Str = y2Str + "(steps/min)"
c0Str = "Lap"
c1Str = "Distance" + "(km)"
c2Str = "Pace" + "(min/km)"
c3Str = "Time" + "(min)"
c4Str = "Calories" + "(kcal)"
}
// Create an object to contain various plot values.
p := Plotvals{Titletext: "",
XName: xStr,
Y0Name: y0Str,
Y1Name: y1Str,
Y2Name: y2Str,
DispDistance: nil,
DispPace: nil,
DispAltitude: nil,
DispCadence: nil,
TimeStamps: nil,
Latlongs: nil,
LapDist: nil,
LapTime: nil,
LapCal: nil,
LapPace: nil,
C0Str: c0Str,
C1Str: c1Str,
C2Str: c2Str,
C3Str: c3Str,
C4Str: c4Str,
TotalDistance: 0.0,
MovingTime: 0.0,
DispTotalDistance: "",
DispMovingTime: "",
TotalPace: "",
TotalCal: "",
AvgPower: "",
StartDateStamp: "",
EndDateStamp: "",
Device: "",
PredictedTimes: nil,
TrainingPaces: nil,
VDOT: 0.0,
DeviceName: "",
DeviceUnitID: "",
DeviceProdID: "",
RunScore: 0.0,
VO2max: 0.0,
}
// Retrieve overview information.
if fType == "FIT" {
p.DeviceName = fitStruct.DeviceInfo[0].Manufacturer
p.DeviceProdID = fitStruct.DeviceInfo[0].Product
p.DeviceUnitID = fmt.Sprint(fitStruct.DeviceInfo[0].Serial_number)
}
if fType == "TCX" {
p.DeviceName, p.DeviceUnitID, p.DeviceProdID = tcx.DeviceInfo(tcxdb)
}
// Here's where the heavy lifting of pulling tracks and performance information
// from (portions of) the fit file into something we can view is done.
p.Latlongs, p.TimeStamps, p.DispDistance, p.DispPace, p.DispAltitude, p.DispCadence =
processFitRecord(runRecs, toEnglish)
p.LapDist, p.LapTime, p.LapCal, p.LapPace, p.TotalDistance, p.MovingTime = processFitLap(runLaps, toEnglish)
// Get the start time.
p.Titletext += time.Unix(p.TimeStamps[0], 0).Format(time.UnixDate)
// Calculate the summary string information.
p.DispTotalDistance, p.TotalPace, p.DispMovingTime, p.TotalCal, p.AvgPower, p.StartDateStamp,
p.EndDateStamp = createStats(toEnglish, p.TotalDistance, p.MovingTime, p.TimeStamps, p.LapCal)
// Calculate the analysis page.
p.PredictedTimes, p.VDOT, p.VO2max, p.RunScore, p.TrainingPaces = createAnalysis(toEnglish,
UI.UseSegment, p.DispDistance, p.TimeStamps, UI.Splitdist, UI.Splithours, UI.Splitmins,
UI.Splitsecs, UI.Racedist, UI.Racehours, UI.Racemins, UI.Racesecs)
//Convert to json.
js, err := json.Marshal(p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//fmt.Println("plotHandler Received Request")
w.Header().Set("Content-Type", "text/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
//Send
w.Write(js)
}
// Create directory if one doesn't exist, otherwise do nothing
func CreateDirIfNotExist(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
}
}
// Find the writeable application documents directory
func workingDir() {
_, err := homedir.Dir()
if err != nil {
panic(err)
}
docDir, err := homedir.Expand("~/Documents")
if err != nil {
panic(err)
}
workingDirPath = filepath.Join(docDir, "fitplot")
CreateDirIfNotExist(workingDirPath)
return
}
// Opens a log file.
func openLog() {
f, err := os.OpenFile(filepath.Join(workingDirPath, "fitplot.log"), os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
panic("Can't open log file. Aborting.")
}
log.SetOutput(f)
}
// Allow the user to shutdown the server from a target in the user interface client.
func stopHandler(w http.ResponseWriter, r *http.Request) {
// Nothing graceful about this exit. Just bail out.
os.Exit(0)
return
}
// Migrate the persistent store (database) to the current version.
func migrate() {
// Play it safe and create a single backup file in the temporary
// directory in the event of problems.
// I don't know what the performance impact might be, this safeguard
// can be removed if performance becomes an issue (e.g. for large databases).
dbName := filepath.Join(workingDirPath, "fitplot.db")
file, err := os.Open(dbName)
if err == nil {
fBytes,_ := ioutil.ReadAll(file)
persist.CreateTempFile(fBytes)
file.Close()
}
db, err := persist.ConnectDatabase("fitplot", workingDirPath)
if err != nil {
panic("Can't locate database. Aborting.")
}
persist.MigrateDatabase(db)
db.Close()
return
}
func main() {
workingDir()
openLog()
// Serve static files if the prefix is "static".
// The static file directory path must be specified as an environment variable.
var staticFileDir, ok = os.LookupEnv("STATIC_FILES")
if !ok {
panic("Could not find path for the help files. Set environment variable.")
}
fs := http.FileServer(http.Dir(staticFileDir))
http.Handle("/static/", http.StripPrefix("/static/", fs))
migrate()
// Handle normal requests.
http.HandleFunc("/", pageloadHandler)
http.HandleFunc("/getplot", plotHandler)
http.HandleFunc("/stop", stopHandler)
http.HandleFunc("/env", envHandler)
http.HandleFunc("/getruns", dbHandler)
http.HandleFunc("/selectrun", dbSelectHandler)
http.HandleFunc("/exportrun", dbExportHandler)
//Listen on port 8080
//fmt.Println("Server starting on port 8080.")
http.ListenAndServe(":8080", nil)
}