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

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