<?php
/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the "LICENSE.txt" file located in the root directory.
 *
 *  This is a modified version of the original file "index.html",
 *  first modified in 2020. The copyright notice for the original
 *  content follows:

/*
  Cyber Mega Phone 2K
  Copyright (C) 2017 Digium, Inc.

  This program is free software, distributed under the terms of the
  MIT License. See the LICENSE file at the top of the source tree.
*/

session_start();

if ($_SESSION['loggedtoroundpin'] == true) {

?>

<script type="text/javascript">
    let validateSToken = "<?php print_r($_SESSION['validate_s_access']); ?>";
    let userName = "<?php print_r($_SESSION['loginname']); ?>";
</script>

<!DOCTYPE html>

<html>
<head>
	<meta charset="utf-8" />
	<title>Roundpin Video Conference</title>
	<link rel="stylesheet" type="text/css" href="css/conference-phone.min.css">
        <link rel="stylesheet" type="text/css" href="../fonts/font-awesome-4.7.0/css/font-awesome.min.css"/>

        <link rel="stylesheet" type="text/css" href="../css/jeegoo-1.0.0.min.css"/>

        <link rel="shortcut icon" type="image/svg" href="../images/favicon.svg" />
	<script type="text/javascript" src="js/sdp-interop-sl-1.4.0.min.js"></script>
        <script type="text/javascript" src="js/jssip-3.7.0.min.js"></script>
	<script type="text/javascript" src="js/utils.min.js"></script>
        <script type="text/javascript" src="../js/jquery-3.3.1.min.js"></script>

	<script type="text/javascript" src="js/conference-phone.min.js"></script>

        <script type="text/javascript" src="../js/jquery.jeegoopopup.1.0.0.min.js"></script>

<script type="text/javascript">

let phone;
let numPressed = null;

window.onload = function() {

        var mvcount = 0;
        var sipPassDec = '';

	document.getElementById("connect").value = "Connect";
	document.getElementById("connect").disabled = false;
	document.getElementById("call").value = "Call";
	document.getElementById("call").disabled = true;
        document.getElementById("call").style.display = 'none';
        document.getElementById("fullscreen").style.display = 'none';

	function findMediaView(parent, stream) {
		let nodes = parent.childNodes;

		for (let i = 0; i < nodes.length; ++i) {
			if (nodes[i].id == stream.id) {
				return nodes[i];
			}
		}
		return null;
	}

        function dtmfMenuShow() {

                $.jeegoopopup.close();

	        var leftPos = event.pageX - 90;
	        var topPos = event.pageY + 28;

		if ($(window).width() < 680) {
		    leftPos = event.pageX - 50;
		}

	        var html = "<div id=\"sendPinDialPad\">";
	        html += "<div><input type=\"text\" id=\"dialText\" class=\"dialTextInput\"></div>";
	        html += "<table cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
	        html += "<tr><td><button class=dtmfButtons onclick=\"phone.dtmfSend('1');new Audio('../sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('2');new Audio('../sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('3');new Audio('../sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>";
	        html += "<tr><td><button class=dtmfButtons onclick=\"phone.dtmfSend('4');new Audio('../sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('5');new Audio('../sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('6');new Audio('../sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>";
	        html += "<tr><td><button class=dtmfButtons onclick=\"phone.dtmfSend('7');new Audio('../sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('8');new Audio('../sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('9');new Audio('../sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>";
	        html += "<tr><td><button class=dtmfButtons onclick=\"phone.dtmfSend('*');new Audio('../sounds/dtmf.mp3').play();\">*</button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('0');new Audio('../sounds/dtmf.mp3').play();\">0</button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('#');new Audio('../sounds/dtmf.mp3').play();\">#</button></td></tr>";
	        html += "</table>";
	        html += "</div>";

	        $.jeegoopopup.open({
			html: html,
			width: "auto",
			height: "auto",
			left: leftPos,
			top: topPos,
			scrolling: 'no',
			skinClass: 'jg_popup_basic',
			overlay: true,
			opacity: 0,
			draggable: true,
			resizable: false,
			fadeIn: 0
	        });

	        $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
	        $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
        }

	function createMediaControls(video) {

		let controls = document.createElement("div");
		controls.className = "media-controls";

                if (video.srcObject.local == true) {
		        let sendPin = document.createElement("button");
                        sendPin.className = "mediaControlBtn";
                        sendPin.id = "sendPinBtn";
		        sendPin.innerHTML = '<i class="fa fa-keyboard-o" aria-hidden="true" title="Show Keypad"></i>';
                        sendPin.onclick = function() { dtmfMenuShow(); }

		        controls.appendChild(sendPin);
                }

		let audioTracks = video.srcObject.getAudioTracks();
		if (audioTracks.length > 0) {
                        let muteAudio = document.createElement("button");
                        muteAudio.className = "mediaControlBtn";
                        muteAudio.innerHTML = '<i class="fa fa-microphone-slash" aria-hidden="true" title="Mute Audio"></i>';
			muteAudio.setAttribute("state", "Unmute");
			muteAudio.onclick = function() {
				let state = this.getAttribute("state");
                                if (state == "Mute") {
                                    this.setAttribute("state", "Unmute");
                                    this.innerHTML = '<i class="fa fa-microphone-slash" aria-hidden="true" title="Mute Audio"></i>';
                                } else if (state == "Unmute") {
                                    this.setAttribute("state", "Mute");
                                    this.innerHTML = '<i class="fa fa-microphone" aria-hidden="true" title="Unmute Audio"></i>';
                                }
				mute(video.srcObject, {audio: this.getAttribute("state") == "Mute"});
			};
			controls.appendChild(muteAudio);
		}

		let videoTracks = video.srcObject.getVideoTracks();
		if (videoTracks.length > 0) {
                        let muteVideo = document.createElement("button");
                        muteVideo.className = "mediaControlBtn";
                        muteVideo.innerHTML = '<i class="fa fa-ban" aria-hidden="true" title="Mute Video"></i>';
			muteVideo.setAttribute("state", "Unmute");
			muteVideo.onclick = function() {
				let state = this.getAttribute("state");
                                if (state == "Mute") {
                                    this.setAttribute("state", "Unmute");
                                    this.innerHTML = '<i class="fa fa-ban" aria-hidden="true" title="Mute Video"></i>';
                                } else if (state == "Unmute") {
                                    this.setAttribute("state", "Mute");
                                    this.innerHTML = '<i class="fa fa-video-camera" aria-hidden="true" title="Unmute Video"></i>';
                                }

				mute(video.srcObject, {video: this.getAttribute("state") == "Mute"});
			};
			controls.appendChild(muteVideo);

                        if (video.srcObject.local == true) {
                                let ScreenShare = document.createElement("button");
                                ScreenShare.className = "mediaControlBtn";
                                ScreenShare.innerHTML = '<i class="fa fa-desktop" aria-hidden="true" title="Share Screen"></i>';
				ScreenShare.onclick = function() {
					phone.ShareScreen();
				};

				controls.appendChild(ScreenShare);

                                let VideoShare = document.createElement("button");
                                VideoShare.className = "mediaControlBtn";
                                VideoShare.innerHTML = '<i class="fa fa-video-camera" aria-hidden="true" title="Share Camera"></i>';
				VideoShare.onclick = function() {
					phone.ShareVideo();
				};

				controls.appendChild(VideoShare);
                        }

                        let fullScreen = document.createElement("button");
                        fullScreen.className = "mediaControlBtn";
                        fullScreen.innerHTML = '<i class="fa fa-expand" aria-hidden="true" title="Full Screen"></i>';
			fullScreen.onclick = function() {
			    this.fullScreen.request();					
			};

			fullScreen.fullScreen = new FullScreen(video);
			controls.appendChild(fullScreen);
		}
		return controls;
	}


	function createMediaView(stream) {

		let mediaView = document.createElement("div");
		mediaView.className = "media-view";
		mediaView.id = "new-media-view"+stream.id; // Makes it easy to find later
                mediaView.style.width = localStorage.getItem("VidConfWindowWidth")+"%";

		let videoView = document.createElement("div");
                videoView.className = "video-view";
                videoView.id = "video-view"+stream.id;

		let video = document.createElement("video");
                video.className = "videoElem";
                video.id = "locVideo"+stream.id;
		video.autoplay = true;
		video.srcObject = stream;
		video.onloadedmetadata = function() {

		      let tracks = stream.getVideoTracks();

		      for (let i = 0; i < tracks.length; ++i) {
			   tracks[i].enabled = true;
		      }

		};

		if (stream.local == false) {

			function checkForVideo() {
				if (video.videoWidth < 10 || video.videoHeight < 10) {
                                    mediaView.style.display = 'none';
				    return;
				}
                                mediaView.style.display = 'inline';
			}
                        checkForVideo();
			setInterval(checkForVideo, 1000);
		}

		// Video elements connected to local streams will by default
		// echo both the video and the audio back to ourselves. Since
		// we don't want to hear ourselves we mute it, which mutes only
		// the audio portion.
		if (stream.local == true) {
			video.muted = true;
		} else if (mvcount == 0) {
			// We hide the video view until we receive video
                        // We hide our own remote video track
                        mvcount = 1;
                        document.getElementById(mediaView.id).style.display = 'none'; 
		}

		videoView.appendChild(video);
		mediaView.appendChild(videoView);
		mediaView.appendChild(createMediaControls(video));

		return mediaView;
	}

	function removeMediaView(parent, stream) {
		let node = findMediaView(parent, stream);
		if (node) {
			parent.removeChild(node);
		}
	}

	function getValue(id) {
		let obj = document.getElementById(id);
		return obj.value ? obj.value : obj.placeholder;
	}

        $.ajax({
            'async': false,
            'global': false,
            type: "POST",
            url: "../get-sippass.php",
            dataType: "JSON",
            data: {
                    username: userName,
                    s_ajax_call: validateSToken
            },
            success: function (sipdatafromdb) {
                           sipPassDec = sipdatafromdb;
            },
            error: function(sipdatafromdb) {
                     alert("An error occurred while attempting to retrieve data from the database!");
            }
        });

        document.getElementById("connect").addEventListener("click", function() {
		if (document.getElementById("connect").value == "Disconnect") {
			document.getElementById("call").value = "Call";
			document.getElementById("call").disabled = true;
			document.getElementById("connect").value = "Disconnecting";
			document.getElementById("connect").disabled = true;

			phone.disconnect();
			return;
		}

                phone = new ConferencePhone(localStorage.getItem("SipUsername"), localStorage.getItem("SipUsername"), sipPassDec, localStorage.getItem("wssServer"), localStorage.getItem("StunServer"), true);

                sipPassDec = '';

		phone.handle("connected", function () {

			if (document.getElementById("connect").value != "Disconnect") {
				document.getElementById("connect").value = "Registering";
			} else {
				document.getElementById("connect").value = "Disconnect";
				document.getElementById("connect").disabled = false;
				document.getElementById("call").disabled = false;
			}
		});

		phone.handle("disconnected", function () {
			document.getElementById("connect").value = "Connect";
			document.getElementById("connect").disabled = false;
			document.getElementById("call").value = "Call";
			document.getElementById("call").disabled = true;
		});

		phone.handle("registered", function () {
			document.getElementById("connect").value = "Disconnect";
			document.getElementById("connect").disabled = false;
			document.getElementById("call").disabled = false;
		});

		phone.handle("registrationFailed", function () {
			phone.disconnect();
		});

		phone.handle("incoming", function (reason) {
			document.getElementById("call").value = "Answer";
		});

		phone.handle("failed", function (reason) {
			document.getElementById("call").value = "Call";
			document.getElementById("call").disabled = false;
		});

		phone.handle("ended", function (reason) {
			document.getElementById("call").value = "Call";
			document.getElementById("call").disabled = document.getElementById("connect").value == "Connect";
		});

		phone.handle("streamAdded", function (stream) {
			document.getElementById("media-views").appendChild(createMediaView(stream));
			document.getElementById("call").value = "Hangup";
			document.getElementById("call").disabled = false;
                        document.getElementById("call").style.display = 'inline';
                        document.getElementById("fullscreen").style.display = 'inline';
                        document.getElementById("fullscreen").innerHTML = '<i class="fa fa-expand" aria-hidden="true"></i><b>&nbsp; Fullscreen';
		});

		phone.handle("streamRemoved", function (stream) {
			removeMediaView(document.getElementById("media-views"), stream);
		});

		phone.connect();

		document.getElementById("connect").disabled = true;
		document.getElementById("connect").value = "Connecting";
	});

        document.getElementById("connect").click();

        let videoConfExtension = localStorage.getItem("VidConfExtension");

        let constraints = { audio: true, video: true };
        navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
            phone.call(videoConfExtension);
        }).catch(function(err) { });

        let node = document.getElementById("call");

        if (node.value == "Answer") {
	    node.disabled = true;
	    node.value = "Hangup";
	}

        document.getElementById("call").addEventListener("click", function() {
            if (node.value == "Hangup") {
	        phone.terminate();
                document.getElementById("call").remove();
                window.close();
            }
        });

	$("#showConnectionBttns").click(function() {
	  if ($("#connection").is(':visible')) {
	      $("#connection").hide();
	      $("#showConnectionBttns").html('<i class="fa fa-caret-down" aria-hidden="true"></i>');
	  } else { 
	      $("#connection").show();
	      $("#showConnectionBttns").html('<i class="fa fa-caret-up" aria-hidden="true"></i>');
	  }
	});

	document.addEventListener("fullscreenchange", onFullScreenChange, false);
	document.addEventListener("webkitfullscreenchange", onFullScreenChange, false);
	document.addEventListener("mozfullscreenchange", onFullScreenChange, false);

	function onFullScreenChange() {
	   if (document.mozFullScreenElement != null || document.webkitFullscreenElement != null || document.fullscreenElement != null) {
	       document.getElementById("fullscreen").innerHTML = '<i class="fa fa-compress" aria-hidden="true"></i><b>&nbsp; Exit Fullscreen';
	       document.getElementById("fullscreen").style.width = "148px";
	   } else { 
	       document.getElementById("fullscreen").innerHTML = '<i class="fa fa-expand" aria-hidden="true"></i><b>&nbsp; Fullscreen';
	       document.getElementById("fullscreen").style.width = "117px";
	   }
	}

}; // window.onload

