How do you create a Twilio Video API Ended Event Hook? - twilio

I can't seem to figure out how to add an "ended" event hook after the "disconnected" event.
I wanted to hide the "End Call" button then notify the other participant via sockets so I can also hide their "End Call" button and do other stuff.
Here are my attempts:
My starting code was from https://github.com/TwilioDevEd/video-quickstart-node/blob/master/public/quickstart.js#L27
My attempts are
1. adding a "then" after stopping the conversation and calling a custom function
webRTCActiveConversation.on('disconnected', function (conversation) {
console.log("Connected to Twilio. Listening for incoming Invites as '" + webRTCConversationsClient.identity + "'");
//results to "conversation.localMedia.stop(...).then is not a function"
conversation.localMedia.stop().then(conversationEnded);
webRTCActiveConversation = null;
});
2. adding an "ended" event hook (somehow this was never triggered):
webRTCActiveConversation.on('ended', function (conversation) {
console.log('conversation has ended...');
//should hide end call button then socket emit to hide the end call button on the other connected client
webRTCActiveConversation = null;
});
3. Adding DOM manipulation and socket emit under disconnect event hook (Disconnects call from this client, DOM manipulation and socket event are working, but Twilio connection has not been disconnected on the other connected client)
webRTCActiveConversation.on('disconnected', function (conversation) {
console.log("disconnect call" + webRTCConversationsClient.identity + "'");
conversation.localMedia.stop();
//hide end call button
var el = document.getElementById('button-end-audio-call');
el.className += " hide-state";
//socket emit to hide the end call button on the other connected client
socket.emit('notifyEndCallRequest');
webRTCActiveConversation = null;
});

I did a workaround for the meantime, I modified my attempt no.3 and it worked. I'm sure this is not the best way to do this as there is an "ended" event hook I can't figure out how to trigger, but it solved my issue (both participants got disconnected to the call).
//when the conversation ends, stop capturing local video
webRTCActiveConversation.on('disconnected', function (conversation) {
console.log("disconnect call '" + webRTCConversationsClient.identity + "'");
conversation.localMedia.stop();
webRTCActiveConversation = null;
//delay DOM manipulation and socket emit
setTimeout(function(){
var el = document.getElementById('button-end-audio-call');
el.className += " app-state-hidden";
//socket emit to hide the end call button on the other connected client
socket.emit('notifyEndCallRequest');
}, 3000);
});
Still hopeful for how others handle such case :p

Related

How to get Call Status(Connected, Busy, No answered & Ringing) from Amazon Connect Streams API?

I am using Amazon Connect Streams API [https://github.com/amazon-connect/amazon-connect-streams/blob/master/Documentation.md] and we have different call status in Amazon Connect e.g. call connected, call missed/no answered!
how can i get call status of the following call dispositions (busy, connected, in progress, ringing, no answered) from within Streams API?
I am using
function subscribeToContactEvents(contact) {
console.log("Subscribing to events for contact");
contact.onMissed(handleOnMissed);
contact.onConnected(handleOnConnected);
contact.onEnded(handleOnEnded);
}
function handleOnMissed(contact){
console.log("[contact.onMissed] Call is Missed. Contact status is " + contact.getStatus().type);
}
function handleOnConnected(contact) {
console.log("[contact.onConnected] Call is ACW. Contact status is " + contact.getStatus().type);
}
function handleOnEnded(contact) {
console.log("[contact.onEnded] Call has ended. Contact status is " + contact.getStatus().type);
}
There are two steps to this, first you need to subscribe to agent events then you trigger based on things happening to the agent. So for example...
connect.agent(async function (agent) {
agent.onStateChange(function (agentState){
console.log("Agent State Changed to: " + agentState.newState);
});
});
You can do similar subscribing to contact events.
connect.contact(function (contact) {
activeContact = contact;
contact.onRefresh(function (contact) {/* do stuff */});
contact.onIncoming(function (contact) {/* do stuff */});
contact.onAccepted(function (contact) {/* do stuff */});
contact.onMissed(function (contact) {/* do stuff */});
});
Subscribing to events is covered here... https://github.com/amazon-connect/amazon-connect-streams/blob/master/Documentation.md#event-subscription

javascript background sync android power button

service worker sync will not fire on case in android chrome
WHAT IM MISSING ???
Same thing in here: JavaScript Background Sync Stops Working if Page is Loaded/Refreshed while offline
unplug usb cable for development (for chrome dev tool)
push android home button
push power button for sleep (black screen)
then i wait 5 minutes (at least)
then i push power button for awake
then i push myapp to wake app (app is not closed but set to sleep)
then i blug in usb cable for debugging
then i click some button to fire sync after that i see ---
in console "REGISTER" but "SYNC" event not fired
if i click power button again (black screen)
and then i click power button again - then it will wake up
or i turn off wifi and then turn on wifi - then it will wake up
AND then is see in console "REGISTER" and "SYNC"
IF i wate 30 minutes then registered sync is deleted
CLIENT SIDE JS
var id = 'background-sync-' + (new Date()).getTime() + $.uniqid(6);
let postData = {
'type': 'background-sync',
'uuid': id,
};
registration.active.postMessage(postData);
SERVICE WORKER SIDE
self.addEventListener('message', function (event) {
//console.log('message=' + event.data.type);
if (event.data.type === 'background-sync') {
registerSync(event.data.uuid, event.data);
}
});
self.addEventListener('sync', function (event) {
console.log('SYNC');
//event.waitUntil(syncIt(event.tag));
});
function registerSync(uuid, data) {
if (data != undefined && data != null) {
let id = data.id;
//append data to storage
syncStore[id] = data;
//this is important
syncStore[id]['sending'] = false;
}
console.log('REGISTER');
//console.log(data);
//console.log(self.registration.sync.getTags());
self.registration.sync.register(uuid)
.then(function () {
})
.catch(function (err) {
return err;
});
}
There no solution. Even background-periodic-sync does not work.
So i have made work around - send regular post if possible and use background.sync as offline data sync.
Problem is if i click power button once then sync request set to wait
AND if second time then sync request will be sent to server.
solution code:
if( this.online ){
let self = this;
$.post(self.requestUrl, self.params, function (returnData) {
if( callback )
callback(returnData);
}).fail(function () {
window.backgroundSync(self.requestUrl, self.params, callback, self.storeData);
});
}
else {
window.backgroundSync(this.requestUrl, this.params, callback, this.storeData);
}

django-channels parse json/data sent via sockets

I have this javascript code that send data to channels
// Note that the path doesn't matter for routing; any WebSocket
// connection gets bumped over to WebSocket consumers
socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
alert(e.data);
}
socket.onopen = function() {
socket.send({"test":"data"});
}
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();
I'm curios how from message I can get the json {"test":"data"}
here's the view
# Connected to websocket.connect
#channel_session
def ws_connect(message, key):
# Accept connection
message.reply_channel.send({"accept": True})
You implemented the connection callback, but did not implement what should happen when a message arrives the server endpoint. Add add message receive function:
def on_receive(message):
print('test received: {}'.format(message.content['test']))
Register the function in routing.py:
channel_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", on_receive),
]
The JSON message you send will be stored in message.content which is basically just a python dict.

