dashboard of nationalrail train times
at main 2.4 kB view raw
1package main 2 3import ( 4 "regexp" 5 "strconv" 6 "strings" 7) 8 9type Departure struct { 10 ScheduledTime string `json:"scheduled_time"` 11 ExpectedTime string `json:"expected_time,omitempty"` 12 Status string `json:"status"` // "On time", "Expected", "Delayed", etc. 13 Destination string `json:"destination"` 14 Via string `json:"via,omitempty"` 15 Platform string `json:"platform"` 16 Duration string `json:"duration"` 17 Stops int `json:"stops"` 18 Operator string `json:"operator"` 19 DelayReason string `json:"delay_reason,omitempty"` 20 ServiceID string `json:"service_id,omitempty"` 21} 22 23// ParseAriaLabel extracts departure information from the aria-label attribute 24func ParseAriaLabel(ariaLabel string) (*Departure, error) { 25 departure := &Departure{} 26 27 // Handle delayed trains first 28 delayPattern := regexp.MustCompile(`^(.*?), (\d{2}:\d{2}), Expected (\d{2}:\d{2}), service for ([^,]+)(?:, via ([^,]+))?, calling at [^,]+, from platform (\d+), duration (\d+) minutes, (\d+) stops, operated by (.+)$`) 29 if matches := delayPattern.FindStringSubmatch(ariaLabel); matches != nil { 30 departure.DelayReason = matches[1] 31 departure.ScheduledTime = matches[2] 32 departure.ExpectedTime = matches[3] 33 departure.Status = "Expected " + matches[3] 34 departure.Destination = strings.TrimSpace(matches[4]) 35 departure.Via = strings.TrimSpace(matches[5]) 36 departure.Platform = matches[6] 37 departure.Duration = matches[7] + " minutes" 38 stops, _ := strconv.Atoi(matches[8]) 39 departure.Stops = stops 40 departure.Operator = strings.TrimSpace(matches[9]) 41 return departure, nil 42 } 43 44 // Handle normal trains 45 normalPattern := regexp.MustCompile(`^(\d{2}:\d{2}), (On time|Cancelled), service for ([^,]+)(?:, via ([^,]+))?, calling at [^,]+, from platform (\d+), duration (\d+) minutes, (\d+) stops, operated by (.+)$`) 46 if matches := normalPattern.FindStringSubmatch(ariaLabel); matches != nil { 47 departure.ScheduledTime = matches[1] 48 departure.Status = matches[2] 49 departure.Destination = strings.TrimSpace(matches[3]) 50 departure.Via = strings.TrimSpace(matches[4]) 51 departure.Platform = matches[5] 52 departure.Duration = matches[6] + " minutes" 53 stops, _ := strconv.Atoi(matches[7]) 54 departure.Stops = stops 55 departure.Operator = strings.TrimSpace(matches[8]) 56 return departure, nil 57 } 58 59 return nil, nil // Unable to parse 60}