Twilio chat events memberUpdated, and userInfoUpdated never fired - javascript

i'm looking on what cases are these events is firing, i have implement it on these code
jQuery(document).ready(function() {
var chatChannel;
var chatClient;
var username;
var $input = $('#chat-input');
$.post("/tokens", function(data) {
username = data.username;
chatClient = new Twilio.Chat.Client(data.token);
chatClient.getSubscribedChannels().then(createOrJoinGeneralChannel);
});
function createOrJoinGeneralChannel() {
// Get the general chat channel, which is where all the messages are
// sent in this simple application
// print('Attempting to join "general" chat channel...');
var promise = chatClient.getChannelByUniqueName("#{params[:chat_channel]}");
promise.then(function(channel) {
chatChannel = channel;
console.log("#{params[:chat_channel]} is exist");
console.log(chatChannel);
setupChannel();
return channel.getMembers();
// $input.removeClass('.hidden')
})
.then(function(members){
members.forEach(function(member){
console.log('member', member);
member.on('userInfoUpdated', function(){
console.log('userInfoUpdated', member);
})
})
})
.catch(function() {
// If it doesn't exist, let's create it
console.log("creating #{params[:chat_channel]} channel");
chatClient.createChannel({
uniqueName: "#{params[:chat_channel]}",
friendlyName: 'General Chat Channel'
}).then(function(channel) {
console.log("Created #{params[:chat_channel]} channel:");
console.log(channel);
chatChannel = channel;
setupChannel();
});
});
}
function setupChannel() {
chatChannel.join().then(function(channel) {
printMessage(username + ' joined the chat.');
chatChannel.on('typingStarted', showTypingStarted);
chatChannel.on('typingEnded', hideTypingStarted);
chatChannel.on('memberJoined', notifyMemberJoined);
chatChannel.on('memberLeft', notifyMemberLeft);
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
});
chatChannel.on('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
}
function updateMemberMessageReadStatus(member){
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
}
function leaveCurrentChannel() {
if (chatChannel) {
chatChannel.leave().then(function (leftChannel) {
console.log('left ' + leftChannel.friendlyName);
leftChannel.removeListener('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
leftChannel.removeListener('typingStarted', showTypingStarted);
leftChannel.removeListener('typingEnded', hideTypingStarted);
leftChannel.removeListener('memberJoined', notifyMemberJoined);
leftChannel.removeListener('memberLeft', notifyMemberLeft);
leftChannel.removeListener('memberUpdated', updateMemberMessageReadStatus);
});
}
}
function showTypingStarted(member) {
console.log('somebody is typing');
$('#is_typing').html(member.identity + ' is typing...');
}
function hideTypingStarted(member) {
$('#is_typing').html('');
}
function notifyMemberJoined(member) {
console.log('notifyMemberJoined');
printMessage(member.identity + ' joined the channel');
}
function notifyMemberLeft(member) {
console.log('notifyMemberLeft');
printMessage(member.identity + ' left the channel');
}
$input.on('keydown', function(e) {
if (e.keyCode == 13) {
chatChannel.sendMessage($input.val());
$input.val('');
} else {
//console.log('typing');
chatChannel.typing();
}
});
window.addEventListener("beforeunload", function (e) {
// var confirmationMessage = "\o/";
(e || window.event).returnValue = leaveCurrentChannel(); //Gecko + IE
return leaveCurrentChannel(); //Webkit, Safari, Chrome
});
});
and i've take alook to the console to see if my
console.log('userInfoUpdated', member);
or these guys
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
and they are never fired, during my test on the chat events, and i'm confused on how exactly i'm going to display how my users online or the status of a message is read or unread
so please enlighten me on the case, thank you

Twilio developer evangelist here.
According to the JS docs for the latest version of Twilio Chat, the event you need to listen for on members is just called 'updated'. So, listening for 'userInfoUpdated' won't work.
I would also recommend that within this code:
chatChannel.join().then(function(channel) {
//...
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
you use the channel passed to the callback, rather than the original chatChannel object. Like this:
chatChannel.join().then(function(channel) {
//...
channel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
I don't know if this will fix the issue, but I can't think of anything else right now.

Related

Why do I have to constantly trigger a GET request in this chat application?

I am new to AJAX and PHP, and I don't quite understand this code:
https://github.com/Artifx/PHP-and-MySQL-Web-Development-5th-Edition/blob/master/Chapter23/client.js
var pollServer = function() {
$.get('chat.php', function(result) {
if(!result.success) {
console.log("Error polling server for new messages!");
return;
}
$.each(result.messages, function(idx) {
var chatBubble;
if(this.sent_by == 'self') {
chatBubble = $('<div class="row bubble-sent pull-right">' +
this.message +
'</div><div class="clearfix"></div>');
} else {
chatBubble = $('<div class="row bubble-recv">' +
this.message +
'</div><div class="clearfix"></div>');
}
$('#chatPanel').append(chatBubble);
});
setTimeout(pollServer, 5000);
});
}
$(document).on('ready', function() {
pollServer();
$('button').click(function() {
$(this).toggleClass('active');
});
});
$('#sendMessageBtn').on('click', function(event) {
event.preventDefault();
var message = $('#chatMessage').val();
$.post('chat.php', {
'message' : message
}, function(result) {
$('#sendMessageBtn').toggleClass('active');
if(!result.success) {
alert("There was an error sending your message");
} else {
console.log("Message sent!");
$('#chatMessage').val('');
}
});
});
Is it not possible to trigger a GET request only after a POST request has been made? What is wrong with this logic, that makes it necessary to run the pollServer function every 5 seconds?

Ionic cant get Reg ID for GCM

I read every topic and tried every way. About 2 days and i still didnt get Reg ID. MY Sender ID is right and check every example in real device. Also i tried
this one
this one
this one
this one
And thoses are just some pages. I almost tried everything and still get just okey message in success handler. Can someone tell me where is my mistake ?
var xxx = angular.module('starter', ['ionic', 'ngCordova'])
xxx.run(function ($ionicPlatform, $cordovaPush) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
var androidConfig = {
"senderID": "5757xxxxxxx",
};
document.addEventListener("deviceready", function () {
$cordovaPush.register(androidConfig).then(function (result) {
alert(result);
}, function (err) {
alert(err);
})
$rootScope.$on('$cordovaPush:notificationReceived', function (event, notification) {
switch (notification.event) {
case 'registered':
if (notification.regid.length > 0) {
alert('registration ID = ' + notification.regid);
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
// WARNING: dangerous to unregister (results in loss of tokenID)
$cordovaPush.unregister(options).then(function (result) {
// Success!
}, function (err) {
// Error
})
}, false)
});
});

Proper syntax for javascript callback

I have a syntax error on the code below, all I want is a function to be executed on a call back but I am not sure what the error is.
should be close to:
onClickCallback: UpdateBillCycleStatusToCompleted(1)
<script type="text/javascript">
SP.SOD.executeFunc("callout.js", "Callout", function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.BaseViewID = 'Callout';
// Define the list template type
itemCtx.ListTemplateType = 101;
itemCtx.Templates.Footer = function (itemCtx) {
// context, custom action function, show the ECB menu (boolean)
return CalloutRenderFooterTemplate(itemCtx, AddCustomCompleteAction, true);
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
});
function AddCustomCompleteAction(renderCtx, calloutActionMenu) {
// Add your custom action
calloutActionMenu.addAction(new CalloutAction({
text: "Custom Action",
tooltip: 'This is your custom action',
onClickCallback: UpdateBillCycleStatusToCompleted(1)
}
}));
// Show the default document library actions
CalloutOnPostRenderTemplate(renderCtx, calloutActionMenu);
// Show the follow action
calloutActionMenu.addAction(new CalloutAction({
text: Strings.STS.L_CalloutFollowAction,
tooltip: Strings.STS.L_CalloutFollowAction_Tooltip,
onClickCallback: function (calloutActionClickEvent, calloutAction) {
var callout = GetCalloutFromRenderCtx(renderCtx);
if (!(typeof (callout) === 'undefined' || callout === null)) callout.close();
SP.SOD.executeFunc('followingcommon.js', 'FollowSelectedDocument', function () {
FollowSelectedDocument(renderCtx);
});
}
}));
}
function UpdateBillCycleStatusToCompleted(itemId) {
alert('Completed');
//var clientContext = new SP.ClientContext.get_current();
//var oList = clientContext.get_web().get_lists().getByTitle('Bill Cycles');
//this.oListItem = oList.getItemById(itemId);
//oListItem.set_item('Bill Cycle Preparation Status', 'Completed');
//oListItem.update();
//clientContext.executeQueryAsync(Function.createDelegate(this, this.StatusCompletedSucceeded), Function.createDelegate(this, this.StatusCompletedFailed));
}
function StatusCompletedSucceeded() {
alert('Item updated!');
}
function StatusCompletedFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
Unless UpdateBillCycleStatusToCompleted(1) actually return function() {...} then you're doing it wrong.
onClickCallback: function() {UpdateBillCycleStatusToCompleted(1);}
That sort of thing should work.

Javascript not running on Facebook iframe

I have a django project which is intended for a facebook application. In the project, the invite friends module runs fine in localhost!
But while it is loaded in facebook application, the javascript responsible for displaying the friends list doesn't work. Although the libraries are properly loaded.
I don't know why it is so. May be some iframe problem.
Here is the javascript code
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '460948667348013', cookie: true});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me', function(response) {
// alert('Your name is ' + response.name);
console.log('Your name is ' + response.name);
init();
});
} else if (response.status === 'not_authorized') {
alert('the user is logged in to Facebook, but has not authenticated your app');
} else {
alert('the user is not logged in to Facebook.');
}
});
}
function init() {
FB.api('/me', function(response) {
$("#username").html("<img src='https://graph.facebook.com/" + response.id + "/picture'/><div>" + response.name + "</div>");
$("#jfmfs-container").jfmfs({
max_selected: 15,
max_selected_message: "{0} of {1} selected",
friend_fields: "id,name,last_name",
pre_selected_friends: [1014025367],
exclude_friends: [1211122344, 610526078],
sorter: function(a, b) {
var x = a.last_name.toLowerCase();
var y = b.last_name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
});
$("#jfmfs-container").bind("jfmfs.friendload.finished", function() {
window.console && console.log("finished loading!");
});
$("#jfmfs-container").bind("jfmfs.selection.changed", function(e, data) {
window.console && console.log("changed", data);
});
$("#logged-out-status").hide();
$("#show-friends").show();
});
}
$("#show-friends").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
$("#selected-friends").html(friendSelector.getSelectedIds().join(', '));
});
function sendRequest() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendUIDs = friendSelector.getSelectedIds().join(', ');
// Use FB.ui to send the Request(s)
FB.ui({method: 'apprequests',
to: sendUIDs,
title: 'My Great Invite',
message: 'Check out this Awesome App!',
}, callback);
}
function callback(response) {
// alert('callback called');
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendUIDs = friendSelector.getSelectedIds().join(',');
var uids = sendUIDs.split(',');
var query = '';
for(i=0;i<uids.length;i++){
if(i==0){
query = query + 'to[' + i + ']=' + uids[i];
}
else{
query = query + '&to[' + i + ']=' + uids[i];
}
}
console.log(query);
if(response){
// alert('successful');
window.location.assign("/?"+ query)
}
else{
alert('failure');
}
}
</script>
Please help ! I am stuck with this problem.
The issue may be SSL issues.
Facebook has made many changes in few months ago.
Also you need to keep update with Facebook developer blog.
So I am going to try to explain few things I suspected.
App on Facebook
Your Canvas Page should be https://apps.facebook.com/yourchoosenname
1a. Your Canvas URL should be https://yoursite.com/yourapplication/
Website
http://yoursite.com/
Page Tab
Your Secure Canvas should be https://yoursite.com/yourapplication/
Your Page Tab URL should be https://yoursite.com/yourapplication/
Your Secure Page Tab URL should be https://yoursite.com/yourapplication/
In this case you will need SSL Certificate for site so You can find reliable yet cheap digital certificate from Here .
This mandatory for any Application to work on facebook.
Hope this will help you and others

