diff --git a/backend/internal/ktmtrainbot/backgroundbookingjob.go b/backend/internal/ktmtrainbot/backgroundbookingjob.go index 01518e5..1f1a372 100644 --- a/backend/internal/ktmtrainbot/backgroundbookingjob.go +++ b/backend/internal/ktmtrainbot/backgroundbookingjob.go @@ -202,6 +202,12 @@ func (env *Env) startBooking(job *Booking, username string, password string, cre for i := 0; i < threadCount; i++ { time.Sleep(time.Millisecond * 100) go func() { + defer func() { + if r := recover(); r != nil { + log.Println("Recovering from getBookingSlot panic...") + } + }() + currPage := getBookingSlots(browser, onwardDate, reverse) log.Println("Booking page loaded.") @@ -358,6 +364,14 @@ func selectBookingSlot(ctx context.Context, page *rod.Page, timeCode string) *ro completed := false for !completed { page.MustWaitLoad() + + // Checks for context before proceeding + select { + case <-ctx.Done(): + return page + default: + } + departTripsTable := page.MustElement(".depart-trips") departRows := departTripsTable.MustElements("tr") var rowElement *rod.Element @@ -368,6 +382,12 @@ func selectBookingSlot(ctx context.Context, page *rod.Page, timeCode string) *ro } } + if rowElement == nil { + log.Println("No timeslot found. Waiting till context cancelled.") + <-ctx.Done() + return nil + } + if !reportedTicketDetails { ticketDetails := rowElement.MustText() log.Printf("Ticket Details: %s", ticketDetails)