remind: Add support for reminders the next day and mixed duration formats

This commit is contained in:
Hamcha 2018-11-02 14:17:38 +01:00
parent 11a0947e7b
commit e1145ecb44
Signed by: hamcha
GPG key ID: A40413D21021EAEE

View file

@ -147,16 +147,45 @@ func isSscanfValid(n int, err error) bool {
return err == nil
}
func parseDuration(date string) (time.Time, error) {
func scanMixedDelay(str string) (bool, time.Time, error) {
remaining := str
now := time.Now()
num := 0
sep := ' '
for len(remaining) > 1 {
scanned, err := fmt.Sscanf(remaining, "%d%c", &num, &sep)
if err != nil {
return false, now, err
}
dur := time.Duration(num)
switch unicode.ToLower(sep) {
case 's':
dur *= time.Second
case 'm':
dur *= time.Minute
case 'h':
dur *= time.Hour
case 'd':
dur *= time.Hour * 24
default:
return true, now, fmt.Errorf("La durata ha una unità che non conosco, usa una di queste: s (secondi) m (minuti) h (ore) d (giorni)")
}
now = now.Add(dur)
remaining = remaining[scanned:]
}
return true, now, nil
}
func parseDuration(date string) (time.Time, error) {
now := time.Now()
hour := now.Hour()
min := now.Minute()
sec := now.Second()
day := now.Day()
month := now.Month()
year := now.Year()
dayunspecified := false
isDurationFmt, duration, err := scanMixedDelay(date)
switch {
case isSscanfValid(fmt.Sscanf(date, "%d/%d/%d-%d:%d:%d", &day, &month, &year, &hour, &min, &sec)):
case isSscanfValid(fmt.Sscanf(date, "%d/%d/%d-%d:%d", &day, &month, &year, &hour, &min)):
@ -169,33 +198,27 @@ func parseDuration(date string) (time.Time, error) {
day = now.Day()
month = now.Month()
year = now.Year()
dayunspecified = true
case isSscanfValid(fmt.Sscanf(date, "%d:%d", &hour, &min)):
day = now.Day()
month = now.Month()
year = now.Year()
sec = 0
case isSscanfValid(fmt.Sscanf(date, "%d%c", &num, &sep)):
dur := time.Duration(num)
switch unicode.ToLower(sep) {
case 's':
dur *= time.Second
case 'm':
dur *= time.Minute
case 'h':
dur *= time.Hour
case 'd':
dur *= time.Hour * 24
default:
return now, fmt.Errorf("La durata ha una unità che non conosco, usa una di queste: s (secondi) m (minuti) h (ore) d (giorni)")
}
return now.Add(dur), nil
dayunspecified = true
case isDurationFmt:
return duration, err
default:
return now, fmt.Errorf("Non capisco quando dovrei ricordartelo!")
}
loc, _ := time.LoadLocation("Local")
targetDate := time.Date(year, month, day, hour, min, sec, 0, loc)
if targetDate.Before(now) {
return now, fmt.Errorf("Non posso ricordarti cose nel passato!")
// If day was not specified assume tomorrow
if dayunspecified {
targetDate = targetDate.Add(time.Hour * 24)
} else {
return now, fmt.Errorf("Non posso ricordarti cose nel passato!")
}
}
if targetDate.After(now.Add(ReminderMaxDuration)) {
return now, fmt.Errorf("Non credo riuscirei a ricordarmi qualcosa per così tanto")