You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var focus = null;
  5. var RTC;
  6. var RTCPeerConnection = null;
  7. var nickname = null;
  8. var sharedKey = '';
  9. var roomUrl = null;
  10. window.onbeforeunload = closePageWarning;
  11. function init() {
  12. RTC = setupRTC();
  13. if (RTC === null) {
  14. window.location.href = '/webrtcrequired.html';
  15. return;
  16. } else if (RTC.browser != 'chrome') {
  17. window.location.href = '/chromeonly.html';
  18. return;
  19. }
  20. RTCPeerconnection = RTC.peerconnection;
  21. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  22. /*
  23. connection.rawInput = function (data) { console.log('RECV: ' + data); };
  24. connection.rawOutput = function (data) { console.log('SEND: ' + data); };
  25. */
  26. connection.jingle.pc_constraints = RTC.pc_constraints;
  27. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  28. connection.connect(jid, document.getElementById('password').value, function (status) {
  29. if (status == Strophe.Status.CONNECTED) {
  30. console.log('connected');
  31. getUserMediaWithConstraints(['audio', 'video'], '360');
  32. document.getElementById('connect').disabled = true;
  33. } else {
  34. console.log('status', status);
  35. }
  36. });
  37. }
  38. function doJoin() {
  39. var roomnode = null;
  40. var path = window.location.pathname;
  41. var roomjid;
  42. if (path.length > 1) {
  43. roomnode = path.substr(1).toLowerCase();
  44. } else {
  45. roomnode = Math.random().toString(36).substr(2, 20);
  46. window.history.pushState('VideoChat', 'Room: ' + roomnode, window.location.pathname + roomnode);
  47. }
  48. roomjid = roomnode + '@' + config.hosts.muc;
  49. if (config.useNicks) {
  50. var nick = window.prompt('Your nickname (optional)');
  51. if (nick) {
  52. roomjid += '/' + nick;
  53. } else {
  54. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  55. }
  56. } else {
  57. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  58. }
  59. connection.emuc.doJoin(roomjid);
  60. }
  61. $(document).bind('mediaready.jingle', function (event, stream) {
  62. connection.jingle.localStream = stream;
  63. RTC.attachMediaStream($('#localVideo'), stream);
  64. document.getElementById('localVideo').muted = true;
  65. document.getElementById('localVideo').autoplay = true;
  66. document.getElementById('localVideo').volume = 0;
  67. document.getElementById('largeVideo').volume = 0;
  68. document.getElementById('largeVideo').src = document.getElementById('localVideo').src;
  69. doJoin();
  70. });
  71. $(document).bind('mediafailure.jingle', function () {
  72. // FIXME
  73. });
  74. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  75. function waitForRemoteVideo(selector, sid) {
  76. var sess = connection.jingle.sessions[sid];
  77. videoTracks = data.stream.getVideoTracks();
  78. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  79. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  80. $(document).trigger('callactive.jingle', [selector, sid]);
  81. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  82. } else {
  83. setTimeout(function () { waitForRemoteVideo(selector, sid); }, 100);
  84. }
  85. }
  86. var sess = connection.jingle.sessions[sid];
  87. var vid = document.createElement('video');
  88. console.log(sess);
  89. var span = document.createElement('span');
  90. // FIXME: how to name this span? sess.peerjid is not right for jingle clients
  91. //console.log('peer: ', Strophe.getResourceFromJid(sess.peerjid));
  92. //span.id = 'remoteVideocontainer_' + Strophe.getResourceFromJid(sess.peerjid);
  93. span.className = 'videocontainer';
  94. var id = 'remoteVideo_' + sid + '_' + data.stream.id;
  95. vid.id = id;
  96. vid.autoplay = true;
  97. vid.oncontextmenu = function () { return false; };
  98. var remotes = document.getElementById('remoteVideos');
  99. span.appendChild(vid);
  100. if (id.indexOf('mixedmslabel') != -1) {
  101. $(span).hide();
  102. }
  103. remotes.appendChild(span);
  104. var sel = $('#' + id);
  105. sel.hide();
  106. RTC.attachMediaStream(sel, data.stream);
  107. waitForRemoteVideo(sel, sid);
  108. data.stream.onended = function () {
  109. console.log('stream ended', this.id);
  110. var src = $('#' + id).attr('src');
  111. $('#' + id).parent().remove();
  112. if (src === $('#largeVideo').attr('src')) {
  113. // this is currently displayed as large
  114. // pick the last visible video in the row
  115. // if nobody else is left, this picks the local video
  116. var pick = $('#remoteVideos>span:visible:last>video').get(0);
  117. // mute if localvideo
  118. document.getElementById('largeVideo').volume = pick.volume;
  119. document.getElementById('largeVideo').src = pick.src;
  120. }
  121. resizeThumbnails();
  122. };
  123. sel.click(
  124. function () {
  125. console.log('hover in', $(this).attr('src'));
  126. var newSrc = $(this).attr('src');
  127. if ($('#largeVideo').attr('src') != newSrc) {
  128. document.getElementById('largeVideo').volume = 1;
  129. $('#largeVideo').fadeOut(300, function () {
  130. $(this).attr('src', newSrc);
  131. $(this).fadeIn(300);
  132. });
  133. }
  134. }
  135. );
  136. });
  137. $(document).bind('callincoming.jingle', function (event, sid) {
  138. var sess = connection.jingle.sessions[sid];
  139. // TODO: check affiliation and/or role
  140. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  141. sess.sendAnswer();
  142. sess.accept();
  143. });
  144. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  145. console.log('call active');
  146. if (videoelem.attr('id').indexOf('mixedmslabel') == -1) {
  147. // ignore mixedmslabela0 and v0
  148. videoelem.show();
  149. resizeThumbnails();
  150. document.getElementById('largeVideo').volume = 1;
  151. $('#largeVideo').attr('src', videoelem.attr('src'));
  152. }
  153. });
  154. $(document).bind('callterminated.jingle', function (event, sid, reason) {
  155. // FIXME
  156. });
  157. $(document).bind('joined.muc', function (event, jid, info) {
  158. console.log('onJoinComplete', info);
  159. updateRoomUrl(window.location.href);
  160. // Once we've joined the muc show the toolbar
  161. showToolbar();
  162. if (Object.keys(connection.emuc.members).length < 1) {
  163. focus = new ColibriFocus(connection, config.hosts.bridge);
  164. return;
  165. }
  166. });
  167. $(document).bind('entered.muc', function (event, jid, info) {
  168. console.log('entered', jid, info);
  169. console.log(focus);
  170. if (focus !== null) {
  171. // FIXME: this should prepare the video
  172. if (focus.confid === null) {
  173. console.log('make new conference with', jid);
  174. focus.makeConference(Object.keys(connection.emuc.members));
  175. } else {
  176. console.log('invite', jid, 'into conference');
  177. focus.addNewParticipant(jid);
  178. }
  179. }
  180. else if (sharedKey) {
  181. updateLockButton();
  182. }
  183. });
  184. $(document).bind('left.muc', function (event, jid) {
  185. console.log('left', jid);
  186. connection.jingle.terminateByJid(jid);
  187. // FIXME: this should actually hide the video already for a nicer UX
  188. if (Object.keys(connection.emuc.members).length === 0) {
  189. console.log('everyone left');
  190. if (focus !== null) {
  191. // FIXME: closing the connection is a hack to avoid some
  192. // problemswith reinit
  193. if (focus.peerconnection !== null) {
  194. focus.peerconnection.close();
  195. }
  196. focus = new ColibriFocus(connection, config.hosts.bridge);
  197. }
  198. }
  199. });
  200. $(document).bind('passwordrequired.muc', function (event, jid) {
  201. console.log('on password required', jid);
  202. $.prompt('<h2>Password required</h2>' +
  203. '<input id="lockKey" type="text" placeholder="shared key" autofocus>',
  204. {
  205. persistent: true,
  206. buttons: { "Ok": true , "Cancel": false},
  207. defaultButton: 1,
  208. loaded: function(event) {
  209. document.getElementById('lockKey').focus();
  210. },
  211. submit: function(e,v,m,f){
  212. if(v)
  213. {
  214. var lockKey = document.getElementById('lockKey');
  215. if (lockKey.value != null)
  216. {
  217. setSharedKey(lockKey);
  218. connection.emuc.doJoin(jid, lockKey.value);
  219. }
  220. }
  221. }
  222. });
  223. });
  224. function toggleVideo() {
  225. if (!(connection && connection.jingle.localStream)) return;
  226. for (var idx = 0; idx < connection.jingle.localStream.getVideoTracks().length; idx++) {
  227. connection.jingle.localStream.getVideoTracks()[idx].enabled = !connection.jingle.localStream.getVideoTracks()[idx].enabled;
  228. }
  229. }
  230. function toggleAudio() {
  231. if (!(connection && connection.jingle.localStream)) return;
  232. for (var idx = 0; idx < connection.jingle.localStream.getAudioTracks().length; idx++) {
  233. connection.jingle.localStream.getAudioTracks()[idx].enabled = !connection.jingle.localStream.getAudioTracks()[idx].enabled;
  234. }
  235. }
  236. function resizeLarge() {
  237. var availableHeight = window.innerHeight;
  238. var chatspaceWidth = $('#chatspace').width();
  239. var numvids = $('#remoteVideos>video:visible').length;
  240. if (numvids < 5)
  241. availableHeight -= 100; // min thumbnail height for up to 4 videos
  242. else
  243. availableHeight -= 50; // min thumbnail height for more than 5 videos
  244. availableHeight -= 79; // padding + link ontop
  245. var availableWidth = window.innerWidth - chatspaceWidth;
  246. var aspectRatio = 16.0 / 9.0;
  247. if (availableHeight < availableWidth / aspectRatio) {
  248. availableWidth = Math.floor(availableHeight * aspectRatio);
  249. }
  250. if (availableWidth < 0 || availableHeight < 0) return;
  251. $('#largeVideo').parent().width(availableWidth);
  252. $('#largeVideo').parent().height(availableWidth / aspectRatio);
  253. resizeThumbnails();
  254. }
  255. function resizeThumbnails() {
  256. // Calculate the available height, which is the inner window height minus 39px for the header
  257. // minus 4px for the delimiter lines on the top and bottom of the large video,
  258. // minus the 36px space inside the remoteVideos container used for highlighting shadow.
  259. var availableHeight = window.innerHeight - $('#largeVideo').height() - 79;
  260. var numvids = $('#remoteVideos>span:visible').length;
  261. // Remove the 1px borders arround videos.
  262. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids;
  263. var availableWidth = availableWinWidth / numvids;
  264. var aspectRatio = 16.0 / 9.0;
  265. var maxHeight = Math.min(160, availableHeight);
  266. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  267. if (availableHeight < availableWidth / aspectRatio) {
  268. availableWidth = Math.floor(availableHeight * aspectRatio);
  269. }
  270. // size videos so that while keeping AR and max height, we have a nice fit
  271. $('#remoteVideos').height(availableHeight+26); // add the 2*18px-padding-top border used for highlighting shadow.
  272. $('#remoteVideos>span').width(availableWidth);
  273. $('#remoteVideos>span').height(availableHeight);
  274. }
  275. $(document).ready(function () {
  276. $('#nickinput').keydown(function(event) {
  277. if (event.keyCode == 13) {
  278. event.preventDefault();
  279. var val = this.value;
  280. this.value = '';
  281. if (!nickname) {
  282. nickname = val;
  283. $('#nickname').css({visibility:"hidden"});
  284. $('#chatconversation').css({visibility:'visible'});
  285. $('#usermsg').css({visibility:'visible'});
  286. $('#usermsg').focus();
  287. return;
  288. }
  289. }
  290. });
  291. $('#usermsg').keydown(function(event) {
  292. if (event.keyCode == 13) {
  293. event.preventDefault();
  294. var message = this.value;
  295. $('#usermsg').val('').trigger('autosize.resize');
  296. this.focus();
  297. connection.emuc.sendMessage(message, nickname);
  298. }
  299. });
  300. $('#usermsg').autosize();
  301. resizeLarge();
  302. $(window).resize(function () {
  303. resizeLarge();
  304. });
  305. if (!$('#settings').is(':visible')) {
  306. console.log('init');
  307. init();
  308. } else {
  309. loginInfo.onsubmit = function (e) {
  310. if (e.preventDefault) e.preventDefault();
  311. $('#settings').hide();
  312. init();
  313. };
  314. }
  315. });
  316. $(window).bind('unload', function () {
  317. if (connection && connection.connected) {
  318. // ensure signout
  319. $.ajax({
  320. type: 'POST',
  321. url: config.bosh,
  322. async: false,
  323. cache: false,
  324. contentType: 'application/xml',
  325. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  326. success: function (data) {
  327. console.log('signed out');
  328. console.log(data);
  329. },
  330. error: function (XMLHttpRequest, textStatus, errorThrown) {
  331. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  332. }
  333. });
  334. }
  335. });
  336. function dump(elem, filename){
  337. elem = elem.parentNode;
  338. elem.download = filename || 'xmpplog.json';
  339. elem.href = 'data:application/json;charset=utf-8,\n';
  340. var data = {};
  341. data.time = new Date();
  342. data.url = window.location.href;
  343. data.ua = navigator.userAgent;
  344. if (connection.logger) {
  345. data.xmpp = connection.logger.log;
  346. }
  347. if (connection.jingle) {
  348. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  349. var session = connection.jingle.sessions[sid];
  350. if (session.peerconnection && session.peerconnection.updateLog) {
  351. // FIXME: should probably be a .dump call
  352. data["jingle_" + session.sid] = session.peerconnection.updateLog;
  353. }
  354. });
  355. }
  356. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  357. return false;
  358. }
  359. function updateChatConversation(nick, message)
  360. {
  361. var divClassName = '';
  362. if (nickname == nick)
  363. divClassName = "localuser";
  364. else
  365. divClassName = "remoteuser";
  366. $('#chatconversation').append('<div class="' + divClassName + '"><b>' + nick + ': </b>' + message + '</div>');
  367. $('#chatconversation').animate({ scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  368. }
  369. /*
  370. * Changes the style class of the element given by id.
  371. */
  372. function buttonClick(id, classname) {
  373. $(id).toggleClass(classname); // add the class to the clicked element
  374. }
  375. /*
  376. * Opens the lock room dialog.
  377. */
  378. function openLockDialog() {
  379. // Only the focus is able to set a shared key.
  380. if (focus == null) {
  381. if (sharedKey)
  382. $.prompt("This conversation is currently protected by a shared secret key.",
  383. {
  384. title: "Secrect key",
  385. persistent: false
  386. });
  387. else
  388. $.prompt("This conversation isn't currently protected by a secret key. Only the owner of the conference could set a shared key.",
  389. {
  390. title: "Secrect key",
  391. persistent: false
  392. });
  393. }
  394. else {
  395. if (sharedKey)
  396. $.prompt("Are you sure you would like to remove your secret key?",
  397. {
  398. title: "Remove secrect key",
  399. persistent: false,
  400. buttons: { "Remove": true, "Cancel": false},
  401. defaultButton: 1,
  402. submit: function(e,v,m,f){
  403. if(v)
  404. {
  405. setSharedKey('');
  406. lockRoom();
  407. }
  408. }
  409. });
  410. else
  411. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  412. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  413. {
  414. persistent: false,
  415. buttons: { "Save": true , "Cancel": false},
  416. defaultButton: 1,
  417. loaded: function(event) {
  418. document.getElementById('lockKey').focus();
  419. },
  420. submit: function(e,v,m,f){
  421. if(v)
  422. {
  423. var lockKey = document.getElementById('lockKey');
  424. if (lockKey.value)
  425. {
  426. console.log("LOCK KEY", lockKey.value);
  427. setSharedKey(lockKey.value);
  428. lockRoom(true);
  429. }
  430. }
  431. }
  432. });
  433. }
  434. }
  435. /*
  436. * Opens the invite link dialog.
  437. */
  438. function openLinkDialog() {
  439. $.prompt('<input id="inviteLinkRef" type="text" value="' + roomUrl + '" onclick="this.select();">',
  440. {
  441. title: "Share this link with everyone you want to invite",
  442. persistent: false,
  443. buttons: { "Cancel": false},
  444. loaded: function(event) {
  445. document.getElementById('inviteLinkRef').select();
  446. }
  447. });
  448. }
  449. /*
  450. * Locks / unlocks the room.
  451. */
  452. function lockRoom(lock) {
  453. connection.emuc.lockRoom(sharedKey);
  454. updateLockButton();
  455. }
  456. /*
  457. * Sets the shared key.
  458. */
  459. function setSharedKey(sKey) {
  460. sharedKey = sKey;
  461. }
  462. /*
  463. * Updates the lock button state.
  464. */
  465. function updateLockButton() {
  466. buttonClick("#lockIcon", "fa fa-unlock fa-lg fa fa-lock fa-lg");
  467. }
  468. /*
  469. * Opens / closes the chat area.
  470. */
  471. function openChat() {
  472. var chatspace = $('#chatspace');
  473. var videospace = $('#videospace');
  474. var chatspaceWidth = chatspace.width();
  475. if (chatspace.css("opacity") == 1) {
  476. chatspace.animate({opacity: 0}, "fast");
  477. chatspace.animate({width: 0}, "slow");
  478. videospace.animate({right: 0, width:"100%"}, "slow");
  479. }
  480. else {
  481. chatspace.animate({width:"20%"}, "slow");
  482. chatspace.animate({opacity: 1}, "slow");
  483. videospace.animate({right:chatspaceWidth, width:"80%"}, "slow");
  484. }
  485. // Request the focus in the nickname field or the chat input field.
  486. if ($('#nickinput').is(':visible'))
  487. $('#nickinput').focus();
  488. else
  489. $('#usermsg').focus();
  490. }
  491. /*
  492. * Shows the call main toolbar.
  493. */
  494. function showToolbar() {
  495. $('#toolbar').css({visibility:"visible"});
  496. }
  497. /*
  498. * Updates the room invite url.
  499. */
  500. function updateRoomUrl(newRoomUrl) {
  501. roomUrl = newRoomUrl;
  502. }
  503. /*
  504. * Warning to the user that the conference window is about to be closed.
  505. */
  506. function closePageWarning() {
  507. if (focus != null)
  508. return "You are the owner of this conference call and you are about to end it.";
  509. else
  510. return "You are about to leave this conversation.";
  511. }