smon/helper.go

77 lines
1.9 KiB
Go
Raw Permalink Normal View History

2024-06-27 13:14:37 +02:00
package main
import (
2024-06-27 13:45:01 +02:00
// External
werr "git.gibonuddevalla.se/go/wrappederror"
2024-06-27 13:14:37 +02:00
// Standard
2024-06-29 11:57:45 +02:00
"regexp"
2024-06-29 20:50:57 +02:00
"strconv"
"time"
2024-06-27 13:14:37 +02:00
)
2024-06-29 11:57:45 +02:00
var rxpTimezone *regexp.Regexp
func init() {
rxpTimezone = regexp.MustCompile(`(\d\d)(\d\d)$`)
}
2024-06-29 20:50:57 +02:00
func stringToTime(strTime string) (t time.Time, err error) { // {{{
2024-06-29 11:57:45 +02:00
// `date` command %z gives timezone like +0200 instead of +02:00.
// This can easily be fixed here, not requiring all scripts to be fixed.
2024-06-27 13:14:37 +02:00
t, err = time.Parse(time.RFC3339, strTime)
2024-06-29 11:57:45 +02:00
if err != nil {
// Check for aforementioned problem.
parseError, ok := err.(*time.ParseError)
if ok && parseError != nil && parseError.LayoutElem == "Z07:00" {
// Insert the missing colon according to RFC 3339 and try again.
patchedTimeStr := rxpTimezone.ReplaceAllString(strTime, `$1:$2`)
t, err = time.Parse(time.RFC3339, patchedTimeStr)
}
// Couldn't convert to time.ParseError or the retry
// failed. Either way, an error occurs.
if err != nil {
err = werr.Wrap(err).WithData(strTime)
return
}
}
2024-06-27 13:14:37 +02:00
return
2024-06-29 20:50:57 +02:00
} // }}}
func parseHTMLDateTime(str string, dflt time.Time) (t time.Time, err error) { // {{{
2024-06-27 13:45:01 +02:00
// Browser sending 2024-06-27T10:43 (16 characters) when seconds is 00.
if len(str) == 16 {
str += ":00"
}
if str == "" {
return dflt, nil
} else {
t, err = time.ParseInLocation("2006-01-02T15:04:05", str, smonConfig.Timezone())
if err != nil {
err = werr.Wrap(err)
}
}
return
2024-06-29 20:50:57 +02:00
} // }}}
func applyTimeOffset(t time.Time, duration time.Duration, amountStr string) time.Time { // {{{
amount, err := strconv.Atoi(amountStr)
if err != nil {
return t
}
return t.Add(duration * time.Duration(amount))
} // }}}
2024-07-04 13:29:39 +02:00
func presetTimeInterval(duration time.Duration, presetStr string, timeFrom, timeTo *time.Time) () {// {{{
2024-06-29 20:50:57 +02:00
if presetStr == "" {
return
}
now := time.Now()
presetTime, _ := strconv.Atoi(presetStr)
(*timeFrom) = now.Add(duration * -1 * time.Duration(presetTime))
(*timeTo) = now
return
2024-07-04 13:29:39 +02:00
}// }}}