Free javascript Hosting


rtc.js

Uploaded on Apr 04 2022 18:17 by demotripat

const Peer = window.Peer;

/**
* Call remote client
*/
function callClient()
{
// Note that you need to ensure the peer has connected to signaling server
// before using methods of peer instance.
if (!peer.open) {
return;
}

mediaConnection = peer.call(clientLink, localStream);

mediaConnection.on('stream', async stream => {
// Render remote stream for caller
remoteVideo.srcObject = stream;
remoteVideo.playsInline = true;
await remoteVideo.play().catch(console.error);

$('.remote-stream > p').hide();
$('#js-local-stream').parent().removeAttr('style');
$('#js-local-stream').removeAttr('style');

if( typeof intervalObject !== 'undefined' ){
clearInterval(intervalObject);
}

intervalCount = 1;
hideModal();
connectAudio.play();

});

mediaConnection.once('close', () => {
remoteVideo.srcObject.getTracks().forEach(track => track.stop());
remoteVideo.srcObject = null;

disconnetionAlert();
});

// closeTrigger.addEventListener('click', () => mediaConnection.close(true));
closeTrigger.addEventListener('click', function(){
mediaConnection.close(true);
// window.close();
});
}

/**
* Generic alert message
*/
function commonError(){

alertModal.head.innerText = 'Error';
alertModal.message.innerText = 'Some unexpected error on the page. Please contact support.';
}

/**
* Client Disconnection Alert
*/
function disconnetionAlert(){
alertModal.head.innerText = 'Connection closed';
alertModal.message.innerHTML = "Call closed or disconnected.<br/>So, please close this browser tab.";
showModal();
}

/**
* Peer joining timer
*/
function startPeerTimer()
{
intervalObject = setInterval(function(){

var totalMinutes = intervalCount * 15;
var hours = Math.floor(totalMinutes / 60);
var minutes = totalMinutes % 60;

alertModal.head.innerText = 'Connecting to '+((isDcotor==1) ? 'Patient' : 'Doctor');

var messageHtml = "<span style=\"font-weight: bold\">";
if( hours > 0 )
{
messageHtml += hours + " hour"+((hours>1) ? 's ' : ' ');
}
if( minutes > 0 )
{
messageHtml += minutes + " minute"+((minutes>1) ? 's ' : ' ');
}
messageHtml += "past</span><br />";

alertModal.message.innerHTML = messageHtml;

alertModal.message.innerHTML += ((isDcotor == 1) ? 'Patient' : 'Doctor') + " has not arrived yet.<br />";
alertModal.message.innerHTML += "Please click ok if you want to continue or close the window to disconnect.";

showModal();
alertAudio.play();

intervalCount++;
}, 900000);

// 900000
}

