-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstationdata.go
388 lines (335 loc) · 14.2 KB
/
stationdata.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package dbapi
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/google/go-querystring/query"
)
const stadaAPIPath = "/stada/v2"
// MailingAddress holds the postal address of the station.
type MailingAddress struct {
City string `json:"city,omitempty"`
Zipcode string `json:"zipcode,omitempty"`
Street string `json:"street,omitempty"`
HouseNumber string `json:"houseNumber,omitempty"`
}
// GeographicCoordinates holds the type of the coordinate and the latitude and longitude of the station.
type GeographicCoordinates struct {
Type string `json:"type,omitempty"`
Coordinates []float64 `json:"coordinates,omitempty"`
}
// EvaNumbers hold the eva (unique train station number), an identifier if this is the main one in case
// a station has multiple eva numbers and the coordinates of the station.
type EvaNumbers struct {
Number int `json:"number,omitempty"`
IsMain bool `json:"isMain,omitempty"`
GeographicCoordinates GeographicCoordinates `json:"geographicCoordinates,omitempty"`
}
// Ril100Identifiers hold the ril (guideline, alphanumeric), an identifier if this is the main one in case
// a station has multiple eva numbers and the coordinates of the station.
type Ril100Identifiers struct {
RilIdentifier string `json:"rilIdentifier,omitempty"`
IsMain bool `json:"isMain,omitempty"`
HasSteamPermission bool `json:"hasSteamPermission,omitempty"`
GeographicCoordinates GeographicCoordinates `json:"geographicCoordinates,omitempty"`
}
// TimetableOffice holds information about the office that is responsible for the timetable at this station.
type TimetableOffice struct {
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
}
// StationManagement holds information about the office that manages this station.
type StationManagement struct {
Name string `json:"name,omitempty"`
Number int `json:"number,omitempty"`
}
// OpeningTimes holds the opening and closing time.
type OpeningTimes struct {
FromTime string `json:"fromTime,omitempty"`
ToTime string `json:"toTime,omitempty"`
}
// LocalServiceStaff holds times when local staff is available.
type LocalServiceStaff struct {
Availability Availability `json:"availability,omitempty"`
}
// DBinformation holds opening times of the DB Information center at the station.
type DBinformation struct {
Availability Availability `json:"availability,omitempty"`
}
// Availability holds the opening times for entities on various days.
type Availability struct {
Monday OpeningTimes `json:"monday,omitempty"`
Tuesday OpeningTimes `json:"tuesday,omitempty"`
Wednesday OpeningTimes `json:"wednesday,omitempty"`
Thursday OpeningTimes `json:"thursday,omitempty"`
Friday OpeningTimes `json:"friday,omitempty"`
Saturday OpeningTimes `json:"saturday,omitempty"`
Sunday OpeningTimes `json:"sunday,omitempty"`
Holiday OpeningTimes `json:"holiday,omitempty"`
}
// Regionalbereich of the station.
// See: https://de.wikipedia.org/wiki/DB_Netz#Netzzugang
type Regionalbereich struct {
Name string `json:"name,omitempty"`
ShortName string `json:"shortName,omitempty"`
Number int `json:"number,omitempty"`
}
// SZentrale holds information about the 3S-Zentrale that is responsible for service, security and cleanliness for
// a station.
// See: https://www.bahnhof.de/bahnhof-de/ueberuns/3-s-konzept-519192
type SZentrale struct {
Address struct {
City string `json:"city,omitempty"`
Zipcode string `json:"zipcode,omitempty"`
Street string `json:"street,omitempty"`
} `json:"address,omitempty"`
PublicFaxNumber string `json:"public_fax_number,omitempty"`
MobilePhoneNumber string `json:"mobile_phone_number,omitempty"`
InternalPhoneNumber string `json:"internal_phone_number,omitempty"`
InternalFaxNumber string `json:"internal_fax_number,omitempty"`
Email string `json:"email,omitempty"`
Number int `json:"number,omitempty"`
PublicPhoneNumber string `json:"public_phone_number,omitempty"`
Name string `json:"name,omitempty"`
}
// Aufgabentraeger holds information about the entity that is responsible for local trains.
// See: https://www.dbregio.de/db_regio/view/wir/nahverkehr-deutschland.shtml
type Aufgabentraeger struct {
Shortname string `json:"shortname,omitempty"`
Name string `json:"name,omitempty"`
}
// Station is a struct containing all fields that the StationData API might return.
type Station struct {
Number int `json:"number,omitempty"`
Name string `json:"name,omitempty"`
MailingAddress MailingAddress `json:"mailingAddress,omitempty"`
Category int `json:"category,omitempty"`
PriceCategory int `json:"priceCategory,omitempty"`
FederalState string `json:"federalState,omitempty"`
HasParking bool `json:"hasParking,omitempty"`
HasBicycleParking bool `json:"hasBicycleParking,omitempty"`
HasLocalPublicTransport bool `json:"hasLocalPublicTransport,omitempty"`
HasPublicFacilities bool `json:"hasPublicFacilities,omitempty"`
HasLockerSystem bool `json:"hasLockerSystem,omitempty"`
HasTaxiRank bool `json:"hasTaxiRank,omitempty"`
HasTravelNecessities bool `json:"hasTravelNecessities,omitempty"`
HasSteplessAccess string `json:"hasSteplessAccess,omitempty"`
HasMobilityService string `json:"hasMobilityService,omitempty"`
HasWiFi bool `json:"hasWiFi,omitempty"`
HasTravelCenter bool `json:"hasTravelCenter,omitempty"`
HasRailwayMission bool `json:"hasRailwayMission,omitempty"`
HasDBLounge bool `json:"hasDBLounge,omitempty"`
HasLostAndFound bool `json:"hasLostAndFound,omitempty"`
HasCarRental bool `json:"hasCarRental,omitempty"`
EvaNumbers []EvaNumbers `json:"evaNumbers,omitempty"`
Ril100Identifiers []Ril100Identifiers `json:"ril100Identifiers,omitempty"`
TimetableOffice TimetableOffice `json:"timetableOffice,omitempty"`
StationManagement StationManagement `json:"stationManagement,omitempty"`
LocalServiceStaff LocalServiceStaff `json:"localServiceStaff,omitempty"`
DBinformation DBinformation `json:"DBinformation,omitempty"`
Regionalbereich Regionalbereich `json:"regionalbereich,omitempty"`
SZentrale SZentrale `json:"szentrale,omitempty"`
Aufgabentraeger Aufgabentraeger `json:"aufgabentraeger,omitempty"`
}
// StationDataStationResponse holds meta information about the response and the actual station set.
type StationDataStationResponse struct {
Offset int `json:"offset,omitempty"`
Total int `json:"total,omitempty"`
Limit int `json:"limit,omitempty"`
Result []Station `json:"result,omitempty"`
}
// StationDataStationRequest is used by ByFilter to query the station API. If it's not changed,
// all stations are queried.
type StationDataStationRequest struct {
Offset int `url:"offset,omitempty"`
Limit int `url:"limit,omitempty"`
Searchstring string `url:"searchstring,omitempty"`
Category string `url:"category,omitempty"`
Federalstate string `url:"federalstate,omitempty"`
Eva int `url:"eva,omitempty"`
Ril string `url:"ril,omitempty"`
Logicaloperator string `url:"logicaloperator,omitempty"`
}
// StationDataStationRequest is used by ByFilter to query the szentralen API.
type StationDataSZentralenRequest struct {
Offset int `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
}
// StationDataStationResponse holds meta information about the response and the actual station set.
type StationDataSZentralenResponse struct {
Offset int `json:"offset,omitempty"`
Total int `json:"total,omitempty"`
Limit int `json:"limit,omitempty"`
Result []SZentrale `json:"result,omitempty"`
}
// StationDataRateErrorDetailsResponse contains information about the rate limit.
type StationDataRateErrorDetailsResponse struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
Description string `json:"description,omitempty"`
}
// StationDataRateErrorResponse holds a field containing information about the rate limit. Occurs when the
// API was called too often.
type StationDataRateErrorResponse struct {
Err StationDataRateErrorDetailsResponse `json:"error,omitempty"`
}
// StationDataErrorResponse holds error information returned by the DB API
type StationDataErrorResponse struct {
ErrNo int `json:"errNo,omitempty"`
ErrMsg string `json:"errMsg,omitempty"`
}
// StationDataAPI is a struct holding internal information about this API. Its methods can be used
// to query the API.
type StationDataAPI struct {
client *Client
rateThrottleTicker *time.Ticker
firstRequestProcessed bool
}
func (e *StationDataRateErrorResponse) Error() string {
return fmt.Sprintf("Error %d: %s - %s", e.Err.Code, e.Err.Message, e.Err.Description)
}
func (e *StationDataErrorResponse) Error() string {
return fmt.Sprintf("Error %d: %s", e.ErrNo, e.ErrMsg)
}
// StationByID returns station information for the given id or an error if the
// id is invalid, rate limiting or some other error occurred.
func (s *StationDataAPI) StationByID(id int) (*StationDataStationResponse, error) {
url := fmt.Sprintf("%s%s/stations/%d", APIURL, stadaAPIPath, id)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
resp, err := s.sendRequest(req)
if err != nil {
return nil, err
}
sdr := &StationDataStationResponse{}
err = s.processResponse(resp, sdr)
return sdr, err
}
// StationByFilter returns a list of station information by the given filter or an error if the
// id is invalid, rate limiting or some other error occurred. If the StationDataStationRequest is
// not set, all stations are returned (max 10.000) - same as All().
func (s *StationDataAPI) StationByFilter(stationRequest StationDataStationRequest) (*StationDataStationResponse, error) {
q, err := query.Values(stationRequest)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s%s/stations?%s", APIURL, stadaAPIPath, q.Encode())
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
resp, err := s.sendRequest(req)
if err != nil {
return nil, err
}
sdr := &StationDataStationResponse{}
err = s.processResponse(resp, sdr)
return sdr, err
}
// StationAll returns station information for all available stations. Same as calling
// StationByFilter(StationDataStationRequest{}).
func (s *StationDataAPI) StationAll() (*StationDataStationResponse, error) {
return s.StationByFilter(StationDataStationRequest{})
}
// SZentralenByID returns station information for the given id or an error if the
// id is invalid, rate limiting or some other error occurred.
func (s *StationDataAPI) SZentralenByID(id int) (*StationDataSZentralenResponse, error) {
url := fmt.Sprintf("%s%s/szentralen/%d", APIURL, stadaAPIPath, id)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
resp, err := s.sendRequest(req)
if err != nil {
return nil, err
}
sdr := &StationDataSZentralenResponse{}
err = s.processResponse(resp, sdr)
return sdr, err
}
// SZentralenByFilter returns a list of szentralen information by the given filter or an error if the
// id is invalid, rate limiting or some other error occurred. If the StationDataSZentralenRequest is
// not set, all szentralen are returned (max 10.000) - same as All().
func (s *StationDataAPI) SZentralenByFilter(szentralenRequest StationDataSZentralenRequest) (*StationDataSZentralenResponse, error) {
q, err := query.Values(szentralenRequest)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s%s/szentralen?%s", APIURL, stadaAPIPath, q.Encode())
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
resp, err := s.sendRequest(req)
if err != nil {
return nil, err
}
sdr := &StationDataSZentralenResponse{}
err = s.processResponse(resp, sdr)
return sdr, err
}
// SZentralenAll returns all SZentralen information. Same as calling
// SZentralenByFilter(StationDataSZentralenRequest{}).
func (s *StationDataAPI) SZentralenAll() (*StationDataSZentralenResponse, error) {
return s.SZentralenByFilter(StationDataSZentralenRequest{})
}
// StationByFilter returns a list of station information by the given filter or an error if the
func (s *StationDataAPI) limitRate() {
// Throttle API in case a tier was specified
if s.rateThrottleTicker != nil && s.firstRequestProcessed {
<-s.rateThrottleTicker.C
}
s.firstRequestProcessed = true
}
func (s *StationDataAPI) sendRequest(req *http.Request) (*http.Response, error) {
if s.client.APIToken == "" {
return nil, errors.New("no API token given")
}
s.limitRate()
req.Header.Set("Authorization", "Bearer "+s.client.APIToken)
return s.client.httpClient.Do(req)
}
func (s *StationDataAPI) processResponse(resp *http.Response, data interface{}) (err error) {
defer func() {
if cerr := resp.Body.Close(); cerr != nil && err == nil {
err = cerr
}
}()
switch resp.StatusCode {
case 200:
err := json.NewDecoder(resp.Body).Decode(data)
if err != nil {
return err
}
return nil
case 404, 500:
stationDataErrorResponse := StationDataErrorResponse{}
err := json.NewDecoder(resp.Body).Decode(&stationDataErrorResponse)
if err != nil {
return err
}
return nil
case 429:
stationDataRateErrorResponse := StationDataRateErrorResponse{}
err := json.NewDecoder(resp.Body).Decode(&stationDataRateErrorResponse)
if err != nil {
return err
}
return nil
default:
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return errors.New(string(body))
}
}