-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
1185 lines (1005 loc) · 29.6 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
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"github.com/thlib/go-timezone-local/tzlocal"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var (
caser = cases.Title(language.English)
client = http.DefaultClient
dosageRegex = regexp.MustCompile("([0-9.]+)([ -_]+)?([μµ]g|mg|g|kg|u|x|mL|)?")
//prefsUrl = "http://localhost:6010/media/doses-prefs.json"
options = &DisplayOptions{}
loadUrl = flag.String("url", "http://localhost:6010/media/doses.json", "URL for doses.json")
saveUrl = flag.String("save-url", "", "URL for saving to a different file (used with -save-filtered)")
urlToken = flag.String("token", "", "token for fs-over-http (default $FOH_TOKEN or $FOH_SERVER_AUTH from env)")
optAdd = flag.Bool("add", false, "Set to add a dose")
optRm = flag.Bool("rm", false, "Set to remove the *last added* dose")
optRmP = flag.Int("rmp", -1, "Set to remove dose *by position*")
optSav = flag.Bool("save", false, "Run a manual save to re-generate the .txt format after a manual edit")
optSfl = flag.Bool("save-filtered", false, "[DANGEROUS] Respect -g when using -save, WILL overwrite doses if set")
optTop = flag.Bool("stat-top", false, "Set to view top statistics")
optAvg = flag.Bool("stat-avg", false, "Set to view average dose statistics")
optNts = flag.Bool("ignore-notes", false, "Set to hide notes (applies before filters)")
optJ = flag.Bool("j", false, "Set for json output")
optU = flag.Bool("u", false, "Show UNIX timestamp in non-json mode")
optT = flag.Bool("t", false, "Show dottime format in non-json mode")
optR = flag.Bool("r", false, "Show in reverse order")
optS = flag.Bool("s", false, "Start reading doses from top (applies before anything else)")
optV = flag.Bool("v", false, "Inverse filter for text")
optG = flag.String("g", "", "Filter for text (applies in all modes)")
optN = flag.Int("n", 0, "Show last n doses, -1 = all (applied after filters, does not apply to -save-filtered)")
aChangeTz = flag.String("change-tz", "", "Change timezone (retain literal date / time) (applies to last -n doses)")
aConvTz = flag.String("convert-tz", "", "Convert timezone (shift relative date / time) (applies to last -n doses)")
aTimezone = flag.String("timezone", "", "Set timezone")
aDate = flag.String("date", "", "Set date (default \"time.Now()\")")
aTime = flag.String("time", "", "Set time (default \"time.Now()\")")
aDosage = flag.String("a", "", "Set dosage")
aDrug = flag.String("d", "", "Set drug name")
aRoa = flag.String("roa", "", "Set RoA")
aNote = flag.String("note", "", "Add note")
)
//type MainPreferences struct {
// Preferences map[string]UserPreferences `json:"preferences,omitempty"`
//}
type UserPreferences struct {
DateFmt string `json:"date_fmt,omitempty"`
TimeFmt string `json:"time_fmt,omitempty"`
}
type Mode int64
const (
ModeGet Mode = iota
ModeAdd
ModeRm
ModeRmPosition
ModeTzChange
ModeTzConvert
ModeSave
ModeSaveFiltered
ModeStatTop
ModeStatAvg
)
func (m Mode) String() string {
switch m {
case ModeGet:
return "-get"
case ModeAdd:
return "-add"
case ModeRm:
return "-rm"
case ModeRmPosition:
return "-rmp"
case ModeTzChange:
return "-change-tz"
case ModeTzConvert:
return "-convert-tz"
case ModeSave:
return "-save"
case ModeSaveFiltered:
return "-save-filtered"
case ModeStatTop:
return "-stat-top"
case ModeStatAvg:
return "-stat-avg"
default:
return "-default"
}
}
type LayoutFormat string
type WrapFormat struct {
Prefix string
Suffix string
}
type TimestampLayout struct {
Formats []LayoutFormat
Layout WrapFormat
Value WrapFormat
}
type DisplayOptions struct {
Mode
Json bool
Unix bool
DotTime bool
IgnoreNotes bool
Reversed bool
StartAtTop bool
FilterInvert bool
Filter string
FilterRegex *regexp.Regexp // generated from Filter
LastAddedPos int // when Mode is ModeAdd this is set after adding a dose
Show int
RmPosition int
Timezone string
LoadUrl string // generated from loadUrl / saveUrl, used by saveDoseFiles()
SaveUrl string // generated from loadUrl / saveUrl, used by saveDoseFiles()
}
func (d *DisplayOptions) Parse() {
var mode Mode
switch {
case *optAdd:
mode = ModeAdd
case *optRm:
mode = ModeRm
case *optRmP > -1:
mode = ModeRmPosition
case *aChangeTz != "":
mode = ModeTzChange
case *aConvTz != "":
mode = ModeTzConvert
case *optSfl:
mode = ModeSaveFiltered
case *optSav:
mode = ModeSave
case *optTop:
mode = ModeStatTop
case *optAvg:
mode = ModeStatAvg
default:
mode = ModeGet
}
// If we're not in a stat mode and the user hasn't set showLast, set it to 5 as a sensible default
showLast := *optN
if showLast == 0 && mode != ModeStatTop && mode != ModeStatAvg {
showLast = 5
}
timezone := ""
switch {
case *aChangeTz != "":
timezone = *aChangeTz
case *aConvTz != "":
timezone = *aConvTz
case *aTimezone != "":
timezone = *aTimezone
}
saveUrlNew := *loadUrl
if len(*saveUrl) > 0 {
saveUrlNew = *saveUrl
}
options = &DisplayOptions{
Mode: mode,
Json: *optJ,
Unix: *optU,
DotTime: *optT,
IgnoreNotes: *optNts,
Reversed: *optR,
StartAtTop: *optS,
FilterInvert: *optV,
Filter: *optG,
//FilterRegex: set after Parse(),
LastAddedPos: -1,
Show: showLast,
RmPosition: *optRmP,
Timezone: timezone,
LoadUrl: *loadUrl,
SaveUrl: saveUrlNew,
}
}
func (d *DisplayOptions) String() string {
j, err := json.MarshalIndent(d, "", " ")
if err != nil {
j = []byte(fmt.Sprintf("error marshalling json: %v", err))
}
return fmt.Sprintf("%s", j)
}
func (d *DisplayOptions) MarshalJSON() ([]byte, error) {
type Alias DisplayOptions
return json.Marshal(&struct {
Mode string
*Alias
}{
Mode: d.Mode.String(),
Alias: (*Alias)(d),
})
}
type TimeData struct {
Timestamp time.Time `json:"timestamp,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
type Dose struct { // timezone,date,time,dosage,drug,roa,note
Position int `json:"position"` // order added, at the top so that it's marshaled as at the top
TimeData
Created *TimeData `json:"created,omitempty"`
Date string `json:"date,omitempty"`
Time string `json:"time,omitempty"`
Dosage string `json:"dosage,omitempty"`
Drug string `json:"drug,omitempty"`
RoA string `json:"roa,omitempty"`
Note string `json:"note,omitempty"`
}
func (d Dose) ParsedTime() (time.Time, error) {
timeZero := time.Unix(0, 0)
loc, err := time.LoadLocation(d.Timezone)
if err != nil {
return timeZero, err
}
if pt, err := time.ParseInLocation("2006/01/0215:04", d.Date+d.Time, loc); err == nil {
return pt, nil
} else {
return timeZero, err
}
}
func (d Dose) StringOptions(options *DisplayOptions) string {
note := ""
if !options.IgnoreNotes && d.Note != "" {
note = ", Note: " + d.Note
}
dosage := ""
if d.Dosage != "" {
dosage = " " + d.Dosage
}
unix := ""
if options.Unix {
unix = fmt.Sprintf("%v ", d.Timestamp.Unix())
}
// print dottime format
if options.DotTime {
zone := d.Timestamp.Format("Z07")
if zone == "Z" {
zone = "+00"
}
return fmt.Sprintf("%s%s%s %s, %s%s", unix, d.Timestamp.UTC().Format("2006-01-02 15·04")+zone, dosage, d.Drug, d.RoA, note)
}
// print regular format
return fmt.Sprintf("%s%s%s %s, %s%s", unix, d.Timestamp.Format("2006/01/02 15:04"), dosage, d.Drug, d.RoA, note)
}
func (d Dose) String() string {
return d.StringOptions(options)
}
// DoseUnitSize represents a dose unit as a factor of micrograms equivalent
type DoseUnitSize int64
const (
DoseUnitSizeDefault DoseUnitSize = 0
DoseUnitSizeMicrogram DoseUnitSize = 1
DoseUnitSizeMilliliter DoseUnitSize = -1 // TODO: FIX
DoseUnitSizeMilligram DoseUnitSize = 1000
DoseUnitSizeGram DoseUnitSize = 1000 * 1000
DoseUnitSizeKilogram DoseUnitSize = 1000 * 1000 * 1000
DoseUnitSizeAlcohol DoseUnitSize = DoseUnitSizeEthanol / 10 // 1u = 0.1mL of EtOH = 1 SI unit of Alcohol
DoseUnitSizeEthanol DoseUnitSize = 789.45 * 1000 // 1mL = 789.45mg EtOH at 20°C * to get micrograms
DoseUnitSizeGHB DoseUnitSize = 1120.0 * 1000 // 1mL = 1120.0mg of GHB at 25°C * to get μg
DoseUnitSizeGBL DoseUnitSize = 1129.6 * 1000 // 1mL = 1129.6mg of GBL at 20°C * to get μg
DoseUnitSizeBDO DoseUnitSize = 1017.3 * 1000 // 1mL = 1017.3mg of 1,4-BDO at 25°C * to get μg
)
func (u DoseUnitSize) String() string {
switch u {
case DoseUnitSizeMicrogram:
return "μg"
case DoseUnitSizeMilligram, DoseUnitSizeGHB:
return "mg"
case DoseUnitSizeGram:
return "g"
case DoseUnitSizeKilogram:
return "kg"
case DoseUnitSizeEthanol, DoseUnitSizeGBL, DoseUnitSizeBDO:
return "mL"
case DoseUnitSizeMilliliter, DoseUnitSizeAlcohol:
return "u"
default:
return ""
}
}
func (u DoseUnitSize) F() float64 {
return float64(u)
}
type DoseStat struct {
Drug string
TotalDoses int64
TotalAmount float64 // in micrograms
UnitLabel string // See UnitOrLabel(): only set if no unit is known
Unit DoseUnitSize
OriginalUnit DoseUnitSize
}
// ToUnit converts the TotalAmount to a new DoseUnitSize
// TODO: Generify and use in normal doses
func (s *DoseStat) ToUnit(u DoseUnitSize) {
if u == DoseUnitSizeDefault || u == s.Unit {
return
}
if s.Unit == DoseUnitSizeMicrogram {
if s.Unit < u {
s.TotalAmount = s.TotalAmount / u.F()
} else {
s.TotalAmount = s.TotalAmount * u.F()
}
} else {
if s.Unit < u {
s.TotalAmount = s.TotalAmount * s.Unit.F() / u.F()
} else {
s.TotalAmount = s.TotalAmount / s.Unit.F() * u.F()
}
}
s.Unit = u
}
// ToSensibleUnit will convert to a larger weight unit if it's value is larger than 1000.
func (s *DoseStat) ToSensibleUnit() {
for _, u := range []DoseUnitSize{DoseUnitSizeMicrogram, DoseUnitSizeMilligram, DoseUnitSizeGram} {
switch s.Unit {
case u:
if s.TotalAmount >= 1000 {
s.ToUnit(u * 1000)
}
}
}
}
// UnitOrLabel will return Unit as a string, or UnitLabel if it's Unit is not known.
func (s *DoseStat) UnitOrLabel() string {
if s.Unit.String() != "" {
return s.Unit.String()
}
return s.UnitLabel
}
func ParseUnit(d, u string) DoseUnitSize {
unit:
switch u {
case "", "?":
break unit
case "u":
switch d {
case "Alcohol":
return DoseUnitSizeAlcohol
default:
break unit
}
case "mL":
switch d {
case "EtOH", "Ethanol":
return DoseUnitSizeEthanol
case "GHB":
return DoseUnitSizeGHB
case "GBL":
return DoseUnitSizeGBL
case "BDO":
return DoseUnitSizeBDO
default:
return DoseUnitSizeMilliliter
}
case "kg":
return DoseUnitSizeKilogram
case "g":
return DoseUnitSizeGram
case "mg":
return DoseUnitSizeMilligram
default:
return DoseUnitSizeMicrogram
}
return DoseUnitSizeDefault
}
func (s *DoseStat) Format(n1, n2 int) string {
offset := 0
if strings.ContainsAny(s.UnitOrLabel(), "μµ") {
offset = 1
}
f1 := fmt.Sprintf(
"%v",
s.TotalDoses,
)
f1 += strings.Repeat(" ", n1-len(f1))
f2 := strings.TrimRight(
strings.TrimRight(
fmt.Sprintf(
"%.2f",
s.TotalAmount,
), "0",
), ".",
) + s.UnitOrLabel()
// TODO: Make offset dynamic
offset = n2 - len(f2) + offset
if offset < 1 {
offset = 1
}
f2 += strings.Repeat(" ", offset)
return f1 + f2 + s.Drug
}
func main() {
flag.Parse()
options.Parse()
loadEnv()
if options.FilterInvert && options.Filter == "" {
fmt.Printf("-v is set but no -g filter is set? Can't invert filter without a filter to invert!\n")
return
}
// ModeGet, ModeTzChange, ModeTzConvert, ModeStatTop, ModeStatAvg
// We do not filter in ModeRm and ModeAdd for performance reasons
if options.Filter != "" {
if filter, err := regexp.Compile(fmt.Sprintf("(?i)%s", options.Filter)); err != nil {
fmt.Printf("-g is set but failed to compile regex: %s\n", err)
return
} else {
options.FilterRegex = filter
}
}
var err error
var doses []Dose
//var prefs MainPreferences
err = getJsonFromUrl(&doses, options.LoadUrl)
if err != nil {
return // already handled
}
//err = getJsonFromUrl(&prefs, prefsUrl)
//if err != nil {
// return // already handled
//}
switch options.Mode {
case ModeSave, ModeSaveFiltered:
if options.Mode == ModeSaveFiltered {
if options.LoadUrl == options.SaveUrl {
fmt.Printf("`%s` is set but you have not set `-save-url`, refusing to save filtered doses to default url in order to prevent data loss!\n", options.Mode)
os.Exit(64)
return
}
// Special case - we want to allow
options.Show = -1
doses = getDosesOptions(doses, options)
}
if !saveFileWrapper(doses, true) {
os.Exit(73)
}
case ModeGet:
fmt.Printf("%s", getDosesFmt(doses))
case ModeRm:
if len(doses) == 0 {
fmt.Printf("`%s` is set but there are no doses to remove?\n", ModeRm)
return
}
pos, posIndex := lastPosition(doses)
// No doses found, shouldn't be possible but try anyway?
if pos == -1 || posIndex == -1 {
doses = SliceRemoveIndex(doses, len(doses)-1)
} else if len(doses) > posIndex {
doses = SliceRemoveIndex(doses, posIndex)
}
if !saveFileWrapper(doses, false) {
return
}
fmt.Printf("%s", getDosesFmt(doses))
case ModeRmPosition:
if len(doses) == 0 {
fmt.Printf("`%s` is set but there are no doses to remove?\n", ModeRmPosition)
return
}
posIndex := -1
for n, d := range doses {
if d.Position == options.RmPosition {
posIndex = n
}
}
if posIndex == -1 {
fmt.Printf("`%s`: couldn't find dose matching position \"%v\"\n", ModeRmPosition, options.RmPosition)
return
}
doses = SliceRemoveIndex(doses, posIndex)
if !saveFileWrapper(doses, false) {
return
}
fmt.Printf("%s", getDosesFmt(doses))
case ModeAdd:
// Ensure `-drug` is set
if *aDrug == "" {
fmt.Printf("`-drug` is not set!\n")
return
} else {
*aDrug = caseFmt(*aDrug)
}
//
// Get timezone from the most chronologically recent dose; if `-timezone` isn't set
if options.Timezone == "" {
if len(doses) > 0 {
options.Timezone = doses[len(doses)-1].Timezone
} else {
fmt.Printf("`-timezone` is not set and no doses with a timezone were found! You must set a timezone to add doses first\n")
return
}
}
// Get timezone locations as a time.Location now
// Used for timezone in normal timestamp / timezone
loc, err := time.LoadLocation(options.Timezone)
if err != nil {
fmt.Printf("`%s`: failed to load location: %v\n", ModeAdd, err)
return
}
// Used for timezone in created timestamp / timezone
locTZ, err := tzlocal.RuntimeTZ()
if err != nil {
fmt.Printf("`%s`: failed to get system timezone: %v\n", ModeAdd, err)
return
}
locCreated, err := time.LoadLocation(locTZ)
if err != nil {
fmt.Printf("`%s`: failed to load location: %v\n", ModeAdd, err)
return
}
//
// Parse provided `-date` and `-time` flags, using pre-defined valid layouts
t := time.Now().In(loc)
pDate := "00000101" // default to earliest possible time.Time()
pTime := "0000"
switch len(*aDate) {
case 5: // 01-02 → 2006-01-02
pDate = t.Format("2006-") + *aDate
case 4: // 0102 → 20060102
pDate = t.Format("2006") + *aDate
case 2: // 02 → 2006/01/02
pDate = t.Format("2006/01/") + *aDate
case 0: // unset → 2006/01/02 (first in LayoutFormat, so it parses the fastest)
pDate = t.Format("2006/01/02")
default: // determined by user, will try to parse
pDate = *aDate
}
switch len(*aTime) {
case 0: // unset → 1504 (only one matching len == 4, so it parses the fastest)
pTime = t.Format("1504")
default: // determined by user, will try to parse
pTime = *aTime
}
parseLayout := func(p string, l *TimestampLayout) (*time.Time, error) {
for _, f := range l.Formats {
// faster than waiting for time.ParseInLocation to fail
if len(p) != len(f) {
continue
}
if ts, err := time.ParseInLocation(
fmt.Sprintf("%s%s%s", l.Layout.Prefix, f, l.Layout.Suffix),
fmt.Sprintf("%s%s%s", l.Value.Prefix, p, l.Value.Suffix),
loc,
); err == nil {
return &ts, nil
}
}
return nil, errors.New(fmt.Sprintf(
"`%s`: failed to parse \"%s\" using layouts: %s",
ModeAdd, p, strings.Join(strings.Fields(fmt.Sprint(l.Formats)), ", "),
))
}
// Parse `-date` flag, using 00:00 as the suffix
if ts, err := parseLayout(pDate, &TimestampLayout{
[]LayoutFormat{"2006/01/02", "2006-01-02", "01/02/2006", "01-02-2006", "20060102", "01-02", "0102", "02"},
WrapFormat{Suffix: "1504"}, WrapFormat{Suffix: "0000"},
}); err != nil {
fmt.Printf("%v\n", err)
return
} else {
t = *ts
}
// Parse `-time` flag, using the date we found as a prefix
if ts, err := parseLayout(pTime, &TimestampLayout{
[]LayoutFormat{"3:04pm", "15:04", "3:04", "1504"},
WrapFormat{Prefix: "20060102"}, WrapFormat{Prefix: t.Format("20060102")},
}); err != nil {
fmt.Printf("%v\n", err)
return
} else {
t = *ts
}
//
// Parse -a and -d flags for dosage and drug
// Replace mathematical symbols in dosage with their greek variation:
dosage := *aDosage
dosage = strings.ReplaceAll(dosage, "µ", "μ") // U+00B5 → U+03BC
dosage = strings.ReplaceAll(dosage, "∆", "Δ") // U+2206 → U+0394
// Replace dosage ml with mL
if strings.HasSuffix(dosage, "ml") {
dosage = strings.TrimSuffix(dosage, "ml")
dosage += "mL"
}
if *aRoa == "" {
*aRoa = "Oral" // Default RoA. TODO: Proper handling / ask user for default.
} else {
*aRoa = caseFmt(*aRoa)
}
pos, _ := lastPosition(doses)
dose := Dose{
Position: pos + 1,
Created: &TimeData{
Timestamp: time.Now().In(locCreated),
Timezone: locTZ,
},
TimeData: TimeData{
Timestamp: t,
Timezone: options.Timezone,
},
Date: t.Format("2006/01/02"),
Time: t.Format("15:04"),
Dosage: dosage,
Drug: *aDrug,
RoA: *aRoa,
Note: *aNote,
}
doses = append(doses, dose)
options.LastAddedPos = dose.Position
// Re-sort by chronological date and time, to handle adding a dose in the past
sort.Slice(doses, func(i, j int) bool {
return doses[i].Timestamp.Unix() < doses[j].Timestamp.Unix()
})
if !saveFileWrapper(doses, false) {
return
}
fmt.Printf("%s", getDosesFmt(doses))
case ModeTzChange, ModeTzConvert:
if len(doses) == 0 {
fmt.Printf("`%s` is set but there are no doses to modify?\n", options.Mode)
return
}
loc, err := time.LoadLocation(options.Timezone)
if err != nil {
fmt.Printf("`%s`: failed to load location: %v\n", ModeAdd, err)
return
}
dosesFiltered := getDosesOptions(doses, options)
dosePositions := make(map[string]int) // [position]index
for n, d := range doses {
dosePositions[strconv.Itoa(d.Position)] = n
}
for _, d := range dosesFiltered {
switch options.Mode {
case ModeTzChange:
d.Timestamp = time.Date(
d.Timestamp.Year(), d.Timestamp.Month(), d.Timestamp.Day(),
d.Timestamp.Hour(), d.Timestamp.Minute(), d.Timestamp.Second(), d.Timestamp.Nanosecond(),
loc)
d.Timezone = options.Timezone
case ModeTzConvert:
d.Timestamp = d.Timestamp.In(loc)
d.Timezone = options.Timezone
d.Date = d.Timestamp.Format("2006/01/02")
d.Time = d.Timestamp.Format("15:04")
default:
fmt.Printf("`%s`: modifying dose in non-supported mode?? how?\n", options.Mode)
return
}
if n, ok := dosePositions[strconv.Itoa(d.Position)]; ok {
doses[n] = d
}
}
if !saveFileWrapper(doses, false) {
return
}
fmt.Printf("%s", getDosesFmt(doses))
case ModeStatTop, ModeStatAvg:
doses = getDosesOptions(doses, options)
stats := make(map[string]DoseStat)
statTotal := DoseStat{Drug: "Total"}
if options.Mode == ModeStatAvg {
statTotal.Drug = "Average"
}
//
// stat.TotalAmount is in MICROGRAMS right now
// increment total doses and total amount for each drug
for _, d := range doses {
stat := stats[d.Drug]
stat.Drug = d.Drug
stat.TotalDoses += 1
statTotal.TotalDoses += 1
stats[d.Drug] = stat // we still want to save the stat, so we can increment the total doses even if the dosage is not set or fails to parse
units := dosageRegex.FindStringSubmatch(d.Dosage)
if len(units) != 4 {
continue
}
amount, err := strconv.ParseFloat(units[1], 64)
if err != nil {
continue
}
// Get unitSize for current dose
unitLabel := units[3]
unitSize := ParseUnit(stat.Drug, unitLabel)
stat.Unit = unitSize
// Only set `stat.OriginalUnit` if it hasn't been set before
if stat.OriginalUnit == DoseUnitSizeDefault {
stat.OriginalUnit = unitSize
if stat.UnitLabel == "" {
stat.UnitLabel = unitLabel
}
}
// Nothing else to do, skip
if amount == 0 {
stats[d.Drug] = stat
continue
}
// We want to set the unit size of this stat if it isn't default.
// We also want to set total specifically here, in case we have a scenario where no doses have any units to go off of
if unitSize != DoseUnitSizeDefault {
stat.Unit = DoseUnitSizeMicrogram
statTotal.Unit = DoseUnitSizeMicrogram
statTotal.OriginalUnit = DoseUnitSizeMicrogram
// Convert amount to micrograms, set unit, so it is converted back to original later
amount = amount * unitSize.F()
} else if statTotal.UnitLabel == "" {
statTotal.UnitLabel = unitLabel // Add a fallback label if it is a default unit size
}
stat.TotalAmount += amount
statTotal.TotalAmount += amount
stats[d.Drug] = stat
}
//
// go through each stat and convert smaller units to larger ones when appropriate
statsOrdered := make([]DoseStat, 0)
for _, v := range stats {
statsOrdered = append(statsOrdered, v)
}
// Sort by total doses.
// If TotalDoses is the same, sort by TotalAmount.
// If TotalAmount is the same, sort by drug name as alphabetical.
// If the drug name starts with a Unicode character, sort first.
// Always ensures that the Total / Average stat is always at the bottom.
sort.SliceStable(statsOrdered, func(i, j int) bool {
if statsOrdered[i].TotalDoses == statsOrdered[j].TotalDoses {
if statsOrdered[i].TotalAmount*statsOrdered[i].Unit.F() == statsOrdered[j].TotalAmount*statsOrdered[j].Unit.F() {
greekI := unicode.Is(unicode.Greek, []rune(statsOrdered[i].Drug)[0])
greekJ := unicode.Is(unicode.Greek, []rune(statsOrdered[j].Drug)[0])
if greekI && !greekJ {
return true
}
if !greekI && greekJ {
return false
}
return strings.Compare(statsOrdered[i].Drug, statsOrdered[j].Drug) <= 0
}
return statsOrdered[i].TotalAmount*statsOrdered[i].Unit.F() < statsOrdered[j].TotalAmount*statsOrdered[j].Unit.F()
}
return statsOrdered[i].TotalDoses < statsOrdered[j].TotalDoses
})
statsOrdered = append(statsOrdered, statTotal)
// stat.TotalAmount is in MICROGRAMS right now
for k, v := range statsOrdered {
// convert TotalAmount in MICROGRAMS to correct unit
v.ToUnit(v.OriginalUnit)
// convert total amount to average amount
if options.Mode == ModeStatAvg {
v.TotalAmount = v.TotalAmount / float64(v.TotalDoses)
}
// convert from micrograms to larger units if too big
v.ToSensibleUnit()
statsOrdered[k] = v
}
// stat.TotalAmount is **NOT IN MICROGRAMS ANYMORE**
// get the longest len to use for spacing later, format lines
highestLen := len(fmt.Sprintf("%v", statTotal.TotalDoses)) + 1
lines := ""
for _, s := range statsOrdered {
lines += fmt.Sprintf("%s\n", s.Format(highestLen, 9))
}
fmt.Printf("%s", lines)
default:
fmt.Printf("Not a valid `mode`!\n")
}
}
func getJsonFromUrl(v any, path string) error {
response, err := http.Get(path)
if err != nil {
fmt.Printf("failed to read json: %v\n", err)
return err
}
defer response.Body.Close()
b, err := io.ReadAll(response.Body)
if err != nil {
fmt.Printf("failed to read body: %v\n", err)
return err
}
err = json.Unmarshal(b, v)
if err != nil {
fmt.Printf("failed to unmarshal doses: \n%s\n%v\n", b, err)
return err
}
return nil
}
func caseFmt(s string) string {
if s == "" {
return s
}
// Removes greek characters,
// which means strings containing lowercase greek & uppercase latin will be treated as all uppercase.
// This is useful for something like α-PHP,
// where otherwise caser.String(s) would return A-Php, which is not what we want.
// Initially, I implemented this as a function that replaced lowercase greek with upper,
// but it's more efficient to simply remove the greek.
removeGreek := func(s string) string {
sr := []rune(s)
for i, c := range sr {
if unicode.Is(unicode.Greek, c) {
sr = append(sr[0:i], sr[i+1:]...)
}
}
return string(sr)
}
// If it Starts with a lowercase letter, uppercase it.
// TODO: This will not work for something like 3-HO-PCP. Need better solution.
// Simply checking for a number isn't enough, as 4-PrO-DMT wouldn't work.
// A database of drug names or using the user's last casing when unsure would probably be the way to go.
if removeGreek(s[:1]) != removeGreek(strings.ToUpper(s[:1])) {
return caser.String(s)
}
return s
}
func lastPosition(doses []Dose) (int, int) {
pos, posIndex := -1, -1
for n, d := range doses {
if d.Position > pos {
pos = d.Position
posIndex = n
}
}
return pos, posIndex
}
func saveFileWrapper(doses []Dose, printSuccess bool) bool {
ok, u := saveDoseFiles(doses)
if !ok || printSuccess {
fmt.Printf("`%s`: saved files:\n- %s\n", options.Mode, strings.Join(u, "\n- "))
}
if !ok {
fmt.Printf("`%s`: failed to save one or more doses files!\n", options.Mode)
}
return ok
}
func saveDoseFiles(doses []Dose) (r bool, p []string) {
optionsJson := &DisplayOptions{Json: true}
optionsTxt := &DisplayOptions{
DotTime: true,
Reversed: true,
StartAtTop: true,
}
if content, err := getDosesFmtOptions(doses, optionsJson); err == nil {
if ok, u := saveFile(content, options.SaveUrl); ok {
p = append(p, u)
} else {
return
}