Which is better approach to send push notification in Kuzzle using hooks or subscription? - kuzzle

I’m using Kuzzle as backend for my realtime chat application.
What is the better approach to sending push notification when user is offline in a mobile chat app?
1. Using custom plugin hooks
// check for every message in chat
this.hooks = {
'document:afterCreate': (request) => {
if (request.input.resource.collection == 'messages') {
let message = request.input.body;
this.context.accessors.sdk.document.get('now', 'user_sessions', message.otherUserId).then((userSession) => {
if (!userSession._source.isOnline) {
userSession._source.devices.forEach(device => {
// send push notification
});
}
})
}
}
}
2. Subscription per user for all users after the Kuzzle server start-up
const app = new Backend('kuzzlebackend')
app.start()
.then(async () => {
// Application started
// Loops through all users and adds their subscriptions to Kuzzle
foreach(user in users) {
app.sdk.realtime.subscribe('now', 'messages', { ‘otherUserId' : user._id }, async (notification: Notification) => {
this.context.accessors.sdk.document.get('now', 'user_sessions', user._id).then((userSession) => {
if (!userSession._source.isOnline) {
userSession._source.devices.forEach(device => {
// send push notification
});
}
})
})
}
})

You should use the hook mechanism on the generic:document:afterWrite event to send notification to offline users when a new message is created.
This event will be triggered every time a document is written with one of the Document controller action, and for the m* action family it you will able to process documents in bulk instead of one by one.

Related

How to close Camera using phonegap-barcode-scanner plugin within service IONIC

I am using phonegap-barcodescanner-plugin to read qr while a service is reading instant payments on background.
I am detecting a new instant payment in the service and launching an event subscribed in the page where the barcodeScanner is launched
event.subscribe('instant-payment', (val) => {
console.log("Hi--------------", val)
this.navCtrl.pop()
});
the event is correctly fired and the log is ok but I'm trying to do a navCtrl.pop() and the Activity is never closed, I thought was going to work same way like cancelling scanner
scan() {
this.barcodeScanner.scan(this.options).then(barcodeData => {
if (barcodeData.cancelled == true) {
this.navCtrl.pop()
} else {
}
}).catch(err => {
console.log('Error', err);
});
}
Is there anyway to force close barcodeScanner and go back to the last "IonicPage".
Thanks for any help.

Ionic FCM push notifications observable does not emit

I am doing the following in an ionic application:
When a user is logged in, subscribe to their user ID topic
When a push notification arrives, console.log something.
this.authState.subscribe((state) => {
if (state) {
this.fcmPush.subscribeToTopic(state.uid);
this.fcmPush.onNotification().subscribe(notification => {
if (notification.wasTapped) {
console.log('Received in background', notification);
} else {
console.log('Received in foreground', notification);
}
});
}
});
Source: https://github.com/AmitMY/ionic-starter-firebase/blob/master/src/app/app.component.ts#L118
Sending a notification to my own topic arrives (after a few minutes), but I never see anything in console, both from outside the app, and inside the app.
What am I doing wrong?
Sending a notification from firebase messaging does not work.
However, using the sdk I must add:
click_action: "FCM_PLUGIN_ACTIVITY",
Which is in the usage guide but I missed

Ionic2: Unsubscribe Event to Avoid Duplicate Entries?

I've followed this tutorial which outlines adding monitoring beacons in an Ionic 2 application. I have it working great: when the view loads, it initializes and begins listening for beacons:
home.ts
ionViewDidLoad() {
this.platform.ready().then(() => {
this.beaconProvider.initialise().then((isInitialised) => {
if (isInitialised) {
this.listenToBeaconEvents();
}
});
});
}
This calls the listenToBeaconEvents function which populates a list in the view with all of the beacons:
home.ts
listenToBeaconEvents() {
this.events.subscribe(‘didRangeBeaconsInRegion’, (data) => {
// update the UI with the beacon list
this.zone.run(() => {
this.beacons = [];
let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});
});
});
}
I'm able to stop ranging using this.beaconProvider.stopRanging() that calls a function from the below function:
beacon-provider.ts
stopRanging() {
if (this.platform.is('cordova')) {
// stop ranging
this.ibeacon.stopRangingBeaconsInRegion(this.region)
.then(
() => {
console.log('Stopped Ranging');
},
error => {
console.error('Failed to stop monitoring: ', error);
}
);
}
}
The problem I'm having is this - in the original tutorial the beacon list is shown at the root, there's no other navigation. I've moved it to a different view, and if the user exits and re-enters the view, it re-initializes and loads everything, resulting in duplicate list entries.
I've tried creating a function within beacon-provider.ts to call before the view exits, but I can't figure out how to keep the subscriptions/events from duplicating.
I've tried this.delegate.didRangeBeaconsInRegion().unsubscribe(), and some other variations but they all result in runtime errors.
In your case you are using Ionic's Events API which has its own unsubscribe(topic, handler) function.
In your component, whenever you need to unsubscribe, you should call this with the same topic:
this.events.unsubscribe(‘didRangeBeaconsInRegion’);
This will remove all handlers you may have registered for the didRangeBeaconsInRegion.
If you want to unsubscribe one specific function, you will have to have registered a named handler which you can send with unsubscribe.
this.events.unsubscribe(‘didRangeBeaconsInRegion’,this.mySubscribedHandler);
And your home.ts would look like:
mySubscribedHandler:any = (data) => {
// update the UI with the beacon list
this.zone.run(() => {
this.beacons = [];
let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});
});
}
listenToBeaconEvents() {
this.events.subscribe(‘didRangeBeaconsInRegion’,this.mySubscribedHandler);
}

Ionic - one signal push notifications sent twice

I am sending push notifications with One Signal to all users from the backend that uses Laravel like this:
OneSignal::sendNotificationToAll($notification->message);
I have set it up on the frontend side like this:
angular.module('coop.services')
.service('PushService', function(
AppSettings,
$rootScope,
$q
) {
var service = {
init: function() {
if (!window.plugins || !window.plugins.OneSignal) {
return;
}
window.plugins.OneSignal
.startInit( AppSettings.oneSignalAppId)
.endInit();
},
receivePush: function(data) {
$rootScope.$broadcast('push:received', data);
},
getDeviceId: function() {
var deferred = $q.defer();
if (window.plugins) {
window.plugins.OneSignal.getIds(function(ids) {
deferred.resolve(ids.userId);
});
}
else {
deferred.reject();
}
return deferred.promise;
}
};
return service;
});
I have tested both from the backend and from the One signal dashboard and when I am sending notification I get two notifications for each I send. One with alarm icon and one without any, what I am doing wrong?
you might have enabled mozila and Chrome with wrong settings, had similar problem I couldn't disactivate the browser though, I just made a new onesignal app and solved.

implement Push Notifications in Ionic 2 with the Pub/Sub Model

Hi this is a duplicate of the question at
Push Notifications in Ionic 2 with the Pub/Sub Model
i have already implemented push notifications following this article >
https://medium.com/#ankushaggarwal/push-notifications-in-ionic-2-658461108c59#.xvoeao59a
what i want is to be able to send notifications to users when some events take place in the app like chat or booking or new job post.
how to go further , this is my first app.
NOTE: code is almost exactly the same as the tutorial, Java has only been converted to Kotlin
This is my acutal ionic side code (on login page). The push.on('registration') will be fired when the user opens the app, the variable this.device_id will later (on succesfull login) be sent to my Kotlin REST API so I know the device_id and have coupled it to a user. This way you can send targeted push notifications.
If you send a push notification from Kotlin (code shown below, looks a bit like Java), the (always open, even opens after startup) connection to Google will send your device (defined by the device_id a message with the notification data (title, message, etc.) after which your device will recognize the senderID and match it to use your ionic application.
initializeApp() {
this.platform.ready().then(() => {
let push = Push.init({
android: {
senderID: "1234567890"
},
ios: {
alert: "true",
badge: false,
sound: "true"
},
windows: {}
});
//TODO - after login
push.on('registration', (data) => {
this.device_id = data.registrationId;
});
push.on('notification', (data) => {
console.log('message', data.message);
let self = this;
//if user using app and push notification comes
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: data.title,
message: data.message,
buttons: [{
text: 'Negeer',
role: 'cancel'
}, {
text: 'Bekijk',
handler: () => {
//TODO: Your logic here
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
this.navCtrl.setRoot(EventsPage, {message: data.message});
console.log("Push notification clicked");
}
});
push.on('error', (e) => {
console.log(e.message);
});
});
}
Kotlin code (converted from the Java example, basically the same
package mycompany.rest.controller
import mycompany.rest.domain.User
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL
class PushNotification {
companion object {
val SERVER_KEY = "sOmE_w31rD_F1r3Ba5E-KEy";
#JvmStatic fun sendPush(user: User, message: String, title: String) {
if(user.deviceId != "unknown"){
val pushMessage = "{\"data\":{\"title\":\"" +
title +
"\",\"message\":\"" +
message +
"\"},\"to\":\"" +
user.deviceId +
"\"}";
val url: URL = URL("https://fcm.googleapis.com/fcm/send")
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY)
conn.setRequestProperty("Content-Type", "application/json")
conn.setRequestMethod("POST")
conn.setDoOutput(true)
//send the message content
val outputStream: OutputStream = conn.getOutputStream()
outputStream.write(pushMessage.toByteArray())
println(conn.responseCode)
println(conn.responseMessage)
}else {
println("Nope, not executed")
}
}
#JvmStatic fun sendPush(users: List<User>, message: String, title: String) {
for(u in users) {
PushNotification.sendPush(u, message, title)
}
}
}
}
Then the method can be called as PushNotification.sendPush(user1, "Hello world!", "my title");
(btw realized you won't need to run the pushnotification from a server (localhost/external). You can just create a main class which sends it with your hardcoded deviceId for testing purposes.