Skip to content

armgit / core

Public Imported from GitHub
0

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

Adding filter on asset fo user, work notification action actuator

Mica Hallin902c0c03cce3
diff --git a/console/android/build.gradle b/console/android/build.gradle
index cc7db2377..4798ae0ae 100644
--- a/console/android/build.gradle
+++ b/console/android/build.gradle
@@ -35,6 +35,7 @@ dependencies {
compile "com.google.firebase:firebase-core:$fcmVersion"
compile "com.google.firebase:firebase-messaging:$fcmVersion"
compile "com.squareup.retrofit2:converter-jackson:$jacksonVersion"
+ compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion"
}
android {
diff --git a/console/android/src/main/AndroidManifest.xml b/console/android/src/main/AndroidManifest.xml
index 943bd14a4..9dd97d891 100644
--- a/console/android/src/main/AndroidManifest.xml
+++ b/console/android/src/main/AndroidManifest.xml
@@ -43,6 +43,10 @@
</intent-filter>
</service>
+ <service android:name="org.openremote.android.ORMessagingActionService">
+
+ </service>
+
<service
android:name="org.openremote.android.ORFirebaseInstanceIDService">
<intent-filter>
diff --git a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
index 3d45b23b8..c79ffc078 100644
--- a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
+++ b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
@@ -113,10 +113,10 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
private void sendNotification(AlertNotification alertNotification) {
int notificationId = alertNotification.getId().hashCode();
- Intent intent = new Intent(this, MainActivity.class);
- intent.putExtra("notifcation", alertNotification);
- intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- PendingIntent pendingIntent = PendingIntent.getActivity(this, notificationId, intent,
+ Intent intent = new Intent(this, ORMessagingActionService.class);
+ intent.putExtra("notification", alertNotification);
+
+ PendingIntent pendingIntent = PendingIntent.getService(this, notificationId, intent,
PendingIntent.FLAG_ONE_SHOT);
@@ -125,14 +125,19 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(alertNotification.getTitle())
.setContentText(alertNotification.getMessage())
-
+ .setDeleteIntent(pendingIntent)
.setSmallIcon(R.drawable.app_icon)
- .setAutoCancel(true)
.setWhen(0)
.setSound(defaultSoundUri);
for (AlertAction alertAction : alertNotification.getActions()) {
- notificationBuilder = notificationBuilder.addAction(new NotificationCompat.Action(R.drawable.empty, alertAction.getTitle(), pendingIntent));
+ Intent actionIntent = new Intent(this, ORMessagingActionService.class);
+ actionIntent.putExtra("action", alertAction);
+ actionIntent.putExtra("notification", alertNotification);
+ actionIntent.setAction(Long.toString(System.currentTimeMillis()));
+ PendingIntent actionPendingIntent = PendingIntent.getService(this, notificationId, actionIntent,
+ PendingIntent.FLAG_ONE_SHOT);
+ notificationBuilder = notificationBuilder.addAction(new NotificationCompat.Action(R.drawable.empty, alertAction.getTitle(), actionPendingIntent));
}
NotificationManager notificationManager =
diff --git a/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java b/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java
new file mode 100644
index 000000000..bc722d8ca
--- /dev/null
+++ b/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java
@@ -0,0 +1,47 @@
+package org.openremote.android;
+
+import android.app.IntentService;
+import android.app.NotificationManager;
+import android.app.Service;
+import android.content.Intent;
+import android.support.annotation.Nullable;
+
+import org.openremote.android.service.AlertAction;
+import org.openremote.android.service.AlertNotification;
+import org.openremote.android.service.TokenService;
+
+public class ORMessagingActionService extends IntentService {
+
+ private TokenService tokenService;
+
+ public ORMessagingActionService() {
+ super("org.openremote.android.ORMessagingActionService");
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ tokenService = new TokenService(getApplicationContext());
+ }
+
+ @Override
+ protected void onHandleIntent(@Nullable Intent intent) {
+ AlertNotification notification = (AlertNotification) intent.getSerializableExtra("notification");
+ tokenService.deleteAlert(notification.getId());
+
+ NotificationManager manager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
+ manager.cancel(notification.getId().hashCode());
+
+ if(intent.hasExtra("action")) {
+
+ AlertAction alertAction = (AlertAction) intent.getSerializableExtra("action");
+ if (AlertNotification.ActionType.ACTUATOR.equals(alertAction.getType())) {
+ tokenService.executeAction(alertAction);
+ } else {
+ //TODO : open app and pass rawJson to webView
+ }
+ }
+
+
+ }
+}
diff --git a/console/android/src/main/java/org/openremote/android/service/AlertNotification.java b/console/android/src/main/java/org/openremote/android/service/AlertNotification.java
index 71961d43d..a56538e07 100644
--- a/console/android/src/main/java/org/openremote/android/service/AlertNotification.java
+++ b/console/android/src/main/java/org/openremote/android/service/AlertNotification.java
@@ -92,7 +92,7 @@ public class AlertNotification implements Serializable {
public enum ActionType {
- ACTION_TYPE1,
- ACTION_TYPE2
+ ACTUATOR,
+ LINK
}
}
diff --git a/console/android/src/main/java/org/openremote/android/service/NotificationService.java b/console/android/src/main/java/org/openremote/android/service/NotificationService.java
index 2af4871a6..c769e4599 100644
--- a/console/android/src/main/java/org/openremote/android/service/NotificationService.java
+++ b/console/android/src/main/java/org/openremote/android/service/NotificationService.java
@@ -4,10 +4,13 @@ package org.openremote.android.service;
import java.util.List;
import retrofit2.Call;
+import retrofit2.http.Body;
+import retrofit2.http.DELETE;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Header;
+import retrofit2.http.Headers;
import retrofit2.http.PUT;
import retrofit2.http.Path;
@@ -20,4 +23,10 @@ public interface NotificationService {
@GET("/{realm}/notification/alert")
Call<List<AlertNotification>> getAlertNotification(@Path("realm") String realm, @Header("Authorization") String authorization);
+ @DELETE("/{realm}/notification/alert/{id}")
+ Call<Void> deleteNotification(@Path("realm") String realm, @Header("Authorization") String authorization,@Path("id") Long id);
+
+ @PUT("/{realm}/asset/{assetId}/attribute/{attributeName}")
+ @Headers("Content-Type:application/json")
+ Call<Void> updateAssetAction(@Path("realm") String realm, @Header("Authorization") String accessToken,@Path("assetId") String assetId,@Path("attributeName") String attributeName,@Body String rawJson);
}
diff --git a/console/android/src/main/java/org/openremote/android/service/TokenCallback.java b/console/android/src/main/java/org/openremote/android/service/TokenCallback.java
index f414809e3..3e853871f 100644
--- a/console/android/src/main/java/org/openremote/android/service/TokenCallback.java
+++ b/console/android/src/main/java/org/openremote/android/service/TokenCallback.java
@@ -1,7 +1,9 @@
package org.openremote.android.service;
+import java.io.IOException;
+
interface TokenCallback {
- void onToken(String accessToken);
+ void onToken(String accessToken) throws IOException;
void onFailure(Throwable t);
}
diff --git a/console/android/src/main/java/org/openremote/android/service/TokenService.java b/console/android/src/main/java/org/openremote/android/service/TokenService.java
index 125f30cef..973d37d0b 100644
--- a/console/android/src/main/java/org/openremote/android/service/TokenService.java
+++ b/console/android/src/main/java/org/openremote/android/service/TokenService.java
@@ -16,6 +16,9 @@ import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
+import retrofit2.converter.scalars.ScalarsConverterFactory;
+
+import static android.R.attr.id;
public class TokenService {
@@ -33,6 +36,7 @@ public class TokenService {
public TokenService(Context context) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(context.getString(R.string.OR_BASE_SERVER))
+ .addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(JacksonConverterFactory.create())
.build();
@@ -84,7 +88,11 @@ public class TokenService {
public void onResponse(Call<Map<String, String>> call, Response<Map<String, String>> response) {
Log.i("TOKEN_SERVICE", "response : " + response.body());
if (response.body() != null) {
- callback.onToken("Bearer " + response.body().get("access_token"));
+ try {
+ callback.onToken("Bearer " + response.body().get("access_token"));
+ } catch (IOException e) {
+ callback.onFailure(e);
+ }
} else {
callback.onFailure(new NullPointerException());
}
@@ -164,4 +172,38 @@ public class TokenService {
editor.remove(tokenIdKey);
editor.commit();
}
+
+ public void deleteAlert(final Long id) {
+
+ getAuthorization(new TokenCallback() {
+ @Override
+ public void onToken(String accessToken) throws IOException {
+ notificationService.deleteNotification(realm, accessToken,id).execute();
+
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ Log.e("TOKEN_SERVICE","Error deleting notification",t);
+ }
+ });
+
+
+ }
+
+ public void executeAction(final AlertAction alertAction) {
+ getAuthorization(new TokenCallback() {
+ @Override
+ public void onToken(String accessToken) throws IOException {
+ notificationService.updateAssetAction(realm, accessToken,alertAction.getAssetId(),alertAction.getAttributeName(),alertAction.getRawJson()).execute();
+
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ Log.e("TOKEN_SERVICE","Error deleting notification",t);
+ }
+ });
+
+ }
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
index 90495ac12..9d5f570f7 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
@@ -245,6 +245,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
// Check attribute exists
AssetAttributes attributes = new AssetAttributes(asset);
+
if (!attributes.hasAttribute(attributeName))
throw new WebApplicationException(NOT_FOUND);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java b/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java
index fe436ada3..350b45e80 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java
@@ -19,6 +19,7 @@
*/
package org.openremote.manager.server.notification;
+import org.apache.http.NoHttpResponseException;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
@@ -35,6 +36,7 @@ import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.Response;
import java.util.List;
+import java.util.logging.Level;
import java.util.logging.Logger;
public class NotificationService implements ContainerService {
@@ -105,25 +107,29 @@ public class NotificationService implements ContainerService {
if (fcmKey != null) {
List<DeviceNotificationToken> allTokenForUser = findAllTokenForUser(userId);
for (DeviceNotificationToken notificationToken : allTokenForUser) {
- Invocation.Builder builder = target.request().header("Authorization", "key="+fcmKey);
- Response response = builder.post(Entity.entity(new FCMMessage(notificationToken.getToken()), "application/json"));
- if (response.getStatus() != 200) {
- LOG.severe("Error send FCM notification status=["+response.getStatus()+"], statusInformation=[" +response.getStatusInfo()+"]");
+
+ try {
+ Invocation.Builder builder = target.request().header("Authorization", "key=" + fcmKey);
+ Response response = builder.post(Entity.entity(new FCMMessage(notificationToken.getToken()), "application/json"));
+ if (response.getStatus() != 200) {
+ LOG.severe("Error send FCM notification status=[" + response.getStatus() + "], statusInformation=[" + response.getStatusInfo() + "]");
+ }
+ response.close();
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Error sending notiifcation to FCM", e);
}
- response.close();
}
}
});
-
}
public List<AlertNotification> getPendingAlertForUserId(String userId) {
return persistenceService.doReturningTransaction(entityManager -> {
Query query = entityManager.createQuery("SELECT an FROM AlertNotification an WHERE an.userId =:userId and an.deliveryStatus =:deliveryStatus");
query.setParameter("userId", userId);
- query.setParameter("deliveryStatus",DeliveryStatus.PENDING);
+ query.setParameter("deliveryStatus", DeliveryStatus.PENDING);
return query.getResultList();
});
}
@@ -132,9 +138,9 @@ public class NotificationService implements ContainerService {
persistenceService.doTransaction(entityManager -> {
Query query = entityManager.createQuery("UPDATE AlertNotification SET deliveryStatus=:status WHERE id =:id");
query.setParameter("id", id);
- query.setParameter("status",DeliveryStatus.DELIVERED);
+ query.setParameter("status", DeliveryStatus.DELIVERED);
query.executeUpdate();
- });
+ });
}
public List<String> findAllUsersWithToken() {
@@ -148,4 +154,14 @@ public class NotificationService implements ContainerService {
public String toString() {
return getClass().getSimpleName() + "{}";
}
+
+ public List<String> findAllUsersWithTokenForAsset(String assetId) {
+ return persistenceService.doReturningTransaction(entityManager -> {
+
+ Query query = entityManager.createQuery("SELECT DISTINCT dnt.id.userId FROM DeviceNotificationToken dnt, UserAsset us WHERE us.userId = dnt.id.userId AND us.assetId = :assetId");
+ query.setParameter("assetId", assetId);
+ return query.getResultList();
+ });
+
+ }
}
\ No newline at end of file
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
index 8257bddae..75fa0c5fb 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
@@ -626,7 +626,12 @@ public class RulesDeployment<T extends Ruleset> {
@Override
public List<String> getResults() {
- return notificationService.findAllUsersWithToken();
+ if (assetId != null) {
+ return notificationService.findAllUsersWithTokenForAsset(assetId);
+ } else {
+
+ return notificationService.findAllUsersWithToken();
+ }
}
@Override
@@ -636,6 +641,7 @@ public class RulesDeployment<T extends Ruleset> {
};
if (TenantRuleset.class.isAssignableFrom(rulesetType)) {
+
//TODO: restrict users of tenant
}
if (AssetRuleset.class.isAssignableFrom(rulesetType)) {
@@ -643,6 +649,7 @@ public class RulesDeployment<T extends Ruleset> {
if (restrictedAsset == null) {
throw new IllegalStateException("Asset is no longer available for this deployment: " + id);
}
+ query.assetId = id;
//TODO: restrict users of assets
}
return query;
diff --git a/model/src/main/java/org/openremote/model/notification/ActionType.java b/model/src/main/java/org/openremote/model/notification/ActionType.java
index bfe89766a..9203d567c 100644
--- a/model/src/main/java/org/openremote/model/notification/ActionType.java
+++ b/model/src/main/java/org/openremote/model/notification/ActionType.java
@@ -2,6 +2,6 @@ package org.openremote.model.notification;
public enum ActionType {
- ACTION_TYPE1,
- ACTION_TYPE2,
+ ACTUATOR,
+ LINK,
}
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/rules/Users.java b/model/src/main/java/org/openremote/model/rules/Users.java
index 1007529e3..c5c504de8 100644
--- a/model/src/main/java/org/openremote/model/rules/Users.java
+++ b/model/src/main/java/org/openremote/model/rules/Users.java
@@ -32,6 +32,8 @@ import java.util.List;
public abstract class Users {
public abstract class RestrictedQuery extends UserQuery<RestrictedQuery> {
+ public String assetId;
+
abstract public List<String> getResults();
abstract public void applyResults(Consumer<List<String>> assetIdListConsumer);