simpleWebRTC with php backend - javascript

I am using simpleWebRTC with xhr to implement peculiar multi-users video chat (no audio)
my main issue in short: i was unable to attach the username from php to the correct video in JS
in my quetion i will
1. explain what i have done - and what are my current issues
2. if my current route is impossible - then i ask for suggestions for a different course of action on my part :-) - my knowledge is in JS and PHP|
the multi-users video allows to chose a few users and see them in a one way connection.
lets say we have users A, B, C, D
user A chooses to see users B, C, D while user B for example only chooses to see users C and D .... and so on
in simpleWebRTC i thought of two courses of action
a. one room for all of the participants and then to filter them down (was unsuccessful as i was unable to attach the correct username to each video - to filter them out)
2. instead i created a room (with username - email, as id) and let each user connect to the appropriate room.
in the first part of the code i have an XHR that pulls a list of the people the user wishes to subscribe to there videos (i.e: chooses to see)
var remoteRoom = [];
$.get('scripts/video/ours/musesSimpleList.php', function(msg){
myRoom = msg.username;
var remoteRoomArray = $.each( msg.museUsername, function(key, value){
remoteRoom.push = value;
return remoteRoom;
});
afterRoomDefined(myRoom, remoteRoomArray);
}, 'json');
function afterRoomDefined(myRoom, remoteRoomArray) is called after the list of people this specific user chose to register to was retrieved from MySQl
in this function, i now try to implement the WebRTC:
function afterRoomDefined(myRoom, remoteRoom){
console.log('remote room name: '+ remoteRoom + ' type: '+ $.type(remoteRoom));
remoteRoom = JSON.stringify(remoteRoom);
console.log('isArray '+$.isArray(remoteRoom));
//Create our WebRTC connection
var webrtc = new SimpleWebRTC({
url:'https://signaling.simplewebrtc.com:443',
//the element that will hold the local video
localVideoEl: 'localVideo',
//the element that will hold remote videos
//remoteVideosEl: 'remotes',
remoteVideosEl: '',
autoRequestMedia: true,
media: {
video: true,
audio: false
},
});
webrtc.mute();
// a peer video has been added
var i = 0;
//When it's ready and we have a room from the URL, join the call
webrtc.on('readyToCall', function(peer){
//each user first creates a room for himself - so other users could connect to
if(myRoom) webrtc.joinRoom(myRoom);
//here a room is created for every person the user subscribed to. each person created a room with his own username (when he opened this page in his browser) - in the line above. so now i open rooms with the same names - so the users will see each other (two ways now)
for(var b=0; b<remoteRoom.museUsername.length; b++){
console.log('remoteRoom loop - separate values: '+ remoteRoom.museUsername[b]);
if(remoteRoom.museUsername[b]) webrtc.joinRoom(remoteRoom.museUsername[b]);
}
});
// a peer video has been added
webrtc.on('videoAdded', function (video, peer) {
var remotes = document.getElementById('remotes');
if (remotes) {
var container = document.createElement('div');
container.className = 'videoContainer'+i;
$(container).attr('data-username', remoteRoom.museUsername[i]);
i++;
container.id = 'container_' + webrtc.getDomId(peer);
container.appendChild(video);
// suppress contextmenu
video.oncontextmenu = function () { return false; };
remotes.appendChild(container);
//this is to remove the other party video - if a user only subscribed to another user - the other user is not
//$('#remotes div:not[data-username]').css('border', 'red 5px solid');
$('#remotes div:not[data-username]').remove();
}
i=i+1;
});
webrtc.on('videoRemoved', function (video, peer) {
var remotes = document.getElementById('remotes');
var el = document.getElementById(peer ? 'container_' + webrtc.getDomId(peer) : 'localScreenContainer');
$('#remotes div').css('border', '#F4171A 2px solid');
if (remotes && el) {
remotes.removeChild(el);
}
});
That's it. and that basically works.
There are three issues though:
a. when one of the users refreshes his page (usually navigate back an forth) his own video is added again (two videos of the same user now - one of them is frozen) to all the other users who watches him. perhaps its an issue with
webrtc.on('videoRemoved'...
b. when user A for example registers to user B... - if user C than subscribes to user A - he will see also user B
the main issue perhaps is:
c. i was never really able to attach the username to the right video under:
webrtc.on('videoAdded',....
$(container).attr('data-username', remoteRoom.museUsername[i]);...
in the main block code.
I used
$('#remotes div:not[data-username]').remove();
to find all videos without username and kick (videos who were duplicated and froze+the other side of the video if user A subscribed to user B and not vice versa so user B will not see user A and so that C will not see in the above explanation) them out - but the username it self is not attached to the correct child in the right order (the moment someone refreshes the page the order scrambles....
am i going the right direction?
i had a look at pubNub, xirsys, firebase and some other solutions
(google appengine - java knowledge required, html5Rocks, easyRTC, signalMaster (no proper explanation on how to use)- but it seems that they all require node.js )
is my current mode of action (php and XHR) is a valid one?
if not - will one of the other solution will be relatively simple and plausible.
I started looking through too many api's and am confused by now
thank you :-)

It's hard to see exactly what goes wrong, because you seems to face multiple issue here, including webRTC in general and DOM insertion/removal problems.
If you are seeking for webRTC solution using PubNub, you should take a look at:
https://github.com/stephenlb/webrtc-sdk
and the demo that you can try:
http://stephenlb.github.io/webrtc-sdk/
also, check out
http://www.pubnub.com/blog/building-a-webrtc-video-and-voice-chat-application/

Related

Javascript: Get BroadcastChannel Subscriber Count

How do I tell if Broadcast channel exists and its subscriber count?
We have a product link, and some chrome page tabs are subscribing to a Broadcast channel. Want to see how many are listening.
const bc = new window.BroadcastChannel('channel_name');
Resources:
https://medium.com/javascript-in-plain-english/using-javascript-and-the-broadcast-channel-api-a3134739781d
Communication between tabs or windows
Using Angular Typescript environment,maybe it has a library function
There is no built-in way to get the count of active ports connected through the same BroadcastChannel.
You could set up something on your own, e.g by using some pinging method where all the ports would respond and the asker just has to count the responses in a given time, but that's a bit cumbersome, makes everything async and actually using LocalStorage just for this count seems like the easiest way.
You can keep in the localStorage the current count of each channels you'll open.
Before each new connection the page can just check that value, since it will shared across the contexts that can communicate through the BroadcastChannel.
const active_connections = localStorage[ channel_name ] || 0;
Then when connecting, it just has to update that value.
if( active_connections < max_count ) {
const channel = new BroadcastChannel( channel_name );
localStorage[ channel_name ] = active_connections + 1;
}
And the trickiest being to decrease that count when the channel gets closed. For that you will need to hook to the beforeunload event:
addEventListener( 'beforeunload', (evt) => {
localStorage[ channel_name ] --;
} );
Note that if your code does call channel.close(), then you should add a line to update that count there too, and to disable the beforeunload one.
(You could still run the pinging way too to ensure the counts are still correct, since e.g if a page crashes, beforeunload could have not fired).
I should note I can't see why you'd need to do something like this, probably something is off in your design, you should double check it, and maybe open a new question about it)

RTCMultiConnection users streams keeps alive

Im using webRTC plugin named (RTCMultiConnection) but if user has his cam on and leave somehow his session stays alive. Because if user1 opens cam, than leaves, again comes back and opens cam than it's not able to join it's cam.
Im trying to append the new connections like;
Webcam.connection.onNewSession = function(session) {
console.log("On new session")
createSession: function(session){
Webcam.sessions[session.sessionid] = session;
$("div").append($("<div />", {
class: "webcam-live ct icon-isight",
html: "LIVE"
}));
}
};
First time opening the cam it appends whenever same user leaves and comesback it doesnt trigger for others. But if take another username than it sends its to new users
Source

Adding chat functionality to website

I've been able to add chat functionality to my website but I'm wondering if there is a more efficient way to do it. This is the current structure of the chat:
HTML page with javascript functions:
sendChat(elmnt) {
var result = XHR("http_sendChat.aspx","POST",0,elmnt); //xmlhttprequest to send chat message by posting elmnt string to page. 0 used for not polling
}
getChat() {
var result = XHR("http_getChat.aspx","GET",50,""); //polls page every 50ms to get new chat messages
addMessageElmnt(result); //update chat window with new messages
}
On the server side in vb.net http_sendChat.aspx:
Application.Lock
Application("chat") = Application("chat") & Request.Form("message") //Global application object stores chat log
Application.Unlock
On the server side in vb.net http_getChat.aspx:
Dim chatTemp
chatTemp = Mid(Application("chat"),Session("chatIndex")) //fetches whatever chat data hasn't been fetched yet
Session("chatIndex") = Session("chatIndex") + Len(chatTemp) //set index to last read position
Response.Write(chatTemp)
There is some more code that mostly checks to make sure the users account is activated and such but as far as the chat goes, is there a better way to do this? I ask because its fairly slow when there are like 100 people logged in and using the chat.

Facebook Application permission

Hi I have developed a Facebook application in Flash using Action-script 3. The application is working fine. I have developed Facebook login and authentication in JavaScript. The problem is then the user is not sign in to Facebook the application works fine, provide the user login panel and application permission panel and post the desire thing on user wall but if the user is already sign in than the JavaScript wont ask for the Facebook app permission and hence the app wont post on user wall. My JavaScript code is
<script type="text/javascript">
var APP_ID = "xxxxxxxxxxxxxxx";
var REDIRECT_URI = "http://apps.facebook.com/engel-tanimiyorum/";
var PERMS = 'publish_stream , email, user_birthday'; //comma separated list of extended permissions
function init()
{
FB.init({appId:APP_ID, status: true, cookie: true, oauth: true});
FB.getLoginStatus(handleLoginStatus);
}
function handleLoginStatus(response)
{
if (response.authResponse && response.status=="connected")
{
//Show the SWF
$('#ConnectDemo').append('<h1>You need at least Flash Player 9.0 to view this page.</h1>');
swfobject.embedSWF("index.swf",
"ConnectDemo", "803", "516", "9.0", null, null, null, {name:"ConnectDemo"});
}
else
{
var params = window.location.toString().slice(window.location.toString().indexOf('?'));
top.location = 'http://graph.facebook.com/oauth/authorize?client_id='
+APP_ID
+'&scope='+PERMS
+'&redirect_uri=' + REDIRECT_URI
+ params;
}
}
$(init);
</script>
Yours quick response will be highly appreciable
Regards
I don't know if this helps or not. But instead of your
var PERMS = 'publish_stream , email, user_birthday';
I do believe it should be states as an Array and then you would list your permissions.
It works for me, so I think it should look like this:
public var PERMS:Array = ["publish_stream","email","user_birthday"];
Also, not having your variables public might be the problem too.
Also, from what I see, you don't have any buttons, or text input?
If not, you need to create those. Then have a click handler for when there is text in the text input it will activate a click handler that then will go to a submit post handler, which then goes to a get status handler that will show you the new status you have created. I may be saying this all wrong. After all, I am not using Java for my app. But it seems logical to me that that is what you would do.. Try my first suggestions out and get back to me. If you'd rather, email me at Shandan_Spencer#live.com, so I can help you some more.

Handling browser window close in a nowjs chat application

I am creating a chat application with nowjs.User can create a chatroom and then invite users to that room.Following is the code used to do this:
everyone.now.addPeopleToChat = function(clientIds,roomName) {
var length = clientIds.length;
var group = nowjs.getGroup(roomName);
for(var i=0;i<length;i++){
group.addUser(clientIds[i]);
}
group.now.roomName = roomName;//User can be in one room only at any given time.Reference to the roomname to be used when user leaves chat
group.now.loadChatWindow();//Load UI
}
So far so good.Users are able to be added to chat room and chatting is also fine.
When a user is in a chat room and he closes the browser window,I want other users in the chat room to be made aware that this person has left the chat.I thought of using the disconnect event to handle this particular situation.This is the code I have used.
nowjs.on('disconnect', function () {
console.log("User name:"+this.now.name);//comes fine
console.log("Room name:"+this.now.roomName);//shows undefined.
var group = nowjs.getGroup(this.now.roomName);//Intention is to get the room in which user was chatting.But it is not working because roomName is undefined.
group.now.broadcast(this.now.name+" has left this room");
});
Why is that roomName is shown as undefined in disconnect handler.I am setting that variable when the users are added to the group right.So each of the user in the group should have that variable set right.Am I missing something here?

Categories

Resources