-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathAbstractEfaProvider.swift
2862 lines (2592 loc) · 172 KB
/
AbstractEfaProvider.swift
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
import os.log
import SWXMLHash
import SwiftyJSON
public class AbstractEfaProvider: AbstractNetworkProvider {
override public var supportedQueryTraits: Set<QueryTrait> { return [.maxChanges] }
let departureMonitorEndpoint: String
let tripEndpoint: String
let stopFinderEndpoint: String
let coordEndpoint: String
let tripStopTimesEndpoint: String
let desktopTripEndpoint: String?
let desktopDeparturesEndpoint: String?
var supportsDesktopTrips: Bool = true
var supportsDesktopDepartures: Bool = true
var language = "de"
static let DEFAULT_DEPARTURE_MONITOR_ENDPOINT = "XSLT_DM_REQUEST"
static let DEFAULT_TRIP_ENDPOINT = "XSLT_TRIP_REQUEST2"
static let DEFAULT_STOPFINDER_ENDPOINT = "XML_STOPFINDER_REQUEST"
static let DEFAULT_COORD_ENDPOINT = "XML_COORD_REQUEST"
static let DEFAULT_TRIPSTOPTIMES_ENDPOINT = "XML_STOPSEQCOORD_REQUEST"
lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd"
dateFormatter.timeZone = timeZone
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter
}()
lazy var timeFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HHmm"
dateFormatter.timeZone = timeZone
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter
}()
var includeRegionId: Bool = true
var useRouteIndexAsTripId: Bool = true
var requestUrlEncoding: String.Encoding = .utf8
var needsSpEncId: Bool = false
var useLineRestriction: Bool = true
var useProxFootSearch: Bool = true
init(networkId: NetworkId, departureMonitorEndpoint: String, tripEndpoint: String, stopFinderEndpoint: String, coordEndpoint: String, tripStopTimesEndpoint: String, desktopTripEndpoint: String? = nil, desktopDeparturesEndpoint: String? = nil) {
self.departureMonitorEndpoint = departureMonitorEndpoint
self.tripEndpoint = tripEndpoint
self.stopFinderEndpoint = stopFinderEndpoint
self.coordEndpoint = coordEndpoint
self.tripStopTimesEndpoint = tripStopTimesEndpoint
self.desktopTripEndpoint = desktopTripEndpoint
self.desktopDeparturesEndpoint = desktopDeparturesEndpoint
super.init(networkId: networkId)
}
init(networkId: NetworkId, apiBase: String, departureMonitorEndpoint: String?, tripEndpoint: String?, stopFinderEndpoint: String?, coordEndpoint: String?, tripStopTimesEndpoint: String?, desktopTripEndpoint: String? = nil, desktopDeparturesEndpoint: String? = nil) {
self.departureMonitorEndpoint = apiBase + (departureMonitorEndpoint ?? AbstractEfaProvider.DEFAULT_DEPARTURE_MONITOR_ENDPOINT)
self.tripEndpoint = apiBase + (tripEndpoint ?? AbstractEfaProvider.DEFAULT_TRIP_ENDPOINT)
self.stopFinderEndpoint = apiBase + (stopFinderEndpoint ?? AbstractEfaProvider.DEFAULT_STOPFINDER_ENDPOINT)
self.coordEndpoint = apiBase + (coordEndpoint ?? AbstractEfaProvider.DEFAULT_COORD_ENDPOINT)
self.tripStopTimesEndpoint = apiBase + (tripStopTimesEndpoint ?? AbstractEfaProvider.DEFAULT_TRIPSTOPTIMES_ENDPOINT)
self.desktopTripEndpoint = desktopTripEndpoint
self.desktopDeparturesEndpoint = desktopDeparturesEndpoint
super.init(networkId: networkId)
}
init(networkId: NetworkId, apiBase: String, desktopTripEndpoint: String? = nil, desktopDeparturesEndpoint: String? = nil) {
self.departureMonitorEndpoint = apiBase + AbstractEfaProvider.DEFAULT_DEPARTURE_MONITOR_ENDPOINT
self.tripEndpoint = apiBase + AbstractEfaProvider.DEFAULT_TRIP_ENDPOINT
self.stopFinderEndpoint = apiBase + AbstractEfaProvider.DEFAULT_STOPFINDER_ENDPOINT
self.coordEndpoint = apiBase + AbstractEfaProvider.DEFAULT_COORD_ENDPOINT
self.tripStopTimesEndpoint = apiBase + AbstractEfaProvider.DEFAULT_TRIPSTOPTIMES_ENDPOINT
self.desktopTripEndpoint = desktopTripEndpoint
self.desktopDeparturesEndpoint = desktopDeparturesEndpoint
super.init(networkId: networkId)
}
// MARK: NetworkProvider implementations – Requests
override public func suggestLocations(constraint: String, types: [LocationType]?, maxLocations: Int, completion: @escaping (HttpRequest, SuggestLocationsResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: stopFinderEndpoint, encoding: requestUrlEncoding)
stopFinderRequestParameters(builder: urlBuilder, constraint: constraint, types: types, maxLocations: maxLocations, outputFormat: "JSON")
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getJson(httpRequest: httpRequest) { result in
switch result {
case .success(let json):
do {
try self.handleJsonStopfinderResponse(httpRequest: httpRequest, json: json, completion: completion)
} catch let err as ParseError {
os_log("suggestLocations parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("suggestLocations handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("suggestLocations network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
override public func queryNearbyLocations(location: Location, types: [LocationType]?, maxDistance: Int, maxLocations: Int, completion: @escaping (HttpRequest, NearbyLocationsResult) -> Void) -> AsyncRequest {
if let coord = location.coord {
return coordRequest(types: types, lat: coord.lat, lon: coord.lon, maxDistance: maxDistance, maxLocations: maxLocations, completion: completion)
} else if location.type == .station, let id = location.id {
return nearbyStationsRequest(stationId: id, maxLocations: maxLocations, completion: completion)
} else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .invalidId)
return AsyncRequest(task: nil)
}
}
func nearbyStationsRequest(stationId: String, maxLocations: Int, completion: @escaping (HttpRequest, NearbyLocationsResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: departureMonitorEndpoint, encoding: requestUrlEncoding)
nearbyStationsRequestParameters(builder: urlBuilder, stationId: stationId, maxLocations: maxLocations)
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleNearbyStationsRequest(httpRequest: httpRequest, xml: xml, maxLocations: maxLocations, completion: completion)
} catch let err as ParseError {
os_log("nearbyStations parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("nearbyStations handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("nearbyStations network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
func coordRequest(types: [LocationType]?, lat: Int, lon: Int, maxDistance: Int, maxLocations: Int, completion: @escaping (HttpRequest, NearbyLocationsResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: coordEndpoint, encoding: requestUrlEncoding)
coordRequestParameters(builder: urlBuilder, types: types, lat: lat, lon: lon, maxDistance: maxDistance, maxLocations: maxLocations)
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleCoordRequest(httpRequest: httpRequest, xml: xml, completion: completion)
} catch let err as ParseError {
os_log("coordRequest parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("coordRequest handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("coordRequest network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
public override func queryTrips(from: Location, via: Location?, to: Location, date: Date, departure: Bool, tripOptions: TripOptions, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: tripEndpoint, encoding: requestUrlEncoding)
queryTripsParameters(builder: urlBuilder, from: from, via: via, to: to, date: date, departure: departure, tripOptions: tripOptions, desktop: false)
let desktopUrl: URL?
if supportsDesktopTrips {
let desktopUrlBuilder = UrlBuilder(path: desktopTripEndpoint ?? tripEndpoint, encoding: requestUrlEncoding)
queryTripsParameters(builder: desktopUrlBuilder, from: from, via: via, to: to, date: date, departure: departure, tripOptions: tripOptions, desktop: true)
desktopUrl = desktopUrlBuilder.build()
} else {
desktopUrl = nil
}
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleTripRequestResponse(httpRequest: httpRequest, xml: xml, desktopUrl: desktopUrl, previousContext: nil, later: false, completion: completion)
} catch is SessionExpiredError {
completion(httpRequest, .sessionExpired)
} catch let err as ParseError {
os_log("queryTrips parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("queryTrips handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("queryTrips network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
override public func queryMoreTrips(context: QueryTripsContext, later: Bool, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
guard let context = context as? Context else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .sessionExpired)
return AsyncRequest(task: nil)
}
let urlBuilder = UrlBuilder(path: tripEndpoint, encoding: requestUrlEncoding)
if later {
commandLink(builder: urlBuilder, sessionId: context.queryLaterContext.sessionId, requestId: context.queryLaterContext.requestId)
} else {
commandLink(builder: urlBuilder, sessionId: context.queryEarlierContext.sessionId, requestId: context.queryEarlierContext.requestId)
}
appendCommonRequestParameters(builder: urlBuilder, outputFormat: "XML")
urlBuilder.addParameter(key: "coordListOutputFormat", value: "STRING")
urlBuilder.addParameter(key: "command", value: later ? "tripNext" : "tripPrev")
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleTripRequestResponse(httpRequest: httpRequest, xml: xml, desktopUrl: context.desktopUrl, previousContext: context, later: later, completion: completion)
} catch is SessionExpiredError {
completion(httpRequest, .sessionExpired)
} catch let err as ParseError {
os_log("queryMoreTrips parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("queryMoreTrips handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("queryMoreTrips network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
switch err {
case .invalidStatusCode(let code):
if code == 404 {
completion(httpRequest, .sessionExpired)
} else {
completion(httpRequest, .failure(err))
}
default:
completion(httpRequest, .failure(err))
}
}
}
}
public override func refreshTrip(context: RefreshTripContext, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
guard let context = context as? EfaRefreshTripContext else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .sessionExpired)
return AsyncRequest(task: nil)
}
let urlBuilder = UrlBuilder(path: tripEndpoint, encoding: requestUrlEncoding)
urlBuilder.addParameter(key: "language", value: "de")
urlBuilder.addParameter(key: "outputFormat", value: "XML")
urlBuilder.addParameter(key: "coordOutputFormat", value: "WGS84")
urlBuilder.addParameter(key: "sessionID", value: context.sessionId)
urlBuilder.addParameter(key: "requestID", value: context.requestId)
urlBuilder.addParameter(key: "command", value: "tripCoordSeq:\(context.routeIndex)")
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleTripRequestResponse(httpRequest: httpRequest, xml: xml, desktopUrl: nil, previousContext: nil, later: false, completion: completion)
} catch is SessionExpiredError {
completion(httpRequest, .sessionExpired)
} catch let err as ParseError {
os_log("refreshTrip parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("refreshTrip handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("refreshTrip network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
switch err {
case .invalidStatusCode(let code):
if code == 404 {
completion(httpRequest, .sessionExpired)
} else {
completion(httpRequest, .failure(err))
}
default:
completion(httpRequest, .failure(err))
}
}
}
}
override public func queryDepartures(stationId: String, departures: Bool, time: Date?, maxDepartures: Int, equivs: Bool, completion: @escaping (HttpRequest, QueryDeparturesResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: departureMonitorEndpoint, encoding: requestUrlEncoding)
queryDeparturesParameters(builder: urlBuilder, stationId: stationId, departures: departures, time: time, maxDepartures: maxDepartures, equivs: equivs, desktop: false)
let desktopUrl: URL?
if supportsDesktopDepartures {
let desktopUrlBuilder = UrlBuilder(path: desktopDeparturesEndpoint ?? departureMonitorEndpoint, encoding: requestUrlEncoding)
queryDeparturesParameters(builder: desktopUrlBuilder, stationId: stationId, departures: departures, time: time, maxDepartures: maxDepartures, equivs: equivs, desktop: true)
desktopUrl = desktopUrlBuilder.build()
} else {
desktopUrl = nil
}
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleQueryDeparturesResponse(httpRequest: httpRequest, xml: xml, departures: departures, desktopUrl: desktopUrl, completion: completion)
} catch let err as ParseError {
os_log("queryDepartures parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("queryDepartures handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("queryDepartures network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
public override func queryJourneyDetail(context: QueryJourneyDetailContext, completion: @escaping (HttpRequest, QueryJourneyDetailResult) -> Void) -> AsyncRequest {
guard let context = context as? EfaJourneyContext, var lineId = context.line.id else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .invalidId)
return AsyncRequest(task: nil)
}
if lineId.hasSuffix(":") {
lineId += "j18"
}
let urlBuilder = UrlBuilder(path: tripStopTimesEndpoint, encoding: requestUrlEncoding)
appendCommonRequestParameters(builder: urlBuilder, outputFormat: "XML")
urlBuilder.addParameter(key: "stopID", value: context.stopId)
urlBuilder.addParameter(key: "tripCode", value: context.tripCode)
urlBuilder.addParameter(key: "line", value: context.line.id)
appendDate(builder: urlBuilder, date: context.stopDepartureTime, dateParam: "date", timeParam: "time")
urlBuilder.addParameter(key: "tStOTType", value: "all")
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleQueryJourneyDetailResponse(httpRequest: httpRequest, xml: xml, line: context.line, completion: completion)
} catch let err as ParseError {
os_log("journeyDetail parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("journeyDetail handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("journeyDetail network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
// MARK: NetworkProvider mobile implementations – Requests
func mobileStopfinderRequest(constraint: String, types: [LocationType]?, maxLocations: Int, completion: @escaping (HttpRequest, SuggestLocationsResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: stopFinderEndpoint, encoding: requestUrlEncoding)
stopFinderRequestParameters(builder: urlBuilder, constraint: constraint, types: types, maxLocations: maxLocations, outputFormat: "XML")
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleMobileStopfinderResponse(httpRequest: httpRequest, xml: xml, completion: completion)
} catch let err as ParseError {
os_log("mobileStopfinder parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("mobileStopfinder handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("mobileStopfinder network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
func mobileCoordRequest(types: [LocationType]?, lat: Int, lon: Int, maxDistance: Int, maxLocations: Int, completion: @escaping (HttpRequest, NearbyLocationsResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: coordEndpoint, encoding: requestUrlEncoding)
coordRequestParameters(builder: urlBuilder, types: types, lat: lat, lon: lon, maxDistance: maxDistance, maxLocations: maxLocations)
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleMobileCoordRequest(httpRequest: httpRequest, xml: xml, completion: completion)
} catch let err as ParseError {
os_log("mobileCoord parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("mobileCoord handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("mobileCoord network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
func queryTripsMobile(from: Location, via: Location?, to: Location, date: Date, departure: Bool, tripOptions: TripOptions, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: tripEndpoint, encoding: requestUrlEncoding)
queryTripsParameters(builder: urlBuilder, from: from, via: via, to: to, date: date, departure: departure, tripOptions: tripOptions, desktop: false)
let desktopUrl: URL?
if supportsDesktopTrips {
let desktopUrlBuilder = UrlBuilder(path: desktopTripEndpoint ?? tripEndpoint, encoding: requestUrlEncoding)
queryTripsParameters(builder: desktopUrlBuilder, from: from, via: via, to: to, date: date, departure: departure, tripOptions: tripOptions, desktop: true)
desktopUrl = desktopUrlBuilder.build()
} else {
desktopUrl = nil
}
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleMobileTripRequestResponse(httpRequest: httpRequest, xml: xml, desktopUrl: desktopUrl, from: from, via: via, to: to, previousContext: nil, later: false, completion: completion)
} catch let err as ParseError {
os_log("mobileTripRequest parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("mobileTripRequest handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("mobileTripRequest network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
func queryMoreTripsMobile(context: QueryTripsContext, later: Bool, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
guard let context = context as? Context else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .sessionExpired)
return AsyncRequest(task: nil)
}
let urlBuilder = UrlBuilder(path: tripEndpoint, encoding: requestUrlEncoding)
if later {
commandLink(builder: urlBuilder, sessionId: context.queryLaterContext.sessionId, requestId: context.queryLaterContext.requestId)
} else {
commandLink(builder: urlBuilder, sessionId: context.queryEarlierContext.sessionId, requestId: context.queryEarlierContext.requestId)
}
appendCommonRequestParameters(builder: urlBuilder, outputFormat: "XML")
urlBuilder.addParameter(key: "command", value: later ? "tripNext" : "tripPrev")
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleMobileTripRequestResponse(httpRequest: httpRequest, xml: xml, desktopUrl: context.desktopUrl, from: nil, via: nil, to: nil, previousContext: context, later: later, completion: completion)
} catch is SessionExpiredError {
completion(httpRequest, .sessionExpired)
} catch let err as ParseError {
os_log("queryMoreTripsMobile parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("queryMoreTripsMobile handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("queryMoreTripsMobile network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
switch err {
case .invalidStatusCode(let code):
if code == 404 {
completion(httpRequest, .sessionExpired)
} else {
completion(httpRequest, .failure(err))
}
default:
completion(httpRequest, .failure(err))
}
}
}
}
func refreshTripMobile(context: RefreshTripContext, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
guard let context = context as? EfaRefreshTripContext else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .sessionExpired)
return AsyncRequest(task: nil)
}
let urlBuilder = UrlBuilder(path: tripEndpoint, encoding: requestUrlEncoding)
urlBuilder.addParameter(key: "language", value: "de")
urlBuilder.addParameter(key: "outputFormat", value: "XML")
urlBuilder.addParameter(key: "coordOutputFormat", value: "WGS84")
urlBuilder.addParameter(key: "sessionID", value: context.sessionId)
urlBuilder.addParameter(key: "requestID", value: context.requestId)
urlBuilder.addParameter(key: "command", value: "tripCoordSeq:\(context.routeIndex)")
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleMobileTripRequestResponse(httpRequest: httpRequest, xml: xml, desktopUrl: nil, from: nil, via: nil, to: nil, previousContext: nil, later: false, completion: completion)
} catch is SessionExpiredError {
completion(httpRequest, .sessionExpired)
} catch let err as ParseError {
os_log("refreshTripMobile parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("refreshTripMobile handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("refreshTripMobile network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
switch err {
case .invalidStatusCode(let code):
if code == 404 {
completion(httpRequest, .sessionExpired)
} else {
completion(httpRequest, .failure(err))
}
default:
completion(httpRequest, .failure(err))
}
}
}
}
func queryDeparturesMobile(stationId: String, departures: Bool, time: Date?, maxDepartures: Int, equivs: Bool, completion: @escaping (HttpRequest, QueryDeparturesResult) -> Void) -> AsyncRequest {
let urlBuilder = UrlBuilder(path: departureMonitorEndpoint, encoding: requestUrlEncoding)
queryDeparturesParameters(builder: urlBuilder, stationId: stationId, departures: departures, time: time, maxDepartures: maxDepartures, equivs: equivs, desktop: false)
let desktopUrl: URL?
if supportsDesktopDepartures {
let desktopUrlBuilder = UrlBuilder(path: desktopDeparturesEndpoint ?? departureMonitorEndpoint, encoding: requestUrlEncoding)
queryDeparturesParameters(builder: desktopUrlBuilder, stationId: stationId, departures: departures, time: time, maxDepartures: maxDepartures, equivs: equivs, desktop: true)
desktopUrl = desktopUrlBuilder.build()
} else {
desktopUrl = nil
}
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleQueryDeparturesMobileResponse(httpRequest: httpRequest, xml: xml, departures: departures, desktopUrl: desktopUrl, completion: completion)
} catch let err as ParseError {
os_log("queryDeparturesMobile parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("queryDeparturesMobile handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("queryDeparturesMobile network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
func queryJourneyDetailMobile(context: QueryJourneyDetailContext, completion: @escaping (HttpRequest, QueryJourneyDetailResult) -> Void) -> AsyncRequest {
guard let context = context as? EfaJourneyContext, var lineId = context.line.id else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .invalidId)
return AsyncRequest(task: nil)
}
if lineId.hasSuffix(":") {
lineId += "j18"
}
let urlBuilder = UrlBuilder(path: tripStopTimesEndpoint, encoding: requestUrlEncoding)
appendCommonRequestParameters(builder: urlBuilder, outputFormat: "XML")
urlBuilder.addParameter(key: "stopID", value: context.stopId)
urlBuilder.addParameter(key: "tripCode", value: context.tripCode)
urlBuilder.addParameter(key: "line", value: context.line.id)
appendDate(builder: urlBuilder, date: context.stopDepartureTime, dateParam: "date", timeParam: "time")
urlBuilder.addParameter(key: "tStOTType", value: "all")
let httpRequest = HttpRequest(urlBuilder: urlBuilder)
return HttpClient.getXml(httpRequest: httpRequest) { result in
switch result {
case .success(let xml):
do {
try self.handleQueryJourneyDetailMobileResponse(httpRequest: httpRequest, xml: xml, line: context.line, completion: completion)
} catch let err as ParseError {
os_log("journeyDetailMobile parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("journeyDetailMobile handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("journeyDetailMobile network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
// MARK: NetworkProvider responses
func handleJsonStopfinderResponse(httpRequest: HttpRequest, json: JSON, completion: @escaping (HttpRequest, SuggestLocationsResult) -> Void) throws {
let head = json["stopFinder"].exists() ? json["stopFinder"] : json
// check for errors
for message in head["message"].arrayValue {
let name = message["name"].stringValue
let value = message["value"].stringValue
if name == "code" && value != "-8010" && value != "-8011" {
throw ParseError(reason: "received illegal message code \(value)")
}
}
var locations: [SuggestedLocation] = []
let pointObj = head["points"]["point"]
func parseJsonPoint(json: JSON) throws -> SuggestedLocation {
var type = json["type"].stringValue
if type == "any" {
type = json["anyType"].string ?? type
}
let id = json["stateless"].string
let name = normalizeLocationName(name: json["name"].string)
let object = normalizeLocationName(name: json["object"].string)
let postcode = json["postcode"].string
let quality = json["quality"].intValue
let place = json["ref"]["place"].string?.emptyToNil
let coordinates = parseCoordinates(string: json["ref"]["coord"].string ?? json["ref"]["coords"].string)
let location: Location?
switch type {
case "stop":
location = Location(type: .station, id: id, coord: coordinates, place: place, name: object)
break
case "poi":
location = Location(type: .poi, id: id, coord: coordinates, place: place, name: object)
break
case "crossing":
location = Location(type: .address, id: id, coord: coordinates, place: place, name: object)
break
case "street", "address", "singlehouse", "buildingname", "loc":
location = Location(type: .address, id: id, coord: coordinates, place: place, name: name)
break
case "postcode":
location = Location(type: .address, id: id, coord: coordinates, place: place, name: postcode)
break
default:
location = Location(type: .any, id: nil, coord: coordinates, place: place, name: name)
break
}
guard let finalLocation = location else {
throw ParseError(reason: "failed to init location")
}
return SuggestedLocation(location: finalLocation, priority: quality)
}
if pointObj.exists() {
locations.append(try parseJsonPoint(json: pointObj))
} else if head["points"].exists() {
for point in head["points"].arrayValue {
locations.append(try parseJsonPoint(json: point))
}
} else if let first = head.arrayValue.first {
locations.append(try parseJsonPoint(json: first))
}
locations.sort {$0.priority > $1.priority}
completion(httpRequest, .success(locations: locations))
}
func handleCoordRequest(httpRequest: HttpRequest, xml: XMLIndexer, completion: @escaping (HttpRequest, NearbyLocationsResult) -> Void) throws {
let request = xml["itdRequest"]["itdCoordInfoRequest"]["itdCoordInfo"]["coordInfoItemList"]
var locations: [Location] = []
for coordItem in request["coordInfoItem"].all {
let type = coordItem.element?.attribute(by: "type")?.text
let locationType: LocationType
if type == "STOP" {
locationType = .station
} else if type == "POI_POINT" {
locationType = .poi
} else {
throw ParseError(reason: "unknown location type \(type ?? "")")
}
let id = coordItem.element?.attribute(by: "stateless")?.text ?? coordItem.element?.attribute(by: "id")?.text
let name = normalizeLocationName(name: coordItem.element?.attribute(by: "name")?.text)
let place = normalizeLocationName(name: coordItem.element?.attribute(by: "locality")?.text)
let coordList = processItdPathCoordinates(coordItem["itdPathCoordinates"])
let coord = coordList == nil ? nil : coordList!.count > 0 ? coordList![0] : nil
let location = Location(type: locationType, id: id, coord: coord, place: place, name: name)
if let location = location {
locations.append(location)
}
}
completion(httpRequest, .success(locations: locations))
}
func handleNearbyStationsRequest(httpRequest: HttpRequest, xml: XMLIndexer, maxLocations: Int, completion: @escaping (HttpRequest, NearbyLocationsResult) -> Void) throws {
let request = xml["itdRequest"]["itdDepartureMonitorRequest"]
var ownStation: Location?
var stations: [Location] = []
let nameState = try processItdOdv(odv: request["itdOdv"], expectedUsage: "dm") { (nameState, location, matchQuality) in
if location.type == .station {
if nameState == "identified" {
ownStation = location
} else if nameState == "assigned" {
stations.append(location)
}
}
}
if nameState == "notidentified" {
completion(httpRequest, .invalidId)
return
}
if let ownStation = ownStation, !stations.contains(ownStation) {
stations.append(ownStation)
}
if maxLocations == 0 || maxLocations >= stations.count {
completion(httpRequest, .success(locations: stations))
} else {
completion(httpRequest, .success(locations: Array(stations[0..<maxLocations])))
}
}
func handleTripRequestResponse(httpRequest: HttpRequest, xml: XMLIndexer, desktopUrl: URL?, previousContext: Context?, later: Bool, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) throws {
var request = xml["itdRequest"]["itdTripRequest"]
if request.all.isEmpty {
request = xml["itdRequest"]
}
let requestId = request.element?.attribute(by: "requestID")?.text
let sessionId = xml["itdRequest"].element?.attribute(by: "sessionID")?.text
if let code = request["itdMessage"].element?.attribute(by: "code")?.text, code == "-4000" {
completion(httpRequest, .noTrips)
return
}
var ambiguousFrom, ambiguousTo, ambiguousVia: [Location]?
var from, to, via: Location?
for odv in request["itdOdv"].all {
guard let usage = odv.element?.attribute(by: "usage")?.text else { continue }
var locations: [Location] = []
var sort: [Location: Int] = [:]
let nameState = try processItdOdv(odv: odv, expectedUsage: usage, callback: { (nameState: String?, location: Location, matchQuality: Int) in
locations.append(location)
sort[location] = matchQuality
})
locations.sort {sort[$0]! > sort[$1]!}
if nameState == "list" {
if usage == "origin" {
ambiguousFrom = locations
} else if usage == "via" {
ambiguousVia = locations
} else if usage == "destination" {
ambiguousTo = locations
} else {
throw ParseError(reason: "unknown usage \(usage)")
}
} else if nameState == "identified" {
if usage == "origin" {
from = locations[0]
} else if usage == "via" {
via = locations[0]
} else if usage == "destination" {
to = locations[0]
} else {
throw ParseError(reason: "unknown usage \(usage)")
}
} else if nameState == "notidentified" {
if usage == "origin" {
completion(httpRequest, .unknownFrom)
} else if usage == "via" {
completion(httpRequest, .unknownVia)
} else if usage == "destination" {
completion(httpRequest, .unknownTo)
} else {
throw ParseError(reason: "unknown usage \(usage)")
}
return
}
}
if ambiguousFrom != nil || ambiguousVia != nil || ambiguousTo != nil {
completion(httpRequest, .ambiguous(ambiguousFrom: ambiguousFrom ?? [], ambiguousVia: ambiguousVia ?? [], ambiguousTo: ambiguousTo ?? []))
return
}
if let message = request["itdTripDateTime"]["itdDateTime"]["itdDate"]["itdMessage"].element?.text, message == "invalid date" {
completion(httpRequest, .invalidDate)
return
}
var messages: [InfoText] = []
for infoLink in xml["itdRequest"]["itdInfoLinkList"]["itdBannerInfoList"]["infoLink"].all {
guard let infoLinkText = infoLink["infoLinkText"].element?.text, let infoLinkUrl = infoLink["infoLinkURL"].element?.text else { continue }
messages.append(InfoText(text: String(htmlEncodedString: infoLinkText) ?? infoLinkText, url: infoLinkUrl))
}
var trips: [Trip] = []
var routes = request["itdItinerary"]["itdRouteList"]["itdRoute"].all
if routes.isEmpty {
routes = request["itdTripCoordSeqRequest"]["itdRoute"].all
}
if routes.isEmpty {
completion(httpRequest, .noTrips)
return
}
for route in routes {
let id = "" // when using query earlier, trip ids are no longer unique, but shift
var legs: [Leg] = []
var firstDepartureLocation: Location?
var lastArrivalLocation: Location?
var cancelled = false
for partialRoute in route["itdPartialRouteList"]["itdPartialRoute"].all {
var legMessages: [String] = []
for infoLink in partialRoute["infoLink"].all {
guard let infoLinkText = infoLink["infoText"]["subtitle"].element?.text else { continue }
legMessages.append(String(htmlEncodedString: infoLinkText) ?? infoLinkText)
}
let points = partialRoute["itdPoint"].all
var point = points[0]
if point.element?.attribute(by: "usage")?.text != "departure" {
throw ParseError(reason: "wrong route usage")
}
guard let departureLocation = processItdPointAttributes(point: point) else {
throw ParseError(reason: "departure location point attr")
}
if firstDepartureLocation == nil {
firstDepartureLocation = departureLocation
}
let departurePosition = parsePosition(position: point.element?.attribute(by: "platformName")?.text)
let plannedDeparturePosition = parsePosition(position: point.element?.attribute(by: "plannedPlatformName")?.text)
guard let departureTime = processItdDateTime(xml: point["itdDateTime"]) else {
throw ParseError(reason: "departure time")
}
let departureTargetTime = processItdDateTime(xml: point["itdDateTimeTarget"])
point = points[1]
if point.element?.attribute(by: "usage")?.text != "arrival" {
throw ParseError(reason: "wrong route usage")
}
guard let arrivalLocation = processItdPointAttributes(point: point) else {
throw ParseError(reason: "arrival location point attr")
}
lastArrivalLocation = arrivalLocation
let arrivalPosition = parsePosition(position: point.element?.attribute(by: "platformName")?.text)
let plannedArrivalPosition = parsePosition(position: point.element?.attribute(by: "plannedPlatformName")?.text)
guard let arrivalTime = processItdDateTime(xml: point["itdDateTime"]) else {
throw ParseError(reason: "arrival time")
}
let arrivalTargetTime = processItdDateTime(xml: point["itdDateTimeTarget"])
let meansOfTransportProductName = partialRoute["itdMeansOfTransport"].element?.attribute(by: "productName")?.text
guard let meansOfTransportType = Int(partialRoute["itdMeansOfTransport"].element?.attribute(by: "type")?.text ?? "") else {
throw ParseError(reason: "means of transport type")
}
if meansOfTransportType <= 16 {
cancelled |= try processPublicLeg(partialRoute, &legs, departureTime, departureTargetTime, departureLocation, departurePosition, plannedDeparturePosition, arrivalTime, arrivalTargetTime, arrivalLocation, arrivalPosition, plannedArrivalPosition, legMessages)
} else if meansOfTransportType == 97 && meansOfTransportProductName == "nicht umsteigen" {
if let last = legs.last as? PublicLeg {
var lastMessage = "Nicht umsteigen, Weiterfahrt im selben Fahrzeug möglich."
if let message = last.message?.emptyToNil {
lastMessage += "\n" + message
}
if let msg = legMessages.joined(separator: "\n").emptyToNil {
lastMessage += "\n" + msg
}
legs[legs.count - 1] = PublicLeg(line: last.line, destination: last.destination, departureStop: last.departureStop, arrivalStop: last.arrivalStop, intermediateStops: last.intermediateStops, message: lastMessage, path: last.path, journeyContext: last.journeyContext)
}
} else if meansOfTransportType == 98 && meansOfTransportProductName == "gesicherter Anschluss" {
// ignore
} else if meansOfTransportType == 99 && meansOfTransportProductName == "Fussweg" {
processIndividualLeg(partialRoute, &legs, .WALK, departureTime, departureLocation, arrivalTime, arrivalLocation)
} else if meansOfTransportType == 100 && (meansOfTransportProductName == nil || meansOfTransportProductName == "Fussweg") {
processIndividualLeg(partialRoute, &legs, .WALK, departureTime, departureLocation, arrivalTime, arrivalLocation)
} else if meansOfTransportType == 105 && meansOfTransportProductName == "Taxi" {
processIndividualLeg(partialRoute, &legs, .CAR, departureTime, departureLocation, arrivalTime, arrivalLocation)
} else {
throw ParseError(reason: "unknown means of transport: \(meansOfTransportType) \(meansOfTransportProductName ?? "")")
}
}
guard let from = firstDepartureLocation, let to = lastArrivalLocation else {
throw ParseError(reason: "from/to location")
}
var fares: [Fare] = []
if let elem = route["itdFare"]["itdSingleTicket"].element, let net = elem.attribute(by: "net")?.text, let currency = elem.attribute(by: "currency")?.text {
let unitName = elem.attribute(by: "unitName")?.text.trimmingCharacters(in: .whitespaces)
if let fareAdult = elem.attribute(by: "fareAdult")?.text, let fare = Float(fareAdult), fare != 0 {
let level = elem.attribute(by: "levelAdult")?.text.trimmingCharacters(in: .whitespaces)
let units = elem.attribute(by: "unitsAdult")?.text.trimmingCharacters(in: .whitespaces)
fares.append(Fare(network: net.uppercased(), type: .adult, currency: currency, fare: fare, unitsName: level ?? "" != "" ? nil : (unitName ?? "" == "" ? nil : unitName), units: level ?? "" != "" ? level : units))
}
if let fareChild = elem.attribute(by: "fareChild")?.text, let fare = Float(fareChild), fare != 0 {
let level = elem.attribute(by: "levelChild")?.text.trimmingCharacters(in: .whitespaces)
let units = elem.attribute(by: "unitsChild")?.text.trimmingCharacters(in: .whitespaces)
fares.append(Fare(network: net.uppercased(), type: .child, currency: currency, fare: fare, unitsName: level ?? "" != "" ? nil : (unitName ?? "" == "" ? nil : unitName), units: level ?? "" != "" ? level : units))
}
} else {
let tickets = route["itdFare"]["itdUnifiedTicket"].all
for ticket in tickets {
guard
let name = ticket.element?.attribute(by: "name")?.text,
name.starts(with: "Einzelfahrschein"),
let net = ticket.element?.attribute(by: "net")?.text,
let currency = ticket.element?.attribute(by: "currency")?.text,
let person = ticket.element?.attribute(by: "person")?.text,
let fareString = ticket.element?.attribute(by: "priceBrutto")?.text,
let fare = Float(fareString)
else {
continue
}
switch person {
case "ADULT":
fares.append(Fare(network: net.uppercased(), type: .adult, currency: currency, fare: fare, unitsName: nil, units: nil))
case "CHILD":
fares.append(Fare(network: net.uppercased(), type: .child, currency: currency, fare: fare, unitsName: nil, units: nil))
default: break
}
}
}
let context: EfaRefreshTripContext?
if let sessionId = sessionId, let requestId = requestId {
context = EfaRefreshTripContext(sessionId: sessionId, requestId: requestId, routeIndex: "\(trips.count + 1)")
} else {
context = nil
}
let trip = Trip(id: id, from: from, to: to, legs: legs, fares: fares, refreshContext: context)
trips.append(trip)
}
if trips.count == 0 {
completion(httpRequest, .noTrips)
return
}
let context: Context?
if let sessionId = sessionId, let requestId = requestId {
if let previousContext = previousContext {
context = Context(queryEarlierContext: later ? previousContext.queryEarlierContext : (sessionId: sessionId, requestId: requestId), queryLaterContext: !later ? previousContext.queryLaterContext : (sessionId: sessionId, requestId: requestId), desktopUrl: desktopUrl)
} else {
context = Context(queryEarlierContext: (sessionId: sessionId, requestId: requestId), queryLaterContext: (sessionId: sessionId, requestId: requestId), desktopUrl: desktopUrl)
}
} else {
context = previousContext
}
completion(httpRequest, .success(context: context, from: from, via: via, to: to, trips: trips, messages: messages))
}
func handleQueryDeparturesResponse(httpRequest: HttpRequest, xml: XMLIndexer, departures: Bool, desktopUrl: URL?, completion: @escaping (HttpRequest, QueryDeparturesResult) -> Void) throws {
let request = xml["itdRequest"]["itdDepartureMonitorRequest"]
var result: [StationDepartures] = []
let departureStop = request["itdOdv"]
let nameState = try self.processItdOdv(odv: departureStop, expectedUsage: "dm", callback: { (nameState: String?, location: Location, matchQuality: Int) in
if location.type == .station {
if !result.contains(where: {$0.stopLocation.id == location.id}) {
result.append(StationDepartures(stopLocation: location, departures: [], lines: []))
}
}
})
if nameState != "identified" {
completion(httpRequest, .invalidStation)
return
}
for servingLine in request["itdServingLines"]["itdServingLine"].all {
guard let (line, destination, _) = self.parseLine(xml: servingLine) else {
throw ParseError(reason: "failed to parse line")
}
let assignedStopId = servingLine.element?.attribute(by: "assignedStopID")?.text
result.first(where: {$0.stopLocation.id == assignedStopId})?.lines.append(ServingLine(line: line, destination: destination))
}
for departure in request[departures ? "itdDepartureList" : "itdArrivalList"][departures ? "itdDeparture" : "itdArrival"].all {
let assignedStopId = departure.element?.attribute(by: "stopID")?.text
let plannedTime = self.parseDate(xml: departure["itdDateTime"])
let predictedTime = self.parseDate(xml: departure["itdRTDateTime"])
guard let (line, destination, cancelled) = self.parseLine(xml: departure["itdServingLine"]) else {
print("WRN - queryDepartures: Failed to parse departure line!")