Skip to content

Commit

Permalink
Ensure HAAPI is always initialized before doing any API operations. M…
Browse files Browse the repository at this point in the history
…ove Keychain and Prefs into AppDelegate as a global.
  • Loading branch information
robbiet480 committed Apr 20, 2017
1 parent da07bab commit c96bec3
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 134 deletions.
46 changes: 40 additions & 6 deletions HomeAssistant/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,22 @@ import PromiseKit
import RealmSwift
import UserNotifications
import AlamofireNetworkActivityIndicator
import KeychainAccess

let realmConfig = Realm.Configuration(schemaVersion: 3, migrationBlock: nil)

// swiftlint:disable:next force_try
let realm = try! Realm(configuration: realmConfig)

let keychain = Keychain(service: "io.robbie.homeassistant", accessGroup: "UTQFCBPQRF.io.robbie.HomeAssistant")

let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant")!

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant")!

// swiftlint:disable:next line_length
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Expand Down Expand Up @@ -54,8 +57,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

// swiftlint:disable:next line_length
if (prefs.object(forKey: "openInChrome") == nil && OpenInChromeController().isChromeInstalled()) || OpenInChromeController().isChromeInstalled() {
self.prefs.setValue(true, forKey: "openInChrome")
self.prefs.synchronize()
prefs.setValue(true, forKey: "openInChrome")
prefs.synchronize()
}

window = UIWindow.init(frame: UIScreen.main.bounds)
Expand Down Expand Up @@ -89,7 +92,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

self.prefs.setValue(tokenString, forKey: "deviceToken")
prefs.setValue(tokenString, forKey: "deviceToken")

print("Registering push with tokenString: \(tokenString)")

Expand All @@ -100,7 +103,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
print("Registered for push. Platform: \(resp.SNSPlatform ?? "MISSING"), PushID: \(pushId)")
CLSLogv("Registered for push:", getVaList([pushId]))
Crashlytics.sharedInstance().setUserIdentifier(pushId)
self.prefs.setValue(pushId, forKey: "pushID")
prefs.setValue(pushId, forKey: "pushID")
HomeAssistantAPI.sharedInstance.pushID = pushId
_ = HomeAssistantAPI.sharedInstance.identifyDevice()
}
Expand All @@ -119,6 +122,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Received remote notification in completion handler!")

if HomeAssistantAPI.sharedInstance.Configured == false {
if let baseURL = keychain["baseURL"], let apiPass = keychain["apiPassword"] {
HomeAssistantAPI.sharedInstance.Setup(baseURL: baseURL, password: apiPass,
deviceID: keychain["deviceID"])
}
}

