Web notification based on pubnub - javascript

I am using pubnub for web based notification on my project. I integrated pubnub and using pubnub subscribe method to show new message available on my channel. But once the page refreshed i can't able to identify new message available in my channel or not. Any other method available in pubnub any new message available in channel in page refresh also.
Please suggest one method for this issue. Now i am showing web based push notification only based on Pubnub subscribe.
Example Code:
$scope.showNotification = function (newmessage){
var ms = 30000; // close notification after 30sec
if ((typeof Notification === 'function') && (typeof Notification != 'undefined')) {
var notification = new Notification('name' , {
body: newmessage.message.fromName+" : "+newmessage.message.topic,
icon: 'images/logo.png'
});
}
notification.onshow = function() {
setTimeout(notification.close, ms);
};
notification.onclick = function(){$rootScope.announceClick(newmessage.message.type,newmessage)};
}
Pubnub.subscribe({
channel: $scope.userID,
callback: function (newMsg) {
var newmessage = {};
newmessage.message = newMsg;
$scope.showNotification(newmessage);
}
});

Related

Twilio Client CallSid Getting Changed in JavaScript

I've implemented a call center in Salesforce with Twilio client JavaScript SDK. I'm trying to save the call record information in Salesforce and I'm using the connection.parameters.CallSid to identify the correct record when the recording call back fires. However my CallSid in client side is getting changed automatically sometimes to a different format and hence the recording call back function can't find the Salesforce end record to update it with the RecordingUrl. Have anyone experienced this before or appreciate any guidance.
Below is my JavaScript code. To be more specific, in the startCall function console.log print the CallSid correctly but when goes to saveLog function it's having a different value with a different format and hence the saved record having an incorrect value.
<script type="text/javascript">
Twilio.Device.setup("{! token }");
var callerSid; // hold the Twilio generated CallSid unique to this call
var parentId; // hold the parent record being called in order to associate as the parent of task being logged for the call
var newTaskId; // hold the id of newly created task
// function to fire when click 2 dial executes
var startCall = function (payload) {
sforce.opencti.setSoftphonePanelVisibility({visible: true}); //pop up CTI softphone
parentId = payload.recordId; // the record that the phone number being called belongs to
var cleanednumber = cleanFormatting(payload.number);
params = {"PhoneNumber": cleanednumber};
var connection = Twilio.Device.connect(params);
callerSid = connection.parameters; // track the unique Twilio CallSid
console.log('clk2dial : ', callerSid.CallSid); **// here it logs correcly as CAc57d05994cd69498e0353a5f4b07f2dc**
setTimeout(function(){
saveLog(); // save the call information in a Task record
}, 2000
);
};
//OpenCTI!!
sforce.opencti.enableClickToDial();
sforce.opencti.onClickToDial({listener : startCall}); // click 2 dial
function cleanFormatting(number) {
//changes a SFDC formatted US number, which would be 415-555-1212 into a twilio understanble number 4155551212
return number.replace(' ','').replace('-','').replace('(','').replace(')','').replace('+','');
}
// save the call information in a Task record
function saveLog() {
var keyPrefix;
var taskToSave;
console.log('callerSid.CallSid : ', callerSid.CallSid); **// surprisingly here it logs as TJSce253eb4-c2a0-47f3-957f-8178e95162aa**
if(parentId != null) {
keyPrefix = parentId.slice(0,3);
}
if(keyPrefix != null && keyPrefix == '003') {
taskToSave = {WhoId:parentId, Type: "Call", CallObject: callerSid.CallSid, entityApiName: "Task", Subject: "Call log"};
} else {
taskToSave = {WhatId:parentId, Type: "Call", CallObject: callerSid.CallSid, entityApiName: "Task", Subject: "Call log"};
}
sforce.opencti.saveLog({value:taskToSave, callback: saveLogCallBack});
}
// call back function for saving the call information in a Task record
var saveLogCallBack = function(response) {
if(response.success) {
newTaskId = response.returnValue.recordId;
console.log('save success! : ', newTaskId);
} else {
console.error('Error saving : ', response.errors);
}
}
</script>
Answering my own question as I got through this. I registered a function for Twilio.Device.connect and in the call back function retrieved the CallSid. Along with that I've updated my click 2 dial function as well accordigly as below. However I was unable to find this approach in Twilio documentation and any comments are welcome.
// function to fire when click 2 dial executes
var startCall = function (payload) {
sforce.opencti.setSoftphonePanelVisibility({visible: true}); //pop up CTI softphone
parentId = payload.recordId; // the record that the phone number being called belongs to
var cleanednumber = cleanFormatting(payload.number);
params = {"PhoneNumber": cleanednumber};
Twilio.Device.connect(params);
};
//OpenCTI!!
sforce.opencti.enableClickToDial();
sforce.opencti.onClickToDial({listener : startCall}); // click 2 dial
// registered a function for Twilio Device connect
Twilio.Device.connect(function(response) {
callSid = response.parameters; // track the unique Twilio CallSid
// nothing change in save function so not posting again
saveLog(); // save the call information in a Task record
});

