-
Notifications
You must be signed in to change notification settings - Fork 278
/
HAAPI.swift
1350 lines (1187 loc) · 55.6 KB
/
HAAPI.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
//
// HAAPI.swift
// HomeAssistant
//
// Created by Robbie Trencheny on 3/25/16.
// Copyright © 2016 Robbie Trencheny. All rights reserved.
//
import Foundation
import Alamofire
import PromiseKit
import CoreLocation
import AlamofireObjectMapper
import ObjectMapper
import DeviceKit
import Crashlytics
import UserNotifications
import RealmSwift
import CoreMotion
import Shared
import KeychainAccess
// swiftlint:disable file_length
// swiftlint:disable:next type_body_length
public class HomeAssistantAPI {
enum APIError: Error {
case managerNotAvailable
case invalidResponse
case cantBuildURL
case notConfigured
}
public enum AuthenticationMethod {
case legacy(apiPassword: String?)
case modern(tokenInfo: TokenInfo)
}
var pushID: String?
var loadedComponents = [String]()
var baseURL: URL {
return self.connectionInfo.baseURL
}
var baseAPIURL: URL {
return self.baseURL.appendingPathComponent("api")
}
var apiPassword: String?
private(set) var manager: Alamofire.SessionManager!
var regionManager = RegionManager()
var locationManager: LocationManager?
var cachedEntities: [Entity]?
var notificationsEnabled: Bool {
return prefs.bool(forKey: "notificationsEnabled")
}
var iosComponentLoaded: Bool {
return self.loadedComponents.contains("ios")
}
var deviceTrackerComponentLoaded: Bool {
return self.loadedComponents.contains("device_tracker")
}
var iosNotifyPlatformLoaded: Bool {
return self.loadedComponents.contains("notify.ios")
}
var enabledPermissions: [String] {
var permissionsContainer: [String] = []
if self.notificationsEnabled {
permissionsContainer.append("notifications")
}
if Current.settingsStore.locationEnabled {
permissionsContainer.append("location")
}
return permissionsContainer
}
private var tokenManager: TokenManager?
private let authenticationController = AuthenticationController()
var connectionInfo: ConnectionInfo
/// Initialzie an API object with an authenticated tokenManager.
public init(connectionInfo: ConnectionInfo, authenticationMethod: AuthenticationMethod) {
self.connectionInfo = connectionInfo
switch authenticationMethod {
case .legacy(let apiPassword):
self.manager = self.configureSessionManager(withPassword: apiPassword)
case .modern(let tokenInfo):
self.tokenManager = TokenManager(baseURL: connectionInfo.baseURL, tokenInfo: tokenInfo)
tokenManager?.authenticationRequiredCallback = {
return self.authenticationController.authenticateWithBrowser(at: connectionInfo.baseURL)
}
let manager = self.configureSessionManager()
manager.retrier = self.tokenManager
manager.adapter = self.tokenManager
self.manager = manager
}
let basicAuthKeychain = Keychain(server: self.baseURL.absoluteString, protocolType: .https,
authenticationType: .httpBasic)
self.configureBasicAuthWithKeychain(basicAuthKeychain)
self.pushID = prefs.string(forKey: "pushID")
if #available(iOS 10, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings) in
prefs.setValue((settings.authorizationStatus == UNAuthorizationStatus.authorized),
forKey: "notificationsEnabled")
})
}
}
private func configureSessionManager(withPassword password: String? = nil) -> SessionManager {
var headers = Alamofire.SessionManager.defaultHTTPHeaders
if let password = password {
headers["X-HA-Access"] = password
}
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = headers
configuration.timeoutIntervalForRequest = 10 // seconds
return Alamofire.SessionManager(configuration: configuration)
}
fileprivate func configureBasicAuthWithKeychain(_ basicAuthKeychain: Keychain) {
if let basicUsername = basicAuthKeychain["basicAuthUsername"],
let basicPassword = basicAuthKeychain["basicAuthPassword"] {
self.manager.delegate.sessionDidReceiveChallenge = { session, challenge in
print("Received basic auth challenge")
let authMethod = challenge.protectionSpace.authenticationMethod
guard authMethod == NSURLAuthenticationMethodDefault ||
authMethod == NSURLAuthenticationMethodHTTPBasic ||
authMethod == NSURLAuthenticationMethodHTTPDigest else {
print("Not handling auth method", authMethod)
return (.performDefaultHandling, nil)
}
return (.useCredential, URLCredential(user: basicUsername, password: basicPassword,
persistence: .synchronizable))
}
}
}
func Connect() -> Promise<ConfigResponse> {
return Promise { seal in
GetConfig().done { config in
if let components = config.Components {
self.loadedComponents = components
}
prefs.setValue(config.ConfigDirectory, forKey: "config_dir")
prefs.setValue(config.LocationName, forKey: "location_name")
prefs.setValue(config.Latitude, forKey: "latitude")
prefs.setValue(config.Longitude, forKey: "longitude")
prefs.setValue(config.TemperatureUnit, forKey: "temperature_unit")
prefs.setValue(config.LengthUnit, forKey: "length_unit")
prefs.setValue(config.MassUnit, forKey: "mass_unit")
prefs.setValue(config.VolumeUnit, forKey: "volume_unit")
prefs.setValue(config.Timezone, forKey: "time_zone")
prefs.setValue(config.Version, forKey: "version")
Crashlytics.sharedInstance().setObjectValue(config.Version, forKey: "hass_version")
Crashlytics.sharedInstance().setObjectValue(self.loadedComponents.joined(separator: ","),
forKey: "loadedComponents")
Crashlytics.sharedInstance().setObjectValue(self.enabledPermissions.joined(separator: ","),
forKey: "allowedPermissions")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "connected"),
object: nil,
userInfo: nil)
_ = self.GetManifestJSON().done { manifest in
if let themeColor = manifest.ThemeColor {
prefs.setValue(themeColor, forKey: "themeColor")
}
}
_ = self.GetStates().done { entities in
self.cachedEntities = entities
self.storeEntities(entities: entities)
if self.loadedComponents.contains("ios") {
CLSLogv("iOS component loaded, attempting identify", getVaList([]))
_ = self.IdentifyDevice()
}
// self.GetHistory()
seal.fulfill(config)
}
}.catch {error in
print("Error at launch!", error)
Crashlytics.sharedInstance().recordError(error)
seal.reject(error)
}
}
}
public enum HomeAssistantAPIError: Error {
case notAuthenticated
}
private static var sharedAPI: HomeAssistantAPI?
public static func authenticatedAPI() -> HomeAssistantAPI? {
if let api = sharedAPI {
return api
}
guard let connectionInfo = Current.settingsStore.connectionInfo else {
return nil
}
if let tokenInfo = Current.settingsStore.tokenInfo {
let api = HomeAssistantAPI(connectionInfo: connectionInfo,
authenticationMethod: .modern(tokenInfo: tokenInfo))
self.sharedAPI = api
return api
} else {
let api = HomeAssistantAPI(connectionInfo: connectionInfo,
authenticationMethod: .legacy(apiPassword: keychain["apiPassword"]))
self.sharedAPI = api
return api
}
}
public static var authenticatedAPIPromise: Promise<HomeAssistantAPI> {
return Promise { seal in
if let api = self.authenticatedAPI() {
seal.fulfill(api)
} else {
seal.reject(APIError.notConfigured)
}
}
}
func submitLocation(updateType: LocationUpdateTrigger,
location: CLLocation?,
visit: CLVisit?,
zone: RLMZone?) {
var loc: CLLocation = CLLocation()
if let location = location {
loc = location
} else if let zone = zone {
loc = zone.location()
} else if let visit = visit {
loc = visit.location()
}
UIDevice.current.isBatteryMonitoringEnabled = true
let payload = DeviceTrackerSee(location: loc)
payload.Trigger = updateType
let isBeaconUpdate = (updateType == .BeaconRegionEnter || updateType == .BeaconRegionExit)
payload.Battery = UIDevice.current.batteryLevel
payload.DeviceID = Current.settingsStore.deviceID
payload.Hostname = UIDevice.current.name
payload.SourceType = (isBeaconUpdate ? .BluetoothLowEnergy : .GlobalPositioningSystem)
if let activity = self.regionManager.lastActivity {
payload.ActivityType = activity.activityType
payload.ActivityConfidence = activity.confidence.description
}
if let zone = zone, zone.ID == "zone.home" {
if updateType == .BeaconRegionEnter || updateType == .RegionEnter {
payload.LocationName = "home"
} else if updateType == .BeaconRegionExit || updateType == .RegionExit {
payload.LocationName = "not_home"
}
}
var jsonPayload = "{\"missing\": \"payload\"}"
if let p = payload.toJSONString(prettyPrint: false) {
jsonPayload = p
}
let payloadDict: [String: Any] = Mapper<DeviceTrackerSee>().toJSON(payload)
UIDevice.current.isBatteryMonitoringEnabled = false
let realm = Current.realm()
// swiftlint:disable:next force_try
try! realm.write {
realm.add(LocationHistoryEntry(updateType: updateType, location: loc,
zone: zone, payload: jsonPayload))
}
if self.regionManager.checkIfInsideAnyRegions(location: loc.coordinate).count > 0 {
print("Not submitting location change since we are already inside of a zone")
for activeZone in self.regionManager.zones {
print("Zone check", activeZone.ID, activeZone.inRegion)
}
return
}
firstly {
self.IdentifyDevice()
}.then {_ in
self.CallService(domain: "device_tracker", service: "see", serviceData: payloadDict,
shouldLog: false)
}.done { _ in
print("Device seen!")
}.catch { err in
print("Error when updating location!", err)
Crashlytics.sharedInstance().recordError(err as NSError)
}
self.sendLocalNotification(withZone: zone, updateType: updateType, payloadDict: payloadDict)
}
func getAndSendLocation(trigger: LocationUpdateTrigger?) -> Promise<Bool> {
var updateTrigger: LocationUpdateTrigger = .Manual
if let trigger = trigger {
updateTrigger = trigger
}
print("getAndSendLocation called via", String(describing: updateTrigger))
return Promise { seal in
regionManager.oneShotLocationActive = true
locationManager = LocationManager { location, error in
self.regionManager.oneShotLocationActive = false
if let location = location {
self.submitLocation(updateType: updateTrigger, location: location, visit: nil, zone: nil)
seal.fulfill(true)
return
}
if let error = error {
seal.reject(error)
}
}
}
}
func GetManifestJSON() -> Promise<ManifestJSON> {
return Promise { seal in
if let manager = self.manager {
let queryUrl = self.connectionInfo.activeURL.appendingPathComponent("manifest.json")
_ = manager.request(queryUrl, method: .get)
.validate()
.responseObject { (response: DataResponse<ManifestJSON>) in
switch response.result {
case .success:
if let resVal = response.result.value {
seal.fulfill(resVal)
} else {
seal.reject(APIError.invalidResponse)
}
case .failure(let error):
CLSLogv("Error on GetManifestJSON() request: %@", getVaList([error.localizedDescription]))
Crashlytics.sharedInstance().recordError(error)
seal.reject(error)
}
}
} else {
seal.reject(APIError.managerNotAvailable)
}
}
}
func GetStatus() -> Promise<StatusResponse> {
return self.request(path: "", callingFunctionName: "\(#function)", method: .get)
}
func GetConfig() -> Promise<ConfigResponse> {
return self.request(path: "config", callingFunctionName: "\(#function)")
}
func GetServices() -> Promise<[ServicesResponse]> {
return self.request(path: "services", callingFunctionName: "\(#function)")
}
func GetStates() -> Promise<[Entity]> {
return self.request(path: "states", callingFunctionName: "\(#function)")
}
func GetEntityState(entityId: String) -> Promise<Entity> {
return self.request(path: "states/\(entityId)", callingFunctionName: "\(#function)")
}
func SetState(entityId: String, state: String) -> Promise<Entity> {
return self.request(path: "states/\(entityId)", callingFunctionName: "\(#function)", method: .post,
parameters: ["state": state], encoding: JSONEncoding.default)
}
func CreateEvent(eventType: String, eventData: [String: Any]) -> Promise<String> {
return Promise { seal in
let queryUrl = self.baseAPIURL.appendingPathComponent("events/\(eventType)")
_ = manager.request(queryUrl, method: .post,
parameters: eventData, encoding: JSONEncoding.default)
.validate()
.responseJSON { response in
switch response.result {
case .success:
if let jsonDict = response.result.value as? [String: String],
let msg = jsonDict["message"] {
seal.fulfill(msg)
}
case .failure(let error):
CLSLogv("Error when attemping to CreateEvent(): %@",
getVaList([error.localizedDescription]))
Crashlytics.sharedInstance().recordError(error)
seal.reject(error)
}
}
}
}
func CallService(domain: String, service: String, serviceData: [String: Any], shouldLog: Bool = true)
-> Promise<[Entity]> {
return Promise { seal in
let queryUrl = self.baseAPIURL.appendingPathComponent("services/\(domain)/\(service)")
_ = manager.request(queryUrl, method: .post,
parameters: serviceData, encoding: JSONEncoding.default)
.validate()
.responseArray { (response: DataResponse<[Entity]>) in
switch response.result {
case .success:
if let resVal = response.result.value {
if shouldLog {
let event = ClientEvent(text: "Calling service: \(domain) - \(service)",
type: .serviceCall, payload: serviceData)
Current.clientEventStore.addEvent(event)
}
seal.fulfill(resVal)
} else {
seal.reject(APIError.invalidResponse)
}
case .failure(let error):
if let afError = error as? AFError {
var errorUserInfo: [String: Any] = [:]
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
if let errorJSON = convertToDictionary(text: utf8Text),
let errMessage = errorJSON["message"] as? String {
errorUserInfo["errorMessage"] = errMessage
}
}
CLSLogv("Error on CallService() request: %@", getVaList([afError.localizedDescription]))
Crashlytics.sharedInstance().recordError(afError)
let customError = NSError(domain: "io.robbie.HomeAssistant",
code: afError.responseCode!,
userInfo: errorUserInfo)
seal.reject(customError)
} else {
CLSLogv("Error on CallService() request: %@", getVaList([error.localizedDescription]))
Crashlytics.sharedInstance().recordError(error)
seal.reject(error)
}
}
}
}
}
func GetDiscoveryInfo(baseUrl: URL) -> Promise<DiscoveryInfoResponse> {
return self.request(path: "discover_info", callingFunctionName: "\(#function)")
}
func IdentifyDevice() -> Promise<String> {
return self.request(path: "ios/identify", callingFunctionName: "\(#function)", method: .post,
parameters: buildIdentifyDict(), encoding: JSONEncoding.default)
}
func RemoveDevice() -> Promise<String> {
return self.request(path: "ios/identify", callingFunctionName: "\(#function)", method: .delete,
parameters: buildRemovalDict(), encoding: JSONEncoding.default)
}
func RegisterDeviceForPush(deviceToken: String) -> Promise<PushRegistrationResponse> {
let queryUrl = "https://ios-push.home-assistant.io/registrations"
return Promise { seal in
Alamofire.request(queryUrl,
method: .post,
parameters: buildPushRegistrationDict(deviceToken: deviceToken),
encoding: JSONEncoding.default
).validate().responseObject {(response: DataResponse<PushRegistrationResponse>) in
switch response.result {
case .success:
if let json = response.result.value {
seal.fulfill(json)
} else {
let retErr = NSError(domain: "io.robbie.HomeAssistant",
code: 404,
userInfo: ["message": "json was nil!"])
CLSLogv("Error when attemping to registerDeviceForPush(), json was nil!: %@",
getVaList([retErr.localizedDescription]))
Crashlytics.sharedInstance().recordError(retErr)
seal.reject(retErr)
}
case .failure(let error):
CLSLogv("Error when attemping to registerDeviceForPush(): %@",
getVaList([error.localizedDescription]))
Crashlytics.sharedInstance().recordError(error)
seal.reject(error)
}
}
}
}
func GetPushSettings() -> Promise<PushConfiguration> {
return self.request(path: "ios/push", callingFunctionName: "\(#function)")
}
func turnOn(entityId: String) -> Promise<[Entity]> {
return CallService(domain: "homeassistant", service: "turn_on", serviceData: ["entity_id": entityId])
}
func turnOnEntity(entity: Entity) -> Promise<[Entity]> {
return CallService(domain: "homeassistant", service: "turn_on", serviceData: ["entity_id": entity.ID])
}
func turnOff(entityId: String) -> Promise<[Entity]> {
return CallService(domain: "homeassistant", service: "turn_off", serviceData: ["entity_id": entityId])
}
func turnOffEntity(entity: Entity) -> Promise<[Entity]> {
return CallService(domain: "homeassistant", service: "turn_off", serviceData: ["entity_id": entity.ID])
}
func toggle(entityId: String) -> Promise<[Entity]> {
return CallService(domain: "homeassistant", service: "toggle", serviceData: ["entity_id": entityId])
}
func toggleEntity(entity: Entity) -> Promise<[Entity]> {
return CallService(domain: "homeassistant", service: "toggle", serviceData: ["entity_id": entity.ID])
}
func buildIdentifyDict() -> [String: Any] {
let deviceKitDevice = Device()
let ident = IdentifyRequest()
if let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") {
if let stringedBundleVersion = bundleVersion as? String {
ident.AppBuildNumber = Int(stringedBundleVersion)
}
}
if let versionNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") {
if let stringedVersionNumber = versionNumber as? String {
ident.AppVersionNumber = stringedVersionNumber
}
}
ident.AppBundleIdentifer = Bundle.main.bundleIdentifier
ident.DeviceID = Current.settingsStore.deviceID
ident.DeviceLocalizedModel = deviceKitDevice.localizedModel
ident.DeviceModel = deviceKitDevice.model
ident.DeviceName = deviceKitDevice.name
ident.DevicePermanentID = DeviceUID.uid()
ident.DeviceSystemName = deviceKitDevice.systemName
ident.DeviceSystemVersion = deviceKitDevice.systemVersion
ident.DeviceType = deviceKitDevice.description
ident.Permissions = self.enabledPermissions
ident.PushID = pushID
ident.PushSounds = listAllInstalledPushNotificationSounds()
UIDevice.current.isBatteryMonitoringEnabled = true
switch UIDevice.current.batteryState {
case .unknown:
ident.BatteryState = "Unknown"
case .charging:
ident.BatteryState = "Charging"
case .unplugged:
ident.BatteryState = "Unplugged"
case .full:
ident.BatteryState = "Full"
}
ident.BatteryLevel = Int(UIDevice.current.batteryLevel*100)
if ident.BatteryLevel == -100 { // simulator fix
ident.BatteryLevel = 100
}
UIDevice.current.isBatteryMonitoringEnabled = false
return Mapper().toJSON(ident)
}
func buildPushRegistrationDict(deviceToken: String) -> [String: Any] {
let deviceKitDevice = Device()
let ident = PushRegistrationRequest()
if let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") {
if let stringedBundleVersion = bundleVersion as? String {
ident.AppBuildNumber = Int(stringedBundleVersion)
}
}
if let versionNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") {
if let stringedVersionNumber = versionNumber as? String {
ident.AppVersionNumber = stringedVersionNumber
}
}
if let isSandboxed = Bundle.main.object(forInfoDictionaryKey: "IS_SANDBOXED") {
if let stringedisSandboxed = isSandboxed as? String {
ident.APNSSandbox = (stringedisSandboxed == "true")
}
}
ident.AppBundleIdentifer = Bundle.main.bundleIdentifier
ident.DeviceID = Current.settingsStore.deviceID
ident.DeviceName = deviceKitDevice.name
ident.DevicePermanentID = DeviceUID.uid()
ident.DeviceSystemName = deviceKitDevice.systemName
ident.DeviceSystemVersion = deviceKitDevice.systemVersion
ident.DeviceType = deviceKitDevice.description
ident.DeviceTimezone = (NSTimeZone.local as NSTimeZone).name
ident.PushSounds = listAllInstalledPushNotificationSounds()
ident.PushToken = deviceToken
if let email = prefs.string(forKey: "userEmail") {
ident.UserEmail = email
}
if let version = prefs.string(forKey: "version") {
ident.HomeAssistantVersion = version
}
if let timeZone = prefs.string(forKey: "time_zone") {
ident.HomeAssistantTimezone = timeZone
}
return Mapper().toJSON(ident)
}
func buildRemovalDict() -> [String: Any] {
let deviceKitDevice = Device()
let ident = IdentifyRequest()
if let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") {
if let stringedBundleVersion = bundleVersion as? String {
ident.AppBuildNumber = Int(stringedBundleVersion)
}
}
if let versionNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") {
if let stringedVersionNumber = versionNumber as? String {
ident.AppVersionNumber = stringedVersionNumber
}
}
ident.AppBundleIdentifer = Bundle.main.bundleIdentifier
ident.DeviceID = Current.settingsStore.deviceID
ident.DeviceLocalizedModel = deviceKitDevice.localizedModel
ident.DeviceModel = deviceKitDevice.model
ident.DeviceName = deviceKitDevice.name
ident.DevicePermanentID = DeviceUID.uid()
ident.DeviceSystemName = deviceKitDevice.systemName
ident.DeviceSystemVersion = deviceKitDevice.systemVersion
ident.DeviceType = deviceKitDevice.description
ident.Permissions = self.enabledPermissions
ident.PushID = pushID
ident.PushSounds = listAllInstalledPushNotificationSounds()
return Mapper().toJSON(ident)
}
func setupPushActions() -> Promise<Set<UIUserNotificationCategory>> {
return Promise { seal in
self.GetPushSettings().done { pushSettings in
var allCategories = Set<UIMutableUserNotificationCategory>()
if let categories = pushSettings.Categories {
for category in categories {
let finalCategory = UIMutableUserNotificationCategory()
finalCategory.identifier = category.Identifier
var categoryActions = [UIMutableUserNotificationAction]()
if let actions = category.Actions {
for action in actions {
let newAction = UIMutableUserNotificationAction()
newAction.title = action.Title
newAction.identifier = action.Identifier
newAction.isAuthenticationRequired = action.AuthenticationRequired
newAction.isDestructive = action.Destructive
var behavior: UIUserNotificationActionBehavior = .default
if action.Behavior.lowercased() == "textinput" {
behavior = .textInput
}
newAction.behavior = behavior
let foreground = UIUserNotificationActivationMode.foreground
let background = UIUserNotificationActivationMode.background
let mode = (action.ActivationMode == "foreground") ? foreground : background
newAction.activationMode = mode
if let textInputButtonTitle = action.TextInputButtonTitle {
let titleKey = UIUserNotificationTextInputActionButtonTitleKey
newAction.parameters[titleKey] = textInputButtonTitle
}
categoryActions.append(newAction)
}
finalCategory.setActions(categoryActions,
for: UIUserNotificationActionContext.default)
allCategories.insert(finalCategory)
} else {
print("Category has no actions defined, continuing loop")
continue
}
}
}
seal.fulfill(allCategories)
}.catch { error in
CLSLogv("Error on setupPushActions() request: %@", getVaList([error.localizedDescription]))
Crashlytics.sharedInstance().recordError(error)
seal.reject(error)
}
}
}
private func sendLocalNotification(withZone: RLMZone?, updateType: LocationUpdateTrigger,
payloadDict: [String: Any]) {
let zoneName = withZone?.Name ?? "Unknown zone"
let notificationOptions = updateType.notificationOptionsFor(zoneName: zoneName)
Current.clientEventStore.addEvent(ClientEvent(text: notificationOptions.body, type: .locationUpdate,
payload: payloadDict))
if notificationOptions.shouldNotify {
if #available(iOS 10, *) {
let content = UNMutableNotificationContent()
content.title = notificationOptions.title
content.body = notificationOptions.body
content.sound = UNNotificationSound.default()
let notificationRequest =
UNNotificationRequest.init(identifier: notificationOptions.identifier ?? "",
content: content, trigger: nil)
UNUserNotificationCenter.current().add(notificationRequest)
} else {
let notification = UILocalNotification()
notification.alertTitle = notificationOptions.title
notification.alertBody = notificationOptions.body
notification.alertAction = "open"
notification.fireDate = NSDate() as Date
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.shared.scheduleLocalNotification(notification)
}
}
}
@available(iOS 10, *)
func setupUserNotificationPushActions() -> Promise<Set<UNNotificationCategory>> {
return Promise { seal in
self.GetPushSettings().done { pushSettings in
var allCategories = Set<UNNotificationCategory>()
if let categories = pushSettings.Categories {
for category in categories {
var categoryActions = [UNNotificationAction]()
if let actions = category.Actions {
for action in actions {
var actionOptions = UNNotificationActionOptions([])
if action.AuthenticationRequired { actionOptions.insert(.authenticationRequired) }
if action.Destructive { actionOptions.insert(.destructive) }
if action.ActivationMode == "foreground" { actionOptions.insert(.foreground) }
var newAction = UNNotificationAction(identifier: action.Identifier,
title: action.Title, options: actionOptions)
if action.Behavior.lowercased() == "textinput",
let btnTitle = action.TextInputButtonTitle,
let place = action.TextInputPlaceholder {
newAction = UNTextInputNotificationAction(identifier: action.Identifier,
title: action.Title,
options: actionOptions,
textInputButtonTitle: btnTitle,
textInputPlaceholder: place)
}
categoryActions.append(newAction)
}
} else {
continue
}
let finalCategory = UNNotificationCategory.init(identifier: category.Identifier,
actions: categoryActions,
intentIdentifiers: [],
options: [.customDismissAction])
allCategories.insert(finalCategory)
}
}
seal.fulfill(allCategories)
}.catch { error in
CLSLogv("Error on setupUserNotificationPushActions() request: %@",
getVaList([error.localizedDescription]))
Crashlytics.sharedInstance().recordError(error)
seal.reject(error)
}
}
}
func setupPush() {
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
if #available(iOS 10, *) {
self.setupUserNotificationPushActions().done { categories in
UNUserNotificationCenter.current().setNotificationCategories(categories)
}.catch {error -> Void in
print("Error when attempting to setup push actions", error)
Crashlytics.sharedInstance().recordError(error)
}
} else {
self.setupPushActions().done { categories in
let types: UIUserNotificationType = ([.alert, .badge, .sound])
let settings = UIUserNotificationSettings(types: types, categories: categories)
UIApplication.shared.registerUserNotificationSettings(settings)
}.catch {error -> Void in
print("Error when attempting to setup push actions", error)
Crashlytics.sharedInstance().recordError(error)
}
}
}
func handlePushAction(identifier: String, userInfo: [AnyHashable: Any], userInput: String?) -> Promise<Bool> {
return Promise { seal in
guard let api = HomeAssistantAPI.authenticatedAPI() else {
throw APIError.notConfigured
}
let device = Device()
var eventData: [String: Any] = ["actionName": identifier,
"sourceDevicePermanentID": DeviceUID.uid(),
"sourceDeviceName": device.name,
"sourceDeviceID": Current.settingsStore.deviceID]
if let dataDict = userInfo["homeassistant"] {
eventData["action_data"] = dataDict
}
if let textInput = userInput {
eventData["response_info"] = textInput
eventData["textInput"] = textInput
}
let eventType = "ios.notification_action_fired"
api.CreateEvent(eventType: eventType, eventData: eventData).done { _ -> Void in
seal.fulfill(true)
}.catch {error in
Crashlytics.sharedInstance().recordError(error)
seal.reject(error)
}
}
}
func storeEntities(entities: [Entity]) {
let storeableComponents = ["zone"]
let storeableEntities = entities.filter { (entity) -> Bool in
return storeableComponents.contains(entity.Domain)
}
for entity in storeableEntities {
// print("Storing \(entity.ID)")
if entity.Domain == "zone", let zone = entity as? Zone {
let storeableZone = RLMZone()
storeableZone.ID = zone.ID
storeableZone.Latitude = zone.Latitude
storeableZone.Longitude = zone.Longitude
storeableZone.Radius = zone.Radius
storeableZone.TrackingEnabled = zone.TrackingEnabled
storeableZone.BeaconUUID = zone.UUID
storeableZone.BeaconMajor.value = zone.Major
storeableZone.BeaconMinor.value = zone.Minor
let realm = Current.realm()
// swiftlint:disable:next force_try
try! realm.write {
realm.add(RLMZone(zone: zone), update: true)
}
}
}
}
}
class BonjourDelegate: NSObject, NetServiceBrowserDelegate, NetServiceDelegate {
var resolving = [NetService]()
var resolvingDict = [String: NetService]()
// Browser methods
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser,
didFind netService: NetService,
moreComing moreServicesComing: Bool) {
NSLog("BonjourDelegate.Browser.didFindService")
netService.delegate = self
resolvingDict[netService.name] = netService
netService.resolve(withTimeout: 0.0)
}
func netServiceDidResolveAddress(_ sender: NetService) {
NSLog("BonjourDelegate.Browser.netServiceDidResolveAddress")
if let txtRecord = sender.txtRecordData() {
let serviceDict = NetService.dictionary(fromTXTRecord: txtRecord)
let discoveryInfo = DiscoveryInfoFromDict(locationName: sender.name, netServiceDictionary: serviceDict)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "homeassistant.discovered"),
object: nil,
userInfo: discoveryInfo.toJSON())
}
}
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser,
didRemove netService: NetService,
moreComing moreServicesComing: Bool) {
NSLog("BonjourDelegate.Browser.didRemoveService")
let discoveryInfo: [NSObject: Any] = ["name" as NSObject: netService.name]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "homeassistant.undiscovered"),
object: nil,
userInfo: discoveryInfo)
resolvingDict.removeValue(forKey: netService.name)
}
private func DiscoveryInfoFromDict(locationName: String,
netServiceDictionary: [String: Data]) -> DiscoveryInfoResponse {
var outputDict: [String: Any] = [:]
for (key, value) in netServiceDictionary {
outputDict[key] = String(data: value, encoding: .utf8)
if outputDict[key] as? String == "true" || outputDict[key] as? String == "false" {
if let stringedKey = outputDict[key] as? String {
outputDict[key] = Bool(stringedKey)
}
}
}
outputDict["location_name"] = locationName
if let baseURL = outputDict["base_url"] as? String {
if baseURL.hasSuffix("/") {
outputDict["base_url"] = baseURL[..<baseURL.index(before: baseURL.endIndex)]
}
}
return DiscoveryInfoResponse(JSON: outputDict)!
}
}
class Bonjour {
var nsb: NetServiceBrowser
var nsp: NetService
var nsdel: BonjourDelegate?
init() {
let device = Device()
self.nsb = NetServiceBrowser()
self.nsp = NetService(domain: "local", type: "_hass-ios._tcp.", name: device.name, port: 65535)
}
func buildPublishDict() -> [String: Data] {
var publishDict: [String: Data] = [:]
if let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") {
if let stringedBundleVersion = bundleVersion as? String {
if let data = stringedBundleVersion.data(using: .utf8) {
publishDict["buildNumber"] = data
}
}
}
if let versionNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") {
if let stringedVersionNumber = versionNumber as? String {
if let data = stringedVersionNumber.data(using: .utf8) {
publishDict["versionNumber"] = data
}
}
}
if let permanentID = DeviceUID.uid().data(using: .utf8) {
publishDict["permanentID"] = permanentID
}
if let bundleIdentifier = Bundle.main.bundleIdentifier {
if let data = bundleIdentifier.data(using: .utf8) {
publishDict["bundleIdentifier"] = data
}
}
return publishDict
}
func startDiscovery() {
self.nsdel = BonjourDelegate()
nsb.delegate = nsdel
nsb.searchForServices(ofType: "_home-assistant._tcp.", inDomain: "local.")
}
func stopDiscovery() {
nsb.stop()
}
func startPublish() {
// self.nsdel = BonjourDelegate()
// nsp.delegate = nsdel
nsp.setTXTRecord(NetService.data(fromTXTRecord: buildPublishDict()))
nsp.publish()
}
func stopPublish() {
nsp.stop()
}
}
public typealias OnLocationUpdated = ((CLLocation?, Error?) -> Void)
class RegionManager: NSObject {
let locationManager = CLLocationManager()
var backgroundTask: UIBackgroundTaskIdentifier?
let activityManager = CMMotionActivityManager()
var lastActivity: CMMotionActivity?
var lastLocation: CLLocation?
var oneShotLocationActive: Bool = false
var zones: [RLMZone] {