From d4f2624635c6c76f31cdd97202ae6a879de2e6bd Mon Sep 17 00:00:00 2001 From: Arti Zirk Date: Fri, 11 Aug 2023 00:57:24 +0300 Subject: [PATCH] Fetch tokens after every longpoll close event --- godoor.go | 51 ++++++++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/godoor.go b/godoor.go index a77b533..4c5432b 100644 --- a/godoor.go +++ b/godoor.go @@ -195,27 +195,6 @@ func setup() { http.DefaultClient.Timeout = 120 * time.Second - go func() { - for { - err := waitEvents() - if err != nil { - apiFailuresCount.WithLabelValues("longpoll", config.api.longpoll).Inc() - log.Printf("LongPoll for events failed: %v", err) - log.Println("Will try to LongPoll again in 120 seconds") - time.Sleep(120 * time.Second) - go func() { - err := reloadTokens() - if err != nil { - apiFailuresCount.WithLabelValues("allowed", config.api.allowed).Inc() - } - }() - } - time.Sleep(1 * time.Second) - } - }() - - log.Println("Initialized longpoll event loop") - for { log.Println("Start initial token population") err := reloadTokens() @@ -230,6 +209,27 @@ func setup() { log.Println("Initial token population success") + go func() { + for { + err := waitEvents() + if err != nil { + apiFailuresCount.WithLabelValues("longpoll", config.api.longpoll).Inc() + log.Printf("LongPoll for events failed: %v", err) + log.Println("Will try to LongPoll again soon") + } + time.Sleep(1 * time.Second) + go func() { + err := reloadTokens() + if err != nil { + log.Printf("ReloadTokens failed: %q", err) + apiFailuresCount.WithLabelValues("allowed", config.api.allowed).Inc() + } + }() + } + }() + + log.Println("Initialized longpoll event loop") + go cardRunner(wiegand) log.Println("Setup completed") @@ -290,7 +290,7 @@ func cardRunner(w Wiegand) { continue } - printCardId(card) + //printCardId(card) hashedHex := hash.HashCardUid(card) log.Println(hashedHex) @@ -464,11 +464,11 @@ func handleKeepDoorOpenCloseCleanup() { } func sendSwipeEvent(cardUidHash string, success bool) error { - swipeEvent := map[string]string{ + swipeEvent := map[string]any{ "uid_hash": cardUidHash, "door": config.door, - "timestamp": time.Now().Format(time.DateTime), - "success": fmt.Sprint(success), + "timestamp": time.Now().Format(time.RFC3339), + "success": success, } data, err := json.Marshal(swipeEvent) @@ -481,6 +481,7 @@ func sendSwipeEvent(cardUidHash string, success bool) error { return err } req.Header.Add("KEY", config.api.key) + req.Header.Add("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return err