-
Notifications
You must be signed in to change notification settings - Fork 8
/
AbstractHafasClientInterfaceProvider.swift
1539 lines (1392 loc) · 80.2 KB
/
AbstractHafasClientInterfaceProvider.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
public class AbstractHafasClientInterfaceProvider: AbstractHafasProvider {
override public var supportedQueryTraits: Set<QueryTrait> { return [.maxChanges, .minChangeTime] }
var mgateEndpoint: String
var apiVersion: String?
var apiAuthorization: Any?
var apiClient: Any?
var extVersion: String?
var jnyFilterIncludes: [[String: Any]]?
var desktopQueryEndpoint: String?
var desktopStboardEndpoint: String?
var requestVerification: RequestVerification = .none
var configJson: [String: Any] = [:]
var userAgent: String?
init(networkId: NetworkId, apiBase: String, productsMap: [Product?]) {
self.mgateEndpoint = apiBase + "mgate.exe"
self.desktopQueryEndpoint = apiBase + "query.exe/dn"
self.desktopStboardEndpoint = apiBase + "stboard.exe/dn"
super.init(networkId: networkId, productsMap: productsMap)
}
init(networkId: NetworkId, apiBase: String, desktopQueryEndpoint: String?, desktopStboardEndpoint: String?, productsMap: [Product?]) {
self.mgateEndpoint = apiBase + "mgate.exe"
self.desktopQueryEndpoint = desktopQueryEndpoint
self.desktopStboardEndpoint = desktopStboardEndpoint
super.init(networkId: networkId, productsMap: productsMap)
}
// MARK: NetworkProvider implementations – Requests
override public func suggestLocations(constraint: String, types: [LocationType]?, maxLocations: Int, completion: @escaping (HttpRequest, SuggestLocationsResult) -> Void) -> AsyncRequest {
var type: String
if let types = types, !types.isEmpty {
if types.contains(.any) || [.station, .poi, .address].allSatisfy(types.contains) {
type = "ALL"
} else {
type = ""
types.forEach { t in
switch t {
case .station:
type += "S"
case .poi:
type += "P"
case .address:
type += "A"
default: break
}
}
}
} else {
type = "ALL"
}
let request = wrapJsonApiRequest(meth: "LocMatch", req: ["input": ["field": "S", "loc": ["name": constraint + "?", "type": type], "maxLoc": maxLocations > 0 ? maxLocations : 50]], formatted: true)
let urlBuilder = UrlBuilder(path: mgateEndpoint, encoding: requestUrlEncoding)
requestVerification.appendParameters(to: urlBuilder, requestString: request)
let httpRequest = HttpRequest(urlBuilder: urlBuilder).setPostPayload(request).setUserAgent(userAgent)
return HttpClient.get(httpRequest: httpRequest) { result in
switch result {
case .success((_, let data)):
do {
try self.handleJsonLocMatch(httpRequest: httpRequest, response: try data.toJson(), 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 jsonLocGeoPos(types: types, lat: coord.lat, lon: coord.lon, maxDistance: maxDistance, maxLocations: maxLocations, completion: completion)
} else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .invalidId) // TODO: nearby locations of station id
return AsyncRequest(task: nil)
}
}
func jsonLocGeoPos(types: [LocationType]?, lat: Int, lon: Int, maxDistance: Int, maxLocations: Int, completion: @escaping (HttpRequest, NearbyLocationsResult) -> Void) -> AsyncRequest {
// TODO: extract parameters to method
var ring: [String: Any] = ["cCrd": ["x": lon, "y": lat]]
if maxDistance > 0 {
ring["maxDist"] = maxDistance
} else {
ring["maxDist"] = 5000
}
var req: [String: Any] = ["ring": ring, "getPOIs": types?.contains(.poi) ?? false, "getStops": types?.contains(.station) ?? true]
if maxLocations > 0 {
req["maxLoc"] = maxLocations
} else {
req["maxLoc"] = 50
}
let request = wrapJsonApiRequest(meth: "LocGeoPos", req: req, formatted: false)
let urlBuilder = UrlBuilder(path: mgateEndpoint, encoding: requestUrlEncoding)
requestVerification.appendParameters(to: urlBuilder, requestString: request)
let httpRequest = HttpRequest(urlBuilder: urlBuilder).setPostPayload(request).setUserAgent(userAgent)
return HttpClient.get(httpRequest: httpRequest) { result in
switch result {
case .success((_, let data)):
do {
try self.handleJsonLocGeoPos(httpRequest: httpRequest, response: try data.toJson(), types: types, 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))
}
}
}
override public func queryDepartures(stationId: String, departures: Bool, time: Date?, maxDepartures: Int, equivs: Bool, completion: @escaping (HttpRequest, QueryDeparturesResult) -> Void) -> AsyncRequest {
// TODO: extract parameters to method
let jsonDate = self.jsonDate(from: time ?? Date())
let jsonTime = self.jsonTime(from: time ?? Date())
let normalizedStationId = normalize(stationId: stationId) ?? ""
var req: [String: Any] = [
"type": departures ? "DEP" : "ARR",
"date": jsonDate,
"time": jsonTime,
"stbLoc": [
"type": "S",
"state": "F",
normalizedStationId.hasSuffix("@") ? "lid" : "extId": normalizedStationId
],
"maxJny": maxDepartures != 0 ? maxDepartures : 50
]
if let apiVersion = apiVersion, apiVersion.compare("1.19", options: .numeric) == .orderedAscending {
req["stbFltrEquiv"] = !equivs
req["getPasslist"] = false
}
let request = wrapJsonApiRequest(meth: "StationBoard", req: req, formatted: false)
let urlBuilder = UrlBuilder(path: mgateEndpoint, encoding: requestUrlEncoding)
requestVerification.appendParameters(to: urlBuilder, requestString: request)
let desktopUrl: URL?
if let desktopStboardEndpoint = desktopStboardEndpoint {
let desktopUrlBuilder = UrlBuilder(path: desktopStboardEndpoint, encoding: requestUrlEncoding)
xmlStationBoardParameters(builder: desktopUrlBuilder, stationId: stationId, departures: departures, time: time, maxDepartures: maxDepartures, equivs: equivs, styleSheet: nil)
desktopUrl = desktopUrlBuilder.build()
} else {
desktopUrl = nil
}
let httpRequest = HttpRequest(urlBuilder: urlBuilder).setPostPayload(request).setUserAgent(userAgent)
return HttpClient.get(httpRequest: httpRequest) { result in
switch result {
case .success((_, let data)):
do {
try self.handleJsonStationBoard(httpRequest: httpRequest, response: try data.toJson(), stationId: stationId, departures: departures, equivs: equivs, 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 queryTrips(from: Location, via: Location?, to: Location, date: Date, departure: Bool, tripOptions: TripOptions, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
if from.id == nil && !from.hasLocation() {
return jsonTripSearchIdentify(location: from) { (request, locations) in
if locations.count > 1 {
completion(request, .ambiguous(ambiguousFrom: locations, ambiguousVia: [], ambiguousTo: []))
} else if let location = locations.first {
let _ = self.queryTrips(from: location, via: via, to: to, date: date, departure: departure, tripOptions: tripOptions, completion: completion)
} else {
completion(request, .unknownFrom)
}
}
} else if let via = via, via.id == nil && !via.hasLocation() {
return jsonTripSearchIdentify(location: via) { (request, locations) in
if locations.count > 1 {
completion(request, .ambiguous(ambiguousFrom: [], ambiguousVia: locations, ambiguousTo: []))
} else if let location = locations.first {
let _ = self.queryTrips(from: from, via: location, to: to, date: date, departure: departure, tripOptions: tripOptions, completion: completion)
} else {
completion(request, .unknownVia)
}
}
} else if to.id == nil && !to.hasLocation() {
return jsonTripSearchIdentify(location: to) { (request, locations) in
if locations.count > 1 {
completion(request, .ambiguous(ambiguousFrom: [], ambiguousVia: [], ambiguousTo: locations))
} else if let location = locations.first {
let _ = self.queryTrips(from: from, via: via, to: location, date: date, departure: departure, tripOptions: tripOptions, completion: completion)
} else {
completion(request, .unknownTo)
}
}
} else {
return doJsonTripSearch(from: from, via: via, to: to, date: date, departure: departure, tripOptions: tripOptions, previousContext: nil, later: false, completion: completion)
}
}
func jsonTripSearchIdentify(location: Location, completion: @escaping (HttpRequest, [Location]) -> Void) -> AsyncRequest {
if let name = location.name {
return suggestLocations(constraint: [location.place, name].compactMap({$0}).joined(separator: " "), types: [.station], maxLocations: 10) { (request, result) in
switch result {
case .success(let locations):
completion(request, locations.map({$0.location}))
case .failure(_):
completion(request, [])
}
}
} else if let coord = location.coord {
return jsonLocGeoPos(types: LocationType.ALL, lat: coord.lat, lon: coord.lon, maxDistance: 0, maxLocations: 0) { (request, result) in
switch result {
case .success(let locations):
completion(request, locations)
case .invalidId, .failure(_):
completion(request, [])
}
}
} else {
completion(HttpRequest(urlBuilder: UrlBuilder()), [])
return AsyncRequest(task: nil)
}
}
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)
}
return doJsonTripSearch(from: context.from, via: context.via, to: context.to, date: context.date, departure: context.departure, tripOptions: context.tripOptions, previousContext: context, later: later, completion: completion)
}
func doJsonTripSearch(from: Location, via: Location?, to: Location, date: Date, departure: Bool, tripOptions: TripOptions, previousContext: Context?, later: Bool, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
let request = wrapJsonApiRequest(meth: "TripSearch", req: jsonTripSearchRequest(from: from, via: via, to: to, date: date, departure: departure, tripOptions: tripOptions, previousContext: previousContext, later: later), formatted: true)
let urlBuilder = UrlBuilder(path: mgateEndpoint, encoding: requestUrlEncoding)
requestVerification.appendParameters(to: urlBuilder, requestString: request)
let desktopUrl: URL?
if let context = previousContext {
desktopUrl = context.desktopUrl
} else if let desktopQueryEndpoint = desktopQueryEndpoint {
let desktopUrlBuilder = UrlBuilder(path: desktopQueryEndpoint, encoding: requestUrlEncoding)
queryTripsBinaryParameters(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).setPostPayload(request).setUserAgent(userAgent)
return HttpClient.get(httpRequest: httpRequest) { result in
switch result {
case .success((_, let data)):
do {
try self.handleJsonTripSearch(httpRequest: httpRequest, response: try data.toJson(), desktopUrl: desktopUrl, from: from, via: via, to: to, date: date, departure: departure, previousContext: previousContext, later: later, tripOptions: tripOptions, completion: completion)
} 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))
}
}
}
public override func refreshTrip(context: RefreshTripContext, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) -> AsyncRequest {
guard let context = context as? HafasClientInterfaceRefreshTripContext else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .sessionExpired)
return AsyncRequest(task: nil)
}
let request = wrapJsonApiRequest(meth: "Reconstruction", req: ["ctxRecon": context.contextRecon,"trfReq": [ "jnyCl": 2, "cType": "PK", "tvlrProf": [[ "type": "E"]]], "getPolyline": true, "getPasslist": true], formatted: true)
let urlBuilder = UrlBuilder(path: mgateEndpoint, encoding: requestUrlEncoding)
requestVerification.appendParameters(to: urlBuilder, requestString: request)
let httpRequest = HttpRequest(urlBuilder: urlBuilder).setPostPayload(request).setUserAgent(userAgent)
return HttpClient.get(httpRequest: httpRequest) { result in
switch result {
case .success((_, let data)):
do {
try self.handleJsonTripSearch(httpRequest: httpRequest, response: try data.toJson(), desktopUrl: nil, from: context.from, via: nil, to: context.to, date: Date(), departure: true, previousContext: nil, later: false, tripOptions: TripOptions(), completion: completion)
} 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))
completion(httpRequest, .failure(err))
}
}
}
public override func queryJourneyDetail(context: QueryJourneyDetailContext, completion: @escaping (HttpRequest, QueryJourneyDetailResult) -> Void) -> AsyncRequest {
guard let context = context as? HafasClientInterfaceJourneyContext else {
completion(HttpRequest(urlBuilder: UrlBuilder()), .invalidId)
return AsyncRequest(task: nil)
}
let req: [String: Any] = [
"jid": context.journeyId,
"getPasslist": true,
"getPolyline": true
]
let request = wrapJsonApiRequest(meth: "JourneyDetails", req: req, formatted: false)
let urlBuilder = UrlBuilder(path: mgateEndpoint, encoding: requestUrlEncoding)
requestVerification.appendParameters(to: urlBuilder, requestString: request)
let httpRequest = HttpRequest(urlBuilder: urlBuilder).setPostPayload(request).setUserAgent(userAgent)
return HttpClient.get(httpRequest: httpRequest) { result in
switch result {
case .success((_, let data)):
do {
try self.handleQueryJourneyDetail(httpRequest: httpRequest, response: try data.toJson(), completion: completion)
} catch let err as ParseError {
os_log("queryJourneyDetail parse error: %{public}@", log: .requestLogger, type: .error, err.reason)
completion(httpRequest, .failure(err))
} catch let err {
os_log("queryJourneyDetail handle response error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
case .failure(let err):
os_log("queryJourneyDetail network error: %{public}@", log: .requestLogger, type: .error, String(describing: err))
completion(httpRequest, .failure(err))
}
}
}
// MARK: NetworkProvider responses
func handleJsonLocMatch(httpRequest: HttpRequest, response: Any?, completion: @escaping (HttpRequest, SuggestLocationsResult) -> Void) throws {
guard let json = response as? [String: Any], json["err"] == nil || json["err"] as? String == "OK", let svcResL = json["svcResL"] as? [Any], svcResL.count == 1, let svcRes = svcResL[0] as? [String: Any], let meth = svcRes["meth"] as? String, meth == "LocMatch", let error = svcRes["err"] as? String else {
throw ParseError(reason: "could not parse json")
}
if error != "OK" {
throw ParseError(reason: "\(error): \(svcRes["errTxt"] as? String ?? "")")
}
guard let res = svcRes["res"] as? [String: Any], let match = res["match"] as? [String: Any], let locList = match["locL"] as? [Any] else {
throw ParseError(reason: "could not parse loc list")
}
let locations = try parseLocList(locList: locList)
let suggestedLocations = locations.map({SuggestedLocation(location: $0, priority: 0)})
completion(httpRequest, .success(locations: suggestedLocations))
}
func handleJsonLocGeoPos(httpRequest: HttpRequest, response: Any?, types: [LocationType]?, completion: @escaping (HttpRequest, NearbyLocationsResult) -> Void) throws {
let types = types ?? [.station]
guard let json = response as? [String: Any], json["err"] == nil || json["err"] as? String == "OK", let svcResL = json["svcResL"] as? [Any], svcResL.count == 1, let svcRes = svcResL[0] as? [String: Any], let meth = svcRes["meth"] as? String, meth == "LocGeoPos", let error = svcRes["err"] as? String else {
throw ParseError(reason: "could not parse json")
}
if error != "OK" {
throw ParseError(reason: "\(error): \(svcRes["errTxt"] as? String ?? "")")
}
guard let res = svcRes["res"] as? [String: Any] else {
throw ParseError(reason: "could not parse loc list")
}
let locations: [Location]
if let locList = res["locL"] as? [Any] {
locations = try parseLocList(locList: locList).filter({types.contains($0.type)})
} else {
locations = []
}
completion(httpRequest, .success(locations: locations))
}
func handleJsonStationBoard(httpRequest: HttpRequest, response: Any?, stationId: String, departures: Bool, equivs: Bool, desktopUrl: URL?, completion: @escaping (HttpRequest, QueryDeparturesResult) -> Void) throws {
guard let json = response as? [String: Any], json["err"] == nil || json["err"] as? String == "OK", let svcResL = json["svcResL"] as? [Any], svcResL.count == 1, let svcRes = svcResL[0] as? [String: Any], let meth = svcRes["meth"] as? String, meth == "StationBoard", let err = svcRes["err"] as? String else {
throw ParseError(reason: "could not parse json")
}
if err != "OK" {
let errTxt = svcRes["errTxt"] as? String ?? ""
// TODO: handle more errors
os_log("Received hafas error %{public}@: %{public}@", log: .requestLogger, type: .error, err, errTxt)
if err == "LOCATION" {
completion(httpRequest, .invalidStation)
} else if err == "FAIL" && errTxt == "HCI Service: request failed" {
throw ParseError(reason: "request failed")
} else if err == "PROBLEMS" && errTxt == "HCI Service: problems during service execution" {
throw ParseError(reason: "problems during service execution")
} else if err == "CGI_READ_FAILED" {
throw ParseError(reason: "cgi read failed")
} else {
throw ParseError(reason: "unknown hafas error \(err): \(errTxt)")
}
return
} else if apiVersion == "1.10", let svcResJson = encodeJson(dict: svcRes), svcResJson.length == 170 {
completion(httpRequest, .invalidStation)
return
}
guard let res = svcRes["res"] as? [String: Any], let common = res["common"] as? [String: Any], let locList = common["locL"] as? [Any], let opList = common["opL"] as? [Any], let prodList = common["prodL"] as? [Any] else {
throw ParseError(reason: "could not parse lists")
}
let locations = try parseLocList(locList: locList)
let operators = try parseOpList(opList: opList)
let lines = try parseProdList(prodList: prodList, operators: operators)
let remList = common["remL"] as? [Any]
let rems = try parseRemList(remList: remList)
var result: [StationDepartures] = []
for jny in res["jnyL"] as? [Any] ?? [] {
guard let jny = jny as? [String: Any], let stbStop = jny["stbStop"] as? [String: Any], let dateString = jny["date"] as? String, let lineIndex = (departures ? stbStop["dProdX"] : stbStop["aProdX"]) as? Int, let jnyDirTxt = jny["dirTxt"] as? String else { throw ParseError(reason: "could not parse jny") }
if let reachable = jny["isRchbl"] as? Bool, !reachable {
continue
}
if let cancelled = jny["dCncl"] as? Bool, cancelled {
continue
}
var dateComponents = DateComponents()
dateComponents.timeZone = timeZone
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
parseIsoDate(from: dateString, dateComponents: &dateComponents)
guard let baseDate = calendar.date(from: dateComponents) else { throw ParseError(reason: "could not parse base date") }
let plannedTime = try parseJsonTime(baseDate: baseDate, dateString: (departures ? stbStop["dTimeS"] : stbStop["aTimeS"]) as? String)
let predictedTime = try parseJsonTime(baseDate: baseDate, dateString: (departures ? stbStop["dTimeR"] : stbStop["aTimeR"]) as? String)
let line = lines[lineIndex]
let location: Location
if equivs {
guard let locationIndex = stbStop["locX"] as? Int else { throw ParseError(reason: "could not parse location index") }
location = locations[locationIndex]
} else {
location = Location(type: .station, id: stationId)!
}
let position = parsePosition(position: (departures ? stbStop["dPlatfR"] : stbStop["aPlatfR"]) as? String)
let plannedPosition = parsePosition(position: (departures ? stbStop["dPlatfS"] : stbStop["aPlatfS"]) as? String)
let destination: Location?
if let stopL = jny["stopL"] as? [Any] {
guard let lastIndex = (stopL.last as? [String: Any])?["locX"] as? Int, let name = (locList[lastIndex] as? [String: Any])?["name"] as? String else { throw ParseError(reason: "could not parse stop destination list") }
if jnyDirTxt == name {
destination = locations[lastIndex]
} else {
let nameAndPlace = split(stationName: stripLineFromDestination(line: line, destinationName: jnyDirTxt))
destination = Location(type: .any, id: nil, coord: nil, place: nameAndPlace.0, name: nameAndPlace.1)
}
} else {
let nameAndPlace = split(stationName: stripLineFromDestination(line: line, destinationName: jnyDirTxt))
destination = Location(type: .any, id: nil, coord: nil, place: nameAndPlace.0, name: nameAndPlace.1)
}
var message = ""
var departureCancelled = false
for msg in jny["msgL"] as? [Any] ?? [] {
guard let msg = msg as? [String: Any], let type = msg["type"] as? String, type == "REM", let remX = msg["remX"] as? Int, remX >= 0 && remX < rems?.count ?? 0, let rem = rems?[remX] else { continue }
switch rem {
case .cancelled(_):
departureCancelled = true
break
case .stopCancelled(_):
departureCancelled = true
break
case .unknown(let reason):
if let reason = reason {
if message != "" {
message += "\n"
}
message += reason.trimmingCharacters(in: .whitespacesAndNewlines)
if !message.hasSuffix(".") && !message.hasSuffix("!") {
message += "."
}
}
break
default:
break
}
}
if departureCancelled {
continue
}
let journeyContext: HafasClientInterfaceJourneyContext?
if let id = jny["jid"] as? String {
journeyContext = HafasClientInterfaceJourneyContext(journeyId: id)
} else {
journeyContext = nil
}
let wagonSequenceContext: URL?
if line.label?.hasPrefix("ICE") ?? false, let number = line.number, let plannedTime = plannedTime {
wagonSequenceContext = getWagonSequenceUrl(number: number, plannedTime: plannedTime)
} else {
wagonSequenceContext = nil
}
let departure = Departure(plannedTime: plannedTime, predictedTime: predictedTime, line: line, position: position, plannedPosition: plannedPosition, destination: destination, capacity: nil, message: !message.isEmpty ? message : nil, journeyContext: journeyContext, wagonSequenceContext: wagonSequenceContext)
var stationDepartures = result.first(where: {$0.stopLocation.id == location.id})
if stationDepartures == nil {
stationDepartures = StationDepartures(stopLocation: location, departures: [], lines: [])
result.append(stationDepartures!)
}
stationDepartures?.departures.append(departure)
}
for stationDeparture in result {
stationDeparture.departures.sort(by: {$0.getTime() < $1.getTime()})
}
completion(httpRequest, .success(departures: result, desktopUrl: desktopUrl))
}
func handleJsonTripSearch(httpRequest: HttpRequest, response: Any?, desktopUrl: URL?, from: Location, via: Location?, to: Location, date: Date, departure: Bool, previousContext: Context?, later: Bool, tripOptions: TripOptions, completion: @escaping (HttpRequest, QueryTripsResult) -> Void) throws {
guard let json = response as? [String: Any], json["err"] == nil || json["err"] as? String == "OK", let svcResL = json["svcResL"] as? [Any], svcResL.count == 1, let svcRes = svcResL[0] as? [String: Any], let meth = svcRes["meth"] as? String, meth == "TripSearch" || meth == "Reconstruction", let err = svcRes["err"] as? String else {
throw ParseError(reason: "could not parse json")
}
if err != "OK" {
let errTxt = svcRes["errTxt"] as? String ?? ""
os_log("Hafas error %{public}@: %{public}@", log: .requestLogger, type: .error, err, errTxt)
if err == "H890" { // No connections found.
completion(httpRequest, .noTrips)
} else if err == "H891" { // No route found (try entering an intermediate station).
completion(httpRequest, .noTrips)
} else if err == "H892" { // HAFAS Kernel: Request too complex (try entering less intermediate stations).
completion(httpRequest, .noTrips)
} else if err == "H895" { // Departure/Arrival are too near.
completion(httpRequest, .tooClose)
} else if err == "H9220" { // Nearby to the given address stations could not be found.
completion(httpRequest, .noTrips)
} else if err == "H886" { // HAFAS Kernel: No connections found within the requested time interval.
throw ParseError(reason: "No connections found within the requested time interval.")
} else if err == "H887" { // HAFAS Kernel: Kernel computation time limit reached.
throw ParseError(reason: "Kernel computation time limit reached.")
} else if err == "H9240" { // HAFAS Kernel: Internal error.
throw ParseError(reason: "Internal error.")
} else if err == "H9360" { // Date outside of the timetable period.
completion(httpRequest, .invalidDate)
} else if err == "H9380" { // Departure/Arrival/Intermediate or equivalent stations def'd more than once
completion(httpRequest, .tooClose)
} else if err == "FAIL" && errTxt == "HCI Service: request failed" {
throw ParseError(reason: "request failed")
} else if err == "LOCATION" && errTxt == "HCI Service: location missing or invalid" {
completion(httpRequest, .ambiguous(ambiguousFrom: [], ambiguousVia: [], ambiguousTo: []))
} else if err == "PROBLEMS" && errTxt == "HCI Service: problems during service execution" {
throw ParseError(reason: "problems during service execution")
} else if err == "CGI_READ_FAILED" {
throw ParseError(reason: "cgi read failed")
} else {
throw ParseError(reason: "unknown hafas error \(err): \(errTxt)")
}
return
}
guard let res = svcRes["res"] as? [String: Any], let common = res["common"] as? [String: Any], let locList = common["locL"] as? [Any], let opList = common["opL"] as? [Any], let prodList = common["prodL"] as? [Any] else {
throw ParseError(reason: "could not parse lists")
}
let remList = common["remL"] as? [Any]
let himList = common["himL"] as? [Any]
let locations = try parseLocList(locList: locList)
let operators = try parseOpList(opList: opList)
let lines = try parseProdList(prodList: prodList, operators: operators)
let rems = try parseRemList(remList: remList)
let messages = try parseMessageList(himList: himList)
let outConL = res["outConL"] as? [Any] ?? []
if outConL.isEmpty {
completion(httpRequest, .noTrips)
return
}
var trips: [Trip] = []
for outCon in outConL {
guard let outCon = outCon as? [String: Any], let depIndex = (outCon["dep"] as? [String: Any])?["locX"] as? Int, let arrIndex = (outCon["arr"] as? [String: Any])?["locX"] as? Int, let dateString = outCon["date"] as? String else { throw ParseError(reason: "could not parse outcon") }
let from = locations[depIndex]
let to = locations[arrIndex]
var dateComponents = DateComponents()
dateComponents.timeZone = timeZone
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
parseIsoDate(from: dateString, dateComponents: &dateComponents)
guard let baseDate = calendar.date(from: dateComponents) else { throw ParseError(reason: "failed to parse outcon base date") }
var legs: [Leg] = []
// var tripCancelled: Bool = false
for sec in outCon["secL"] as? [Any] ?? [] {
guard let sec = sec as? [String: Any], let dep = sec["dep"] as? [String: Any], let arr = sec["arr"] as? [String: Any] else { throw ParseError(reason: "could not parse outcon sec") }
let leg: Leg
switch sec["type"] as? String ?? "" {
case "JNY", "TETA":
guard let jny = sec["jny"] as? [String: Any], let prodX = jny["prodX"] as? Int, let stopL = jny["stopL"] as? [Any] else { throw ParseError(reason: "failed to parse outcon jny") }
let attrs: [Line.Attr]?
var legMessages = Set<String>()
var cancelled = jny["isCncl"] as? Bool ?? false
if let remL = jny["remL"] as? [Any] ?? jny["msgL"] as? [Any] {
var result = Set<Line.Attr>()
for rem in remL {
guard let rem = rem as? [String: Any] else { continue }
if rem["type"] as? String == "REM", let remX = rem["remX"] as? Int {
guard remX >= 0 && remX < rems?.count ?? 0, let attr = rems?[remX] else { continue }
switch attr {
case .bicycleCarriage: result.insert(.bicycleCarriage)
case .wheelChairAccess: result.insert(.wheelChairAccess)
case .boardRestaurant: result.insert(.restaurant)
case .airConditioned: result.insert(.airConditioned)
case .wifi: result.insert(.wifiAvailable)
case .powerSockets: result.insert(.powerSockets)
case .cancelled(let reason):
if let reason = reason {
legMessages.insert(reason.trimmingCharacters(in: .whitespacesAndNewlines))
}
cancelled = true
case .unknown(let reason):
if let reason = reason {
legMessages.insert(reason.trimmingCharacters(in: .whitespacesAndNewlines))
}
default:
break
}
} else if rem["type"] as? String == "HIM", let himX = rem["himX"] as? Int {
guard himX >= 0 && himX < messages?.count ?? 0, let text = messages?[himX] else { continue }
legMessages.insert(text.trimmingCharacters(in: .whitespacesAndNewlines))
}
}
attrs = result.isEmpty ? nil : Array(result)
} else {
attrs = nil
}
if let himL = jny["himL"] as? [Any] {
for him in himL {
guard let him = him as? [String: Any], let himX = him["himX"] as? Int else { throw ParseError(reason: "failed to parse him") }
guard let text = messages?[himX] else { continue }
legMessages.insert(text.trimmingCharacters(in: .whitespacesAndNewlines))
}
}
let l = lines[prodX]
let line = Line(id: l.id, network: l.network, product: l.product, label: l.label, name: l.name, number: l.number, vehicleNumber: l.vehicleNumber, style: l.style, attr: attrs, message: l.message)
let dirTxt = jny["dirTxt"] as? String
let nameAndPlace = split(stationName: stripLineFromDestination(line: line, destinationName: dirTxt))
let destination: Location? = dirTxt == nil ? nil : Location(type: .any, id: nil, coord: nil, place: nameAndPlace.0, name: nameAndPlace.1)
guard let departureStop = try parseStop(dict: dep, locations: locations, rems: rems, baseDate: baseDate, line: line), let arrivalStop = try parseStop(dict: arr, locations: locations, rems: rems, baseDate: baseDate, line: line) else { throw ParseError(reason: "failed to parse departure/arrival stop") }
var intermediateStops: [Stop] = []
for stop in stopL {
guard let stop = stop as? [String: Any] else { throw ParseError(reason: "failed to parse jny stop") }
if let border = stop["border"] as? Bool, border { continue } // hide borders from intermediate stops
guard let intermediateStop = try parseStop(dict: stop, locations: locations, rems: rems, baseDate: baseDate, line: line) else { continue }
intermediateStops.append(intermediateStop)
}
if intermediateStops.count >= 2 {
intermediateStops.removeFirst()
intermediateStops.removeLast()
}
let path: [LocationPoint]
if let polyline = try? decodePolyline(from: (jny["poly"] as? [String: Any])?["crdEncYX"] as? String) {
path = polyline
} else {
path = []
}
if cancelled {
intermediateStops.forEach({$0.departureCancelled = true; $0.arrivalCancelled = true})
}
let journeyContext: HafasClientInterfaceJourneyContext?
if let id = jny["jid"] as? String {
journeyContext = HafasClientInterfaceJourneyContext(journeyId: id)
} else {
journeyContext = nil
}
if let arrivalMessage = arrivalStop.message {
legMessages.insert(arrivalMessage)
}
leg = PublicLeg(line: line, destination: destination, departureStop: departureStop, arrivalStop: arrivalStop, intermediateStops: intermediateStops, message: legMessages.joined(separator: "\n").emptyToNil, path: path, journeyContext: journeyContext)
break
case "WALK", "TRSF", "DEVI":
guard let departureStop = try parseStop(dict: dep, locations: locations, rems: rems, baseDate: baseDate, line: nil), let arrivalStop = try parseStop(dict: arr, locations: locations, rems: rems, baseDate: baseDate, line: nil) else { throw ParseError(reason: "failed to parse departure/arrival stop") }
guard let gis = sec["gis"] as? [String: Any] else { throw ParseError(reason: "failed to parse outcon gis") }
let distance = gis["distance"] as? Int ?? 0
let addTime: TimeInterval = !legs.isEmpty ? max(0, -departureStop.getMinTime().timeIntervalSince(legs.last!.getMaxTime())) : 0
leg = IndividualLeg(type: .WALK, departureTime: departureStop.getMinTime().addingTimeInterval(addTime), departure: departureStop.location, arrival: arrivalStop.location, arrivalTime: arrivalStop.getMaxTime().addingTimeInterval(addTime), distance: distance, path: [])
break
default:
throw ParseError(reason: "could not parse outcon sec type \(sec["type"] as? String ?? "")")
}
legs.append(leg)
}
// if tripCancelled {
// continue
// }
var fares: [Fare] = []
if let trfRes = outCon["trfRes"] as? [String: Any] {
for fareSet in trfRes["fareSetL"] as? [Any] ?? [] {
guard let fareSet = fareSet as? [String: Any] else { throw ParseError(reason: "failed to parse fareset") }
let fareSetName = fareSet["name"] as? String
let fareSetDescription = fareSet["desc"] as? String
if fareSetName != nil || fareSetDescription != nil {
for fare in fareSet["fareL"] as? [Any] ?? [] {
guard let fare = fare as? [String: Any], let name = fare["name"] as? String else { throw ParseError(reason: "failed to parse fare") }
if let ticketList = fare["ticketL"] as? [Any] {
for ticket in ticketList {
guard let ticket = ticket as? [String: Any], let ticketName = ticket["name"] as? String, let currency = ticket["cur"] as? String, let priceInt = ticket["prc"] as? Int else { throw ParseError(reason: "failed to parse fare arr") }
let price = Float(priceInt) / 100.0
if let fare = parseJsonTripFare(fareSetName: name, fareSetDescription: fareSetDescription ?? "", name: ticketName, currency: currency, price: price) {
fares.append(fare)
}
}
} else {
guard let currency = fare["cur"] as? String, let priceInt = fare["prc"] as? Int else { throw ParseError(reason: "failed to parse fare obj") }
let price = Float(priceInt) / 100.0
if let fare = parseJsonTripFare(fareSetName: fareSetName ?? "", fareSetDescription: fareSetDescription ?? "", name: name, currency: currency, price: price) {
fares.append(fare)
}
}
}
} else if let fareL = fareSet["fareL"] as? [Any], let fare = fareL.first as? [String: Any], let priceInt = fare["prc"] as? Int, priceInt > 0 {
let price = Float(priceInt) / 100.0
let fare = Fare(network: "", type: .adult, currency: "EUR", fare: price, unitsName: nil, units: nil)
fares.append(fare)
}
}
}
let context: HafasClientInterfaceRefreshTripContext?
if let ctxRecon = outCon["ctxRecon"] as? String {
context = HafasClientInterfaceRefreshTripContext(contextRecon: ctxRecon, from: from, to: to)
} else {
context = nil
}
let trip = Trip(id: "", from: from, to: to, legs: legs, fares: fares, refreshContext: context)
trips.append(trip)
}
let context: Context
if let previousContext = previousContext {
context = Context(from: from, via: via, to: to, date: date, departure: departure, laterContext: later ? res["outCtxScrF"] as? String : previousContext.laterContext, earlierContext: !later ? res["outCtxScrB"] as? String : previousContext.earlierContext, desktopUrl: desktopUrl, tripOptions: tripOptions)
} else {
context = Context(from: from, via: via, to: to, date: date, departure: departure, laterContext: res["outCtxScrF"] as? String, earlierContext: res["outCtxScrB"] as? String, desktopUrl: desktopUrl, tripOptions: tripOptions)
}
completion(httpRequest, .success(context: context, from: from, via: via, to: to, trips: trips, messages: []))
}
func handleQueryJourneyDetail(httpRequest: HttpRequest, response: Any?, completion: @escaping (HttpRequest, QueryJourneyDetailResult) -> Void) throws {
guard let json = response as? [String: Any], json["err"] == nil || json["err"] as? String == "OK", let svcResL = json["svcResL"] as? [Any], svcResL.count == 1, let svcRes = svcResL[0] as? [String: Any], let meth = svcRes["meth"] as? String, meth == "JourneyDetails", let error = svcRes["err"] as? String else {
throw ParseError(reason: "could not parse json")
}
if error != "OK" {
let errTxt = svcRes["errTxt"] as? String ?? ""
print("Hafas error \(error) \(errTxt)")
if error == "LOCATION" {
completion(httpRequest, .invalidId)
} else if error == "FAIL" || error == "CGI_READ_FAILED" {
throw ParseError(reason: "cgi read failed")
} else {
throw ParseError(reason: "Unknown Hafas error \(error): \(errTxt)")
}
return
} else if apiVersion == "1.10", let svcResJson = encodeJson(dict: svcRes), svcResJson.length == 170 {
completion(httpRequest, .invalidId)
return
}
guard let res = svcRes["res"] as? [String: Any], let common = res["common"] as? [String: Any], let locList = common["locL"] as? [Any], let opList = common["opL"] as? [Any], let prodList = common["prodL"] as? [Any] else {
throw ParseError(reason: "could not parse lists")
}
let locations = try parseLocList(locList: locList)
let operators = try parseOpList(opList: opList)
let lines = try parseProdList(prodList: prodList, operators: operators)
let remList = common["remL"] as? [Any]
let rems = try parseRemList(remList: remList)
guard let journey = res["journey"] as? [String: Any], let stopL = journey["stopL"] as? [Any], let baseDateString = journey["date"] as? String else {
throw ParseError(reason: "could not parse journey stop list")
}
let path: [LocationPoint]
if let polyline = try? decodePolyline(from: (journey["poly"] as? [String: Any])?["crdEncYX"] as? String) {
path = polyline
} else {
path = []
}
var dateComponents = DateComponents()
dateComponents.timeZone = timeZone
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
parseIsoDate(from: baseDateString, dateComponents: &dateComponents)
guard let baseDate = calendar.date(from: dateComponents) else { throw ParseError(reason: "failed to parse base date") }
guard let prodX = journey["prodX"] as? Int, prodX >= 0 && prodX < lines.count else { throw ParseError(reason: "failed to parse line") }
let l = lines[prodX]
var message = ""
var attr = Set<Line.Attr>()
for msg in journey["msgL"] as? [Any] ?? [] {
guard let msg = msg as? [String: Any], let type = msg["type"] as? String, type == "REM", let remX = msg["remX"] as? Int, remX >= 0 && remX < rems?.count ?? 0, let rem = rems?[remX] else { continue }
switch rem {
case .bicycleCarriage:
attr.insert(.bicycleCarriage)
case .wheelChairAccess:
attr.insert(.wheelChairAccess)
case .boardRestaurant:
attr.insert(.restaurant)
case .airConditioned:
attr.insert(.airConditioned)
case .wifi:
attr.insert(.wifiAvailable)
case .powerSockets:
attr.insert(.powerSockets)
case .unknown(let reason):
if let reason = reason {
if message != "" {
message += "\n"
}
message += reason.trimmingCharacters(in: .whitespacesAndNewlines)
if !message.hasSuffix(".") && !message.hasSuffix("!") {
message += "."
}
}
break
default:
break
}
}
let line: Line
if !attr.isEmpty {
line = Line(id: l.id, network: l.network, product: l.product, label: l.label, name: l.name, vehicleNumber: l.vehicleNumber, style: l.style, attr: Array(attr), message: l.message)
} else {
line = l
}
var intermediateStops: [Stop] = []
for stop in stopL {
guard let stop = stop as? [String: Any] else { throw ParseError(reason: "failed to parse stop") }
if let border = stop["border"] as? Bool, border { continue } // hide borders from intermediate stops
guard let s = try parseStop(dict: stop, locations: locations, rems: rems, baseDate: baseDate, line: line) else { throw ParseError(reason: "failed to parse stop") }
intermediateStops.append(s)
}
guard intermediateStops.count >= 2 else { throw ParseError(reason: "failed to parse arr/dep stop") }
let departure = intermediateStops.removeFirst()
let arrival = intermediateStops.removeLast()
if let arrivalMessage = arrival.message {
if message != "" {
message += "\n"
}
message += arrivalMessage
}
let destination: Location?
if let dirTxt = journey["dirTxt"] as? String {
let nameAndPlace = split(stationName: stripLineFromDestination(line: line, destinationName: dirTxt))
destination = Location(type: .any, id: nil, coord: nil, place: nameAndPlace.0, name: nameAndPlace.1)
} else {
destination = arrival.location
}
let leg = PublicLeg(line: line, destination: destination, departureStop: departure, arrivalStop: arrival, intermediateStops: intermediateStops, message: !message.isEmpty ? message : nil, path: path, journeyContext: nil)
let trip = Trip(id: "", from: departure.location, to: arrival.location, legs: [leg], fares: [])
completion(httpRequest, .success(trip: trip, leg: leg))
}
// MARK: Request parameters
func jsonTripSearchRequest(from: Location, via: Location?, to: Location, date: Date, departure: Bool, tripOptions: TripOptions, previousContext: Context?, later: Bool) -> [String: Any] {
let outDate = jsonDate(from: date)
let outTime = jsonTime(from: date)
let outFrwdKey = apiVersion == "1.10" ? "frwd" : "outFrwd"
let outFrwd = departure
let jnyFltr = productsString(products: tripOptions.products ?? Product.allCases)
let meta: String
switch tripOptions.walkSpeed ?? .normal {
case .slow:
meta = "foot_speed_slow"
case .fast:
meta = "foot_speed_fast"
case .normal:
meta = "foot_speed_normal"
}
var req: [String: Any] = [
"depLocL": [
jsonLocation(from: from)
],
"arrLocL": [
jsonLocation(from: to)
],
"outDate": outDate,
"outTime": outTime,
outFrwdKey: outFrwd,
"gisFltrL": [
[
"mode": "FB",
"profile": [
"type": "F",
"linDistRouting": false,
"maxdist": 2000
],
"type": "M",
"meta": meta
]
],
"getPolyline": true,
"getPasslist": true,
"extChgTime": -1,
"trfReq": [
"jnyCl": 2,
"cType": "PK",
"tvlrProf": [[
"type": "E"
]]
]
]
if let via = via {
req["viaLocL"] = [["loc": jsonLocation(from: via)]]
}
if let previousContext = previousContext, let moreContext = later ? previousContext.laterContext : previousContext.earlierContext {
req["ctxScr"] = moreContext
}
var filterList: [[String: Any]] = [["value": jnyFltr, "mode": "BIT", "type": "PROD"]]
if let jnyFilterIncludes = jnyFilterIncludes {
filterList.append(contentsOf: jnyFilterIncludes)
}
if let accessibility = tripOptions.accessibility, accessibility != .neutral {
filterList.append([
"type": "META",
"mode": "INC",
"meta": accessibility == .limited ? "limitedBarrierfree" : "completeBarrierfree"
])
}
if let options = tripOptions.options, options.contains(.bike) {
filterList.append([
"type": "BC",
"mode": "INC"
])
}
req["jnyFltrL"] = filterList
if let maxChanges = tripOptions.maxChanges {
req["maxChg"] = maxChanges
}
if let minChangeTime = tripOptions.minChangeTime {
req["minChgTime"] = minChangeTime
}
return req
}
func wrapJsonApiRequest(meth: String, req: [String: Any], formatted: Bool) -> String? {
var dict = ["auth": apiAuthorization ?? "", "client": apiClient ?? "", "ver": apiVersion ?? "", "lang": "de", "svcReqL": [["cfg": configJson, "meth": meth, "req": req]], "formatted": formatted]
if let extVersion = extVersion {
dict["ext"] = extVersion
}
return encodeJson(dict: dict)
}
// MARK: Response parse methods
func parseJsonTripFare(fareSetName: String, fareSetDescription: String, name: String, currency: String, price: Float) -> Fare? {
if name.hasSuffix("- Jahreskarte") || name.hasSuffix("- Monatskarte") {
return nil
} else if name.hasPrefix("Vollpreis - ") {
return Fare(network: fareSetName, type: .adult, currency: currency, fare: price, unitsName: name.substring(from: 12), units: nil)
} else if name.hasPrefix("Kind - ") {
return Fare(network: fareSetName, type: .child, currency: currency, fare: price, unitsName: name.substring(from: 7), units: nil)
} else {
return nil
}
}
func parseStop(dict: [String: Any], locations: [Location], rems: [RemAttrib]?, baseDate: Date, line: Line?) throws -> Stop? {
guard let locationIndex = dict["locX"] as? Int else { throw ParseError(reason: "failed to get stop index") }
let location = locations[locationIndex]
let arrivalCancelled = dict["isCncl"] as? Bool ?? dict["aCncl"] as? Bool ?? false
let plannedArrivalTime = try parseJsonTime(baseDate: baseDate, dateString: dict["aTimeS"] as? String)
let predictedArrivalTime = try parseJsonTime(baseDate: baseDate, dateString: dict["aTimeR"] as? String)
let plannedArrivalPosition = normalize(position: dict["aPlatfS"] as? String)
let predictedArrivalPosition = normalize(position: dict["aPlatfR"] as? String)