-
Notifications
You must be signed in to change notification settings - Fork 1
/
status.go
125 lines (92 loc) · 2.6 KB
/
status.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"io"
"io/ioutil"
"log"
"net/http"
"regexp"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/bradfitz/slice"
"github.com/tidwall/gjson"
)
const RouteStatusURL = `https://www.scotrail.co.uk/ajax/interactive_map/status`
// ServiceStatus type
type ServiceStatus struct {
ID string `json:"id"`
Time time.Time `json:"time"`
Due time.Time `json:"due"`
Origin string `json:"origin"`
Destination string `json:"destination"`
Status string `json:"status"`
}
// Issue type
type Issue struct {
Severity string `json:"severity"`
Details []ServiceStatus `json:"details"`
}
// Route type
type Route struct {
RouteID int `json:"route_id"`
Region string `json:"region"`
Type string `json:"type"`
Map string `json:"map"`
Status string `json:"status"`
Stations []string `json:"stations"`
Issue Issue `json:"issue"`
}
func getRouteStatuses() (routes []Route) {
r, err := http.Get(RouteStatusURL)
if err != nil {
return
}
defer r.Body.Close()
routes = parseRoutes(r.Body)
slice.Sort(routes[:], func(i, j int) bool {
return routes[i].RouteID < routes[j].RouteID
})
return
}
func parseRoutes(r io.Reader) (routes []Route) {
b, _ := ioutil.ReadAll(r)
data := gjson.Get(string(b), "routes").Map()
for k, v := range data {
r, ok := Routes[k]
if !ok {
log.Fatalf("Route: %s was not found in routes.json", k)
}
r.Map, r.Status = v.Get("map").String(), v.Get("status").String()
if v.Get("html").Exists() {
parseRouteDetails(v.Get("html").String(), &r)
}
routes = append(routes, r)
}
return
}
func parseRouteDetails(html string, r *Route) {
doc, _ := goquery.NewDocumentFromReader(strings.NewReader(html))
issue := new(Issue)
re, err := regexp.Compile(`^([0-9]{2}):([0-9]{2})\s([a-zA-Z\s]{1,})\sto\s([a-zA-Z\s]{1,})\sdue\s([0-9]{2}):([0-9]{2})\s(will be|has been|was)\s(cancelled|reinstated|started)`)
if err != nil {
log.Fatalln(err.Error())
}
doc.Find("span.issues").Each(func(i int, s *goquery.Selection) {
issue.Severity = s.Text()
doc.Find("ul.services").Children().Each(func(i int, s *goquery.Selection) {
id := s.Children().First().AttrOr("href", "#")
s.Find("div" + id).Children().Each(func(i int, s *goquery.Selection) {
matches := re.FindAllStringSubmatch(s.Text(), -1)
if len(matches) == 0 {
return
}
ss := ServiceStatus{
ID: id[1:], Origin: matches[0][3], Destination: matches[0][4],
Status: matches[0][7] + " " + matches[0][8],
}
issue.Details = append(issue.Details, ss)
})
})
})
r.Issue = *issue
}