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.

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