Skip to content

armgit / core

Public Imported from GitHub
0

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

Working on FCM notification (WIP)

Mica Hallinb36332ee42fa
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 6d7bc1120..42fb5e43a 100644
--- a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
+++ b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
@@ -1,36 +1,44 @@
-/**
- * Copyright 2016 Google Inc. All Rights Reserved.
- * <p>
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
package org.openremote.android;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
+import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
+import android.preference.PreferenceManager;
+import android.service.notification.StatusBarNotification;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.RemoteMessage;
+import org.openremote.android.service.AlertAction;
+import org.openremote.android.service.AlertNotification;
+import org.openremote.android.service.TokenService;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+
public class ORFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
+ private TokenService tokenService;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ tokenService = new TokenService(getApplicationContext());
+ }
+
/**
* Called when message is received.
*
@@ -63,33 +71,61 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
+ tokenService.getAlerts(new Callback<List<AlertNotification>>() {
+ @Override
+ public void onResponse(Call<List<AlertNotification>> call, Response<List<AlertNotification>> response) {
+ List<AlertNotification> alertNotifications = response.body();
+ Set<String> actualAlertIds = new HashSet<>();
+ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
+ Set<String> previousAlertIds = sharedPreferences.getStringSet(getString(R.string.SHARED_PREF_OPENED_ALERT), new HashSet<String>());
+
+ for (AlertNotification alertNotification : alertNotifications) {
+ if (!previousAlertIds.contains(alertNotification.getId().toString())) {
+ sendNotification(alertNotification);
+ previousAlertIds.add(alertNotification.getId().toString());
+ }
+ actualAlertIds.add(alertNotification.getId().toString());
+ Log.d("NOTIFICATION", alertNotification.toString());
+ }
+ previousAlertIds.retainAll(actualAlertIds);
+ sharedPreferences.edit().putStringSet(getString(R.string.SHARED_PREF_OPENED_ALERT) ,previousAlertIds ).commit();
+ }
+
+ @Override
+ public void onFailure(Call<List<AlertNotification>> call, Throwable t) {
+ Log.e("NOTIFICATION", "Error retriving alert", t);
+ }
+ });
+
+
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]
- /**
- * Create and show a simple notification containing the received FCM message.
- *
- * @param messageBody FCM message body received.
- */
- private void sendNotification(String messageBody) {
+
+ private void sendNotification(AlertNotification alertNotification) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
+
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
- .setContentTitle("OR Notification")
- .setContentText(messageBody)
+ .setContentTitle(alertNotification.getTitle())
+ .setContentText(alertNotification.getMessage())
+ .setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
- .setSound(defaultSoundUri)
- .setContentIntent(pendingIntent);
+ .setWhen(0)
+ .setSound(defaultSoundUri);
+
+ for (AlertAction alertAction : alertNotification.getActions()) {
+ notificationBuilder = notificationBuilder.addAction(new NotificationCompat.Action(-1, alertAction.getName(), pendingIntent));
+ }
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-
- notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
+ notificationManager.notify(alertNotification.getId().hashCode(), notificationBuilder.build());
}
}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/service/AlertAction.java b/console/android/src/main/java/org/openremote/android/service/AlertAction.java
new file mode 100644
index 000000000..5f22d0778
--- /dev/null
+++ b/console/android/src/main/java/org/openremote/android/service/AlertAction.java
@@ -0,0 +1,34 @@
+package org.openremote.android.service;
+
+
+public class AlertAction {
+ private AlertNotification.ActionType type;
+ private String name;
+
+ public AlertAction() {
+ }
+
+ public AlertNotification.ActionType getType() {
+ return type;
+ }
+
+ public void setType(AlertNotification.ActionType type) {
+ this.type = type;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "AlertAction{" +
+ "type=" + type +
+ ", name='" + name + '\'' +
+ '}';
+ }
+}
\ No newline at end of file
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
new file mode 100644
index 000000000..19f1c9b1f
--- /dev/null
+++ b/console/android/src/main/java/org/openremote/android/service/AlertNotification.java
@@ -0,0 +1,97 @@
+package org.openremote.android.service;
+
+
+import java.util.List;
+
+public class AlertNotification {
+ private Long id;
+
+ private String title;
+
+ private String message;
+
+ private List<AlertAction> actions;
+
+ private String appUrl;
+
+ private String userId;
+
+ private DeliveryStatus deliveryStatus;
+
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public List<AlertAction> getActions() {
+ return actions;
+ }
+
+ public void setActions(List<AlertAction> actions) {
+ this.actions = actions;
+ }
+
+ public String getAppUrl() {
+ return appUrl;
+ }
+
+ public void setAppUrl(String appUrl) {
+ this.appUrl = appUrl;
+ }
+
+ public String getUserId() {
+ return userId;
+ }
+
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public DeliveryStatus getDeliveryStatus() {
+ return deliveryStatus;
+ }
+
+ public void setDeliveryStatus(DeliveryStatus deliveryStatus) {
+ this.deliveryStatus = deliveryStatus;
+ }
+
+ @Override
+ public String toString() {
+ return "AlertNotification{" +
+ "id=" + id +
+ ", title='" + title + '\'' +
+ ", message='" + message + '\'' +
+ ", actions=" + actions +
+ ", appUrl='" + appUrl + '\'' +
+ ", userId='" + userId + '\'' +
+ ", deliveryStatus=" + deliveryStatus +
+ '}';
+ }
+
+
+
+ public enum ActionType {
+ ACTION_TYPE1,
+ ACTION_TYPE2
+ }
+}
diff --git a/console/android/src/main/java/org/openremote/android/service/DeliveryStatus.java b/console/android/src/main/java/org/openremote/android/service/DeliveryStatus.java
new file mode 100644
index 000000000..1c785cb3c
--- /dev/null
+++ b/console/android/src/main/java/org/openremote/android/service/DeliveryStatus.java
@@ -0,0 +1,7 @@
+package org.openremote.android.service;
+
+
+enum DeliveryStatus {
+ PENDING,
+ DELIVERED
+}
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 b30f9a548..2af4871a6 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
@@ -1,9 +1,12 @@
package org.openremote.android.service;
+import java.util.List;
+
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
+import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.PUT;
import retrofit2.http.Path;
@@ -12,4 +15,9 @@ public interface NotificationService {
@FormUrlEncoded
@PUT("/{realm}/notification/token")
Call<Void> updateToken(@Path("realm") String realm, @Header("Authorization") String authorization, @Field("token") String token, @Field("device_id") String deviceId);
+
+
+ @GET("/{realm}/notification/alert")
+ Call<List<AlertNotification>> getAlertNotification(@Path("realm") String realm, @Header("Authorization") String authorization);
+
}
diff --git a/console/android/src/main/java/org/openremote/android/service/RefreshedToken.java b/console/android/src/main/java/org/openremote/android/service/RefreshedToken.java
deleted file mode 100644
index 3263d3d48..000000000
--- a/console/android/src/main/java/org/openremote/android/service/RefreshedToken.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package org.openremote.android.service;
-
-/**
- * Created by mica on 15/03/17.
- */
-
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 67e9f67e0..a6fb3d54e 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
@@ -8,6 +8,7 @@ import android.util.Log;
import org.openremote.android.R;
import java.io.IOException;
+import java.util.List;
import java.util.Map;
import retrofit2.Call;
@@ -140,4 +141,19 @@ public class TokenService {
});
}
+
+ public void getAlerts(final Callback<List<AlertNotification>> callback) {
+
+ getAuthorization(new TokenCallback() {
+ @Override
+ public void onToken(String accessToken) {
+ notificationService.getAlertNotification(realm, accessToken).enqueue(callback);
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ callback.onFailure(null,t);
+ }
+ });
+ }
}
diff --git a/console/android/src/main/res/values/strings.xml b/console/android/src/main/res/values/strings.xml
index a21929d27..275702026 100644
--- a/console/android/src/main/res/values/strings.xml
+++ b/console/android/src/main/res/values/strings.xml
@@ -10,4 +10,5 @@
<string name="SHARED_PREF_DEVICE_ID">FCM_DEVICE_ID_KEY</string>
<string name="reload">reload</string>
<string name="noConnectivity">No connectivity Detected</string>
+ <string name="SHARED_PREF_OPENED_ALERT">OPENED_ALERT</string>
</resources>
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 24245bd1d..af25800fa 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
@@ -105,16 +105,18 @@ 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=");
+ 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();
}
}
});
+
}
public List<AlertNotification> getPendingAlertForUserId(String userId) {
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/notification/ActionType.java b/manager/shared/src/main/java/org/openremote/manager/shared/notification/ActionType.java
new file mode 100644
index 000000000..b1fa3340b
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/notification/ActionType.java
@@ -0,0 +1,7 @@
+package org.openremote.manager.shared.notification;
+
+
+public enum ActionType {
+ ACTION_TYPE1,
+ ACTION_TYPE2,
+}
\ No newline at end of file
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/notification/AlertAction.java b/manager/shared/src/main/java/org/openremote/manager/shared/notification/AlertAction.java
index 76cb00d28..813c23609 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/notification/AlertAction.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/notification/AlertAction.java
@@ -1,29 +1,52 @@
package org.openremote.manager.shared.notification;
-import javax.persistence.*;
-import javax.validation.constraints.NotNull;
+import elemental.json.Json;
+import elemental.json.JsonObject;
+import elemental.json.JsonValue;
-import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
-
-@Entity
-@Table(name = "ALERT_ACTION")
public class AlertAction {
- @Id
- @Column(name = "ID")
- @GeneratedValue(generator = PERSISTENCE_SEQUENCE_ID_GENERATOR)
- Long id;
-
- @NotNull
- @Column(name = "TYPE", nullable = false)
- String type;
-
- @NotNull
- @Column(name = "NAME", nullable = false)
- String name;
-
- /*
- * action (button) name ◦ type & parameters
- * */
+ private JsonObject jsonObject ;
+
+ public AlertAction() {
+ jsonObject = Json.createObject();
+
+ }
+
+ public String getTitle() {
+ if (jsonObject.hasKey("title")) {
+ return jsonObject.getString("title");
+ } else {
+ return null;
+ }
+ }
+
+ public void setTitle(String title) {
+ if (title != null) {
+ jsonObject.put("title", Json.create(title));
+ } else if (jsonObject.hasKey("title")) {
+ jsonObject.remove("title");
+ }
+ }
+
+ public ActionType getType() {
+ if (jsonObject.hasKey("type")) {
+ return ActionType.valueOf(jsonObject.getString("type"));
+ } else {
+ return null;
+ }
+ }
+
+ public void setType(ActionType type) {
+ if (type != null) {
+ jsonObject.put("type", Json.create(type.name()));
+ } else if (jsonObject.hasKey("type")) {
+ jsonObject.remove("type");
+ }
+ }
+
+ public JsonObject getValue() {
+ return jsonObject;
+ }
}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/notification/AlertNotification.java b/manager/shared/src/main/java/org/openremote/manager/shared/notification/AlertNotification.java
index c5536cbd9..713652473 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/notification/AlertNotification.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/notification/AlertNotification.java
@@ -1,10 +1,19 @@
package org.openremote.manager.shared.notification;
+import elemental.json.Json;
+import elemental.json.JsonArray;
+import elemental.json.JsonObject;
+import elemental.json.impl.JreJsonArray;
+
import javax.persistence.*;
import javax.validation.constraints.NotNull;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Set;
+import static org.openremote.model.Constants.PERSISTENCE_JSON_ARRAY_TYPE;
+import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;
import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
@Entity
@@ -24,9 +33,9 @@ public class AlertNotification {
@Column(name = "MESSAGE", nullable = false)
private String message;
- @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
- @JoinColumn(name="ALERT_ID")
- private Set<AlertAction> actions;
+ @Column(name = "ACTIONS", columnDefinition = "jsonb")
+ @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_ARRAY_TYPE)
+ private JsonArray actions = Json.createArray();
@NotNull
@Column(name = "APP_URL", nullable = false)
@@ -41,9 +50,7 @@ public class AlertNotification {
@Enumerated(EnumType.STRING)
private DeliveryStatus deliveryStatus;
- /*
- Actuator
- */
+ /* Actuator */
public Long getId() {
return id;
@@ -69,12 +76,26 @@ public class AlertNotification {
this.message = message;
}
- public Set<AlertAction> getActions() {
+ public void setActions(JsonArray actions) {
+ this.actions = actions;
+ }
+
+ public JsonArray getActions() {
return actions;
}
- public void setActions(Set<AlertAction> actions) {
- this.actions = actions;
+ public List<AlertAction> getActionsAsList() {
+ List actions = new ArrayList<>(this.actions.length());
+ for (int i = 0; i < actions.size(); i++) {
+ actions.add(this.actions.get(i).toNative());
+
+ }
+
+ return actions;
+ }
+
+ public void addAction(AlertAction action) {
+ this.actions.set(this.actions.length(), action.getValue());
}
public String getAppUrl() {
diff --git a/manager/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy
index ad85ad741..0a21700ca 100644
--- a/manager/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy
@@ -3,6 +3,7 @@ package org.openremote.test.user
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.server.notification.NotificationService
+import org.openremote.manager.shared.notification.ActionType
import org.openremote.manager.shared.notification.AlertAction
import org.openremote.manager.shared.notification.AlertNotification
import org.openremote.manager.shared.notification.NotificationResource
@@ -34,15 +35,16 @@ class NotificationServiceTest extends Specification implements ManagerContainerT
def notificationAlert = new AlertNotification(
title: "The Title",
- actions: [new AlertAction(
- name: "TEST_ACTION",
- type: "TEST"
- )],
appUrl: '#test',
message: "Message",
-
)
+ def alertAction = new AlertAction();
+
+ alertAction.setTitle("TEST_ACTION")
+ alertAction.setType(ActionType.ACTION_TYPE1)
+ notificationAlert.addAction(alertAction)
+
and: "the notification resource"
def client = createClient(container).build()
def serverUri = serverUri(serverPort)
@@ -73,7 +75,7 @@ class NotificationServiceTest extends Specification implements ManagerContainerT
when: "the alert Notification is acknowledge"
notificationResource.removeAlertNotification(alerts.get(0).id)
- then: "it should be no allert"
+ then: "it should be no alert"
notificationResource.getAlertNotification().size() == 0
cleanup: "the server should be stopped"