Unable to disconnect/destroy/unpublish opentok stream - javascript

I'm building a basic audio/video chat feature and all seems to work fine but i'm not able to get rid of session and it doesn't get destroyed.
I have tried it just as in the docs:
call_session = OT.initSession(params['api_key'], params['session_id']);
I get session_id from server which is using PHP SDK.
Following are event streamCreated and streamDestroyed
call_session.on('streamCreated', function(event) {
call_stream = event.stream;
var subscriber = call_session.subscribe(event.stream, 'subscriber', {
insertMode: 'append'
}, CHAT_CALL.handleError);
});
call_session.on("streamDestroyed", function(event) {
console.log("Stream " + event.stream.name + " ended. " + event.reason);
});
And here is the session connect call:
call_session.connect(params['token'], function(error) {
// If the connection is successful, publish to the session
if (error) {
CHAT_CALL.handleError(error);
} else {
// console.log("Connected !!!");
// Create a publisher
call_publisher = OT.initPublisher('publisher', {
insertMode: 'append',
width: '100%',
height: '100%',
publishAudio: enable_audio,
publishVideo: enable_video,
// style: {
// buttonDisplayMode: 'on'
// }
}, CHAT_CALL.handleError);
call_session.publish(call_publisher, CHAT_CALL.handleError);
}
});
}
But the problematic part is the the below function where i try to unpublish and disconnect session.
end_call: function(){
call_session.disconnect();
call_session.unpublish(call_publisher);
call_publisher.destroy();
}
Calling end_call gives me below error:
The publisher XYZ is trying to unpublish from a session ABC it is not attached to (it is attached to no session)
Followed by below error:
Invalid state transition: Event 'disconnect' not possible in state 'disconnected'

Related

Trying to implement ADAL (Azure AD) in Javascript, keep getting a login/redirect loop

So I've got to create a calendar in html that gets events from Outlook and then deploy that as a custom page to Sharepoint, so it can be included as a webpart/iframe in site collections.
The problem is that I've tried adding ADAL security because you need to be logged in & send a token to Microsoft Exchange Online API in order to get calendar events etc. To display the calendar part, I'm using FullCalendar.io .
Now I've been keep getting a login/redirect loop that never ends. Does anyone see the fault in code? Here it is:
var $this = this;
$(document).ready(function() {
debugger;
window.config = {
tenantId: {tenant},
clientId: {clientid},
popUp: true,
callback: callbackFunction,
redirectUri: {custom aspx page URL on our Sharepoint},
cacheLocation: 'localStorage'
};
var authenticationContext = new AuthenticationContext(config);
authenticationContext.handleWindowCallback();
function callbackFunction(errorDesc, token, error, tokenType) {
alert('callbackFunction reached!');
}
var items = null;
if (authenticationContext.TokenCache) {
items = authenticationContext.TokenCache.ReadItems();
}
if (authenticationContext['_user']) {
authenticationContext.acquireToken(config.clientId, function (errorDesc, token, error) {
if (error) { //acquire token failure
if (config.popUp) {
// If using popup flows
authenticationContext.acquireTokenPopup(config.clientId, null, null, function (errorDesc, token, error)
{});
}
else {
// In this case the callback passed in the Authentication request constructor will be called.
authenticationContext.acquireTokenRedirect(config.clientId, null, null);
}
}
else {
//acquired token successfully
// alert('token success');
$this.DisplayEvents(token);
}
});
}
else {
// Initiate login
authenticationContext.login();
}
});
function DisplayEvents(adalToken) {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listWeek'
},
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
events: function(start, end, timezone, callback) {
var headers = new Headers();
var bearerToken = "Bearer " + adalToken;
headers.append('Authorization', bearer);
var options = {
method: 'GET',
headers: headers
};
var exchangeEndpoint = 'https://outlook.office.com/api/v2.0/me/events';
fetch(exchangeEndpoint, options).then(function (response) {
alert('Response data from successful call: ' + response);
});
}
});
}
So the code does get to "acquire token" and then the last "else", so "$this.DisplayEvents(token)" does get called! However, after acquire token, the app just keeps redirecting forever and ever... The Reply URL in my Azure AD App registration is also the window.config redirectURL value, or else I'd get an error stating the reply URL's don't match between request and Azure.
Does anyone know where it's going wrong?
I can reproduce your issue on my side by using your code. If you use authContext.getCachedUser() to check login status, redirect issue will disappear.
if (authContext.getCachedUser()) {
authContext.acquireToken(config.clientId, function (error, token) {
if (error) { //acquire token failure
if (config.popUp) {
// If using popup flows
authContext.acquireTokenPopup(config.clientId, null, null, function (errorDesc, token, error) { });
}
else {
// In this case the callback passed in the Authentication request constructor will be called.
authContext.acquireTokenRedirect(config.clientId, null, null);
}
}
else {
//acquired token successfully
// alert('token success');
alert(token);
}
});
}
else {
// Initiate login
authContext.login();
}

Not getting message on Subscribing to Channel in PubNub Javascript (Angular JS)

I am published to a channel, message got published.. while subscribing to channel, My callback function is not getting triggered..
here is the code..
Pubnub.publish(
{
message: {
signal: 'switch',
state: 0
},
channel: 'myChannel'
},
function (status, response) {
if (status.error) {
console.log(status)
} else {
console.log("message Published w/ timetoken", response.timetoken)
}
}
);
Pubnub.subscribe({
channels: ['myChannel'],
message : function(m){ alert(m) }
});
Can anyone please help me how to trigger this event.... Also I am stuck to save this published message in global js variable.

