Twilio Chat: Trying to get notification of Member Reachability on a Channel - javascript

I'm trying get notifications to other members of a channel when a member of a chat channel has left the room. Specifically if they navigate away from the page in their browser. I have "Reachability Enabled" on the service, and am getting verification of that by checking the Client.reachabilityEnabled member.
I'm able to access a list of all of the members of the channel by calling on Channel.getMembers(), but the userInfoUpdated event does not fire when a member enters or leaves the chat page.
A side, but possibly relevant item is that the member.state.attributes object is empty when I inspect any member in the console.(reference this question Twilio chat member online status is always null -- it shows an image of the console inspector that has values including online status in the member.state.attributes object) -
Running the code below, I get my notification that Reachability is enabled and my console log of the members, but when I have some other member enter/exit the page no event fires.
/*twilioChat is the return from require: https://media.twiliocdn.com/sdk/js/chat/v3.3/twilio-chat.min.js*/
function chatInit(twilioChat){
$scope.twilioChat = twilioChat;
$scope.twilioChat.Client.create($scope.TOKEN).then(client => {
console.log('Created chat client');
$scope.chatClient = client;
$scope.chatClient.getSubscribedChannels().then(function(){
$scope.chatReady = true;
console.log('chat is ready');
createOrJoinMonitorChannel();
});
}).catch((err) =>{
console.error(err);
})
}
function createOrJoinMonitorChannel(){
$scope.chatClient.getChannelByUniqueName($scope.monitor_listen)
.then(function(channel){
$scope.monitorListenChannel = channel;
setupMonitorChannel();
}).catch(function(err){
console.log(err);
$scope.chatClient.createChannel({
uniqueName: $scope.monitor_listen,
friendlyName: $scope.monitor_listen,
}).then(function(channel){
$scope.monitorListenChannel = channel;
setupMonitorChannel();
}).catch(function(err){
console.log('Monitor Channel could not be created');
console.log(err);
});
});
}
function setupMonitorChannel(){
var status = $scope.monitorListenChannel.state.status;
if(status !== 'joined'){
$scope.monitorListenChannel.join().then(function(channel){
});
}else{
}
$scope.monitorListenChannel.on('memberJoined',function(m){
console.log('member joined');
});
$scope.monitorListenChannel.on('memberLeft',function(m){
console.log('member left');
});
if($scope.chatClient.reachabilityEnabled){
console.log('Enabled');
}else{
console.log('Not Enabled');
}
$member_promise = $scope.monitorListenChannel.getMembers();
$member_promise.then(members=>{
console.log(members);
members.forEach(member=>{
member.on('userInfoUpdated',function(user){
console.log('user info updated') ;
});
})
});
$scope.monitorListenChannel.on('messageAdded', function(message){
var data = isJSONSTR(message.body);
$handler.classroomMonitor(data);
});
}

When you enable Reachability it fires off an event when a user is online or not. You can use the user.on("updated", ({user, updateReasons}) => {}) event listener. Depending on which version you are using, userInfoUpdated might not be supported.
When you are listening for when a member has left a channel, you have to call channel.leave() yourself. Does this help?
https://media.twiliocdn.com/sdk/js/chat/releases/4.0.0/docs/User.html

Related

Discord.js "voiceStateUpdate" called twice

