-
Notifications
You must be signed in to change notification settings - Fork 10
/
apihandler.go
163 lines (139 loc) · 4.14 KB
/
apihandler.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package brigades
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/MKuranowski/WarsawGTFS/realtime/util"
)
// routeStopPair is a struct, for a (route_id, stop_id) pair
type routeStopPair struct{ Route, Stop string }
// mapTimeBrigade is an alias for a map from a timestamp to a brigade_id
type mapTimeBrigade = map[string]string
// invalidTTableAPIResp represents an invalid response from api.um.warszawa.pl
type invalidTTableAPIResp struct{ text string }
func (e invalidTTableAPIResp) Error() string {
return e.text
}
// ttableAPI is an object for communcating with the timetable api at api.um.warszawa.pl
type ttableAPI struct {
Key string
Client *http.Client
Respones map[routeStopPair]mapTimeBrigade // routeStop → time → brigade
ForwardErrors bool
}
// BuildURL returns the URL to retrieve timetables of a specific route-stop pair
func (api *ttableAPI) BuildURL(rs routeStopPair) string {
queryParams := url.Values{}
// cSpell: disable
queryParams.Set("id", "e923fa0e-d96c-43f9-ae6e-60518c9f3238")
queryParams.Set("apikey", api.Key)
queryParams.Set("busstopId", rs.Stop[:4])
queryParams.Set("busstopNr", rs.Stop[4:6])
queryParams.Set("line", rs.Route)
requestURL := url.URL{
Scheme: "https",
Host: "api.um.warszawa.pl",
Path: "/api/action/dbtimetable_get/",
RawQuery: queryParams.Encode(),
}
// cSpell: enable
return requestURL.String()
}
// Get returns the time→brigade map for a particular route-stop pair
func (api *ttableAPI) Get(rs routeStopPair) (mapTimeBrigade, bool, error) {
// Check if this pair was defined earlier
ttb, hasCached := api.Respones[rs]
if hasCached {
return ttb, true, nil
}
// Prepare request
logPrintf("Making call for R %s | S %s", true, rs.Route, rs.Stop)
requestURL := api.BuildURL(rs)
resp, err := api.Client.Get(requestURL)
if err != nil {
return nil, false, err
}
defer resp.Body.Close()
// Check response code
if resp.StatusCode <= 199 || resp.StatusCode >= 300 {
logPrintf("Timetable API for %+v responded with status code: %d", false, rs, resp.StatusCode)
if api.ForwardErrors {
err = util.RequestError{
URL: strings.ReplaceAll(requestURL, api.Key, "xxxxxx"),
Status: resp.Status,
StatusCode: resp.StatusCode,
}
}
return nil, false, err
}
// Read the response
rawData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, false, err
}
// Parse the response
ttb, err = parseBrigadesResponse(rawData, rs, api.ForwardErrors)
if err != nil {
api.Respones[rs] = make(mapTimeBrigade)
return nil, false, err
}
api.Respones[rs] = ttb
return ttb, false, nil
}
// parseBrigadesResponse parses UM Warszawa API response when requesting a timetable for specific
// route_id, stop_id pair
func parseBrigadesResponse(rawData []byte, rs routeStopPair, forwardErrors bool) (mtb mapTimeBrigade, err error) {
mtb = make(mapTimeBrigade)
// Unmarshall JSON
var decodedData struct {
Result []struct {
Values []struct {
Key string
Value string
}
}
}
err = json.Unmarshal(rawData, &decodedData)
if err != nil {
logPrintf("Failed to parse API response: %s", false, string(rawData))
return
}
// Check if there actually is a timetable
if len(decodedData.Result) == 0 {
errInfo := fmt.Sprintf("Timetable API for %+v returned an empty departures list (%q)", rs, string(rawData))
logPrint(errInfo, false)
if forwardErrors {
err = invalidTTableAPIResp{errInfo}
return
}
}
// Extract time→brigade mapping
for _, result := range decodedData.Result {
var brigade string
var time string
// try to find matching fields
for _, value := range result.Values {
if value.Key == "brygada" {
brigade = value.Value
} else if value.Key == "czas" {
time = value.Value
}
}
// check if "brygada" and "czas" fields exist
if (brigade == "" || time == "") && forwardErrors {
errInfo := fmt.Sprintf(
"Timetable API for %+v returned a timetable with missing times or brigades (%q)",
rs, string(rawData))
logPrint(errInfo, false)
if forwardErrors {
err = invalidTTableAPIResp{errInfo}
return
}
}
mtb[time] = brigade
}
return
}