MeshCentral/public/messenger.htm

279 lines
17 KiB
HTML
Raw Normal View History

2018-11-29 20:59:29 -05:00
<!DOCTYPE html>
<html style=height:100%>
<head>
<title>MeshMessenger</title>
2018-11-29 20:59:29 -05:00
<meta http-equiv=X-UA-Compatible content="IE=edge">
<meta content="text/html;charset=utf-8" http-equiv=Content-Type>
<meta name=format-detection content="telephone=no">
<link type="text/css" href="styles/style.css" media="screen" rel="stylesheet" title="CSS" />
2018-12-16 16:44:49 -05:00
<link type="text/css" href="styles/messenger.css" media="screen" rel="stylesheet" title="CSS" />
2018-11-29 20:59:29 -05:00
<script type="text/javascript" src="scripts/common-0.0.1.js"></script>
</head>
<body style="font-family:Arial,Helvetica,sans-serif">
2018-12-16 16:44:49 -05:00
<div id="xtop" style="position:absolute;left:0;right:0;top:0;height:38px;background-color:#036;color:#c8c8c8">
<div id="fileButton" class="icon4 topButton" title="Share a file" style="display:none" onclick="fileButtonClick()"></div>
<div id="camButton" class="icon2 topButton" title="Activate camera & microphone" style="display:none" onclick="camButtonClick()"></div>
<div id="micButton" class="icon6 topButton" title="Activate microphone" style="display:none" onclick="micButtonClick()"></div>
<div style="display:inline-block;width:2px"></div>
<div style="padding-top:9px;padding-left:6px;font-size:20px;display:inline-block;"><b>MeshMessenger<span id="xtitle"></span></b></div>
</div>
<div id="xmiddle" style="position:absolute;left:0;right:0;top:38px;bottom:30px">
<div style="position:absolute;left:0;right:0;top:0;bottom:0;overflow-y:scroll">
<div id="xmsg" style="position:absolute;left:0;right:0;bottom:0;padding:5px"></div>
</div>
2018-11-29 20:59:29 -05:00
</div>
<div id="xbottom" style="position:absolute;left:0;right:0;bottom:0px;height:30px;background-color:#036">
<div style="position:absolute;left:5px;right:215px;bottom:4px;top:4px;background-color:aliceblue"><input id="xouttext" type="text" style="width:calc(100% - 5px)" onfocus=onUserInputFocus(1) onblur=onUserInputFocus(0) /></div>
<input type="button" id="sendButton" value="Send" style="position:absolute;right:110px;width:100px;top:4px;" onclick="xsend(event)" />
<input type="button" id="clearButton" value="Clear" style="position:absolute;right:5px;width:100px;top:4px;" onclick="displayClear()" />
2018-11-29 20:59:29 -05:00
</div>
2018-12-16 16:44:49 -05:00
<div id="localVideo" style="position:absolute;right:24px;top:45px;width:320px;height:260px;background-color:black;border-radius:12px 12px 0px 0px;box-shadow:3px 3px 10px gray;display:none">
<div style="position:absolute;right:0;left:0;top:0px;height:20px;background-color:gray;text-align:center;border-radius:10px 10px 0px 0px"><div style="padding:3px">Local</div></div>
<video id="localVideoCanvas" autoplay muted style="position:absolute;top:20px;left:0;width:320px;height:240px;background-color:black"></video>
</div>
<div id="remoteVideo" style="position:absolute;left:6px;top:45px;width:320px;height:260px;background-color:black;border-radius:12px 12px 0px 0px;display:none">
<div style="position:absolute;right:0;left:0;top:0px;height:20px;background-color:gray;text-align:center;border-radius:10px 10px 0px 0px"><div style="padding:3px">Remote</div></div>
<video id="remoteVideoCanvas" autoplay style="position:absolute;top:20px;left:0;width:320px;height:240px;background-color:black"></video>
</div>
2018-11-29 20:59:29 -05:00
<script type="text/javascript">
var userInputFocus = 0;
var controlsEnabled = true;
var args = parseUriArgs();
var socket = null; // Websocket object
var state = 0; // Connection state. 0 = Disconnected, 1 = Connecting, 2 = Connected.
var random = Math.random(); // Selected random, larger value initiates WebRTC.
var webrtc = null; // Main WebRTC object
var webchannel = null; // WebRTC data channel
var webrtcconfiguration = null; //{ "iceServers": [ { 'urls': 'stun:stun.services.mozilla.com' }, { 'urls': 'stun:stun.l.google.com:19302' } ] };
2018-12-16 16:44:49 -05:00
var localStream = null;
2018-11-29 20:59:29 -05:00
// Set the title
if (args.title) { QH('xtitle', ' - ' + args.title); document.title = document.title + ' - ' + args.title; }
2018-11-29 20:59:29 -05:00
// Trap document key presses
document.onkeypress = function ondockeypress(e) {
if (controlsEnabled == true) {
if ((e.keyCode == 8) && (userInputFocus == 0)) {
// Backspace
var outtext = Q('xouttext').value;
if (outtext.length > 0) { Q('xouttext').value = outtext.substring(0, outtext.length - 1); }
} else if (e.keyCode == 13) {
// Return
xsend(e);
} else {
// Any other key
if ((userInputFocus == 0) && (e.key.length == 1)) { Q('xouttext').value = Q('xouttext').value + e.key; }
}
}
if (userInputFocus == 0) { haltEvent(e); return false; }
}
function onUserInputFocus(x) { userInputFocus = x; }
function displayClear() { QH('xmsg', ''); }
// Display a control message
function displayControl(msg) {
2018-11-29 20:59:29 -05:00
QA('xmsg', '<div style="clear:both"><div style="color:gray;float:left;margin-bottom:2px">' + msg + '</div><div></div></div>');
Q('xmsg').scrollTop = Q('xmsg').scrollHeight;
}
2018-12-16 16:44:49 -05:00
function displayLocalVideo(active) { QV('localVideo', active); }
function displayRemoteVideo(active) { QV('remoteVideo', active); }
// Display a message from the remote user
function displayRemote(msg) {
2018-11-29 20:59:29 -05:00
QA('xmsg', '<div style="clear:both"><div style="background-color:#00cc99;color:black;border-radius:5px;padding:5px;float:left;margin-bottom:5px;margin-right:20px">' + msg + '</div><div></div></div>');
Q('xmsg').scrollTop = Q('xmsg').scrollHeight;
}
// Display and send a message from the local user
2018-11-29 20:59:29 -05:00
function xsend(event) {
var outtext = Q('xouttext').value;
if (outtext.length > 0) {
Q('xouttext').value = '';
QA('xmsg', '<div style="clear:both"><div style="background-color:#0099ff;color:black;border-radius:5px;padding:5px;float:right;margin-bottom:5px;margin-left:20px">' + outtext + '</div><div></div></div>');
Q('xmsg').scrollTop = Q('xmsg').scrollHeight;
send({ action: 'chat', msg: outtext });
2018-11-29 20:59:29 -05:00
}
}
// Enable user controls
2018-12-16 16:44:49 -05:00
function enableControls(lock, webrtc) { controlsEnabled = lock; QE('sendButton', lock); QE('clearButton', lock); QE('xouttext', lock); /*QV('fileButton', lock);*/ QV('camButton', lock & webrtc); QV('micButton', lock & webrtc); }
2018-11-29 20:59:29 -05:00
function haltEvent(e) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); return false; }
function parseUriArgs() { var name, r = {}, parsedUri = window.document.location.href.split(/[\?&|\=]/); parsedUri.splice(0, 1); for (x in parsedUri) { switch (x % 2) { case 0: { name = parsedUri[x]; break; } case 1: { r[name] = parsedUri[x]; var x = parseInt(r[name]); if (x == r[name]) { r[name] = x; } break; } } } return r; }
// This is the WebRTC setup
function startWebRTC(description) {
// Setup the WebRTC object
if (webrtc == null) {
if (typeof RTCPeerConnection !== 'undefined') { webrtc = new RTCPeerConnection(webrtcconfiguration); }
else if (typeof webkitRTCPeerConnection !== 'undefined') { webrtc = new webkitRTCPeerConnection(webrtcconfiguration); }
if (webrtc == null) return;
webrtc.onicecandidate = function (e) { try { if (e.candidate != null) { sendws({ action: 'webRtcIce', ice: e.candidate }); } } catch (ex) { } }
webrtc.oniceconnectionstatechange = function () { if (webrtc && webrtc.iceConnectionState == 'failed') { closeWebRTC(); } }
webrtc.ondatachannel = function (ev) {
webchannel = ev.channel;
webchannel.onmessage = function (event) { processMessage(event.data, 2); };
2018-12-16 16:44:49 -05:00
webchannel.onopen = function () { webchannel.ok = true; enableControls(true, true); sendws({ action: 'rtcSwitch', v: 0 }); };
webchannel.onclose = function (event) { if (webchannel && webchannel.ok) { disconnect(); } else { closeWebRTC(); } }
}
}
// Initiate the WebRTC offer or handle the offer from the peer.
if (description == null) {
webchannel = webrtc.createDataChannel("DataChannel", {}); // { ordered: false, maxRetransmits: 2 }
webchannel.onmessage = function (event) { processMessage(event.data, 2); };
2018-12-16 16:44:49 -05:00
webchannel.onopen = function () { webchannel.ok = true; enableControls(true, true); sendws({ action: 'rtcSwitch', v: 0 }); };
webchannel.onclose = function (event) { if (webchannel && webchannel.ok) { disconnect(); } else { closeWebRTC(); } }
webrtc.createOffer(function (offer) {
webrtc.setLocalDescription(offer, function () { try { sendws({ action: 'webRtcSdp', sdp: offer }); } catch (ex) { } }, closeWebRTC);
}, closeWebRTC, { mandatory: { OfferToReceiveAudio: false, OfferToReceiveVideo: false } });
} else {
webrtc.setRemoteDescription(new RTCSessionDescription(description), function () {
if (description.type == 'offer') {
webrtc.createAnswer(function (answer) {
webrtc.setLocalDescription(answer, function () { try { sendws({ action: 'webRtcSdp', sdp: answer }); } catch (ex) { } }, closeWebRTC);
}, closeWebRTC);
}
}, closeWebRTC);
}
}
// Indicate to peer that data traffic will no longer be sent over websocket and start holding traffic.
function performWebRtcSwitch() {
if (webchannel && webchannel.ok) { sendws({ action: 'rtcSwitch', v: 1 }); webchannel.xoutBuffer = []; }
}
// Close the WebRTC connection, should be called if a problem occurs during WebRTC setup.
function closeWebRTC() {
if (webchannel != null) { try { webchannel.close(); } catch (e) { } webchannel = null; }
if (webrtc != null) { try { webrtc.close(); } catch (e) { } webrtc = null; }
}
// Disconnect everything
function disconnect() {
enableControls(false);
closeWebRTC();
2018-12-16 16:44:49 -05:00
displayLocalVideo(false);
displayRemoteVideo(false);
if (socket != null) { socket.close(); socket = null; }
if (state > 0) { displayControl('Connection closed.'); }
if (state > 1) { setTimeout(start, 500); }
state = 0;
}
// Send data over the current transport (WebRTC first)
function send(data) {
if (state != 2) return; // If not in connected state, ignore this.
if (typeof data == 'object') { data = JSON.stringify(data); } // If this is an object, convert it to a string.
if (webchannel && webchannel.ok) { if (webchannel.xoutBuffer != null) { webchannel.xoutBuffer.push(data); } else { webchannel.send(data); } } // If WebRTC channel is possible, use it or hold until we can use it.
else { if (socket != null) { socket.send(data); } } // If a websocket channel is present, use that.
}
// Send data over the websocket transport (WebSocket only)
function sendws(data) {
if (state != 2) return;
if (typeof data == 'object') { data = JSON.stringify(data); }
if (socket != null) { socket.send(data); }
}
// Process incoming messages
function processMessage(data, transport) {
if (typeof data == 'string') {
try { data = JSON.parse(data); } catch (ex) { console.log('Unable to parse', data); return; }
switch (data.action) {
case 'chat': { displayRemote(data.msg); break; } // Incoming chat message.
case 'random': { if (random > data.random) { startWebRTC(); } break; } // If we have a larger random value, we start WebRTC.
case 'webRtcSdp': { startWebRTC(data.sdp); break; } // Remote WebRTC offer or answer.
case 'webRtcIce': { if (webrtc) { webrtc.addIceCandidate(new RTCIceCandidate(data.ice)); } break; } // Remote ICE candidate
case 'rtcSwitch': { // WebRTC switch over commands.
switch (data.v) {
case 0: { performWebRtcSwitch(); break; } // Other side is ready for switch over to WebRTC
case 1: { sendws({ action: 'rtcSwitch', v: 2 }); break; } // Other side no longer sending data on websocket, confirm we got the end marker
case 2: { for (var i in webchannel.xoutBuffer) { webchannel.send(webchannel.xoutBuffer[i]); } delete webchannel.xoutBuffer; break; } // Send any pending data over WebRTC and start using WebRTC with all traffic
}
break;
}
default: { console.log('Unhandled object data', data); break; }
}
} else {
console.log('Unhandled data', typeof data, data);
}
}
2018-12-16 16:44:49 -05:00
// File sharing button
function fileButtonClick() {
}
// Camera button
function camButtonClick() {
if (localStream == null) { startLocalStream({ video: true, audio: true }); } else { stopLocalStream(); }
}
// Microphone
function micButtonClick() {
if (localStream == null) { startLocalStream({ video: false, audio: true }); } else { stopLocalStream(); }
}
// Setup local audio/video
function startLocalStream(constraints) {
if (localStream != null) return;
if (navigator.mediaDevices.getUserMedia) {
localStream = 1;
navigator.mediaDevices.getUserMedia(constraints)
.then(function (stream) {
localStream = stream;
if (constraints.video == true) {
var video = Q('localVideoCanvas');
video.srcObject = stream;
video.onloadedmetadata = function (e) { video.play(); };
displayLocalVideo(true);
}
})
.catch(function (err) {
console.log('getUserMedia error');
localStream = null;
});
}
}
// Stop local audio/video
function stopLocalStream() {
if ((localStream != null) && (localStream != 1)) {
localStream.getTracks().forEach(track => track.stop());
localStream = null;
displayLocalVideo(false);
}
}
// This is the main start
function start() {
// Get started
enableControls(false);
if ((typeof args.id == 'string') && (args.id.length > 0)) {
socket = new WebSocket(window.location.protocol.replace("http", "ws") + "//" + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + '/meshrelay.ashx?id=' + args.id);
socket.onopen = function () { state = 1; displayControl('Waiting for other user...'); }
socket.onerror = function (e) { console.error(e); }
socket.onclose = function () { disconnect(); }
socket.onmessage = function (msg) {
if ((state < 2) && (typeof msg.data == 'string')) {
enableControls(true);
closeWebRTC();
displayControl('Connected.');
state = 2;
sendws({ action: 'random', random: random }); // Send a random number. Higher number starts the WebRTC session.
return;
2018-11-29 20:59:29 -05:00
}
if (state == 2) { processMessage(msg.data, 1); }
2018-11-29 20:59:29 -05:00
}
} else {
displayControl('Error: No connection key specified.');
2018-11-29 20:59:29 -05:00
}
}
start();
2018-11-29 20:59:29 -05:00
</script>
</body>
</html>