How can I close the client-side JavaScript 'Hub' connection in SignalR?

I have followed this tutorial.
But there is no hint how to close the Websocket connection via the HubConnection class in signalr.js-file. The file is V1.0.4.
This solution does not resolve my problem because I am using the microsofts javascript-library.
Here ist the code:
var lHubConnection = null;
var Init = function () {
// create instance
lHubConnection = new signalR.lHubConnectionBuilder().withUrl("/chatHub").build();
// receive message
lHubConnection.on("ReceiveMessage", function (pMessage) {
// show message
console.log(JSON.parse(pMessage));
});
// [...]
};
// close websocket connection
var CloseConnection = function(){
if (lHubConnection !== null && lHubConnection.connection.connectionState === 1) {
// lHubConnection.invoke("?"); ???
}
};
Here is an console output of the lHubConnection instance:
According to Microsoft the JavaScript client contains a stop function.
https://learn.microsoft.com/en-us/javascript/api/%40aspnet/signalr/hubconnection?view=signalr-js-latest#stop
In addition, you can find the .stop()-Method in the prototype of the framework:

How manage the online/offline status of the user in SignalR

I have created the chat application with SignalR version 2.2.1 and I would like to create the information about user status - that means online/offline state.
I have tried use the method:
public override Task OnConnected()
{
var token = Context.QueryString["token"];
if (string.IsNullOrEmpty(token)) return Task.FromResult(0);
using (var dbContext = new AppDbContext())
{
dbContext.UserConnections.Add(new UserConnection { ConnectionKey = Context.ConnectionId, UserId = token.GetUserId() });
dbContext.SaveChanges();
}
Clients.Others.UserConnected(token.GetUserId());
return Task.FromResult(0);
}
public override Task OnDisconnected(bool stopCalled)
{
using (var dbContext = new AppDbContext())
{
var connection = dbContext.UserConnections.First(x => x.ConnectionKey == Context.ConnectionId);
var userId = connection.UserId;
if (connection == null) return Task.FromResult(0);
dbContext.UserConnections.Remove(connection);
dbContext.SaveChanges();
}
Clients.Others.UserDisconnected(userId);
return Task.FromResult(0);
}
I don't know how correctly work with disconnect method on the client - because when user refresh the browser automaticly is called the OnDisconnected event with parameter stopCalled=true - I can now send some information about disconnection this user and set the icon for offline but immediately is user connect again and the icon is set to the online state and the user experience is strange.
How can I manage the disconnect state on javascript client without blinking the online/offline status especialy thought refresh page?

WebRTC ondatachannel event not getting triggered

