Pubnub.subscribe not working - javascript

I am trying to implement a simple chat in my AngularJs 1.4.5 web app using pubnub.
I am following the steps as given in the pubnub tutorial.
$scope.channel = 'chat_for_trial';
$scope.uuid = 'user1';
Pubnub.init({
publishKey: 'demo',
subscribeKey: 'demo',
uuid: $scope.uuid
});
// Send the messages over PubNub Network
$scope.messageContent = {message: ''};
$scope.sendMessage = function() {
// $scope.messageContent = data;
// Don't send an empty message
if (!$scope.messageContent.message || $scope.messageContent.message === '') {
return;
}
Pubnub.publish({
channel: $scope.channel,
message: {
content: $scope.messageContent.message,
sender_uuid: $scope.uuid,
date: new Date()
},
callback: function(m) {
console.log(m);
}
});
// Reset the messageContent input
$scope.messageContent.message = '';
};
//get messages
$scope.messageContent.messages = [];
// Subscribing to the ‘messages-channel’ and trigering the message callback
Pubnub.subscribe({
channel: $scope.channel,
triggerEvents: ['callback']
});
// Listening to the callbacks
$scope.$on(Pubnub.getMessageEventNameFor($scope.channel), function (ngEvent, m) {
$scope.$apply(function () {
console.log("i am here")
$scope.messageContent.messages.push(m)
});
});
I can send message to the channel chat_for_trial but when checking the occupancy in pubnub console, the subscribed uuid is not listed.
When I sending the message from console it is not displayed in the web app. But data sent from web app can be seen in the pubnub console.
I am working with pubnub: 4.20.1, pubnub-angular: 4.1.0, angularjs: 1.4.5
I would like to know what I am missing here.

The issue was due to the mismatch of the pubnub and pubnub-angular version from the tutorial and the one installed using bower in my application.
The tutorial was for sdk v3 and the current sdk version v4.
Refer this link for working with pubnub sdk v4.

Related

How to use servicebus topic sessions in azure functionapp using javascript

I have an Azure Functionapp that processes some data and pushes that data into an Azure servicebus topic.
I require sessions to be enabled on my servicebus topic subscription. I cannot seem to find a way to set the session id when using the javascript functionapp API.
Here is a modified extract from my function app:
module.exports = function (context, streamInput) {
context.bindings.outputSbMsg = [];
context.bindings.logMessage = [];
function push(response) {
let message = {
body: CrowdSourceDatum.encode(response).finish()
, customProperties: {
protoType: manifest.Type
, version: manifest.Version
, id: functionId
, rootType: manifest.RootType
}
, brokerProperties: {
SessionId: "1"
}
context.bindings.outputSbMsg.push(message);
}
.......... some magic happens here.
push(crowdSourceDatum);
context.done();
}
But the sessionId does not seem to get set at all. Any idea on how its possible to enable this?
I tested sessionid on my function, I can set the session id property of a message and view it in Service Bus explorer. Here is my sample code.
var connectionString = 'servicebus_connectionstring';
var serviceBusService = azure.createServiceBusService(connectionString);
var message = {
body: '',
customProperties:
{
messagenumber: 0
},
brokerProperties:
{
SessionId: "1"
}
};
message.body= 'This is Message #101';
serviceBusService.sendTopicMessage('testtopic', message, function(error)
{
if (error)
{
console.log(error);
}
});
Here is the test result.
Please make sure you have enabled the portioning and sessions when you created the topic and the subscription.

Phonegap Plugin Push & Node-gcm NotRegistered

So I have seen other people with this issue post on here. Nothing seems to right with what I am having. Here is the steps of my issues:
1) I installed my Ionic app onto my phone.
2) Setup my sender key and API key with the google console.
3) Created my node-gcm server.
4) Sent notifications to my phone using my phonegap-plugin-push device token.
5) uninstalled my app
6) reinstalled the app.
7) tried sending notifications, and now I am getting a NotRegistered Error by GCM.
I cross checked all of my keys: server, sender, device. All are correct. I cannot figure out why after reinstallation of the app, i get a notregistered error. Here are the tools I am using:
Ionic framework, android phone, NodeJS server, Node-gcm, google dev console, phonegap-plugin-push
And lastly, Code:
.run(function($ionicPlatform, $ionicPopup, $rootScope, $http, $state) {
$ionicPlatform.ready(function() {
var push = PushNotification.init({
android: {
senderID: "7821....1490",
sound: "true",
vibration: "true"
},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
},
ios: {
alert: "true",
badge: true,
sound: "true",
vibration: "true",
clearBadge: true
},
windows: {}
});
push.on('registration', function(data) {
console.log("Device Token: " + data.registrationId);
$rootScope.devToken = data.registrationId;
})
var message = new gcm.Message();
message.addData('title', 'Alert');
message.addData('message', 'Message From: '+ messageUser + '\n' + 'Message Text: ' + messageText);
//message.addData('image', image);
sender.send(message, android, function (err, response) {
if(err) {}
else {
console.log(response.results);
//response is NotRegistered, unregister devices
for (var i = 0; i < response.results.length; i++) {
if (response.results[i].error == 'NotRegistered') {
console.log("ERROR");
}
}
}
});
I am willing to work through this with you. Just know, I have checked all keys, and all are the correct keys. When I reinstalled the app, I got a new device token and I am trying to push to that new device token.
OK! FOR ANYONE WITH THIS PROBLEM READ HERE!
With push plugin, on app uninstall. It does not clear all the data. I am storing the device token in a scope variable and storing it in local storage. On app uninstall, go to settings and clear all data before uninstalling. Once you reinstall, you will get a new token and it should work!

Handle Push notification in Nativescript

I am working on application in Nativescript which implements push notification. Lets say server sends push notification and based on action mentioned in payload of notification i will have to redirect in application. This redirection should be performed if user taps on notification from drawer and application is in background. Other case when application should not redirect if its in foreground. I have managed a flag for that as follow
app.js
application.on(application.launchEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.suspendEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.resumeEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.exitEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.lowMemoryEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.uncaughtErrorEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
And on Push notification listener
var settings = {
// Android settings
senderID: '1234567890', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(data, pushNotificationObject) { // Android: Callback to invoke when a new push is received.
var payload = JSON.parse(JSON.parse(pushNotificationObject).data);
if (appSettings.getBoolean('AppForground') == false){
switch (payload.action) {
case "APPOINTMENT_DETAIL":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id
}
});
break;
case "MESSAGE":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id,
from: "messages"
}
});
break;
case "REFERENCES":
frame.topmost().navigate({
moduleName: views.clientDetails,
context: {
id: payload.id,
name: ""
}
});
break;
default:
}
}
},
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};
pushPlugin.register(settings,
// Success callback
function(token) {
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
},
// Error Callback
function(error) {
alert(error);
}
);
Now the problem, is that if application is in killed state and notification arrives. Then it sets flag to true as application is launched which it should not. So due to that redirection is not performed and in other cases when application is in foreground state then also its navigating through pages (which should not be) on receiving notification.
I doubt about flag management is causing the problem but not sure. Would you please guide me if anything is wrong with what i did ?
UPDATE
I am using push-plugin.
Thanks.
I use this for notifications
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
This plugin use FCM, it adds to datas received from notifications foreground parameter so from payload you can determine if app was background(foreground==false, app is not active or was started after notification arrived) or foreground(foreground==true, app is open and active), but you need to some changes to code as they are different plugins
You can use pusher-nativescript npm module.
import { Pusher } from 'pusher-nativescript';
/*Observation using the above.
- Project gets build successfully.
- on run -> ERROR TypeError: pusher_nativescript__WEBPACK_IMPORTED_MODULE_6__.Pusher is not a constructor
- Use: import * as Pusher from 'pusher-nativescript';
- Make sure to install nativescript-websocket with this package.
*/
var pusher = new Pusher('Your_app_key', { cluster: 'your_cluster_name' });
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});

GCM Android notification received on device but not displaying

