Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $(function() {
- $("#logArea").html('');
- var ui = {
- $usersTitle: $('.j-users__title'),
- $usersList: $('.j-users__list'),
- $panel: $('.j-pl'),
- $callees: $('.j-callees'),
- $btnCall: $('.j-call'),
- $btnHangup: $('.j-hangup'),
- $ctrlBtn: $('.j-caller__ctrl'),
- filterClassName: '.j-filter',
- modal: {
- 'income_call': '#income_call'
- },
- sounds: {
- 'call': 'callingSignal',
- 'end': 'endCallSignal',
- 'rington': 'ringtoneSignal'
- },
- setPositionFooter: function() {
- var $footer = $('.j-footer'),
- invisibleClassName = 'invisible',
- footerFixedClassName = 'footer-fixed';
- if( $(window).outerHeight() > $('.j-wrapper').outerHeight() ) {
- $footer.addClass(footerFixedClassName);
- }
- else {
- $footer.removeClass(footerFixedClassName);
- }
- $footer.removeClass(invisibleClassName);
- },
- togglePreloadMain: function(action) {
- var $main = $('.j-main'),
- preloadClassName = 'main-preload';
- if(action === 'show') {
- $main.addClass( preloadClassName );
- }
- else {
- $main.removeClass( preloadClassName );
- }
- },
- createUsers: function(users, $node) {
- var tpl = _.template( $('#user_tpl').html() ),
- usersHTML = '';
- $node.empty();
- _.each(users, function(user, i, list) {
- console.log(user);
- console.log(list);
- usersHTML += tpl(user);
- });
- $node.append(usersHTML);
- },
- showCallBtn: function() {
- this.$btnHangup.addClass('hidden');
- this.$btnCall.removeClass('hidden');
- },
- hideCallBtn: function() {
- this.$btnHangup.removeClass('hidden');
- this.$btnCall.addClass('hidden');
- },
- toggleRemoteVideoView: function(userID, action) {
- var $video = $('#remote_video_' + userID);
- if(!_.isEmpty(app.currentSession) && $video.length){
- if(action === 'show') {
- $video.parents('.j-callee').removeClass('callees__callee-wait');
- }
- else if(action === 'hide') {
- $video.parents('.j-callee').addClass('callees__callee-wait');
- }
- else if(action === 'clear') {
- app.currentSession.detachMediaStream('remote_video_' + userID);
- $video.removeClass('fw-video-wait');
- }
- }
- },
- classesNameFilter: 'no aden reyes perpetua inkwell toaster walden hudson gingham mayfair lofi xpro2 _1977 brooklyn',
- changeFilter: function(selector, filterName) {
- $(selector)
- .removeClass(this.classesNameFilter)
- .addClass( filterName );
- },
- callTime: 0,
- updTimer: function() {
- this.callTime += 1000;
- $('#timer').removeClass('hidden').text( new Date(this.callTime).toUTCString().split(/ /)[4] );
- }
- },
- app = {
- caller: {},
- callees: {},
- currentSession: {},
- mainVideo: 0
- },
- isDeviceAccess = true,
- takedCallCallee = [],
- remoteStreamCounter = 0,
- authorizationing = false,
- callTimer,
- network = {
- users: {}
- },
- is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
- window.app = app;
- function initializeUI(arg) {
- var params = arg || {};
- ui.createUsers(QBUsers, ui.$usersList);
- ui.$usersTitle.text(MESSAGES.title_login);
- if(!params.withoutUpdMsg || params.msg) {
- //qbApp.MsgBoard.update(params.msg);
- $("#logArea").append(params.msg+'n');
- }
- }
- function showErrorAccessPermission(error) {
- var errorTitle = 'Error: ',
- errorMsg = 'Failed to get access to your camera or microphone. Please check your hardware configuration.';
- if(error && error.message) {
- alert(errorTitle + error.message);
- }
- else {
- alert(errorTitle + errorMsg);
- }
- }
- function isBytesReceivedChanges(userId, inboundrtp) {
- var res = true,
- inbBytesRec = inboundrtp.bytesReceived;
- if(network[userId] === undefined) {
- network[userId] = {
- 'bytesReceived': inbBytesRec
- };
- }
- else {
- if(network[userId].bytesReceived === inbBytesRec) {
- res = false;
- }
- else {
- network[userId] = {
- 'bytesReceived': inbBytesRec
- };
- }
- }
- return res;
- }
- function notifyIfUserLeaveCall(session, userId, reason, title) {
- var userInfo = _.findWhere(QBUsers, {id: +userId}),
- currentUserInfo = _.findWhere(QBUsers, {id: session.currentUserID});
- if(session.opponentsIDs.length === 1) {
- $("#logArea").append('Call Update : n p2p_call_stopn name : '+userInfo.full_name+'n currentName:'+currentUserInfo.full_name+'n reason : '+reason+'n');
- console.log('Call Update : n p2p_call_stopn name : '+userInfo.full_name+'n currentName:'+currentUserInfo.full_name+'n reason : '+reason+'n');
- }
- $('.j-callee_status_' + userId).text(title);
- }
- /**
- * INITIALIZE
- */
- ui.setPositionFooter();
- if (!QB.webrtc) {
- $("logArera").append('webrtc_not_avaible n');
- $("logArera").append('Error: ' + window.MESSAGES.webrtc_not_avaible+'n');
- return;
- }
- //*** Events ***
- $(document).on('click', '.btnVideoCal', function(e) {
- QBUsers = [];
- $('input[name="list_user"]:checked').each(function(){
- alert('checkbox checked'+$(this).val());
- QBUsers.push({
- "id" : $(this).val(),
- "email" : $(this).attr('data-email'),
- "password" : $(this).attr('data-password'),
- "fullname" : $(this).attr('data-fullname')
- });
- });
- console.log('QBUsers Build');
- console.log(QBUsers);
- var $el = $(this),
- usersWithoutCaller = [],
- user = {},
- classNameCheckedUser = 'users__user-active';
- if(!window.navigator.onLine) {
- $("logArera").append('No internet n');
- }
- else
- {
- if(_.isEmpty(app.caller)) {
- authorizationing = true;
- ui.togglePreloadMain('show');
- app.caller = {
- id: +$.trim( $("#loggedUserInfo").attr('data-id') ),
- email: $.trim( $("#loggedUserInfo").attr('data-email') ),
- password: $.trim( $("#loggedUserInfo").attr('data-pass') ),
- full_name: $.trim( $("#loggedUserInfo").attr('data-name') )
- };
- console.log('app.caller Build');
- console.log(app.caller);
- usersWithoutCaller = _.filter(QBUsers, function(i) { return i.id !== app.caller.id; });
- console.log('Users with out caller ');
- console.log(usersWithoutCaller);
- ui.$usersList.empty();
- $("logArera").append('Connect n');
- QB.chat.connect({
- jid: QB.chat.helpers.getUserJid( app.caller.id, QBApp.appId ),
- password: app.caller.password
- }, function(err, res) {
- if(err !== null) {
- $("#logArera").append('QB.chat.connect Error Part n');
- app.caller = {};
- ui.setPositionFooter();
- ui.togglePreloadMain('hide');
- QB.chat.disconnect();
- }
- else {
- console.log('QB.chat.connect Else Part');
- ui.createUsers(usersWithoutCaller, ui.$usersList);
- ui.$usersTitle.text(MESSAGES.title_callee);
- $("logArera").append('Set logout to message board n');
- ui.$panel.removeClass('hidden');
- ui.setPositionFooter();
- ui.togglePreloadMain('hide');
- }
- authorizationing = false;
- });
- }
- $('input[name="list_user"]:checked').each(function(){
- user.id = +$.trim( $(this).val() );
- user.name = $.trim( $(this).attr('data-fullname') );
- //if want to remove user form call in demo it is checked with class.
- // Remove code will go here check above delete app.callees[user.id];
- $("#logArea").append('Adding Calleesn');
- app.callees[user.id] = user.name;
- });
- }
- return false;
- });
- //## Logout
- $(document).on('click', '.j-logout', function() {
- QB.chat.disconnect();
- });
- $(document).on('click', '.j-call', function(e) {
- $("#logArea").append('Start call Clicked n');
- var videoElems = '',
- mediaParams = {
- audio: true,
- video: true,
- options: {
- muted: true,
- mirror: true
- },
- elemId: 'localVideo'
- };
- if(!window.navigator.onLine) {
- $("#logArea").append('No internet n');
- }
- else {
- if ( _.isEmpty(app.callees) ) {
- $("#logArea").append('Please select user to call n');
- }
- else {
- app.currentSession = QB.webrtc.createNewSession(Object.keys(app.callees), QB.webrtc.CallType.VIDEO);
- app.currentSession.getUserMedia(mediaParams, function(err, stream) {
- if (err || !stream.getAudioTracks().length || !stream.getVideoTracks().length) {
- var errorMsg = '';
- if(err && err.message) {
- errorMsg += 'Error: ' + err.message;
- $("#logArea").append('Media Error : '+errorMsg+' n');
- }
- else {
- errorMsg += 'device_not_found';
- $("#logArea").append('Media Error : '+errorMsg+' n');
- }
- app.currentSession.stop({});
- showErrorAccessPermission(err);
- }
- else {
- app.currentSession.call({}, function(error) {
- if(error) {
- console.warn(error.detail);
- $("#logArea").append('Call Error : '+error.detail+' n');
- }
- else {
- var compiled = _.template( $('#callee_video').html() );
- console.log('Calling......');
- $("#logArea").append('Calling....n');
- document.getElementById(ui.sounds.call).play();
- Object.keys(app.callees).forEach(function(userID, i, arr) {
- videoElems += compiled({userID: userID, name: app.callees[userID] });
- });
- $("#logArea").append('Append Callees Video Elementn');
- ui.$callees.append(videoElems);
- ui.hideCallBtn();
- //ui.setPositionFooter();
- $("#logArea").append('Leaving start call clickn');
- }
- });
- }
- });
- }
- }
- });
- // ## Hangup
- $(document).on('click', '.j-hangup', function() {
- if(!_.isEmpty(app.currentSession)) {
- app.currentSession.stop({});
- app.currentSession = {};
- }
- });
- //## Accept
- $(document).on('click', '.j-accept', function() {
- var mediaParams = {
- audio: true,
- video: true,
- elemId: 'localVideo',
- options: {
- muted: true,
- mirror: true
- }
- },
- videoElems = '';
- $(ui.modal.income_call).modal('hide');
- document.getElementById(ui.sounds.rington).pause();
- app.currentSession.getUserMedia(mediaParams, function(err, stream) {
- if (err || !stream.getAudioTracks().length || !stream.getVideoTracks().length) {
- var errorMsg = '';
- if(err && err.message) {
- errorMsg += 'Error: ' + err.message;
- }
- else {
- errorMsg += 'device_not_found';
- }
- showErrorAccessPermission(err);
- isDeviceAccess = false;
- app.currentSession.stop({});
- }
- else {
- var opponents = [app.currentSession.initiatorID],
- compiled = _.template( $('#callee_video').html() );
- ui.hideCallBtn();
- app.currentSession.opponentsIDs.forEach( function(userID, i, arr) {
- if(userID != app.currentSession.currentUserID){
- opponents.push(userID);
- }
- });
- opponents.forEach(function(userID, i, arr) {
- var peerState = app.currentSession.connectionStateForUser(userID),
- userInfo = _.findWhere(QBUsers, {id: userID});
- if( (document.getElementById('remote_video_' + userID) === null) ) {
- videoElems += compiled({userID: userID, name: userInfo.full_name});
- if(peerState === QB.webrtc.PeerConnectionState.CLOSED){
- ui.toggleRemoteVideoView(userID, 'clear');
- }
- }
- });
- ui.$callees.append(videoElems);
- ui.setPositionFooter();
- app.currentSession.accept({});
- }
- });
- });
- //## Reject
- $(document).on('click', '.j-decline', function() {
- if (!_.isEmpty(app.currentSession)) {
- app.currentSession.reject({});
- $(ui.modal.income_call).modal('hide');
- document.getElementById(ui.sounds.rington).pause();
- }
- });
- /** Mute / Unmute cam / mic */
- $(document).on('click', '.j-caller__ctrl', function() {
- var $btn = $(this),
- isActive = $btn.hasClass('active');
- if( _.isEmpty( app.currentSession)) {
- return false;
- } else {
- if(isActive) {
- $btn.removeClass('active');
- app.currentSession.unmute( $btn.data('target') );
- } else {
- $btn.addClass('active');
- app.currentSession.mute( $btn.data('target') );
- }
- }
- });
- /** set main video */
- $(document).on('click', '.j-callees__callee_video', function() {
- var $that = $(this),
- userID = +($(this).data('user')),
- classesName = [],
- activeClass = [];
- if( app.currentSession.peerConnections[userID].stream && !_.isEmpty( $that.attr('src')) ) {
- if( $that.hasClass('active') ) {
- $that.removeClass('active');
- app.currentSession.detachMediaStream('main_video');
- ui.changeFilter('#main_video', 'no');
- app.mainVideo = 0;
- } else {
- $('.j-callees__callee_video').removeClass('active');
- $that.addClass('active');
- ui.changeFilter('#main_video', 'no');
- activeClass = _.intersection($that.attr('class').split(/s+/), ui.classesNameFilter.split(/s+/) );
- if(activeClass.length) {
- ui.changeFilter('#main_video', activeClass[0]);
- }
- app.currentSession.attachMediaStream('main_video', app.currentSession.peerConnections[userID].stream);
- app.mainVideo = userID;
- }
- }
- });
- /** Change filter for filter */
- $(document).on('change', ui.filterClassName, function() {
- var val = $.trim( $(this).val() );
- ui.changeFilter('#localVideo', val);
- if(!_.isEmpty( app.currentSession)) {
- app.currentSession.update({filter: val});
- }
- });
- $(window).on('resize', function() {
- ui.setPositionFooter();
- });
- /**
- * QB Event listener.
- */
- QB.chat.onDisconnectedListener = function() {
- console.log('onDisconnectedListener.');
- var initUIParams = authorizationing ? {withoutUpdMsg: false, msg: 'no_internet'} : {withoutUpdMsg: false, msg: 'login'};
- app.caller = {};
- app.callees = [];
- app.mainVideo = 0;
- remoteStreamCounter = 0;
- ui.togglePreloadMain('hide');
- initializeUI(initUIParams);
- ui.$panel.addClass('hidden');
- /** delete callee video elements */
- $('.j-callee').remove();
- ui.setPositionFooter();
- authorizationing = false;
- };
- QB.webrtc.onCallStatsReport = function onCallStatsReport(session, userId, stats) {
- $("#logArea").append('onCallStatsReport n');
- console.group('onCallStatsReport');
- console.log('userId: ' + userId);
- // console.log('Stats: ', stats);
- console.groupEnd();
- /**
- * Hack for Firefox
- * (https://bugzilla.mozilla.org/show_bug.cgi?id=852665)
- */
- if(is_firefox) {
- var inboundrtp = _.findWhere(stats, {type: 'inboundrtp'});
- if(!inboundrtp || !isBytesReceivedChanges(userId, inboundrtp)) {
- console.warn("This is Firefox and user " + userId + " has lost his connection.");
- if(!_.isEmpty(app.currentSession)) {
- app.currentSession.closeConnection(userId);
- notifyIfUserLeaveCall(session, userId, 'disconnected', 'Disconnected');
- }
- }
- }
- };
- QB.webrtc.onSessionCloseListener = function onSessionCloseListener(session){
- console.log('onSessionCloseListener: ' + session);
- /** pause play call sound */
- document.getElementById(ui.sounds.call).pause();
- document.getElementById(ui.sounds.end).play();
- ui.showCallBtn();
- if(!isDeviceAccess) {
- isDeviceAccess = true;
- } else {
- if(session.opponentsIDs.length > 1) {
- //qbApp.MsgBoard.update('call_stop', {name: app.caller.full_name});
- $("#logArea").append('call_stop : name : '+app.caller.full_name+' n ');
- }
- }
- /** delete blob from myself video */
- document.getElementById('localVideo').src = '';
- /** disable controls (mute cam/min) */
- ui.$ctrlBtn.removeClass('active');
- /** delete callee video elements */
- $('.j-callee').remove();
- /** clear main video */
- app.currentSession.detachMediaStream('main_video');
- app.mainVideo = 0;
- remoteStreamCounter = 0;
- };
- QB.webrtc.onUserNotAnswerListener = function onUserNotAnswerListener(session, userId) {
- console.group('onUserNotAnswerListener.');
- console.log('UserId: ' + userId);
- console.log('Session: ' + session);
- console.groupEnd();
- var userInfo = _.findWhere(QBUsers, {id: +userId}),
- currentUserInfo = _.findWhere(QBUsers, {id: app.currentSession.currentUserID});
- /** It's for p2p call */
- if(session.opponentsIDs.length === 1) {
- /*qbApp.MsgBoard.update(
- 'p2p_call_stop',
- {
- name: userInfo.full_name,
- currentName: currentUserInfo.full_name,
- reason: 'not answered'
- }
- );*/
- //$("#logArea").append('onUserNotAnswerListener : p2p_call_stop=> name : '+userInfo.full_name+'n currentName : '+currentUserInfo.full_name+'n reason : '+not answered+'n');
- }
- $('.j-callee_status_' + userId).text('No Answer');
- };
- QB.webrtc.onUpdateCallListener = function onUpdateCallListener(session, userId, extension) {
- console.group('onUpdateCallListener.');
- console.log('UserId: ' + userId);
- console.log('Session: ' + session);
- console.log('Extension: ' + JSON.stringify(extension));
- console.groupEnd();
- ui.changeFilter('#remote_video_' + userId, extension.filter);
- if (+(app.mainVideo) === userId) {
- ui.changeFilter('#main_video', extension.filter);
- }
- };
- QB.webrtc.onCallListener = function onCallListener(session, extension) {
- alert('Now in onCallListener');
- $("#logArea").append('Start : onCallListener n');
- console.group('onCallListener.');
- console.log('Session: ' + session);
- console.log('Extension: ' + JSON.stringify(extension));
- console.groupEnd();
- /** close previous modal if his is exist */
- $(ui.modal.income_call).modal('hide');
- var userInfo = _.findWhere(QBUsers, {id: session.initiatorID});
- app.currentSession = session;
- /** set name of caller */
- $('.j-ic_initiator').text( 'Call from caller' );//
- console.log('Open accept call window');
- $(ui.modal.income_call).modal('show');
- //document.getElementById(ui.sounds.rington).play();
- };
- QB.webrtc.onAcceptCallListener = function onAcceptCallListener(session, userId, extension) {
- console.group('onAcceptCallListener.');
- console.log('UserId: ' + userId);
- console.log('Session: ' + session);
- console.log('Extension: ' + JSON.stringify(extension));
- console.groupEnd();
- var userInfo = _.findWhere(QBUsers, {id: userId}),
- filterName = $.trim( $(ui.filterClassName).val() );
- document.getElementById(ui.sounds.call).pause();
- app.currentSession.update({filter: filterName});
- /** update list of callee who take call */
- takedCallCallee.push(userInfo);
- if(app.currentSession.currentUserID === app.currentSession.initiatorID) {
- //qbApp.MsgBoard.update('accept_call', {users: takedCallCallee});
- $("#logArea").append('onAcceptCallListener => accept_call : users : '+takedCallCallee+' n');
- }
- };
- QB.webrtc.onRejectCallListener = function onRejectCallListener(session, userId, extension) {
- console.group('onRejectCallListener.');
- console.log('UserId: ' + userId);
- console.log('Session: ' + session);
- console.log('Extension: ' + JSON.stringify(extension));
- console.groupEnd();
- var userInfo = _.findWhere(QBUsers, {id: userId}),
- currentUserInfo = _.findWhere(QBUsers, {id: app.currentSession.currentUserID});
- /** It's for p2p call */
- if(session.opponentsIDs.length === 1) {
- qbApp.MsgBoard.update(
- 'p2p_call_stop',
- {
- name: userInfo.full_name,
- currentName: currentUserInfo.full_name,
- reason: 'rejected the call'
- }
- );
- }
- /** It's for groups call */
- $('.j-callee_status_' + userId).text('Rejected');
- };
- QB.webrtc.onStopCallListener = function onStopCallListener(session, userId, extension) {
- console.group('onStopCallListener.');
- console.log('UserId: ' + userId);
- console.log('Session: ' + session);
- console.log('Extension: ' + JSON.stringify(extension));
- console.groupEnd();
- notifyIfUserLeaveCall(session, userId, 'hung up the call', 'Hung Up');
- };
- QB.webrtc.onRemoteStreamListener = function onRemoteStreamListener(session, userID, stream) {
- console.group('onRemoteStreamListener.');
- console.log('userID: ' + userID);
- console.log('Session: ' + session);
- console.groupEnd();
- app.currentSession.peerConnections[userID].stream = stream;
- app.currentSession.attachMediaStream('remote_video_' + userID, stream);
- if( remoteStreamCounter === 0) {
- $('#remote_video_' + userID).click();
- app.mainVideo = userID;
- ++remoteStreamCounter;
- }
- if(!callTimer) {
- callTimer = setInterval( function(){ ui.updTimer.call(ui); }, 1000);
- }
- };
- QB.webrtc.onSessionConnectionStateChangedListener = function onSessionConnectionStateChangedListener(session, userID, connectionState) {
- console.group('onSessionConnectionStateChangedListener.');
- console.log('UserID: ' + userID);
- console.log('Session: ' + session);
- console.log('Сonnection state: ' + connectionState);
- console.groupEnd();
- var connectionStateName = _.invert(QB.webrtc.SessionConnectionState)[connectionState],
- $calleeStatus = $('.j-callee_status_' + userID),
- isCallEnded = false;
- if(connectionState === QB.webrtc.SessionConnectionState.CONNECTING) {
- $calleeStatus.text(connectionStateName);
- }
- if(connectionState === QB.webrtc.SessionConnectionState.CONNECTED) {
- ui.toggleRemoteVideoView(userID, 'show');
- $calleeStatus.text(connectionStateName);
- }
- if(connectionState === QB.webrtc.SessionConnectionState.COMPLETED) {
- ui.toggleRemoteVideoView(userID, 'show');
- $calleeStatus.text('connected');
- }
- if(connectionState === QB.webrtc.SessionConnectionState.DISCONNECTED){
- ui.toggleRemoteVideoView(userID, 'hide');
- $calleeStatus.text('disconnected');
- }
- if(connectionState === QB.webrtc.SessionConnectionState.CLOSED){
- ui.toggleRemoteVideoView(userID, 'clear');
- document.getElementById(ui.sounds.rington).pause();
- if(app.mainVideo === userID) {
- $('#remote_video_' + userID).removeClass('active');
- ui.changeFilter('#main_video', 'no');
- app.currentSession.detachMediaStream('main_video');
- app.mainVideo = 0;
- }
- if( !_.isEmpty(app.currentSession) ) {
- if ( Object.keys(app.currentSession.peerConnections).length === 1 || userID === app.currentSession.initiatorID) {
- $(ui.modal.income_call).modal('hide');
- }
- }
- isCallEnded = _.every(app.currentSession.peerConnections, function(i) {
- return i.iceConnectionState === 'closed';
- });
- /** remove filters */
- if( isCallEnded ) {
- ui.changeFilter('#localVideo', 'no');
- ui.changeFilter('#main_video', 'no');
- $(ui.filterClassName).val('no');
- takedCallCallee = [];
- }
- if (app.currentSession.currentUserID === app.currentSession.initiatorID && !isCallEnded) {
- /** get array if users without user who ends call */
- takedCallCallee = _.reject(takedCallCallee, function(num){ return num.id === +userID; });
- //qbApp.MsgBoard.update('accept_call', {users: takedCallCallee});
- $("#logArea").append('onSessionConnectionStateChangedListener => accept_call users: '+takedCallCallee+'n ');
- }
- if( _.isEmpty(app.currentSession) || isCallEnded ) {
- if(callTimer) {
- $('#timer').addClass('hidden');
- clearInterval(callTimer);
- callTimer = null;
- ui.callTime = 0;
- network = {};
- }
- }
- }
- };
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement