package main import ( "context" "fmt" "log/slog" "time" "git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/store" ) const ( // remindWithin is how close to its end a listing gets a reminder. It // matches the web UI, which marks a listing in this range as running out. remindWithin = 5 * 24 * time.Hour // remindAgain is how long a reminder for one listing keeps quiet. Renewing // is manual on purpose (an abandoned listing should lapse), so the node // reminds, but not on every check. remindAgain = 24 * time.Hour // remindCheckEvery is how often the node looks; remindFirst waits until the // start-up lines (the sign-in link) have been printed and read. remindCheckEvery = time.Hour remindFirst = 20 * time.Second ) // reminder tells the owner on the terminal which listings are about to lapse. type reminder struct { list func(context.Context) ([]*listing.Listing, error) log *slog.Logger httpAddr string now func() time.Time said map[string]time.Time // listing id -> when it was last mentioned } // check says one line for each listing that ends within remindWithin and has // not been mentioned lately. It returns how many it mentioned. func (r *reminder) check(ctx context.Context) int { ls, err := r.list(ctx) if err != nil { if ctx.Err() == nil { r.log.Debug("could not check for expiring listings", "err", err) } return 0 } now := r.now() n := 0 for _, l := range ls { end := time.Unix(l.ExpiresAt, 0) left := end.Sub(now) if left > remindWithin || left <= 0 { continue } if t, ok := r.said[l.ID]; ok && now.Sub(t) < remindAgain { continue } r.said[l.ID] = now n++ r.log.Warn("a listing runs out soon: renew it, or it disappears", "listing", l.Title, "ends", end.Local().Format("2006-01-02 15:04"), "left", leftText(left), "renew", uiURL(r.httpAddr, "/mine")) } return n } // leftText is the time left, rounded the way a person reads it. func leftText(d time.Duration) string { switch { case d >= 36*time.Hour: return fmt.Sprintf("%d days", int((d+12*time.Hour)/(24*time.Hour))) case d >= time.Hour: return fmt.Sprintf("%d hours", int(d/time.Hour)) default: return "less than an hour" } } // remindExpiring watches the owner's listings until ctx ends. func remindExpiring(ctx context.Context, log *slog.Logger, st *store.Store, author, httpAddr string) { r := &reminder{ list: func(ctx context.Context) ([]*listing.Listing, error) { return st.ByAuthor(ctx, author) }, log: log, httpAddr: httpAddr, now: time.Now, said: map[string]time.Time{}, } timer := time.NewTimer(remindFirst) defer timer.Stop() for { select { case <-ctx.Done(): return case <-timer.C: } r.check(ctx) timer.Reset(remindCheckEvery) } }