From 2492e84b559bfaaae890bdd3d5be0b6cf3664909 Mon Sep 17 00:00:00 2001 From: Orangerot Date: Fri, 27 Dec 2024 14:55:04 +0100 Subject: [PATCH] feat: only fetch big list of all events every ten minutes instead of on every request --- main.go | 42 +++++++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index 08b9050..ca87e05 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "strings" + "sync" "time" ) @@ -16,7 +17,11 @@ const ( API_URL = "https://api.events.ccc.de/congress/2024" ) -var ROOMS []Room +var ( + SCHEDULE_MUTEX sync.Mutex + SCHEDULE []Event + ROOMS []Room +) type Token struct { Token string `json:"token"` @@ -91,6 +96,24 @@ func scrape_hub() ([]Event, error) { return events, nil } +func cron_fetch() { + for { + fmt.Println("starting cron...") + schedule, err := scrape_hub() + if err != nil { + fmt.Println("Cron failed; retrying in a minute") + time.Sleep(1 * time.Minute) + continue + } + + SCHEDULE_MUTEX.Lock() + SCHEDULE = schedule + SCHEDULE_MUTEX.Unlock() + + time.Sleep(10 * time.Minute) + } +} + func get_rooms() ([]Room, error) { println("get rooms") resp, err := http.Get(fmt.Sprintf("%s/rooms", API_URL)) @@ -215,14 +238,12 @@ func get_schedule(w http.ResponseWriter, r *http.Request) { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } - schedule, err := scrape_hub() - if err != nil { - http.Error(w, "Unauthorized", http.StatusUnauthorized) - return - } + + SCHEDULE_MUTEX.Lock() + defer SCHEDULE_MUTEX.Unlock() var my_events []Event - for _, event := range schedule { + for _, event := range SCHEDULE { for _, id := range ids { if event.ID == id { my_events = append(my_events, event) @@ -263,6 +284,13 @@ func main() { return } ROOMS = rooms + schedule, err := scrape_hub() + if err != nil { + return + } + SCHEDULE = schedule + + go cron_fetch() println("Stating Server") // Start a web server to serve the iCal file