if let userInfoDict = userInfo as? [String:Any] {
if let hadict = userInfoDict["homeassistant"] as? [String:String] {
if let command = hadict["command"] {
Expand Down Expand Up @@ -155,6 +165,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Background fetch activated!")
if HomeAssistantAPI.sharedInstance.Configured == false {
if let baseURL = keychain["baseURL"], let apiPass = keychain["apiPassword"] {
HomeAssistantAPI.sharedInstance.Setup(baseURL: baseURL, password: apiPass,
deviceID: keychain["deviceID"])
}
}
HomeAssistantAPI.sharedInstance.sendOneshotLocation().then { success -> Void in
if success == true {
completionHandler(UIBackgroundFetchResult.newData)
Expand All @@ -172,6 +188,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
forRemoteNotification userInfo: [AnyHashable : Any],
withResponseInfo responseInfo: [AnyHashable : Any],
completionHandler: @escaping () -> Void) {
if HomeAssistantAPI.sharedInstance.Configured == false {
if let baseURL = keychain["baseURL"], let apiPass = keychain["apiPassword"] {
HomeAssistantAPI.sharedInstance.Setup(baseURL: baseURL, password: apiPass,
deviceID: keychain["deviceID"])
}
}
var userInput: String?
if let userText = responseInfo[UIUserNotificationActionResponseTypedTextKey] as? String {
userInput = userText
Expand All @@ -184,6 +206,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ app: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if HomeAssistantAPI.sharedInstance.Configured == false {
if let baseURL = keychain["baseURL"], let apiPass = keychain["apiPassword"] {
HomeAssistantAPI.sharedInstance.Setup(baseURL: baseURL, password: apiPass,
deviceID: keychain["deviceID"])
}
}
var serviceData: [String:String] = url.queryItems!
serviceData["sourceApplication"] = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
switch url.host! {
Expand Down Expand Up @@ -214,6 +242,12 @@ extension AppDelegate: UNUserNotificationCenterDelegate {
public func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if HomeAssistantAPI.sharedInstance.Configured == false {
if let baseURL = keychain["baseURL"], let apiPass = keychain["apiPassword"] {
HomeAssistantAPI.sharedInstance.Setup(baseURL: baseURL, password: apiPass,
deviceID: keychain["deviceID"])
}
}
var userText: String?
if let textInput = response as? UNTextInputNotificationResponse {
userText = textInput.userText
Expand Down
2 changes: 1 addition & 1 deletion HomeAssistant/Classes/Entity.swift
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ open class HomeAssistantTimestampTransform: DateFormatterTransform {
let formatter = DateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let HATimezone = UserDefaults(suiteName: "group.io.robbie.homeassistant")!.string(forKey: "time_zone") {
if let HATimezone = prefs.string(forKey: "time_zone") {
formatter.timeZone = TimeZone(identifier: HATimezone)!
} else {
formatter.timeZone = TimeZone.autoupdatingCurrent
Expand Down
6 changes: 2 additions & 4 deletions HomeAssistant/HAAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ import Crashlytics
import RealmSwift
import UserNotifications

let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant")!

let APIClientSharedInstance = HomeAssistantAPI()

// swiftlint:disable file_length
Expand Down Expand Up @@ -61,7 +59,7 @@ public class HomeAssistantAPI {

var cachedEntities: [Entity]?

func Setup(baseURL: String, password: String, deviceID: String?) -> Promise<StatusResponse> {
func Setup(baseURL: String, password: String, deviceID: String?) {
self.baseURL = baseURL
self.baseAPIURL = baseURL+"/api/"
if let dID = deviceID {
Expand Down Expand Up @@ -92,7 +90,7 @@ public class HomeAssistantAPI {
deviceToken = deviceTok
}

return GetStatus()
return

}

Expand Down
19 changes: 6 additions & 13 deletions HomeAssistant/Utilities/Utils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,6 @@ func migrateUserDefaultsToAppGroups() {

func migrateSecretsToKeychain() {

let keychain = Keychain(service: "io.robbie.homeassistant", accessGroup: "UTQFCBPQRF.io.robbie.homeassistant")

let groupDefaults = UserDefaults(suiteName: "group.io.robbie.homeassistant")

let didMigrateToKeychain = "DidMigrateSecretsToKeychain"
Expand All @@ -274,8 +272,6 @@ func migrateSecretsToKeychain() {

func migrateDeviceIDToKeychain() {

let keychain = Keychain(service: "io.robbie.homeassistant", accessGroup: "UTQFCBPQRF.io.robbie.homeassistant")

let groupDefaults = UserDefaults(suiteName: "group.io.robbie.homeassistant")

let didMigrateToKeychain = "DidMigrateDeviceIDToKeychain"
Expand All @@ -296,7 +292,6 @@ func migrateDeviceIDToKeychain() {
}

func resetStores() {
let keychain = Keychain(service: "io.robbie.homeassistant", accessGroup: "UTQFCBPQRF.io.robbie.HomeAssistant")
do {
try keychain.removeAll()
} catch {
Expand All @@ -316,15 +311,13 @@ func openURLStringInBrowser(url: String) {
}

func openURLInBrowser(urlToOpen: URL) {
if let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant") {
if OpenInChromeController.sharedInstance.isChromeInstalled() && prefs.bool(forKey: "openInChrome") {
_ = OpenInChromeController.sharedInstance.openInChrome(urlToOpen, callbackURL: nil)
if OpenInChromeController.sharedInstance.isChromeInstalled() && prefs.bool(forKey: "openInChrome") {
_ = OpenInChromeController.sharedInstance.openInChrome(urlToOpen, callbackURL: nil)
} else {
if #available(iOS 10, *) {
UIApplication.shared.open(urlToOpen, options: [:], completionHandler: nil)
} else {
if #available(iOS 10, *) {
UIApplication.shared.open(urlToOpen, options: [:], completionHandler: nil)
} else {
_ = UIApplication.shared.openURL(urlToOpen)
}
_ = UIApplication.shared.openURL(urlToOpen)
}
}
}
Expand Down
43 changes: 18 additions & 25 deletions HomeAssistant/Views/RootTabBarViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ import KeychainAccess

class RootTabBarViewController: UITabBarController, UITabBarControllerDelegate {

let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant")!

override func viewDidLoad() {
super.viewDidLoad()

Expand All @@ -32,30 +30,25 @@ class RootTabBarViewController: UITabBarController, UITabBarControllerDelegate {

override func viewDidAppear(_ animated: Bool) {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
let keychain = Keychain(service: "io.robbie.homeassistant", accessGroup: "UTQFCBPQRF.io.robbie.HomeAssistant")
if let baseURL = keychain["baseURL"], let apiPass = keychain["apiPassword"] {
firstly {
// swiftlint:disable:next line_length
HomeAssistantAPI.sharedInstance.Setup(baseURL: baseURL, password: apiPass, deviceID: keychain["deviceID"])
}.then {_ in
HomeAssistantAPI.sharedInstance.Connect()
}.then { _ -> Void in
if HomeAssistantAPI.sharedInstance.notificationsEnabled {
UIApplication.shared.registerForRemoteNotifications()
}
print("Connected!")
hud.hide(animated: true)
self.loadTabs()
return
}.catch {err -> Void in
print("ERROR on connect!!!", err)
hud.hide(animated: true)
let settingsView = SettingsViewController()
settingsView.showErrorConnectingMessage = true
settingsView.showErrorConnectingMessageError = err
settingsView.doneButton = true
let navController = UINavigationController(rootViewController: settingsView)
self.present(navController, animated: true, completion: nil)
HomeAssistantAPI.sharedInstance.Setup(baseURL: baseURL, password: apiPass, deviceID: keychain["deviceID"])
HomeAssistantAPI.sharedInstance.Connect().then { _ -> Void in
if HomeAssistantAPI.sharedInstance.notificationsEnabled {
UIApplication.shared.registerForRemoteNotifications()
}
print("Connected!")
hud.hide(animated: true)
self.loadTabs()
return
}.catch {err -> Void in
print("ERROR on connect!!!", err)
hud.hide(animated: true)
let settingsView = SettingsViewController()
settingsView.showErrorConnectingMessage = true
settingsView.showErrorConnectingMessageError = err
settingsView.doneButton = true
let navController = UINavigationController(rootViewController: settingsView)
self.present(navController, animated: true, completion: nil)
}
} else {
let settingsView = SettingsViewController()
Expand Down
16 changes: 7 additions & 9 deletions HomeAssistant/Views/SettingsDetailViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import Crashlytics

class SettingsDetailViewController: FormViewController {

let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant")!

var detailGroup: String = "display"

// swiftlint:disable:next function_body_length cyclomatic_complexity
Expand All @@ -32,15 +30,15 @@ class SettingsDetailViewController: FormViewController {
$0.title = L10n.SettingsDetails.General.Chrome.title
$0.value = prefs.bool(forKey: "openInChrome")
}.onChange { row in
self.prefs.setValue(row.value, forKey: "openInChrome")
self.prefs.synchronize()
prefs.setValue(row.value, forKey: "openInChrome")
prefs.synchronize()
}
// <<< SwitchRow("allowAllGroups") {
// $0.title = "Show all groups"
// $0.value = prefs.bool(forKey: "allowAllGroups")
// }.onChange { row in
// self.prefs.setValue(row.value, forKey: "allowAllGroups")
// self.prefs.synchronize()
// prefs.setValue(row.value, forKey: "allowAllGroups")
// prefs.synchronize()
// }
case "location":
self.title = L10n.SettingsDetails.Location.title
Expand All @@ -51,23 +49,23 @@ class SettingsDetailViewController: FormViewController {
$0.value = prefs.bool(forKey: "enterNotifications")
}.onChange({ (row) in
if let val = row.value {
self.prefs.set(val, forKey: "enterNotifications")
prefs.set(val, forKey: "enterNotifications")
}
})
<<< SwitchRow {
$0.title = L10n.SettingsDetails.Location.Notifications.Exit.title
$0.value = prefs.bool(forKey: "exitNotifications")
}.onChange({ (row) in
if let val = row.value {
self.prefs.set(val, forKey: "exitNotifications")
prefs.set(val, forKey: "exitNotifications")
}
})
<<< SwitchRow {
$0.title = L10n.SettingsDetails.Location.Notifications.LocationChange.title
$0.value = prefs.bool(forKey: "significantLocationChangeNotifications")
}.onChange({ (row) in
if let val = row.value {
self.prefs.set(val, forKey: "significantLocationChangeNotifications")
prefs.set(val, forKey: "significantLocationChangeNotifications")
}
})
if let cachedEntities = HomeAssistantAPI.sharedInstance.cachedEntities {
Expand Down

0 comments on commit c96bec3

Please sign in to comment.