forked from art-institute-of-chicago/aic-mobile-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppDataParser.swift
executable file
·1532 lines (1294 loc) · 53.7 KB
/
AppDataParser.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
/*
Abstract:
Parses the main app data file
*/
import SwiftyJSON
import CoreLocation
import Kingfisher
import MapKit
import Alamofire
class AppDataParser {
enum ParseError: Error {
case objectParseFailure
case missingKey(key: String)
case badURLString(string: String)
case badBoolString(string: String)
case badFloatString(string: String)
case badIntString(string: String)
case badCLLocationString(string: String)
case badPointString(string: String)
case newsBadDateString(dateString: String)
case audioFileNotFound(nid: Int)
case objectNotFound(nid: Int)
case galleryDisabled(galleryName: String)
case galleryNameNotFound(galleryName: String)
case galleryIdNotFound(galleryId: Int)
case tourStopsNotFound
case jsonObjectNotFoundForKey(key: String)
case noValidTourStops
case searchAutocompleteFailure
}
private var galleries = [AICGalleryModel]()
private var audioFiles = [AICAudioFileModel]()
private var objects = [AICObjectModel]()
private var restaurants = [AICRestaurantModel]()
private var tourCategories = [AICTourCategoryModel]()
private var exhibitionsInCMS = [AICExhibitionInCMS]()
private var searchArtworks = [AICObjectModel]()
private var mapFloorsURLs: [URL] = []
// MARK: App Data
func parse(appData data: Data) -> AICAppDataModel {
// TODO: Proper error handling for SwiftyJSON
let appDataJson = try! JSON(data: data)
let generalInfo = parse(generalInfoJSON: appDataJson["general_info"])
self.galleries = parse(galleriesJSON: appDataJson["galleries"])
self.audioFiles = parse(audioFilesJSON: appDataJson["audio_files"])
self.objects = parse(objectsJSON: appDataJson["objects"])
self.exhibitionsInCMS = parse(exhibitionsInCMSJSON: appDataJson["exhibitions"])
self.tourCategories = parse(tourCategoriesJSON: appDataJson["tour_categories"])
let tours = parse(toursJSON: appDataJson["tours"])
let dataSettings = parse(dataSettingsJSON: appDataJson["data"])
let searchStrings = parse(searchStringsJSON: appDataJson["search"]["search_strings"])
self.searchArtworks = parse(searchArtworks: appDataJson["search"])
let map = parse(mapFloorsJSON: appDataJson["map_floors"],
mapAnnotationsJSON: appDataJson["map_annontations"])
let appData = AICAppDataModel(generalInfo: generalInfo,
galleries: self.galleries,
objects: self.objects,
audioFiles: self.audioFiles,
tours: tours,
tourCategories: self.tourCategories,
map: map,
restaurants: self.restaurants,
dataSettings: dataSettings,
searchStrings: searchStrings,
searchArtworks: self.searchArtworks
)
// clean up data used for parsing only
self.galleries.removeAll()
self.audioFiles.removeAll()
self.objects.removeAll()
self.restaurants.removeAll()
self.searchArtworks.removeAll()
self.tourCategories.removeAll()
return appData
}
// MARK: General Info
func parse(generalInfoJSON: JSON) -> AICGeneralInfoModel {
do {
let nid = try getInt(fromJSON: generalInfoJSON, forKey: "nid")
var translations: [Common.Language: AICGeneralInfoTranslationModel] = [:]
let translationsJSON = generalInfoJSON["translations"].array
let translationEng = try parseTranslation(generalInfoJSON: generalInfoJSON)
translations[.english] = translationEng
for translationJSON in translationsJSON! {
do {
let language = try getLanguageFor(translationJSON: translationJSON)
let translation = try parseTranslation(generalInfoJSON: translationJSON)
translations[language] = translation
} catch {
if Common.Testing.printDataErrors {
print("Could not parse General Info translation:\n\(translationJSON)\n")
}
}
}
return AICGeneralInfoModel(nid: nid, translations: translations)
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC General Info Data:\n\(generalInfoJSON)\n")
}
}
return AICGeneralInfoModel(nid: 0, translations: [Common.Language: AICGeneralInfoTranslationModel]())
}
func parseTranslation(generalInfoJSON: JSON) throws -> AICGeneralInfoTranslationModel {
let museumHours = try getString(fromJSON: generalInfoJSON, forKey: "museum_hours", optional: true)
let homeMemberPrompt = try getString(fromJSON: generalInfoJSON, forKey: "home_member_prompt_text", optional: true)
let seeAllToursIntro = try getString(fromJSON: generalInfoJSON, forKey: "see_all_tours_intro", optional: true)
let audioTitle = try getString(fromJSON: generalInfoJSON, forKey: "audio_title", optional: true)
let audioSubtitle = try getString(fromJSON: generalInfoJSON, forKey: "audio_subtitle", optional: true)
let mapTitle = try getString(fromJSON: generalInfoJSON, forKey: "map_title", optional: true)
let mapSubtitle = try getString(fromJSON: generalInfoJSON, forKey: "map_subtitle", optional: true)
let infoTitle = try getString(fromJSON: generalInfoJSON, forKey: "info_title", optional: true)
let infoSubtitle = try getString(fromJSON: generalInfoJSON, forKey: "info_subtitle", optional: true)
let giftShopsTitle = try getString(fromJSON: generalInfoJSON, forKey: "gift_shops_title", optional: true)
let giftShopsText = try getString(fromJSON: generalInfoJSON, forKey: "gift_shops_text", optional: true)
let membersLoungeTitle = try getString(fromJSON: generalInfoJSON, forKey: "members_lounge_title", optional: true)
let membersLoungeText = try getString(fromJSON: generalInfoJSON, forKey: "members_lounge_text", optional: true)
let restroomsTitle = try getString(fromJSON: generalInfoJSON, forKey: "restrooms_title", optional: true)
let restroomsText = try getString(fromJSON: generalInfoJSON, forKey: "restrooms_text", optional: true)
return AICGeneralInfoTranslationModel(museumHours: museumHours.stringByDecodingHTMLEntities,
homeMemberPrompt: homeMemberPrompt.stringByDecodingHTMLEntities,
seeAllToursIntro: seeAllToursIntro,
audioTitle: audioTitle.stringByDecodingHTMLEntities,
audioSubtitle: audioSubtitle.stringByDecodingHTMLEntities,
mapTitle: mapTitle.stringByDecodingHTMLEntities,
mapSubtitle: mapSubtitle.stringByDecodingHTMLEntities,
infoTitle: infoTitle.stringByDecodingHTMLEntities,
infoSubtitle: infoSubtitle.stringByDecodingHTMLEntities,
giftShopsTitle: giftShopsTitle.stringByDecodingHTMLEntities,
giftShopsText: giftShopsText.stringByDecodingHTMLEntities,
membersLoungeTitle: membersLoungeTitle.stringByDecodingHTMLEntities,
membersLoungeText: membersLoungeText.stringByDecodingHTMLEntities,
restroomsTitle: restroomsTitle.stringByDecodingHTMLEntities,
restroomsText: restroomsText.stringByDecodingHTMLEntities
)
}
// MARK: Galleries
private func parse(galleriesJSON: JSON) -> [AICGalleryModel] {
var galleries = [AICGalleryModel]()
for (_, galleryJSON):(String, JSON) in galleriesJSON.dictionaryValue {
do {
try handleParseError({ [unowned self] in
let gallery = try self.parse(galleryJSON: galleryJSON)
galleries.append(gallery)
})
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC Gallery Data:\n\(galleryJSON)\n")
}
}
}
return galleries
}
func parse(galleryJSON: JSON?) throws -> AICGalleryModel {
let nid = try getInt(fromJSON: galleryJSON!, forKey: "nid")
let title = try getString(fromJSON: galleryJSON!, forKey: "title")
let galleryId = try getInt(fromJSON: galleryJSON!, forKey: "gallery_id")
var displayTitle = title.replacingOccurrences(of: "Gallery ", with: "")
displayTitle = displayTitle.replacingOccurrences(of: "Galleries ", with: "")
//Check for gallery disabled
let isOpen: Bool = !(try getBool(fromJSON: galleryJSON!, forKey: "closed"))
let location = try getCLLocation2d(fromJSON: galleryJSON!, forKey: "location")
// Floor 0 comes through as LL, so parse that out
let lowerLevel = try? getString(fromJSON: galleryJSON!, forKey: "floor")
let floorNumber: Int! = lowerLevel == "LL" ? 0 : try getInt(fromJSON: galleryJSON!, forKey: "floor")
let gallery = AICGalleryModel(id: nid,
galleryId: galleryId,
title: title,
displayTitle: displayTitle,
location: CoordinateWithFloor(coordinate: location, floor: floorNumber),
isOpen: isOpen
)
return gallery
}
// MARK: Objects
fileprivate func parse(objectsJSON: JSON) -> [AICObjectModel] {
var objects = [AICObjectModel]()
for (_, objectData):(String, JSON) in objectsJSON.dictionaryValue {
do {
try handleParseError({ [unowned self] in
let object = try self.parse(objectJSON: objectData)
objects.append(object)
})
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC Object Data:\n\(objectData)\n")
}
}
}
return objects
}
fileprivate func parse(objectJSON: JSON) throws -> AICObjectModel {
let nid = try getInt(fromJSON: objectJSON, forKey: "nid")
let location = try getCLLocation2d(fromJSON: objectJSON, forKey: "location")
let galleryName = try getString(fromJSON: objectJSON, forKey: "gallery_location")
let gallery = try getGallery(forGalleryName: galleryName)
let floorNumber = gallery.location.floor
let title = try getString(fromJSON: objectJSON, forKey: "title")
// Optional Fields
var objectId: Int?
do {
objectId = try getInt(fromJSON: objectJSON, forKey: "id")
} catch {}
var tombstone: String?
do {
tombstone = try getString(fromJSON: objectJSON, forKey: "artist_culture_place_delim").replacingOccurrences(of: "|", with: "\r")
} catch {}
var credits: String?
do {
credits = try getString(fromJSON: objectJSON, forKey: "credit_line")
credits = credits!.stringByDecodingHTMLEntities
} catch {}
var imageCopyright: String?
do {
imageCopyright = try getString(fromJSON: objectJSON, forKey: "copyright_notice")
imageCopyright = imageCopyright!.stringByDecodingHTMLEntities
} catch {}
// Get images
var image: URL! = nil
var thumbnail: URL! = nil
do {
// Try to load override images
image = try getURL(fromJSON: objectJSON, forKey: "image_url")
thumbnail = image
//imageHasBeenOverridden = true
} catch {
// Try loading from cms default images
image = try getURL(fromJSON: objectJSON, forKey: "large_image_full_path")
thumbnail = try getURL(fromJSON: objectJSON, forKey: "thumbnail_full_path")
}
// Get Image Crop Rects if they exist
let thumbnailCropRect: CGRect? = try? getRect(fromJSON: objectJSON, forKey: "thumbnail_crop_v2")
let imageCropRect: CGRect? = try? getRect(fromJSON: objectJSON, forKey: "large_image_crop_v2")
// Ingest all audio IDs
var audioCommentaries = [AICAudioCommentaryModel]()
if let audioCommentariesJSON = objectJSON["audio_commentary"].array {
for audioCommentaryJSON in audioCommentariesJSON {
do {
let audioCommentary = try parse(audioCommentaryJSON: audioCommentaryJSON)
audioCommentaries.append(audioCommentary)
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC AUdio Commentary Data:\n\(audioCommentaryJSON)\n")
}
}
}
}
return AICObjectModel(nid: nid,
objectId: objectId,
thumbnailUrl: thumbnail,
thumbnailCropRect: thumbnailCropRect,
imageUrl: image,
imageCropRect: imageCropRect,
title: title.stringByDecodingHTMLEntities,
audioCommentaries: audioCommentaries,
tombstone: tombstone,
credits: credits,
imageCopyright: imageCopyright,
location: CoordinateWithFloor(coordinate: location, floor: floorNumber),
gallery: gallery
)
}
// MARK: Audio Commentary
func parse(audioCommentaryJSON: JSON) throws -> AICAudioCommentaryModel {
// Selector number is optional
var selectorNumber: Int?
do {
selectorNumber = try getInt(fromJSON: audioCommentaryJSON, forKey: "object_selector_number")
} catch {}
let audioID = try getInt(fromJSON: audioCommentaryJSON, forKey: "audio")
let audioFile = try getAudioFile(forNID: audioID)
return AICAudioCommentaryModel(selectorNumber: selectorNumber,
audioFile: audioFile
)
}
// MARK: Audio Files
fileprivate func parse(audioFilesJSON: JSON) -> [AICAudioFileModel] {
var audioFiles = [AICAudioFileModel]()
for (_, audioFileData):(String, JSON) in audioFilesJSON.dictionaryValue {
do {
try handleParseError({
let audioFile = try self.parse(audioFileJSON: audioFileData)
audioFiles.append(audioFile)
})
} catch {
if Common.Testing.printDataErrors {
print("Could not parse Audio File Data:\n\(audioFileData)\n")
}
}
}
return audioFiles
}
fileprivate func parse(audioFileJSON: JSON) throws -> AICAudioFileModel {
let nid = try getInt(fromJSON: audioFileJSON, forKey: "nid")
let title = try getString(fromJSON: audioFileJSON, forKey: "title")
var translations: [Common.Language: AICAudioFileTranslationModel] = [:]
let translationsJSON = audioFileJSON["translations"].array
var translationEng = try parseTranslation(audioFileJSON: audioFileJSON)
// default to the title of the Audio File if English track title is not provided
if translationEng.trackTitle.isEmpty {
translationEng.trackTitle = title
}
translations[.english] = translationEng
for translationJSON in translationsJSON! {
do {
let language = try getLanguageFor(translationJSON: translationJSON)
var translation = try parseTranslation(audioFileJSON: translationJSON)
// default to English track title or if a Spanish/Chinese track title is not provided
if translation.trackTitle.isEmpty {
translation.trackTitle = translationEng.trackTitle
}
translations[language] = translation
} catch {
if Common.Testing.printDataErrors {
print("Could not parse Audio translation:\n\(translationJSON)\n")
}
}
}
return AICAudioFileModel(nid: nid,
translations: translations,
language: .english
)
}
func parseTranslation(audioFileJSON: JSON) throws -> AICAudioFileTranslationModel {
let url: URL = try getURL(fromJSON: audioFileJSON, forKey: "audio_file_url")!
let transcript = try getString(fromJSON: audioFileJSON, forKey: "audio_transcript", optional: true)
let trackTitle = try getString(fromJSON: audioFileJSON, forKey: "track_title", optional: true)
return AICAudioFileTranslationModel(trackTitle: trackTitle.stringByDecodingHTMLEntities,
url: url,
transcript: transcript.stringByDecodingHTMLEntities
)
}
// MARK: Tours
fileprivate func parse(tourCategoriesJSON: JSON) -> [AICTourCategoryModel] {
var categories: [AICTourCategoryModel] = []
for (_, categoryJSON):(String, JSON) in tourCategoriesJSON.dictionaryValue {
do {
let categoryID = try getString(fromJSON: categoryJSON, forKey: "category")
var titles: [Common.Language: String] = [.english: categoryID]
let translationsJSON = categoryJSON["translations"]
for translationJSON in translationsJSON.arrayValue {
let language = try getLanguageFor(translationJSON: translationJSON)
let title = try getString(fromJSON: translationJSON, forKey: "category")
titles[language] = title
}
let category = AICTourCategoryModel(
id: categoryID,
title: titles
)
categories.append(category)
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC Tour Category:\n\(categoryJSON)\n")
}
}
}
return categories
}
fileprivate func parse(toursJSON: JSON) -> [AICTourModel] {
var tours = [AICTourModel]()
for tourJSON in toursJSON.arrayValue {
do {
try handleParseError({
let tour = try self.parse(tourJSON: tourJSON)
tours.append(tour)
})
} catch {
if Common.Testing.printDataErrors {
print("Could not parse Tour Data:\n\(tourJSON)\n")
}
}
}
return tours
}
fileprivate func parse(tourJSON: JSON) throws -> AICTourModel {
let nid = try getInt(fromJSON: tourJSON, forKey: "nid")
let imageUrl: URL = try getURL(fromJSON: tourJSON, forKey: "image_url")!
let audioFileID = try getInt(fromJSON: tourJSON, forKey: "tour_audio")
let audioFile = try getAudioFile(forNID: audioFileID)
let order = try getInt(fromJSON: tourJSON, forKey: "weight")
// Selector number (optional)
var selectorNumber: Int?
do {
selectorNumber = try getInt(fromJSON: tourJSON, forKey: "selector_number")
} catch {}
// Audio Commentary
let audioCommentary = AICAudioCommentaryModel(selectorNumber: selectorNumber, audioFile: audioFile)
// Category
var category: AICTourCategoryModel?
let categoryID = try getString(fromJSON: tourJSON, forKey: "category", optional: true)
if categoryID.isEmpty == false {
for tourCategory in self.tourCategories {
if tourCategory.id == categoryID {
category = tourCategory
}
}
}
// Create Stops
var stops: [AICTourStopModel] = []
guard let stopsData = tourJSON["tour_stops"].array else {
throw ParseError.tourStopsNotFound
}
var stop = 0
for stopData in stopsData {
do {
try handleParseError({
let order = try self.getInt(fromJSON: stopData, forKey: "sort")
let objectID = try self.getInt(fromJSON: stopData, forKey: "object")
let object = try self.getObject(forNID: objectID)
let audioFileID = try self.getInt(fromJSON: stopData, forKey: "audio_id")
let audioFile = try self.getAudioFile(forNID: audioFileID)
// Selector number is optional
var audioBumper: AICAudioFileModel?
do {
let audioBumperID = try getInt(fromJSON: stopData, forKey: "audio_bumper")
audioBumper = try self.getAudioFile(forNID: audioBumperID)
} catch {
audioBumper = nil
}
let stop = AICTourStopModel(order: order,
object: object,
audio: audioFile,
audioBumper: audioBumper
)
stops.append(stop)
})
} catch {
if Common.Testing.printDataErrors {
print("Could not parse stop data:\n\(stopData) in Tour \(nid)\n")
}
}
stop = stop + 1
}
if stops.count == 0 {
throw ParseError.noValidTourStops
}
let location = try getCLLocation2d(fromJSON: tourJSON, forKey: "location")
var floor: Int?
do {
floor = try getInt(fromJSON: tourJSON, forKey: "floor")
} catch {
floor = stops.first!.object.location.floor
}
let coordinate = CoordinateWithFloor(coordinate: location, floor: floor!)
var translations: [Common.Language: AICTourTranslationModel] = [:]
let translationsJSON = tourJSON["translations"].array
let translationEng = try parseTranslation(tourJSON: tourJSON, imageUrl: imageUrl, audioFile: audioFile)
translations[.english] = translationEng
for translationJSON in translationsJSON! {
do {
let language = try getLanguageFor(translationJSON: translationJSON)
let translation = try parseTranslation(tourJSON: translationJSON, imageUrl: imageUrl, audioFile: audioFile)
translations[language] = translation
} catch {
if Common.Testing.printDataErrors {
print("Could not parse General Info translation:\n\(translationJSON)\n")
}
}
}
return AICTourModel(nid: nid,
audioCommentary: audioCommentary,
order: order,
category: category,
imageUrl: imageUrl,
location: coordinate,
allStops: stops,
translations: translations,
language: .english
)
}
func parseTranslation(tourJSON: JSON, imageUrl: URL, audioFile: AICAudioFileModel) throws -> AICTourTranslationModel {
let title = try getString(fromJSON: tourJSON, forKey: "title")
let shortDescription = try getString(fromJSON: tourJSON, forKey: "description")
var longDescription = try getString(fromJSON: tourJSON, forKey: "intro")
longDescription = "\(shortDescription)\r\r\(longDescription)"
let durationInMinutes = try? getString(fromJSON: tourJSON, forKey: "tour_duration")
return AICTourTranslationModel(title: title.stringByDecodingHTMLEntities,
shortDescription: shortDescription.stringByDecodingHTMLEntities,
longDescription: longDescription.stringByDecodingHTMLEntities,
durationInMinutes: durationInMinutes,
credits: "Copyright 2016 Art Institue of Chicago"
)
}
// MARK: Map
func parseMapFloorsURLs(fromAppData: Data) -> [URL] {
var result: [URL] = []
do {
let appDataJSON = try JSON(data: fromAppData)
let mapFloorsJSON = appDataJSON["map_floors"]
for floorNumber in 0..<Common.Map.totalFloors {
let mapFloorJSON = mapFloorsJSON["map_floor\(floorNumber)"]
let floorPdfURL: URL = try getURL(fromJSON: mapFloorJSON, forKey: "floor_plan")!
result.append(floorPdfURL)
}
} catch {
}
return result
}
func parse(mapFloorsJSON: JSON, mapAnnotationsJSON: JSON) -> AICMapModel {
do {
var floorOverlays: [FloorplanOverlay] = []
var floorGalleryAnnotations: [Int: [MapTextAnnotation]] = [:]
var floorObjectAnnotations: [Int: [MapObjectAnnotation]] = [
0: [MapObjectAnnotation](),
1: [MapObjectAnnotation](),
2: [MapObjectAnnotation](),
3: [MapObjectAnnotation]()
]
// Floors
for floorNumber in 0..<Common.Map.totalFloors {
let mapFloorJSON = mapFloorsJSON["map_floor\(floorNumber)"]
let floorPdfURL: URL = AppDataManager.sharedInstance.mapFloorURLs[floorNumber]!
let anchorPixel1 = try getPoint(fromJSON: mapFloorJSON, forKey: "anchor_pixel_1")
let anchorPixel2 = try getPoint(fromJSON: mapFloorJSON, forKey: "anchor_pixel_2")
let anchorLocation1 = try getCLLocation2d(fromJSON: mapFloorJSON, forKey: "anchor_location_1")
let anchorLocation2 = try getCLLocation2d(fromJSON: mapFloorJSON, forKey: "anchor_location_2")
let anchor1 = GeoAnchor(latitudeLongitudeCoordinate: anchorLocation1, pdfPoint: anchorPixel1)
let anchor2 = GeoAnchor(latitudeLongitudeCoordinate: anchorLocation2, pdfPoint: anchorPixel2)
let floorOverlay = FloorplanOverlay(floorplanUrl: floorPdfURL,
withPDFBox: CGPDFBox.trimBox,
andAnchors: GeoAnchorPair(fromAnchor: anchor1, toAnchor: anchor2))
floorOverlays.append(floorOverlay)
// Galleries
let galleryAnnotations = getGalleryAnnotations(forFloorNumber: floorNumber)
floorGalleryAnnotations[floorNumber] = galleryAnnotations
// Artworks
let floorObjects = self.objects.filter({ $0.location.floor == floorNumber })
var objectAnnotations: [MapObjectAnnotation] = []
for object in floorObjects {
objectAnnotations.append(MapObjectAnnotation(object: object))
}
floorObjectAnnotations[floorNumber] = objectAnnotations
}
// Annotations
var imageAnnotations: [MapImageAnnotation] = []
var landmarkAnnotations: [MapTextAnnotation] = []
var gardenAnnotations: [MapTextAnnotation] = []
var floorAmenityAnnotations: [Int: [MapAmenityAnnotation]] = [
0: [MapAmenityAnnotation](),
1: [MapAmenityAnnotation](),
2: [MapAmenityAnnotation](),
3: [MapAmenityAnnotation]()
]
var floorDepartmentAnnotations: [Int: [MapDepartmentAnnotation]] = [
0: [MapDepartmentAnnotation](),
1: [MapDepartmentAnnotation](),
2: [MapDepartmentAnnotation](),
3: [MapDepartmentAnnotation]()
]
var floorSpaceAnnotations: [Int: [MapTextAnnotation]] = [
0: [MapTextAnnotation](),
1: [MapTextAnnotation](),
2: [MapTextAnnotation](),
3: [MapTextAnnotation]()
]
for (_, annotationJSON):(String, JSON) in mapAnnotationsJSON.dictionaryValue {
do {
var floorNumber: Int?
do {
floorNumber = try getInt(fromJSON: annotationJSON, forKey: "floor")
} catch {}
let type = try getString(fromJSON: annotationJSON, forKey: "annotation_type")
if type == "Amenity" && floorNumber != nil {
let amenityAnnotation = try parse(amenityAnnotationJSON: annotationJSON, floorNumber: floorNumber!)
floorAmenityAnnotations[floorNumber!]!.append(amenityAnnotation)
} else if type == "Text" {
let textType = try getString(fromJSON: annotationJSON, forKey: "text_type")
if textType == MapTextAnnotation.AnnotationType.Space.rawValue && floorNumber != nil {
let textAnnotation = try parse(textAnnotationJSON: annotationJSON, type: MapTextAnnotation.AnnotationType.Space)
floorSpaceAnnotations[floorNumber!]!.append(textAnnotation)
} else if textType == MapTextAnnotation.AnnotationType.Landmark.rawValue {
let textAnnotation = try parse(textAnnotationJSON: annotationJSON, type: MapTextAnnotation.AnnotationType.Landmark)
landmarkAnnotations.append(textAnnotation)
} else if textType == MapTextAnnotation.AnnotationType.Garden.rawValue {
let textAnnotation = try parse(textAnnotationJSON: annotationJSON, type: MapTextAnnotation.AnnotationType.Garden)
gardenAnnotations.append(textAnnotation)
}
} else if type == "Department" && floorNumber != nil {
let departmentAnnotation = try parse(departmentAnnotationJSON: annotationJSON)
floorDepartmentAnnotations[floorNumber!]!.append(departmentAnnotation)
}
// else if type == "Image" {
// let imageAnnotation = try parse(imageAnnotationJSON: annotationJSON)
// imageAnnotations.append(imageAnnotation)
// }
// Restaurant Model
if type == "Amenity" && floorNumber != nil {
let amenityType = try getString(fromJSON: annotationJSON, forKey: "amenity_type")
if amenityType == "Dining" {
let restaurant = try parse(restaurantJSON: annotationJSON, floorNumber: floorNumber!)
self.restaurants.append(restaurant)
}
}
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC Map Annotations for node: \(annotationJSON)\n")
}
}
}
// Far Objects
var floorFarObjectAnnotations: [Int: [MapObjectAnnotation]] = [
0: [MapObjectAnnotation](),
1: [MapObjectAnnotation](),
2: [MapObjectAnnotation](),
3: [MapObjectAnnotation]()
]
// Add object visible from far to each floor
for floorNumber in 0..<Common.Map.totalFloors {
// first add all artworks from the search
for artwork in self.searchArtworks {
if artwork.location.floor == floorNumber {
if let objectAnnotation = floorObjectAnnotations[floorNumber]!.filter({ $0.nid == artwork.nid }).first as MapObjectAnnotation? {
floorFarObjectAnnotations[floorNumber]!.append(objectAnnotation)
}
}
}
}
// Lions
let lion1 = MapImageAnnotation(coordinate: CLLocationCoordinate2DMake(41.879678006591391, -87.624091248446064), image: #imageLiteral(resourceName: "Lion1"), identifier: "Lion1")
let lion2 = MapImageAnnotation(coordinate: CLLocationCoordinate2DMake(41.879491568164525, -87.624089977901931), image: #imageLiteral(resourceName: "Lion2"), identifier: "Lion2")
imageAnnotations.append(lion1)
imageAnnotations.append(lion2)
var floors: [AICMapFloorModel] = []
for floorNumber in 0..<Common.Map.totalFloors {
let floor = AICMapFloorModel(floorNumber: floorNumber,
overlay: floorOverlays[floorNumber],
objects: floorObjectAnnotations[floorNumber]!,
farObjects: floorFarObjectAnnotations[floorNumber]!,
amenities: floorAmenityAnnotations[floorNumber]!,
departments: floorDepartmentAnnotations[floorNumber]!,
galleries: floorGalleryAnnotations[floorNumber]!,
spaces: floorSpaceAnnotations[floorNumber]!
)
floors.append(floor)
}
return AICMapModel(imageAnnotations: imageAnnotations,
landmarkAnnotations: landmarkAnnotations,
gardenAnnotations: gardenAnnotations,
floors: floors)
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC Map\n")
}
}
return AICMapModel(imageAnnotations: [MapImageAnnotation](),
landmarkAnnotations: [MapTextAnnotation](),
gardenAnnotations: [MapTextAnnotation](),
floors: [AICMapFloorModel]())
}
// Gallery annotations
private func getGalleryAnnotations(forFloorNumber floorNumber: Int) -> [MapTextAnnotation] {
var galleryAnnotations: [MapTextAnnotation] = []
let galleriesForThisFloor = self.galleries.filter({ $0.location.floor == floorNumber })
for gallery in galleriesForThisFloor {
galleryAnnotations.append(MapTextAnnotation(coordinate: gallery.location.coordinate, text: gallery.displayTitle, type: MapTextAnnotation.AnnotationType.Gallery))
}
return galleryAnnotations
}
// Amenity Annotations
private func parse(amenityAnnotationJSON: JSON, floorNumber: Int) throws -> MapAmenityAnnotation {
let nid = try getInt(fromJSON: amenityAnnotationJSON, forKey: "nid")
let coordinate = try getCLLocation2d(fromJSON: amenityAnnotationJSON, forKey: "location")
let typeString = try getString(fromJSON: amenityAnnotationJSON, forKey: "amenity_type")
if let type: MapAmenityAnnotationType = MapAmenityAnnotationType(rawValue: typeString) {
return MapAmenityAnnotation(nid: nid, coordinate: coordinate, floor: floorNumber, type: type)
}
throw ParseError.badBoolString(string: typeString)
}
// Department Annotations
private func parse(departmentAnnotationJSON: JSON) throws -> MapDepartmentAnnotation {
let coordinate = try getCLLocation2d(fromJSON: departmentAnnotationJSON, forKey: "location")
let title = try getString(fromJSON: departmentAnnotationJSON, forKey: "label")
let imageUrl = try getURL(fromJSON: departmentAnnotationJSON, forKey: "image_url")!
return MapDepartmentAnnotation(coordinate: coordinate, title: title, imageUrl: imageUrl)
}
// Text Annotations
private func parse(textAnnotationJSON: JSON, type: MapTextAnnotation.AnnotationType) throws -> MapTextAnnotation {
let coordinate = try getCLLocation2d(fromJSON: textAnnotationJSON, forKey: "location")
let text = try getString(fromJSON: textAnnotationJSON, forKey: "label")
return MapTextAnnotation(coordinate: coordinate, text: text, type: type)
}
// Image Annotations
private func parse(imageAnnotationJSON: JSON) throws -> MapImageAnnotation {
let coordinate = try getCLLocation2d(fromJSON: imageAnnotationJSON, forKey: "location")
let imageUrl = try getURL(fromJSON: imageAnnotationJSON, forKey: "image_url")!
return MapImageAnnotation(coordinate: coordinate, imageUrl: imageUrl)
}
// MARK: Restaurants
func parse(restaurantJSON: JSON, floorNumber: Int) throws -> AICRestaurantModel {
let nid = try getInt(fromJSON: restaurantJSON, forKey: "nid")
let title = try getString(fromJSON: restaurantJSON, forKey: "label", optional: true)
let description = try getString(fromJSON: restaurantJSON, forKey: "description", optional: true)
let coreLocation = try getCLLocation2d(fromJSON: restaurantJSON, forKey: "location")
let location = CoordinateWithFloor(coordinate: coreLocation, floor: floorNumber)
let imageUrl: URL? = try getURL(fromJSON: restaurantJSON, forKey: "image_url", optional: true)
return AICRestaurantModel(nid: nid,
title: title,
imageUrl: imageUrl,
description: description,
location: location)
}
// MARK: Exhibitions in CMS
func parse(exhibitionsInCMSJSON: JSON) -> [AICExhibitionInCMS] {
var exhibitionsInCMS: [AICExhibitionInCMS] = []
for exhibitionJSON in exhibitionsInCMSJSON.arrayValue {
do {
try handleParseError({
let exhibitionId: Int = try getInt(fromJSON: exhibitionJSON, forKey: "exhibition_id")
let imageUrl: URL? = try getURL(fromJSON: exhibitionJSON, forKey: "image_url", optional: true)
let sort: Int = try getInt(fromJSON: exhibitionJSON, forKey: "sort")
exhibitionsInCMS.append(AICExhibitionInCMS(id: exhibitionId,
imageUrl: imageUrl,
sort: sort))
})
} catch {
if Common.Testing.printDataErrors {
print("Could not parse Exhibition in CMS:\n\(exhibitionJSON)\n")
}
}
}
return exhibitionsInCMS
}
// MARK: Data Settings
func parse(dataSettingsJSON: JSON) -> [Common.DataSetting: String] {
var dataSettings = [Common.DataSetting: String]()
do {
dataSettings[.imageServerUrl] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.imageServerUrl.rawValue)
dataSettings[.dataApiUrl] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.dataApiUrl.rawValue)
dataSettings[.exhibitionsEndpoint] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.exhibitionsEndpoint.rawValue)
dataSettings[.artworksEndpoint] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.artworksEndpoint.rawValue)
dataSettings[.galleriesEndpoint] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.galleriesEndpoint.rawValue)
dataSettings[.imagesEndpoint] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.imagesEndpoint.rawValue)
dataSettings[.eventsEndpoint] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.eventsEndpoint.rawValue)
dataSettings[.autocompleteEndpoint] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.autocompleteEndpoint.rawValue)
dataSettings[.toursEndpoint] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.toursEndpoint.rawValue)
dataSettings[.multiSearchEndpoint] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.multiSearchEndpoint.rawValue)
dataSettings[.websiteUrl] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.websiteUrl.rawValue)
dataSettings[.membershipUrl] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.membershipUrl.rawValue)
dataSettings[.ticketsUrl] = try getString(fromJSON: dataSettingsJSON, forKey: Common.DataSetting.ticketsUrl.rawValue)
} catch {
if Common.Testing.printDataErrors {
print("Could not parse Data Settings:\n\(dataSettingsJSON)\n")
}
}
return dataSettings
}
// MARK: Exhibitions
func parse(exhibitionsData data: Data) -> [AICExhibitionModel] {
var exhibitionItems: [AICExhibitionModel] = []
// TODO: Proper error handling for SwiftyJSON
let json = try! JSON(data: data)
let dataJSON: JSON = json["data"]
for exhibitionJSON: JSON in dataJSON.arrayValue {
do {
try handleParseError({ [unowned self] in
let exhibitionItem = try self.parse(exhibitionJSON: exhibitionJSON)
exhibitionItems.append(exhibitionItem)
})
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC Exhibition:\n\(exhibitionJSON)\n")
}
}
}
// Order by order in the CMS
let exhibitionsOrdered: [AICExhibitionModel] = exhibitionItems.sorted(by: { (A, B) -> Bool in
var Asort = Int.max
var Bsort = Int.max
// find exhibitions in CMS array to get the sort index
if self.exhibitionsInCMS.filter({ $0.id == A.id }).count > 0 {
Asort = self.exhibitionsInCMS.filter({ $0.id == A.id }).first!.sort
}
if self.exhibitionsInCMS.filter({ $0.id == B.id }).count > 0 {
Bsort = self.exhibitionsInCMS.filter({ $0.id == B.id }).first!.sort
}
return Asort < Bsort
})
self.exhibitionsInCMS.removeAll()
return exhibitionsOrdered
}
private func parse(exhibitionJSON: JSON) throws -> AICExhibitionModel {
let id = try getInt(fromJSON: exhibitionJSON, forKey: "id")
let title = try getString(fromJSON: exhibitionJSON, forKey: "title")
// optional description
let description: String = try getString(fromJSON: exhibitionJSON, forKey: "short_description", optional: true)
// Image
var imageURL: URL?
let exhibitionUrl = try getString(fromJSON: exhibitionJSON, forKey: "image_url")
let fullExhibitionUrl: String = exhibitionUrl + "&w=600"
imageURL = URL(string: fullExhibitionUrl)
// Override with exhibitions optional images from CMS, if available
if self.exhibitionsInCMS.filter({ $0.id == id }).count > 0 {
let url = self.exhibitionsInCMS.filter({ $0.id == id }).first!.imageUrl
if url != nil {
imageURL = url
}
}
// optional location
var galleryId: Int?
var location: CoordinateWithFloor?
do {
let id = try getInt(fromJSON: exhibitionJSON, forKey: "gallery_id")
let gallery = try getGallery(forGalleryId: id)
galleryId = id
location = gallery.location
} catch {}
// Get date exibition ends
let startDateString = try getString(fromJSON: exhibitionJSON, forKey: "aic_start_at")
let endDateString = try getString(fromJSON: exhibitionJSON, forKey: "aic_end_at")
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
guard let startDate: Date = dateFormatter.date(from: startDateString) else {
throw ParseError.newsBadDateString(dateString: startDateString)
}
guard let endDate: Date = dateFormatter.date(from: endDateString) else {
throw ParseError.newsBadDateString(dateString: endDateString)
}
// Return news item
return AICExhibitionModel(
id: id,
title: title.stringByDecodingHTMLEntities,
shortDescription: description.stringByDecodingHTMLEntities,
imageUrl: imageURL,
startDate: startDate,
endDate: endDate,
galleryId: galleryId,
location: location
)
}
// MARK: Events
func parse(eventsData data: Data) -> [AICEventModel] {
var eventItems: [AICEventModel] = []
// TODO: Proper error handling for SwiftyJSON
let json = try! JSON(data: data)
let dataJson: JSON = json["data"]
for eventJson: JSON in dataJson.arrayValue {
do {
try handleParseError({ [unowned self] in
let eventItem = try self.parse(eventJson: eventJson)
eventItems.append(eventItem)
})
} catch {
if Common.Testing.printDataErrors {
print("Could not parse AIC Event:\n\(json)\n")
}
}