Twilio Device.destroy() not releasing the device and event handlers

We are using Twilio in our application for voice communication.
When making voice call, we are setting up Twilio device as below.
If call is not successful, we are retrying few more time calling below function again.
My question is doesn't destroy function delete the event handlers as well? And why do I see in log "[Device] Found existing Device; using new token but ignoring options" when I call setup after calling destroy?
function setupTwilio(token) {
if (angular.isFunction(Twilio.Device.destroy)) {
console.log('Destroying Twilio device');
Twilio.Device.destroy(); // Destroy before setup incase we have already run this
}
startEventHandlers(); // add event handlers for Twilio events e.g. connect, disconnect
trySetup = function () {
var params = { debug: ( DEBUG ? true : false ) };
if (DEBUG) {
console.log('trying the twilio setup at ' + new Date());
console.log(Twilio.Device.instance);
}
// Twilio will not hit the handlers specified in startEventHandlers until a successful setup has been created, so run try catch here
try {
Twilio.Device.setup(token, params);
} catch (e) {
if (DEBUG) {
console.log('TwilioSetup uncaught error: ' + e);
}
}
};
if (angular.isDefined(token)) {
trySetup();
}
}
Destroy will trigger the offline event handler. Try setting up the device inside the offline event handler:
Twilio.Device.offline(function() {
Twilio.Device.setup(token, params);
});

Can I listen for a XUL type event in the add-on SDK

I am trying to listen for the event which occurs when an "Authorisation Required" dialogue is displayed (see Firefox Addon SDK Hotkeys and contect menu options dont work on Authentication Required Popup).
However I notice that XUL addons can listen for a DOMWillOpenModalDialog event which is apparently triggered when this dialogue box opens. None of the SDK panel events seem to be triggered.
Is there a way to listen for this event from within the addon SDK?
------Edit------
Going on from Noitidart 's sugestion I then tried a couple of other events and they fire. Both the attempts below work.
var events = require("sdk/system/events");
function listener(event) {console.log("An event popup was activated.");}
events.on("xul-window-visible", listener);
CWin.addEventListener("DOMWillOpenModalDialog", function() {CWin.setTimeout(NfyBox, 500);}, true);
function NfyBox() {
console.log("An event popup was activated.");
worker = tabs.activeTab.attach({
contentScriptFile: self.data.url("notifybox.js")
});
worker.port.emit("notify");
}
However that is as far as I get, in the contentScriptFile, a console.log of document produces :-
console.log: infstr: {"location":{"assign":"function assign() {\n [native cod
e]\n}","replace":"function replace() {\n [native code]\n}","reload":"function
reload() {\n [native code]\n}","toString":"function toString() {\n [nativ
e code]\n}","valueOf":"function valueOf() {\n [native code]\n}","href":"http:
//c1s4-1e-syd.hosting-services.net.au:2082/unprotected/redirect.html","origin":"
http://c1s4-1e-syd.hosting-services.net.au:2082","protocol":"http:","username":"
","password":"","host":"c1s4-1e-syd.hosting-services.net.au:2082","hostname":"c1
s4-1e-syd.hosting-services.net.au","port":"2082","pathname":"/unprotected/redire
ct.html","search":"","hash":""}}
But an attempt to get getElementById or anything else I tried comes back undefined. I am obviously making some simple mistake, but can’t see what it is.
Yes listen to popup events. In this case popupshowing: MDN : PopupEvents
This is an example that prevents the main menu at top right (tri stripe menu button) from closing by listening to popuphiding and preventing it:
var PUI = Services.wm.getMostRecentWindow('navigator:browser').document.querySelector('#PanelUI-popup');
try {
PUI.removeEventListener('popuphiding', previt, false);
} catch (ignore) {}
var previt = function(e) {
PUI.style.opacity = 1;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
return false;
}
PUI.addEventListener('popuphiding', previt, false);

Resources