(async function main() {

const localVideo = document.getElementById('js-local-stream');
localId = '';
const muteLocal = document.getElementById('mute-local-audio').firstElementChild;
closeTrigger = document.getElementById('disconnect-call');
remoteVideo = document.getElementById('js-remote-stream');

localStream = await navigator.mediaDevices
.getUserMedia({
audio: true,
video: true,
})
.catch( function(error) {

alertModal.head.innerText = 'Media device error';

switch( error.name )
{
case 'NotAllowedError':
alertModal.message.innerHTML = "Unable to access audio devices and camera.<br />Please check media access for this page.<br />";
alertModal.message.innerHTML += 'It is required to access the funcitonality.';
break;

case 'NotFoundError':
alertModal.message.innerHTML = "Unable to locate audio devices and camera.<br />These are rquried to access the funcitonality.";
alertModal.message.innerHTML += "<br/>Please make the devices available and refresh this screen.";
break;

case 'NotReadableError':
alertModal.message.innerHTML = "Unable to access audio devices and camera.<br/>These might be busy already.";
alertModal.message.innerHTML += "So, please close the application using these devices and refresh this screen.";
break;

default:
alertModal.message.innerHTML = "Unable to start video chat<br />Please contact support";
break;
}

showModal();
alertAudio.play();

});

// Render local stream
localVideo.muted = true;
localVideo.srcObject = localStream;
localVideo.playsInline = true;
await localVideo.play().catch(console.error);

const peer = (window.peer = new Peer(meetingLink, {
key: '1e04ee21-a359-4b6e-b153-1e1c5dbe9deb',
debug: 3,
}));

peer.once('open', function(){
localId = peer.id;

$.ajax({
method: "POST",
data: {action: "mark_user_active", clientId: localId},
url: ajax_url,
success: function(resp){
console.log(resp);
},
complete: function(){
if( isClientActive == 1)
{
callClient();
}
else
{
intervalCount = 1;
startPeerTimer();
}
}
});

});

// Register callee handler
peer.on('call', mediaConnection => {

/**
* Check if call from the correct link and the botht the users are from the same meeting scheduled.
*/
// console.log(mediaConnection);
mediaConnection.answer(localStream);

mediaConnection.on('stream', async stream => {
// Render remote stream for callee
remoteVideo.srcObject = stream;
remoteVideo.playsInline = true;
await remoteVideo.play().catch(console.error);
});

mediaConnection.once('close', () => {
remoteVideo.srcObject.getTracks().forEach(track => track.stop());
remoteVideo.srcObject = null;

disconnetionAlert();
});

$.ajax({
method: "POST",
data: {clientId: localId, remoteId: mediaConnection.remoteId, isPhysician: isDcotor, action: 'validate_client'},
url: ajax_url,
success: function(resp){

if( resp == 'success' )
{
$('.remote-stream > p').hide();
$('#js-local-stream').parent().removeAttr('style');
$('#js-local-stream').removeAttr('style');
}
else
{
mediaConnection.close(true);
$('.remote-stream > p').text('meeting not linked');
$('.remote-stream > p').show();
}
},
complete: function(){

if( typeof intervalObject !== 'undefined' ){
clearInterval(intervalObject);
}
intervalCount = 1;
hideModal();
connectAudio.play();
}
});

// // closeTrigger.addEventListener('click', () => mediaConnection.close(true));
closeTrigger.addEventListener('click', function(){
mediaConnection.close(true);
// window.close();
});
});

// When No Call Initiated
closeTrigger.addEventListener('click', function(){
const remoteVideo = document.getElementById('js-remote-stream');
if (remoteVideo.srcObject) {
remoteVideo.srcObject.getTracks().forEach(track => track.stop());
remoteVideo.srcObject = null;
}
const localVideo = document.getElementById('js-local-stream');
if (localVideo.srcObject) {
localVideo.srcObject.getTracks().forEach(track => track.stop());
localVideo.srcObject = null;
}
const win = window.open("about:blank", "_self");
win.close();
});

muteLocal.addEventListener('click', function(){

if( localStream.getAudioTracks()[0].enabled === false)
{
localStream.getAudioTracks()[0].enabled = true;
$(this).attr('src', imagepath+'unmute.png');
}
else
{
localStream.getAudioTracks()[0].enabled = false;
$(this).attr('src', imagepath+'muted.png');
}
})

peer.on('error', error => {

switch(error.type)
{
case 'unavailable-id':
alertModal.head.innerText = 'Meeting link already active';
alertModal.message.innerHTML = "This meeting link is already in use<br/>";
alertModal.message.innerHTML += "Please close all previous tab(s)/windows(s) and relaunch the meeting link after 30 seconds.";
break;
case 'peer-unavailable':

alertModal.head.innerText = 'Connecting to '+((isDcotor==1) ? 'Patient' : 'Doctor');

alertModal.message.innerHTML = '';

if(isDcotor==1)
{
alertModal.message.innerHTML += "The patient has not connected yet.<br />";
alertModal.message.innerHTML += "Please leave the window open. We will notify as soon as the patient joins.";
}
else
{
alertModal.message.innerHTML += "The doctor is attending other patients.<br />";
alertModal.message.innerHTML += "Please wait while we connect to the doctor. ";
alertModal.message.innerHTML += "You will be notified as soon as the doctor joins the call.";
}

intervalCount = 1;
startPeerTimer();
break;
default:

commonError();

console.log('=========================');
console.log(error.type);
console.log(error.message);
console.log('=========================');

break;
}

showModal();
alertAudio.play();

});

})();

Back to list