I have been trying to get data chat working using webrtc. It was working previously in google chrome and suddenly stopped working, I have narrowed down the issue to 'ondatachannel' callback function not getting triggered. The exact same code works fine in Mozilla.
Here's the overall code:
app.pc_config =
{'iceServers': [
{'url': 'stun:stun.l.google.com:19302'}
]};
app.pc_constraints = {
'optional': [
/* {'DtlsSrtpKeyAgreement': true},*/
{'RtpDataChannels': true}
]};
var localConnection = null, remoteConnection = null;
try {
localConnection = new app.RTCPeerConnection(app.pc_config, app.pc_constraints);
localConnection.onicecandidate = app.setIceCandidate;
localConnection.onaddstream = app.handleRemoteStreamAdded;
localConnection.onremovestream = app.handleRemoteStreamRemoved;
}
catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
return;
}
isStarted = true;
In Create Channel that follows this:
var localConnection = app.localConnection;
var sendChannel = null;
try {
sendChannel = localConnection.createDataChannel(app.currentchannel,
{reliable: false});
sendChannel.onopen = app.handleOpenState;
sendChannel.onclose = app.handleCloseState;
sendChannel.onerror = app.handleErrorState;
sendChannel.onmessage = app.handleMessage;
console.log('created send channel');
} catch (e) {
console.log('channel creation failed ' + e.message);
}
if (!app.isInitiator){
localConnection.ondatachannel = app.gotReceiveChannel;
}
app.sendChannel = sendChannel;
I create Offer:
app.localConnection.createOffer(app.gotLocalDescription, app.handleError);
and Answer:
app.localConnection.createAnswer(app.gotLocalDescription, app.handleError);
the offer and answer get created successfully, candidates are exchanged and onicecandidate event is triggered at both ends! Local Description and RemoteDescription are set on both respective ends.
I have a pusher server for signalling, I am able to send and receive messages through the pusher server successfully.
The same webrtc code works for audio/video = true, the only issue is when I try to create datachannel. The only step that does not get executed is the callback function not getting executed i.e "gotReceiveChannel"
I'm starting to think it's the version of chrome.. I am not able to get the GitHub example working in chrome either: (Step4 for data chat)
https://bitbucket.org/webrtc/codelab
While the same code works in Mozilla.
The sendChannel from the offerer has a "readyState" of "connecting"
Any help much appreciated.

Dealing with titanium Push notifications ios

Here is my code:
Titanium.Network.registerForPushNotifications({
types: [
Titanium.Network.NOTIFICATION_TYPE_BADGE,
Titanium.Network.NOTIFICATION_TYPE_ALERT
],
success:function(e)
{
var deviceToken = e.deviceToken;
Ti.API.info("Push notification device token is: "+deviceToken);
alert('device token is' +e.deviceToken);
Ti.API.info("Push notification types: "+Titanium.Network.remoteNotificationTypes);
Ti.API.info("Push notification enabled: "+Titanium.Network.remoteNotificationsEnabled);
},
error:function(e)
{
Ti.API.info("Error during registration: "+e.error);
},
callback:function(e)
{
// called when a push notification is received.
//Titanium.Media.vibrate();
var data = JSON.parse(e.data);
var badge = data.badge;
if(badge > 0){
Titanium.UI.iPhone.appBadge = badge;
}
var message = data.message;
if(message != ''){
var my_alert = Ti.UI.createAlertDialog({title:'', message:message});
my_alert.show();
}
}
});
}
The callback function:
callback:function(e)
{
// called when a push notification is received.
//Titanium.Media.vibrate();
var data = JSON.parse(e.data);
var badge = data.badge;
if(badge > 0){
Titanium.UI.iPhone.appBadge = badge;
}
var message = data.message;
if(message != ''){
var my_alert = Ti.UI.createAlertDialog({title:'', message:message});
my_alert.show();
}
}
});
is fired when the push notification is recieved when the app is running in the foreground.
Question , if I have 2 files:
app.js -> newwindow.js
and say that I am in newwindow.js , will I still receive push notifications? (if the code above is all pasted in app.js?)
2) When I recieve a push notification when the app is running in the background, how can I write a callback method for it, so I can tell the app what to do with that notification
3) What is the best way of handling different notifications, i.e. say I need to open different windows, when its in background mode?
notification 1 - > win1.js
notification 2 - > win2.js
notification 3 - > win3.js
First of all you should Implement it in your app(It seems you just copied from docs) and see how actually push notification appear it will make every thing a lot clear.
The callback you have written above will fetch the message that you have send using the Push notification.
As for part 2 of your question : Once the user clicks on the push received your app will come into foreground and the callback will be automatically called.
And to handle different notifications, there are never different push notifications, there is always a single push notification.you have to parse the data and have act according to the condition. you can modify your push message and open window according to it.

Categories

Resources