Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Some code formatting

Eric Bariauxcc75f0e1dfa4
diff --git a/console/iOS/NotificationExtension/NotificationService.swift b/console/iOS/NotificationExtension/NotificationService.swift
index e17c49f34..5b8507efe 100644
--- a/console/iOS/NotificationExtension/NotificationService.swift
+++ b/console/iOS/NotificationExtension/NotificationService.swift
@@ -21,10 +21,10 @@
import UserNotifications
class NotificationService: UNNotificationServiceExtension, URLSessionDelegate {
-
+
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
-
+
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
@@ -34,8 +34,8 @@ class NotificationService: UNNotificationServiceExtension, URLSessionDelegate {
let defaults = UserDefaults(suiteName: AppGroup.entitlement)
defaults?.synchronize()
-
- guard let tkurlRequest = URL(string:String(format: "\(Server.scheme)://%@/auth/realms/%@/protocol/openid-connect/token",Server.hostURL,Server.realm))
+
+ guard let tkurlRequest = URL(string:String(format: "\(Server.scheme)://%@/auth/realms/%@/protocol/openid-connect/token", Server.hostURL, Server.realm))
else { return }
let tkRequest = NSMutableURLRequest(url: tkurlRequest)
tkRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
@@ -45,7 +45,7 @@ class NotificationService: UNNotificationServiceExtension, URLSessionDelegate {
let sessionConfiguration = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
let req = session.dataTask(with: tkRequest as URLRequest, completionHandler: { (data, response, error) in
- if (data != nil){
+ if (data != nil) {
do {
let jsonDictionnary: Dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
if ((jsonDictionnary["access_token"]) != nil) {
@@ -63,34 +63,33 @@ class NotificationService: UNNotificationServiceExtension, URLSessionDelegate {
//print(String(data: data!, encoding: .utf8) ?? "")
let json = try JSONSerialization.jsonObject(with: data!) as? [[String: Any]]
if (json?.count)! > 0 {
- let detailedJson = (json?[0])! as [String: Any]
- bestAttemptContent.title = detailedJson["title"] as! String
- bestAttemptContent.body = detailedJson["message"] as! String
- bestAttemptContent.userInfo["appUrl"] = detailedJson["appUrl"]
- bestAttemptContent.userInfo["alertId"] = detailedJson["id"]
- let actions = detailedJson["actions"] as! [[String : Any]]
- var notificationActions = [UNNotificationAction]()
- for var i in (0..<actions.count) {
- let actionTitle = actions[i]["title"]! as! String
- let actionType = actions[i]["type"]! as! String
- switch actionType {
- case ActionType.ACTION_ACTUATOR :
- bestAttemptContent.userInfo["actions"] = actions[i]
-
- notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.destructive))
- case ActionType.ACTION_DEEP_LINK :
- notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.foreground))
- default : break
-
- }
+ let detailedJson = (json?[0])! as [String: Any]
+ bestAttemptContent.title = detailedJson["title"] as! String
+ bestAttemptContent.body = detailedJson["message"] as! String
+ bestAttemptContent.userInfo["appUrl"] = detailedJson["appUrl"]
+ bestAttemptContent.userInfo["alertId"] = detailedJson["id"]
+ let actions = detailedJson["actions"] as! [[String : Any]]
+ var notificationActions = [UNNotificationAction]()
+ for var i in (0..<actions.count) {
+ let actionTitle = actions[i]["title"]! as! String
+ let actionType = actions[i]["type"]! as! String
+ switch actionType {
+ case ActionType.ACTION_ACTUATOR :
+ bestAttemptContent.userInfo["actions"] = actions[i]
+
+ notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.destructive))
+ case ActionType.ACTION_DEEP_LINK :
+ notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.foreground))
+ default : break
+ }
i += 1
- }
- let categoryName = "openremoteNotification"
- let category = UNNotificationCategory(identifier: categoryName, actions: notificationActions, intentIdentifiers: [], options: [])
- let categories : Set = [category]
- UNUserNotificationCenter.current().setNotificationCategories(categories)
+ }
+ let categoryName = "openremoteNotification"
+ let category = UNNotificationCategory(identifier: categoryName, actions: notificationActions, intentIdentifiers: [], options: [])
+ let categories : Set = [category]
+ UNUserNotificationCenter.current().setNotificationCategories(categories)
} else {
- bestAttemptContent.body = "could not deserialize JSON"
+ bestAttemptContent.body = "could not deserialize JSON"
}
} catch {
bestAttemptContent.body = "could not deserialize JSON"
@@ -122,7 +121,7 @@ class NotificationService: UNNotificationServiceExtension, URLSessionDelegate {
}
})
req.resume()
-
+
}
}
@@ -144,7 +143,6 @@ class NotificationService: UNNotificationServiceExtension, URLSessionDelegate {
} else {
completionHandler(.performDefaultHandling,nil)
}
-
}
}
}
diff --git a/console/iOS/console/AppDelegate.swift b/console/iOS/console/AppDelegate.swift
index 7ce87e977..46f5e2ce0 100644
--- a/console/iOS/console/AppDelegate.swift
+++ b/console/iOS/console/AppDelegate.swift
@@ -115,86 +115,79 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
switch response.actionIdentifier {
case ActionType.ACTION_DEEP_LINK :
if let urlToOpen = response.notification.request.content.userInfo["appUrl"] { // until now we are considering anchor name (without the #)
- guard let urlRequest = URL(string:String(format: "%@://%@/%@%@",Server.scheme, Server.hostURL, Server.navigationPath, urlToOpen as! String)) else { return }
+ guard let urlRequest = URL(string:String(format: "%@://%@/%@%@", Server.scheme, Server.hostURL, Server.navigationPath, urlToOpen as! String)) else { return }
(self.window?.rootViewController as! ViewController).loadUrl(url:urlRequest)
- NSLog("Action asked : %@",response.actionIdentifier)
+ NSLog("Action asked : %@", response.actionIdentifier)
}
case ActionType.ACTION_ACTUATOR :
- NSLog("Action asked : %@",response.actionIdentifier)
+ NSLog("Action asked : %@", response.actionIdentifier)
if let actions = response.notification.request.content.userInfo["actions"] {
assetId = (actions as! Dictionary<String,String>)["assetId"]!
- attributeName = (actions as! Dictionary<String,String>)["attributeName"]!
- rawJson = (actions as! Dictionary<String,String>)["rawJson"]!
+ attributeName = (actions as! Dictionary<String,String>)["attributeName"]!
+ rawJson = (actions as! Dictionary<String,String>)["rawJson"]!
}
(self.window?.rootViewController as! ViewController).updateAssetAttribute(assetId : assetId, attributeName : attributeName, rawJson : rawJson)
default : break
}
if let alertId = response.notification.request.content.userInfo["alertId"] {
-
- TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in
- switch accessTokenResult {
- case .Failure(let error) :
- UIApplication.shared.isNetworkActivityIndicatorVisible = false
- ErrorManager.showError(error: error!)
- case .Success(let accessToken) :
- guard let urlRequest = URL(string: String(format:"%@%i", Server.deleteNotifiedAlertResource, alertId as! Int)) else { return }
- let request = NSMutableURLRequest(url: urlRequest)
- request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
- request.httpMethod = "DELETE"
- let postString = String(format:"token=%@&device_id=%@", TokenManager.sharedInstance.deviceId!, (UIDevice.current.identifierForVendor?.uuidString)!)
- request.httpBody = postString.data(using: .utf8)
- request.addValue(String(format:"Bearer %@", accessToken!), forHTTPHeaderField: "Authorization")
- let sessionConfiguration = URLSessionConfiguration.default
- let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
- let reqDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
- DispatchQueue.main.async {
- UIApplication.shared.isNetworkActivityIndicatorVisible = false
- if (error != nil) {
- NSLog("error %@", (error! as NSError).localizedDescription)
- let error = NSError(domain: "", code: 0, userInfo: [
- NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")
- ])
- ErrorManager.showError(error: error)
- } else {
- if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 204 {
+ TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in
+ switch accessTokenResult {
+ case .Failure(let error) :
+ UIApplication.shared.isNetworkActivityIndicatorVisible = false
+ ErrorManager.showError(error: error!)
+ case .Success(let accessToken) :
+ guard let urlRequest = URL(string: String(format:"%@%i", Server.deleteNotifiedAlertResource, alertId as! Int)) else { return }
+ let request = NSMutableURLRequest(url: urlRequest)
+ request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
+ request.httpMethod = "DELETE"
+ let postString = String(format:"token=%@&device_id=%@", TokenManager.sharedInstance.deviceId!, (UIDevice.current.identifierForVendor?.uuidString)!)
+ request.httpBody = postString.data(using: .utf8)
+ request.addValue(String(format:"Bearer %@", accessToken!), forHTTPHeaderField: "Authorization")
+ let sessionConfiguration = URLSessionConfiguration.default
+ let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
+ let reqDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
+ DispatchQueue.main.async {
+ UIApplication.shared.isNetworkActivityIndicatorVisible = false
+ if (error != nil) {
+ NSLog("error %@", (error! as NSError).localizedDescription)
let error = NSError(domain: "", code: 0, userInfo: [
- NSLocalizedDescriptionKey : NSLocalizedString("ErrorSendingDeviceId", value: "Could not delete server alert", comment: "")
+ NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")
])
ErrorManager.showError(error: error)
} else {
- NSLog("Deleted notification alert %i",alertId as! Int)
+ if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 204 {
+ let error = NSError(domain: "", code: 0, userInfo: [
+ NSLocalizedDescriptionKey : NSLocalizedString("ErrorSendingDeviceId", value: "Could not delete server alert", comment: "")
+ ])
+ ErrorManager.showError(error: error)
+ } else {
+ NSLog("Deleted notification alert %i",alertId as! Int)
+ }
}
}
- }
- })
- reqDataTask.resume()
+ })
+ reqDataTask.resume()
+ }
}
-
- }
- completionHandler()
+ completionHandler()
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
- return true
+ return true
}
-
- func connectToFcm()
- {
+ func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
- if (error != nil)
- {
+ if (error != nil) {
if let token = FIRInstanceID.instanceID().token() {
NSLog("Connected to FCM. Token is %@",token as String)
TokenManager.sharedInstance.storeDeviceId(token: token)
}
- }
- else
- {
+ } else {
if let token = FIRInstanceID.instanceID().token() {
NSLog("Connected to FCM. Token is %@",token as String)
TokenManager.sharedInstance.storeDeviceId(token: token)
@@ -203,8 +196,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
}
}
- func tokenRefreshNotification(notification: NSNotification)
- {
+ func tokenRefreshNotification(notification: NSNotification) {
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
@@ -258,6 +250,3 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
}
}
}
-
-
-
diff --git a/console/iOS/console/ORViewController.swift b/console/iOS/console/ORViewController.swift
index 28600416d..b26abb54e 100644
--- a/console/iOS/console/ORViewController.swift
+++ b/console/iOS/console/ORViewController.swift
@@ -89,7 +89,7 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
if let response = navigationResponse.response as? HTTPURLResponse {
if response.statusCode != 200 && response.statusCode != 204 {
decisionHandler(.cancel)
- NSLog("error http status : %@ message : %@",response.statusCode,response.description)
+ NSLog("error http status : %@ message : %@", response.statusCode, response.description)
let error = NSError(domain: "", code: 0, userInfo: [
NSLocalizedDescriptionKey : NSLocalizedString("HTTPErrorReturned", value: "Connection Error", comment: "")
])
@@ -144,7 +144,6 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
} else {
completionHandler(.performDefaultHandling, nil)
}
-
}
}
@@ -183,7 +182,7 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
UIApplication.shared.isNetworkActivityIndicatorVisible = false
ErrorManager.showError(error: error!)
case .Success(let accessToken) :
- guard let urlRequest = URL(string: String(String(format: "\(Server.scheme)://%@/%@/asset/%@/attribute/%@", Server.hostURL, Server.realm, assetId,attributeName))) else { return }
+ guard let urlRequest = URL(string: String(String(format: "\(Server.scheme)://%@/%@/asset/%@/attribute/%@", Server.hostURL, Server.realm, assetId, attributeName))) else { return }
let request = NSMutableURLRequest(url: urlRequest)
request.httpMethod = "PUT"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
@@ -207,5 +206,4 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
}
}
}
-
}