Search in sources :

Example 1 with AndroidMessage

use of com.willshex.blogwt.server.helper.push.AndroidMessage in project blogwt by billy1380.

the class NotificationHelper method sendNotification.

public static List<Notification> sendNotification(String code, User user, final Map<String, ?> values) {
    List<Notification> notifications = new ArrayList<>();
    final MetaNotification meta = MetaNotificationServiceProvider.provide().getCodeMetaNotification(code);
    if (meta == null) {
        if (LOG.isLoggable(Level.WARNING)) {
            LOG.warning("No meta notification found for code [" + code + "]");
        }
    } else {
        NotificationSetting setting = NotificationSettingServiceProvider.provide().getMetaUserNotificationSetting(meta, user);
        if (setting == null) {
            setting = NotificationSettingServiceProvider.provide().addNotificationSetting(new NotificationSetting().meta(meta).selected(meta.defaults).user(user));
        }
        String content;
        final Notification template = new Notification().content(content = InflatorHelper.inflate(values, meta.content)).meta(meta).target(user);
        Notification notification;
        String title = "Message from " + PropertyHelper.value(PropertyServiceProvider.provide().getNamedProperty(PropertyHelper.TITLE));
        if (setting.selected == null || setting.selected.size() == 0) {
            if (LOG.isLoggable(Level.INFO)) {
                LOG.info("No notification modes found for [" + code + "] and user [" + user + "] adding template [" + template + "]");
            }
            notifications.add(NotificationServiceProvider.provide().addNotification(template));
        } else {
            for (NotificationModeType mode : setting.selected) {
                notification = JsonableHelper.copy(template, new Notification()).mode(mode);
                switch(mode) {
                    case NotificationModeTypeEmail:
                        EmailHelper.sendEmail(user.email, UserHelper.name(user), title, content, false);
                        break;
                    case NotificationModeTypePush:
                        List<PushToken> tokens = PushTokenServiceProvider.provide().getUserPushTokens(user);
                        Jsonable data = new Jsonable() {

                            @Override
                            public JsonObject toJson() {
                                JsonObject object = super.toJson();
                                object.addProperty("code", meta.code);
                                if (values != null) {
                                    Object value;
                                    DataType slim;
                                    for (String key : values.keySet()) {
                                        value = values.get(key);
                                        if (value instanceof DataType) {
                                            slim = PersistenceHelper.slim(DataType.class, (DataType) value, null);
                                            object.add(key, slim.toJson());
                                        }
                                    }
                                }
                                return object;
                            }
                        };
                        for (PushToken pushToken : tokens) {
                            PushHelper.push(pushToken, meta.name, content, data);
                        }
                        if (LOG.isLoggable(Level.FINE) && tokens.size() == 0) {
                            LOG.fine("Could not push because no tokens found [" + meta.name + "], [" + content + "] payload approximation [" + PushHelper.buildPayload(new PushToken().platform("android").user(user).value("approx-test-token"), new AndroidMessage().title(meta.name).body(content), data) + "]");
                        }
                        break;
                    case NotificationModeTypeSms:
                        break;
                }
                notifications.add(NotificationServiceProvider.provide().addNotification(notification));
            }
        }
    }
    return notifications;
}
Also used : AndroidMessage(com.willshex.blogwt.server.helper.push.AndroidMessage) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) MetaNotification(com.willshex.blogwt.shared.api.datatype.MetaNotification) Jsonable(com.willshex.gson.shared.Jsonable) Notification(com.willshex.blogwt.shared.api.datatype.Notification) MetaNotification(com.willshex.blogwt.shared.api.datatype.MetaNotification) NotificationSetting(com.willshex.blogwt.shared.api.datatype.NotificationSetting) DataType(com.willshex.blogwt.shared.api.datatype.DataType) JsonObject(com.google.gson.JsonObject) NotificationModeType(com.willshex.blogwt.shared.api.datatype.NotificationModeType) PushToken(com.willshex.blogwt.shared.api.datatype.PushToken)

Example 2 with AndroidMessage

use of com.willshex.blogwt.server.helper.push.AndroidMessage in project blogwt by billy1380.

the class PushHelper method push.

public static void push(PushToken pushToken, String subject, String content, Jsonable data) {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Pushing notification to [" + pushToken + "] with subject [" + subject + "] message [" + content + "]");
    }
    String apiKey = PropertyHelper.value(PropertyServiceProvider.provide().getNamedProperty(PropertyHelper.FIREBASE_API_KEY));
    if (apiKey != null) {
        Message message = null;
        switch(pushToken.platform) {
            case "android":
                message = new AndroidMessage().title(subject).body(content);
                break;
            case "ios":
                message = new IosMessage().title(subject).body(content);
                break;
        }
        Payload payload = buildPayload(pushToken, message, data);
        try {
            URL endpoint = new URL(PUSH_ENDPOINT);
            HTTPRequest request = new HTTPRequest(endpoint, HTTPMethod.POST);
            HTTPHeader contentTypeHeader = new HTTPHeader("Content-Type", "application/json");
            request.setHeader(contentTypeHeader);
            HTTPHeader authHeader = new HTTPHeader("Authorization", "key=" + apiKey);
            request.setHeader(authHeader);
            String payloadString;
            request.setPayload((payloadString = JsonUtils.cleanJson(payload.toJson().toString())).getBytes(ServletHelper.UTF8));
            URLFetchService client = URLFetchServiceFactory.getURLFetchService();
            HTTPResponse response = client.fetch(request);
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("Sending push payload [" + payloadString + "]");
            }
            byte[] responseBytes;
            String responseText = null;
            if ((responseBytes = response.getContent()) != null) {
                responseText = new String(responseBytes, ServletHelper.UTF8);
            }
            if (response.getResponseCode() >= 200 && response.getResponseCode() < 300 && responseText != null) {
                if ("".equals(responseText) || "null".equalsIgnoreCase(responseText)) {
                    if (LOG.isLoggable(Level.WARNING)) {
                        LOG.warning("No push response text for payload");
                    }
                } else {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("Push response [" + responseText + "]");
                    }
                    try {
                        JsonElement el = (new JsonParser()).parse(responseText);
                        if (el.isJsonObject()) {
                            JsonObject ro = el.getAsJsonObject();
                            if (ro.has("failure")) {
                                JsonElement fel = ro.get("failure");
                                if (fel.isJsonPrimitive()) {
                                    if (fel.getAsInt() == 1) {
                                        if (LOG.isLoggable(Level.WARNING)) {
                                            LOG.log(Level.WARNING, "Push failed: check response");
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        if (LOG.isLoggable(Level.WARNING)) {
                            LOG.log(Level.WARNING, "Could not parse response [" + responseText + "]", e);
                        }
                    }
                }
            } else if (response.getResponseCode() >= 400) {
                if (LOG.isLoggable(Level.SEVERE)) {
                    LOG.severe("Response error [" + response.getResponseCode() + "] and body [" + responseText + "] for payload");
                }
            }
        } catch (IOException e) {
            if (LOG.isLoggable(Level.WARNING)) {
                LOG.log(Level.WARNING, "Error sending push notification", e);
            }
        }
    } else {
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info("Not sending push message because property [" + PropertyHelper.FIREBASE_API_KEY + "] has not been set");
        }
    }
}
Also used : HTTPRequest(com.google.appengine.api.urlfetch.HTTPRequest) AndroidMessage(com.willshex.blogwt.server.helper.push.AndroidMessage) AndroidMessage(com.willshex.blogwt.server.helper.push.AndroidMessage) Message(com.willshex.blogwt.server.helper.push.Message) IosMessage(com.willshex.blogwt.server.helper.push.IosMessage) URLFetchService(com.google.appengine.api.urlfetch.URLFetchService) HTTPResponse(com.google.appengine.api.urlfetch.HTTPResponse) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) URL(java.net.URL) IOException(java.io.IOException) IosMessage(com.willshex.blogwt.server.helper.push.IosMessage) JsonElement(com.google.gson.JsonElement) Payload(com.willshex.blogwt.server.helper.push.Payload) HTTPHeader(com.google.appengine.api.urlfetch.HTTPHeader) JsonParser(com.google.gson.JsonParser)

Aggregations

JsonObject (com.google.gson.JsonObject)2 AndroidMessage (com.willshex.blogwt.server.helper.push.AndroidMessage)2 HTTPHeader (com.google.appengine.api.urlfetch.HTTPHeader)1 HTTPRequest (com.google.appengine.api.urlfetch.HTTPRequest)1 HTTPResponse (com.google.appengine.api.urlfetch.HTTPResponse)1 URLFetchService (com.google.appengine.api.urlfetch.URLFetchService)1 JsonElement (com.google.gson.JsonElement)1 JsonParser (com.google.gson.JsonParser)1 IosMessage (com.willshex.blogwt.server.helper.push.IosMessage)1 Message (com.willshex.blogwt.server.helper.push.Message)1 Payload (com.willshex.blogwt.server.helper.push.Payload)1 DataType (com.willshex.blogwt.shared.api.datatype.DataType)1 MetaNotification (com.willshex.blogwt.shared.api.datatype.MetaNotification)1 Notification (com.willshex.blogwt.shared.api.datatype.Notification)1 NotificationModeType (com.willshex.blogwt.shared.api.datatype.NotificationModeType)1 NotificationSetting (com.willshex.blogwt.shared.api.datatype.NotificationSetting)1 PushToken (com.willshex.blogwt.shared.api.datatype.PushToken)1 Jsonable (com.willshex.gson.shared.Jsonable)1 IOException (java.io.IOException)1 URL (java.net.URL)1