Message callback synchronization error

In my extension's content script, I request data from background.js like so:
fireOnNewTopic (); // Initial run on cold start or full reload.
window.addEventListener ("hashchange", fireOnNewTopic, false);
function fireOnNewTopic () {
/*-- For the pages we want, location.hash will contain values
like: "#!newtopic/{group title}"
*/
if (location.hash) {
var locHashParts = location.hash.split ('/');
if (locHashParts.length > 1 && locHashParts[0] == '#!newtopic') {
var subjectStr = '';
var bodyStr = '';
switch (locHashParts[1]) {
case 'opencomments-site-discussions':
chrome.extension.sendMessage({name:"domain"},
function(response)
{
subjectStr = response.domain;
});
chrome.extension.sendMessage({name:"url"},
function(response)
{
bodyStr = "URL of last page visited: " + response.url;
});
break;
default:
break;
}
if (subjectStr && bodyStr) {
runPayloadCode (subjectStr, bodyStr);
}
}
}
}
Unfortunately, since sendMessage() runs asynchronously with the callback, at the time the code reaches runPayloadCode(), subjectStr and bodyStr are still null, since the code in background.js hasn't completed. What's the best way to synchronize the code so that subjectStr and bodyStr are filled in by the time runPayloadCode() is called?
To elaborate on what Sudarshan said about combining the two requests into one (sorry, need code so couldn't just comment) here's what you could do...
send
chrome.extension.sendMessage({url: true, domain:true}, function(response) {
console.debug('The url is "'+response.url+'" and the domain is"'+response.domain+'"');
if (repsone.url && response.domain) {
runPayloadCode (subjectStr, "URL of last page visited: " + response.domain);
}
});
or, if you wanted it more like your case way for some reason, maybe this is the sorta thing you'd like...
if(location.hash) {
var locHashParts = location.hash.split('/');
if(locHashParts.length > 1 && locHashParts[0] == '#!newtopic') {
var subjectStr = '';
var bodyStr = '';
var request = {};
switch(locHashParts[1]) {
case 'opencomments-site-discussions':
request = {
url: true,
domain: true
}
break;
default:
break;
}
chrome.extension.sendMessage(request, function(response) {
console.debug('The url is "' + response.url + '" and the domain is"' + response.domain + '"');
if(repsone.url && response.domain) {
runPayloadCode(subjectStr, "URL of last page visited: " + response.domain);
}
});
}
}
}
listen
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
var response = {};
if(request.url) {
response.url = "someURL";
}
if(request.domain) {
response.domain = "someDomain";
}
sendResponse(response);
});
You can try the following code:
case 'opencomments-site-discussions':
chrome.extension.sendMessage({
name: "domain"
},
function (response) {
subjectStr = response.domain;
if(subjectStr){
chrome.extension.sendMessage({
name: "url"
},
function (response) {
bodyStr = "URL of last page visited: " + response.url;
if (bodyStr) {
runPayloadCode(subjectStr, bodyStr);
}
});
}
});
However, can't you merge both message's chrome.extension.sendMessage({name: "url"}) and chrome.extension.sendMessage({name: "domain"}) into single message(Because i see them independent) and eliminate multiple nesting?

Categories