window.onbeforeunload = function() {
       phone.terminate();
}; 

window.onunload = function() {
       if (phone) {
	   phone.disconnect();
       }
}; // window.onunload
</script>
</head>
<body>
	<div id="connection">
               <div id="VideoConferenceLogo"><img src="../images/small-logo.svg" /></div>
	       <input type="button" id="connect" class="connect" value="Connect" style="display:none;" />
               <button id="call" class="call"><i class="fa fa-phone" aria-hidden="true"></i><b>&nbsp; Hangup</b></button>
               <button id="fullscreen" class="fullscreen" onclick="toggleFullScreen(document.body)"><i class="fa fa-expand" aria-hidden="true"></i><b>&nbsp; Fullscreen</b></button>
	</div>
        <div id="showConnectionBttns"><i class="fa fa-caret-down" aria-hidden="true"></i></div>

	<div id="media-views" class="media-views"></div>

<script type="text/javascript">

FullScreen.prototype.request = function() {
	if (this.is()) {
		return;
	}

	if (this._obj.requestFullscreen) {
		this._obj.requestFullscreen();
	} else if (this._obj.mozRequestFullScreen) {
		this._obj.mozRequestFullScreen();
	} else if (this._obj.webkitRequestFullScreen) {
		this._obj.webkitRequestFullScreen();
	} else if (this._obj.msRequestFullscreen) {
		this._obj.msRequestFullscreen();
	}

	this.setData(true);
};

function toggleFullScreen(elem) {

    if ((document.fullScreenElement !== undefined && document.fullScreenElement === null) || (document.msFullscreenElement !== undefined && document.msFullscreenElement === null) ||
       (document.mozFullScreen !== undefined && !document.mozFullScreen) || (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen)) {
        if (elem.requestFullScreen) {
            elem.requestFullScreen();
        } else if (elem.mozRequestFullScreen) {
            elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullScreen) {
            elem.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        } else if (elem.msRequestFullscreen) {
            elem.msRequestFullscreen();
        }

    } else {
        if (document.cancelFullScreen) {
            document.cancelFullScreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

window.onclick = function(event) {
	let modal = document.getElementById("account-modal");
	if (event.target == modal) {
		modal.style.display = "none";
	}
}

</script>
</body>
</html>

<?php

} else {
     header("Location: ../roundpin-login.php");
  }

?>