GCM Cloud messaging notifications for my Ionic Android app are not appearing in my device's home screen, despite the notification registering in the app itself.
I'm using the npm module node-gcm to send push notifications.
var gcm = require('node-gcm');
var message = new gcm.Message({
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 10,
dryRun: false,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP."
}
});
var regIds = ['*device id*'];
var sender = new gcm.Sender('*api key*');
sender.send(message, { registrationIds: regIds }, function (err, result) {
if(err) console.error(err);
else console.log(result);
});
When I send a push notification to my device's ID, I get a successful response:
{ multicast_id: 8406385547051869000,
success: 1,
failure: 0,
canonical_ids: 0,
results: [ { message_id: '0:1441962697347777%b67ee170f9fd7ecd' } ] }
I then get the following message in my Android Studio console:
V/GCMBroadcastReceiver﹕ onReceive: com.google.android.c2dm.intent.RECEIVE
V/GCMBroadcastReceiver﹕ GCM IntentService class: com.plugin.gcm.GCMIntentService
V/GCMBaseIntentService﹕ Acquiring wakelock
V/GCMBaseIntentService﹕ Intent service name: GCMIntentService-GCMIntentService-5
D/GCMIntentService﹕ onMessage - context: android.app.Application#2dc6dbff
V/GCMBaseIntentService﹕ Releasing wakelock
In the Google Play Developer Console GCM Debugger, my notifications also to appear to have been confirmed.
0: 1441899623073525% b67ee170f9fd7ecd Confirmed
Other than this I receive no error message in the Android Studio console when a notification has been received.
The Ionic app itself registers the notification once I've sent one. However when I'm out of the app. no notification is displayed in the home screen.
$rootScope.$on('$cordovaPush:notificationReceived', function (event, notification) {
alert(notification);
if (ionic.Platform.isAndroid() && notification.event == "registered") {
window.localStorage['token'] = notification.regid;
var params = {
deviceType: 'android',
tokenId: notification.regid
};
NotificationService.registerDevice(params);
}
if (notification.badge) {
$cordovaPush.setBadgeNumber(notification.badge);
}
//notifications payload
if (notification.foreground == '0') {
if (notification.view) {
$timeout(function () {
$state.go('app.notifications');
});
} else {
if (notification.id) {
NotificationService.markNotificationAsRead(notification.id).success(function () {
$rootScope.$emit('notifications-read');
});
}
if (notification.chat) {
$timeout(function () {
$state.go('app.message', {id: notification.chat});
});
} else if (notification.post) {
$timeout(function () {
$state.go('app.singlePost', {id: notification.post});
});
} else if (notification.group) {
$timeout(function () {
$state.go('app.group', {id: notification.group});
});
}
}
}
});
You must add icon field in your notification block:
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP.",
icon: "#drawable/ic_launcher"
}
I was having the same issue, using the sample provided at the node-gcm page. After struggling for quite some time i came across this blogpost: http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/
and modified my code according to the example provided in the blog post.
i guess there is an issue with "notification" object on node-gcm code, using message.addData seems to make it work,
in short replacing the message creation and sending logic as below worked for my application :
// For Android
if (row.device === "Android" && row.deviceToken) {
console.log(row.deviceToken);
var sender = new gcm.Sender(serverApiKey);
var message = new gcm.Message();
message.addData('title','İş Geliştirme Platformu');
message.addData('message','Yeni İleti');
message.addData('msgcnt','1');
//message.collapseKey = 'demo';
message.delayWhileIdle = true;
message.timeToLive = 3;
var registrationIds = [];
registrationIds.push(row.deviceToken);
sender.send(message, registrationIds, 4, function (err, result) {
console.log(result);
res.send(200,result);
});
}
add your server IP to white list and try again:
console.developers.google.com > APIs & auth > credential > select your server key > and add your server IP

Pusher - Private channel subscription

I have a code with subscribe private channels, and when I try make a subscription I have the next message:
Pusher : Couldn't get auth info from your webapp : 404
Scenario:
Javascript(Sencha touch) and PHP(Laravel)
The subscription is in javascript:
Pusher.channel_auth_endpoint = "/pusher.php";
var APP_KEY = '4324523452435234523';
var pusher = new Pusher(APP_KEY);
var channel = pusher.subscribe('private-l2');
channel.bind('pusher:subscription_succeeded', function() {
alert("ahora siiii");
});
// for debugging purposes. Not required.
Pusher.log = function(msg) {
if(window.console && window.console.log) {
window.console.log("PUSHER LOG: "+msg);
}
}
AND the pusher.php / LARAVEL
$this->app_id = '66981';
$this->app_key = '4324523452435234523';
$this->app_secret = 'f34632459911e2670dcf';
$pusher = new Pusher($this->app_key, $this->app_secret, $this->app_id);
$auth = $pusher->socket_auth(Input::get('channel_name'), Input::get('socket_id'));
echo $auth;
The result is the error:
Pusher : State changed : connecting -> connected
Pusher : Couldn't get auth info from your webapp : 404
You should set up a route for the Pusher authentication
Route::post('pusher/auth', 'ApiController#pusherAuth');
In that method you should first disable php debugbar (if you're using it) authenticate the user and if authentication checks, then return the response.
I'll paste my controller code below.
public function pusherAuth()
{
\Debugbar::disable();
$user = auth()->user();
if ($user) {
$pusher = new \Pusher(config('broadcasting.connections.pusher.key'), config('broadcasting.connections.pusher.secret'), config('broadcasting.connections.pusher.app_id'));
echo $pusher->socket_auth(request()->input('channel_name'), request()->input('socket_id'));
return;
}else {
header('', true, 403);
echo "Forbidden";
return;
}
}
My JS code:
var pusher = new Pusher(project.pusherKey, {
cluster: 'eu',
encrypted: true,
authEndpoint: apiUrl(['pusher', 'auth']), // just a helper method to create a link
auth: {
headers: {
'X-CSRF-Token': project.token // CSRF token
}
}
});
var channelName = 'private-notifications-' + project.userId; // channel for the user id
var channel = pusher.subscribe(channelName);
channel.bind('new_notification', function (data)
{
app.addNotification(data); // send the notification in the JS app
});
I hope this helps.
Cheers!
Private Pusher channels require the client to authenticate for access. See http://pusher.com/docs/authenticating_users for details on configuring the client for authentication and setting up an authentication endpoint.
Change
Pusher.channel_auth_endpoint = "/pusher.php";
for:
Pusher.channel_auth_endpoint = "/public/broadcasting/auth";
I am not expert at laravel but I guess you have used get request to retrieve data(Socket id & channel name) while it's the post request from pusher server to your server endpoint. Use post to retrieve the data.

Categories

Resources