Mercurial > code > home > repos > gcalendarwatch
diff calsync/notificationrouter/notificationrouter.go @ 61:8aee4f5c4bdd
receive notifications and route them to calendar sync functions
author | drewp@bigasterisk.com |
---|---|
date | Fri, 06 Sep 2024 16:43:14 -0700 |
parents | |
children | 629d9ad289fe |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/calsync/notificationrouter/notificationrouter.go Fri Sep 06 16:43:14 2024 -0700 @@ -0,0 +1,47 @@ +package notificationrouter + +// Holds the map of (random) watchIds and the sync functions for the affected calendars. + +import ( + "log" + "net/http" + "time" + + "github.com/dchest/uniuri" +) + +type SyncFunc func() + +type NotificationRouter struct { + handlers map[string]SyncFunc +} + +func New() *NotificationRouter { + return &NotificationRouter{ + handlers: make(map[string]SyncFunc), + } +} + +func (nr *NotificationRouter) AddHandler(watchId string, handler SyncFunc, lifetime time.Duration) { + nr.handlers[watchId] = handler + go func() { + time.Sleep(lifetime) + delete(nr.handlers, watchId) + }() +} + +func (nr *NotificationRouter) NotificationHandler(w http.ResponseWriter, r *http.Request) { + watchId := r.Header.Get("X-Goog-Channel-ID") + if nr.handlers[watchId] == nil { + log.Println("incoming notification for unknown watch id", watchId, "(ignoring)") + } else { + // todo: The first notification on a given watchId is the confirmation, + // and the sync func is probably (surely?) not needed. + log.Println("incoming notification for known watch id", watchId) + nr.handlers[watchId]() + } +} + +func NewWatchId() string { + return uniuri.New() + "_" + time.Now().Format("15_04_05") +}