I am trying to create a temporary channel what is working with "Slash" commands. I am almost there but I am getting an error when creating a second channel because the "voiceStateUpdate" is getting called twice.
else if (commandName === "createchannel") {
var channelName = options.getString("channelname");
var rolesThatCanJoin = options.getRole("roles");
var state = options.getString("state");
var channel = interection.guild.channels.create(channelName, {
type: "GUILD_VOICE"
}).then((channel) => {
channel.setParent("670691620844470320")
createdChannelID = channel.id;
interection.reply({
content: `**Channel named:** ${channelName}\n**Role that can join:** ${rolesThatCanJoin}\n**State:** ${state}`,
ephemeral: true,
})
client.on('voiceStateUpdate', (oldState, newState) => {
var newChannelID = newState.channelId;
if (newChannelID === createdChannelID) {
console.log("User has joined voice channel with id " + newChannelID);
}
else {
console.log("User has left");
channel.delete()
}
});
});
}
Console:
User has joined voice channel with id 936252040865284156
User has left
User has joined voice channel with id 936252068568641576
User has joined voice channel with id 936252068568641576
User has left
User has left
Error:
DiscordAPIError: Unknown Channel
It seems like every time the command runs, you are calling client.on('voiceStateUpdate'... again, which adds another listener. This is causing you to receive the same event multiple times. I suggest you move your client.on('voiceStateUpdate'... code to another location where it will get called once, same as how you are handling other events like client.on('messageCreate'... or client.on('interactionCreate'...

How to get wix chat channel Id when user enterto my website

I want to get channel Id so I used corvid documentation and follow instructions
First I added wix chat app
then I added the following function :
export async function wixGetChannelId() {
let channel = await $w("#myChatbox").getChannel({type: "Business"});
console.log("channel id",channelId) }
and call wixGetChannelId function from onReady
But I got undefied, what I need to change?
So I tried the below code to loop for the channel id.
$w.onReady(function () {
setInterval( () => {
getId();
}, 1500);
});
function getId() {
$w("#wixChat1").getChannel({type: "Business"})
.then((channel) => {
console.log(channel);
})
.catch((err) => {
console.log(err);
});
}
Basically, I get error the first few times (you are receiving the undefined because you dont catch the error) but as soon as I click on the chatbox icon (which I think triggers the creation of the channel) I start getting the channel information.
So I think the user needs to first initiate a conversation which triggers a new channel creation.

Firebase logout user all sessions

I am using Firebase authentication in my iOS app. Is there any way in Firebase when user login my app with Firebase then logout that user all other devices(sessions)? Can I do that with Firebase admin SDK?
When i had this issue i resolved it with cloud functions
Please visit this link for more details https://firebase.google.com/docs/auth/admin/manage-sessions#revoke_refresh_tokens
Do the following;
Set up web server with firebase cloud functions (if none exists)
use the admin sdk(thats the only way this method would work) - [Visit this link] (
(https://firebase.google.com/docs/admin/setup#initialize_the_sdk).
Create an api that receives the uid and revokes current sessions as specified in the first link above
admin.auth().revokeRefreshTokens(uid)
.then(() => {
return admin.auth().getUser(uid);
})
.then((userRecord) => {
return new Date(userRecord.tokensValidAfterTime).getTime() / 1000;
})
.then((timestamp) => {
//return valid response to ios app to continue the user's login process
});
Voila users logged out. I hope this gives insight into resolving the issue
Firebase doesn't provide such feature. You need to manage it yourself.
Here is the Firebase Doc and they haven't mentioned anything related to single user sign in.
Here is what you can do for this-
Take one token in User node (Where you save user's other data) in Firebase database and regenerate it every time you logged in into application, Match this token with already logged in user's token (Which is saved locally) in appDidBecomeActive and appDidFinishLaunching or possibly each time you perform any operation with Firebase or may be in some fixed time interval. If tokens are different logged out the user manually and take user to authenticate screen.
What i have done is:
Created collection in firestore called "activeSessions".User email as an id for object and "activeID" field for holding most recent session id.
in sign in page code:
Generating id for a user session every time user is logging in.
Add this id to localstorage(should be cleaned everytime before adding).
Replace "activeID" by generated id in collection "activeSessions" with current user email.
function addToActiveSession() {
var sesID = gen();
var db = firebase.firestore();
localStorage.setItem('userID', sesID);
db.collection("activeSessions").doc(firebase.auth().currentUser.email).set({
activeID: sesID
}).catch(function (error) {
console.error("Error writing document: ", error);
});
}
function gen() {
var buf = new Uint8Array(1);
window.crypto.getRandomValues(buf);
return buf[0];
}
function signin(){
firebase.auth().signInWithEmailAndPassword(email, password).then(function (user) {
localStorage.clear();
addToActiveSession();
}
}), function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('wrong pass');
} else {
alert(errorMessage);
}
console.log(error);
};
}
Then i am checking on each page if the id session in local storage is the same as "activeID" in firestore,if not then log out.
function checkSession(){
var db = firebase.firestore();
var docRef = db.collection("activeSessions").doc(firebase.auth().currentUser.email);
docRef.get().then(function (doc) {
alert(doc.data().activeID);
alert(localStorage.getItem('userID'));
if (doc.data().activeID != localStorage.getItem('userID')) {
alert("bie bie");
firebase.auth().signOut().then(() => {
window.location.href = "signin.html";
}).catch((error) => {
// An error happened.
});
window.location.href = "accountone.html";
} else{alert("vse ok");}
}).catch(function (error) {
console.log("Error getting document:", error);
});
}
PS: window has to be refreshed to log inactive session out.

Unable to get serviceWorkerRegistration

I followed this tutorial ,to make Push notification on Google Chrome by using GCM. My problem is I'm unable to complete the operation! i have no idea why.
In subscribe function, it breaks out the function whenever it tries to execute
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe()
.then(function(subscription) {
// ...
};
});
It has no console error and no console warning and it doesn't enter the catch! Here is what I did:
function subscribe() {
var pushButton = document.querySelector('.js-push-button');
pushButton.disabled = true;
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe()
.then(function(subscription) {
// The subscription was successful
isPushEnabled = true;
pushButton.textContent = 'Disable Push Messages';
pushButton.disabled = false;
console.log("sending sub");
sendSubscriptionToServer(subscription);
// TODO: Send the subscription.endpoint to your server
// and save it to send a push message at a later date
return sendSubscriptionToServer(subscription);
})
.catch(function(e) {
if (Notification.permission === 'denied') {
// The user denied the notification permission which
// means we failed to subscribe and the user will need
// to manually change the notification permission to
// subscribe to push messages
console.warn('Permission for Notifications was denied');
pushButton.disabled = true;
} else {
// A problem occurred with the subscription; common reasons
// include network errors, and lacking gcm_sender_id and/or
// gcm_user_visible_only in the manifest.
console.error('Unable to subscribe to push.', e);
pushButton.disabled = false;
pushButton.textContent = 'Enable Push Messages';
}
});
});
}
The only thing that did work for me is the 'getRegistration' method, used as the following code
navigator.serviceWorker.getRegistration('/Workers/').then( r => subscribe( r ) );
where '/Workers/' is the path where the ServiceWorker.js is

how to get current user on firebase

I would like to know how how to get the current user. I am making a function where the user is creating a group and would like to add the user making the group to it at the same time. I can make the group fine, that was simple enough. But I do not know how to get to the user object outside of the simple login object.
I'm sorry if there are several topics stating this already, but I have been looking for hours and have not been able to find anything that explains it. Any help would be appreciated.
The currently logged in user is returned from Simple Login's callback. This callback runs when your user authenticates, or if your user is already authenticated, it runs at the time of page load.
Take this code form the simple login docs:
var myRef = new Firebase("https://<your-firebase>.firebaseio.com");
var authClient = new FirebaseSimpleLogin(myRef, function(error, user) {
if (error) {
// an error occurred while attempting login
console.log(error);
} else if (user) {
// user authenticated with Firebase
console.log("User ID: " + user.uid + ", Provider: " + user.provider);
} else {
// user is logged out
}
});
The user object is exposed in the callback. It's only in scope during the execution of that callback, so if you want to use it outside, store it in a variable for reuse later like this:
var currentUser = {};
var myRef = new Firebase("https://<your-firebase>.firebaseio.com");
var authClient = new FirebaseSimpleLogin(myRef, function(error, user) {
if (error) {
// an error occurred while attempting login
console.log(error);
} else if (user) {
// user authenticated with Firebase
currentUser = user;
} else {
// user is logged out
}
});
...
// Later on in your code (that runs some time after that login callback fires)
console.log("User ID: " + currentUser.uid + ", Provider: " + currentUser.provider);

Categories