Skip to content

armgit / core

Public Imported from GitHub
0

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

Made implemented notification with custom notification.

Michael Rademakera783e22c9edf
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsActivity.java b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsActivity.java
index 8681a4efa..d1ce70608 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsActivity.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsActivity.java
@@ -183,11 +183,13 @@ public class AdminUserNotificationsActivity
AlertNotification alertNotification = new AlertNotification(
"Hello User",
"This is a test message.",
+ // TODO: Remove below once consoles updated to use action appUrl
"/#"
);
AlertAction alertAction = new AlertAction();
alertAction.setTitle(environment.getMessages().notificationOpenApplicationDetails());
alertAction.setActionType(ActionType.LINK);
+ alertAction.setAppUrl("/#");
alertNotification.addAction(alertAction);
return alertNotification;
}
diff --git a/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj b/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj
index addf97a47..96c22ed85 100644
--- a/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj
+++ b/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj
@@ -8,6 +8,7 @@
/* Begin PBXBuildFile section */
4C4C2FB81FD8044A0071CBDA /* ORNotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C4C2FB71FD8044A0071CBDA /* ORNotificationService.swift */; };
+ 4C56E5E520C583FB004483C7 /* ORAssetResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C56E5E420C583FB004483C7 /* ORAssetResource.swift */; };
4C77278520BC13E800322CBC /* PushNotificationProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C77278320BC13E800322CBC /* PushNotificationProvider.swift */; };
4C77278620BC13E800322CBC /* GeofenceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C77278420BC13E800322CBC /* GeofenceProvider.swift */; };
4C82D73F1FC58ED2009DE853 /* ORLib.h in Headers */ = {isa = PBXBuildFile; fileRef = 4C82D73D1FC58ED2009DE853 /* ORLib.h */; settings = {ATTRIBUTES = (Public, ); }; };
@@ -24,6 +25,7 @@
/* Begin PBXFileReference section */
4C4C2FB71FD8044A0071CBDA /* ORNotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ORNotificationService.swift; sourceTree = "<group>"; };
+ 4C56E5E420C583FB004483C7 /* ORAssetResource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ORAssetResource.swift; sourceTree = "<group>"; };
4C77278320BC13E800322CBC /* PushNotificationProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushNotificationProvider.swift; sourceTree = "<group>"; };
4C77278420BC13E800322CBC /* GeofenceProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeofenceProvider.swift; sourceTree = "<group>"; };
4C82D73A1FC58ED2009DE853 /* ORLib.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ORLib.framework; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -96,6 +98,7 @@
4C82D73D1FC58ED2009DE853 /* ORLib.h */,
4C82D73E1FC58ED2009DE853 /* Info.plist */,
4C4C2FB71FD8044A0071CBDA /* ORNotificationService.swift */,
+ 4C56E5E420C583FB004483C7 /* ORAssetResource.swift */,
);
path = ORLib;
sourceTree = "<group>";
@@ -236,6 +239,7 @@
buildActionMask = 2147483647;
files = (
4C77278620BC13E800322CBC /* GeofenceProvider.swift in Sources */,
+ 4C56E5E520C583FB004483C7 /* ORAssetResource.swift in Sources */,
4C77278520BC13E800322CBC /* PushNotificationProvider.swift in Sources */,
4C4C2FB81FD8044A0071CBDA /* ORNotificationService.swift in Sources */,
4C82D7581FC590FB009DE853 /* ErrorManager.swift in Sources */,
@@ -371,7 +375,6 @@
};
4C82D7431FC58ED2009DE853 /* Debug */ = {
isa = XCBuildConfiguration;
- baseConfigurationReference = C641D9E59892499E90E68616 /* Pods-ORLib.debug.xcconfig */;
buildSettings = {
CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = NO;
CLANG_ENABLE_MODULES = YES;
@@ -414,7 +417,6 @@
};
4C82D7441FC58ED2009DE853 /* Release */ = {
isa = XCBuildConfiguration;
- baseConfigurationReference = 572EED7F064AF79DDABE9FC8 /* Pods-ORLib.release.xcconfig */;
buildSettings = {
CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = NO;
CLANG_ENABLE_MODULES = YES;
diff --git a/console/iOS/ORLib/ORLib.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate b/console/iOS/ORLib/ORLib.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate
index c96bbd4d1..4c2ad43b2 100644
Binary files a/console/iOS/ORLib/ORLib.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate and b/console/iOS/ORLib/ORLib.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate differ
diff --git a/console/iOS/ORLib/ORLib/ConsoleProviders/GeofenceProvider.swift b/console/iOS/ORLib/ORLib/ConsoleProviders/GeofenceProvider.swift
index 15b1dffd9..da521ff46 100644
--- a/console/iOS/ORLib/ORLib/ConsoleProviders/GeofenceProvider.swift
+++ b/console/iOS/ORLib/ORLib/ConsoleProviders/GeofenceProvider.swift
@@ -108,7 +108,7 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
fetchGeofences()
}
- public func fetchGeofences(callback: (([GeofenceDefinition]) -> ())? = nil) {
+ func fetchGeofences(callback: (([GeofenceDefinition]) -> ())? = nil) {
if let tkurlRequest = URL(string: "\(baseURL)/\(geofenceFetchEndpoint)\(consoleId)") {
let tkRequest = NSMutableURLRequest(url: tkurlRequest)
tkRequest.httpMethod = "GET"
@@ -141,31 +141,21 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
}
}
- private func sendGeofenceRequest(url: URL, data:[String: Any]?) {
+ private func sendGeofenceRequest(url: URL, data:[String: Any]) {
let request = NSMutableURLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField:"Content-Type");
request.httpMethod = "POST"
- if (data != nil) {
- if let postBody = try? JSONSerialization.data(withJSONObject: data!, options: []) {
- request.httpBody = postBody
- }
- }
+ let refreshToken = TokenManager.sharedInstance.refreshToken
- let sessionConfiguration = URLSessionConfiguration.default
- let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
- let req = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
- if (data != nil){
+ if let postBody = try? JSONSerialization.data(withJSONObject: data, options: []) {
+ if refreshToken != nil {
+ ORAssetResoure.sharedInstance.updateAssetAttribute(assetId: consoleId, attributeName: "location", rawJson: postBody)
} else {
- NSLog("error %@", (error! as NSError).localizedDescription)
- let error = NSError(domain: "", code: 0, userInfo: [
- NSLocalizedDescriptionKey : NSLocalizedString("NoDataReceived", value: "Did not receive any data", comment: "")
- ])
- print(error)
+ ORAssetResoure.sharedInstance.updatePublicAssetAttibute(assetId: consoleId, attributeName: "location", rawJson: postBody)
}
- })
- req.resume()
+ }
}
public class GeofenceDefinition: NSObject, Decodable {
@@ -187,11 +177,9 @@ extension GeofenceProvider: CLLocationManagerDelegate {
guard let tkurlRequest = URL(string: "\(baseURL)\(postString)") else { return }
let postData = [
- "objectValue" : [
- "type": "Point",
- "coordinates": [manager.location?.coordinate.longitude, manager.location?.coordinate.latitude]
- ]
- ]
+ "type": "Point",
+ "coordinates": [manager.location?.coordinate.longitude, manager.location?.coordinate.latitude]
+ ] as [String : Any]
sendGeofenceRequest(url: tkurlRequest, data: postData)
}
@@ -204,7 +192,12 @@ extension GeofenceProvider: CLLocationManagerDelegate {
}
guard let tkurlRequest = URL(string: "\(baseURL)\(postString)") else { return }
- sendGeofenceRequest(url: tkurlRequest, data: nil)
+ let postData = [
+ "type": "Point",
+ "coordinates": [0, 0]
+ ] as [String : Any]
+
+ sendGeofenceRequest(url: tkurlRequest, data: postData)
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
diff --git a/console/iOS/ORLib/ORLib/ORAssetResource.swift b/console/iOS/ORLib/ORLib/ORAssetResource.swift
new file mode 100644
index 000000000..150e0ce65
--- /dev/null
+++ b/console/iOS/ORLib/ORLib/ORAssetResource.swift
@@ -0,0 +1,60 @@
+//
+// ORAssetResoure.swift
+// GoogleToolboxForMac
+//
+// Created by Michael Rademaker on 04/06/2018.
+//
+
+import UIKit
+
+open class ORAssetResoure: NSObject, URLSessionDelegate {
+
+ public static let sharedInstance = ORAssetResoure()
+
+ private override init() {
+ super.init()
+ }
+
+ open func updateAssetAttribute(assetId : String, attributeName : String, rawJson : Data) {
+ UIApplication.shared.isNetworkActivityIndicatorVisible = true
+ TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in
+ switch accessTokenResult {
+ case .Failure(let error) :
+ UIApplication.shared.isNetworkActivityIndicatorVisible = false
+ ErrorManager.showError(error: error!)
+ case .Success(let accessToken) :
+ self.updateAssetAttribute(assetId: assetId, attributeName: attributeName, accessToken: accessToken, rawJson: rawJson)
+ }
+ }
+ }
+
+ open func updatePublicAssetAttibute(assetId : String, attributeName : String, rawJson : Data) {
+ updateAssetAttribute(assetId: assetId, attributeName: attributeName, accessToken: nil, rawJson: rawJson)
+ }
+
+ private func updateAssetAttribute(assetId : String, attributeName : String, accessToken :String?, rawJson : Data) {
+ guard let urlRequest = URL(string: String(String(format: "\(ORServer.scheme)://%@/%@/asset/%@/attribute/%@", ORServer.hostURL, ORServer.realm, assetId, attributeName))) else { return }
+ let request = NSMutableURLRequest(url: urlRequest)
+ request.httpMethod = "PUT"
+ request.addValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = rawJson
+ if let token = accessToken {
+ request.addValue(String(format:"Bearer %@", token), 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)
+ }
+ }
+ })
+ reqDataTask.resume()
+ }
+}
diff --git a/console/iOS/ORLib/ORLib/ORNotificationService.swift b/console/iOS/ORLib/ORLib/ORNotificationService.swift
index a18e59599..64add3a08 100644
--- a/console/iOS/ORLib/ORLib/ORNotificationService.swift
+++ b/console/iOS/ORLib/ORLib/ORNotificationService.swift
@@ -28,99 +28,38 @@ open class ORNotificationService: UNNotificationServiceExtension, URLSessionDele
open override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
- NSLog("NotifExtension Change content : %@ ", bestAttemptContent?.userInfo ?? "")
+ print("NotifExtension Change content : %@ ", bestAttemptContent?.userInfo ?? "")
if let bestAttemptContent = bestAttemptContent {
- // Call backend to get payload and adapt title, body and actions
- let defaults = UserDefaults(suiteName: ORAppGroup.entitlement)
-
- defaults?.synchronize()
-
- guard let tkurlRequest = URL(string:String(format: "\(ORServer.scheme)://%@/auth/realms/%@/protocol/openid-connect/token", ORServer.hostURL, ORServer.realm))
- else { return }
- let tkRequest = NSMutableURLRequest(url: tkurlRequest)
- tkRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
- tkRequest.httpMethod = "POST"
- let postString = String(format: "grant_type=refresh_token&refresh_token=%@&client_id=openremote", defaults!.object(forKey: DefaultsKey.refreshToken) as! CVarArg)
- tkRequest.httpBody = postString.data(using: .utf8)
- 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) {
- do {
- let jsonDictionnary: Dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
- if ((jsonDictionnary["access_token"]) != nil) {
- guard let urlRequest = URL(string: ORServer.apiTestResource) else { return }
- let request = NSMutableURLRequest(url: urlRequest)
- request.addValue(String(format:"Bearer %@", jsonDictionnary["access_token"] as! String), 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 {
- if (error != nil) {
- bestAttemptContent.body = error.debugDescription
- } else {
- do {
- //print(String(data: data!, encoding: .utf8) ?? "")
- let json = try JSONSerialization.jsonObject(with: data!) as? [[String: Any]]
- if (json?.count)! > 0 {
- let categoryName = "openremoteNotification"
- let detailedJson = (json?[0])! as [String: Any]
- bestAttemptContent.categoryIdentifier = categoryName
- 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 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 category = UNNotificationCategory(identifier: categoryName, actions: notificationActions, intentIdentifiers: [], options: [])
- let categories : Set = [category]
- UNUserNotificationCenter.current().setNotificationCategories(categories)
- } else {
- bestAttemptContent.body = "could not deserialize JSON"
- }
- } catch {
- bestAttemptContent.body = "could not deserialize JSON"
- }
- contentHandler(bestAttemptContent)
- }
+ if let actionsString = bestAttemptContent.userInfo["actions"] as? String {
+ if let actionsData = actionsString.data(using: .utf8){
+ if let actions = try? JSONSerialization.jsonObject(with: actionsData, options: []) as? [[String: String]], actions != nil {
+ let categoryName = "openremoteNotification"
+ bestAttemptContent.categoryIdentifier = categoryName
+ var notificationActions = [UNNotificationAction]()
+ for i in (0..<actions!.count) {
+ let actionTitle = actions![i]["title"]!
+ let actionType = actions![i]["type"]!
+ 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 :
+ if let appUrl = actions![i]["appUrl"] {
+ bestAttemptContent.userInfo["appUrl"] = appUrl
+ notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.foreground))
+ } else {
+ notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.destructive))
}
- })
- reqDataTask.resume()
- } else {
- if let httpResponse = response as? HTTPURLResponse {
- let error = NSError(domain: "", code: httpResponse.statusCode, userInfo: jsonDictionnary)
- bestAttemptContent.body = error.debugDescription
- contentHandler(bestAttemptContent)
- } else {
- let error = NSError(domain: "", code: 0, userInfo: jsonDictionnary)
- bestAttemptContent.body = error.debugDescription
- contentHandler(bestAttemptContent)
+ default : break
}
}
+ let category = UNNotificationCategory(identifier: categoryName, actions: notificationActions, intentIdentifiers: [], options: [])
+ let categories : Set = [category]
+ UNUserNotificationCenter.current().setNotificationCategories(categories)
}
- catch let error as NSError {
- bestAttemptContent.body = error.debugDescription
- contentHandler(bestAttemptContent)
- }
- } else {
- bestAttemptContent.body = error.debugDescription
- contentHandler(bestAttemptContent)
}
- })
- req.resume()
-
+ contentHandler(bestAttemptContent)
+ }
}
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
index af81c704c..a748caebf 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
@@ -370,7 +370,10 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
// Process asynchronously but block for a little while waiting for the result
Map<String, Object> headers = new HashMap<>();
headers.put(AttributeEvent.HEADER_SOURCE, CLIENT);
- headers.put(Constants.AUTH_CONTEXT, getAuthContext());
+ //TODO needed for anonymous?
+ if(isAuthenticated()) {
+ headers.put(Constants.AUTH_CONTEXT, getAuthContext());
+ }
Object result = messageBrokerService.getProducerTemplate().requestBodyAndHeaders(
AssetProcessingService.ASSET_QUEUE, event, headers
);
diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java b/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java
index 8ec50058d..064521df0 100644
--- a/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java
@@ -164,7 +164,8 @@ public class FCMDeliveryService {
// Use alert dictionary for apns
// https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html
- apsBuilder.setAlert(ApsAlert.builder().setTitle(notification.getTitle()).setBody(notification.getBody()).build());
+ apsBuilder.setAlert(ApsAlert.builder().setTitle(notification.getTitle()).setBody(notification.getBody()).build())
+ .setSound("default");
webpushConfigBuilder.setNotification(new WebpushNotification(notification.getTitle(), notification.getBody()));
}
@@ -178,8 +179,6 @@ public class FCMDeliveryService {
// set the following APNS flag to allow console to customise the notification before delivery and to ensure delivery
apsBuilder.setMutableContent(true);
- // TODO: Tidy up APNS config
- apsBuilder.setContentAvailable(true);
if (timeToLiveSeconds != null) {
timeToLiveSeconds = Math.max(timeToLiveSeconds, 0);