Getting messages in chat history to display in messenger Pubnub

I have come to post this question after 2 days of torture not being able to understand how I can actually publish the historic messages stored on my pubnub storage account. To try and understand it at its most basic I have made a chat app and used the history function as described in the SDK but still every time I refresh the page the messages are lost. I have tried the backfill and the restore attributes in subscribe with no luck. All I want to do is click refresh on chrome and see the messages still there.
<div><input id=input placeholder=you-chat-here /></div>
Chat Output
<div id=box></div>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.0.min.js"></script>
<script>(function(){
var pubnub = new PubNub({ publishKey : 'demo', subscribeKey : 'demo' });
function $(id) { return document.getElementById(id); }
var box = $('box'), input = $('input'), channel = 'chat';
pubnub.addListener({
message: function(obj) {
box.innerHTML = (''+obj.message).replace( /[<>]/g, '' ) + '<br>' + box.innerHTML
}});
pubnub.history({
channel: 'chat',
reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
count: 100, // how many items to fetch
callback : function(msgs) {
pubnub.each( msgs[0], chat );
}
},
function (status, response) {
// handle status, response
console.log("messages successfully retreived")
});
pubnub.subscribe({channels:[channel],
restore: true,
backfill: true,
ssl: true});
input.addEventListener('keyup', function(e) {
if ((e.keyCode || e.charCode) === 13) {
pubnub.publish({channel : channel, message : input.value,x : (input.value='')});
}
});
})();
</script>
</body>
EDIT: updated link that was broken. New version of history function is called fetchMessages.
I think your history code is not correct. No need for the callback as your code response will be in the function argument. This example is from the JavaScript SDK docs.
// deprecated function
pubnub.history(
{
channel: 'chat',
},
function (status, response) {
var msgs = response.messages;
if (msgs != undefined && msgs.length > 0) {
// if msgs were retrieved, do something useful
console.log(msgs);
}
}
);
// latest function (response output format has changed)
pubnub.fetchMessages(
{
channels: ['chat']
},
(status, response) => {
console.log(msgs);
}
);

Using Pusher with SimpleWebRTC

I've come across the SimpleWebRTC package. Trying to get it to work, but can't seem to get the remote stream coming through. I'm also using Pusher for signalling, rather than the default that comes with SimpleWebRTC.
I've set up my own connection:
var myConnection = {
pusher: new Pusher('mypusherkey', { cluster: 'ap1' } ),
channel: null,
on: function (event, callback) {
this.pusher.bind (event, callback);
},
emit: function () {
if (arguments.length == 1) {
if (arguments[0] === "join") {
this.channel = this.pusher.subscribe(arguments[1]);
}
}
else
this.channel.trigger(arguments);
},
getSessionId: function() {
return this.pusher.connection.socket_id;
},
disconnect: function() {
this.pusher.disconnect();
}
};
Then I have the SimpleWebRTC initialisation:
var webrtc = new SimpleWebRTC({
// the id/element dom element that will hold "our" video
localVideoEl: 'localVideo',
// the id/element dom element that will hold remote videos
remoteVideosEl: 'remotesVideos',
// immediately ask for camera access
autoRequestMedia: true,
debug: true,
connection: myConnection
});
// we have to wait until it's ready
webrtc.on('readyToCall', function () {
console.log('ready to join');
// you can name it anything
webrtc.joinRoom('test-video-chat');
});
Doing a simple test between 2 PCs, it's not setting up the remote stream. In the dev console apart from the intitial event hook ups, I'm not seeing any other activity happening, especially SimpleWebRTC "readyToCall" not firing.
you probably need to emit a 'connect' signal from your socket adapter to trigger this code

can't create phonertc client

I found very good project on Github, but I can not understand all of it.
I installed a signaling server (socket.io) and a turn server. I'm trying to make an app for IOS and I'm using code like:
<video height="300" id="localVideo"></video>
<video id="remotesVideos"></video>
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var phonertc = cordova.require('com.dooble.phonertc.PhoneRTC');
var socket = io('http://mysait.com:3000');
socket.on("connect", function() {
socket.emit("join", "myroom");
socket.on("message", function(message) {
console.log("GOT MESSAGE:");
message.payload.sdp = message.payload.sdp.replace(/(\r\n|\n|\r)/gm,"");
// when a message is received from the signaling server,
// notify the PhoneRTC plugin.
phonertc.receiveMessage(message.payload);
});
});
socket.on('connect',function() {
alert ('is connect!');
});
phonertc.call({
isInitator: true, // Caller or callee?
turn: {
host: 'turn:mysait.com:3478',
username: 'test',
password: 'test'
},
sendMessageCallback: function (data) {
// PhoneRTC wants to send a message to your target, use
// your signaling server here to send the message.
console.log(data);
socket.emit("message", data);
},
answerCallback: function () {
alert('Callee answered!');
},
disconnectCallback: function () {
alert('Call disconnected!');
},
video: { // Remove this property if you don't want video chat
localVideo: document.getElementById('localVideo'),
remoteVideo: document.getElementById('remoteVideo')
}
});
}
</script>
I have an alert when connection is made to server, but I don't see local and remote video. Can someone suggest what could be wrong? Can you send me example of client-side, I can't find it here.
It looks like this is a very old version of the demo app. The correct link is:
https://github.com/alongubkin/phonertc/tree/master/demo

Categories