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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. 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. console.log('onJoinComplete', info);
  172. updateRoomUrl(window.location.href);
  173. // Once we've joined the muc show the toolbar
  174. showToolbar();
  175. if (Object.keys(connection.emuc.members).length < 1) {
  176. focus = new ColibriFocus(connection, config.hosts.bridge);
  177. return;
  178. }
  179. });
  180. $(document).bind('entered.muc', function (event, jid, info) {
  181. console.log('entered', jid, info);
  182. console.log(focus);
  183. if (focus !== null) {
  184. // FIXME: this should prepare the video
  185. if (focus.confid === null) {
  186. console.log('make new conference with', jid);
  187. focus.makeConference(Object.keys(connection.emuc.members));
  188. } else {
  189. console.log('invite', jid, 'into conference');
  190. focus.addNewParticipant(jid);
  191. }
  192. }
  193. else if (sharedKey) {
  194. updateLockButton();
  195. }
  196. });
  197. $(document).bind('left.muc', function (event, jid) {
  198. console.log('left', jid);
  199. connection.jingle.terminateByJid(jid);
  200. // FIXME: this should actually hide the video already for a nicer UX
  201. if (Object.keys(connection.emuc.members).length === 0) {
  202. console.log('everyone left');
  203. if (focus !== null) {
  204. // FIXME: closing the connection is a hack to avoid some
  205. // problemswith reinit
  206. if (focus.peerconnection !== null) {
  207. focus.peerconnection.close();
  208. }
  209. focus = new ColibriFocus(connection, config.hosts.bridge);
  210. }
  211. }
  212. });
  213. $(document).bind('passwordrequired.muc', function (event, jid) {
  214. console.log('on password required', jid);
  215. $.prompt('<h2>Password required</h2>' +
  216. '<input id="lockKey" type="text" placeholder="shared key" autofocus>',
  217. {
  218. persistent: true,
  219. buttons: { "Ok": true , "Cancel": false},
  220. defaultButton: 1,
  221. loaded: function(event) {
  222. document.getElementById('lockKey').focus();
  223. },
  224. submit: function(e,v,m,f){
  225. if(v)
  226. {
  227. var lockKey = document.getElementById('lockKey');
  228. if (lockKey.value != null)
  229. {
  230. setSharedKey(lockKey);
  231. connection.emuc.doJoin(jid, lockKey.value);
  232. }
  233. }
  234. }
  235. });
  236. });
  237. function toggleVideo() {
  238. if (!(connection && connection.jingle.localStream)) return;
  239. for (var idx = 0; idx < connection.jingle.localStream.getVideoTracks().length; idx++) {
  240. connection.jingle.localStream.getVideoTracks()[idx].enabled = !connection.jingle.localStream.getVideoTracks()[idx].enabled;
  241. }
  242. }
  243. function toggleAudio() {
  244. if (!(connection && connection.jingle.localStream)) return;
  245. for (var idx = 0; idx < connection.jingle.localStream.getAudioTracks().length; idx++) {
  246. connection.jingle.localStream.getAudioTracks()[idx].enabled = !connection.jingle.localStream.getAudioTracks()[idx].enabled;
  247. }
  248. }
  249. function resizeLarge() {
  250. var availableHeight = window.innerHeight;
  251. var chatspaceWidth = $('#chatspace').width();
  252. var numvids = $('#remoteVideos>video:visible').length;
  253. if (numvids < 5)
  254. availableHeight -= 100; // min thumbnail height for up to 4 videos
  255. else
  256. availableHeight -= 50; // min thumbnail height for more than 5 videos
  257. availableHeight -= 79; // padding + link ontop
  258. var availableWidth = window.innerWidth - chatspaceWidth;
  259. var aspectRatio = 16.0 / 9.0;
  260. if (availableHeight < availableWidth / aspectRatio) {
  261. availableWidth = Math.floor(availableHeight * aspectRatio);
  262. }
  263. if (availableWidth < 0 || availableHeight < 0) return;
  264. $('#largeVideo').parent().width(availableWidth);
  265. $('#largeVideo').parent().height(availableWidth / aspectRatio);
  266. resizeThumbnails();
  267. }
  268. function resizeThumbnails() {
  269. // Calculate the available height, which is the inner window height minus 39px for the header
  270. // minus 4px for the delimiter lines on the top and bottom of the large video,
  271. // minus the 36px space inside the remoteVideos container used for highlighting shadow.
  272. var availableHeight = window.innerHeight - $('#largeVideo').height() - 79;
  273. var numvids = $('#remoteVideos>span:visible').length;
  274. // Remove the 1px borders arround videos.
  275. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids;
  276. var availableWidth = availableWinWidth / numvids;
  277. var aspectRatio = 16.0 / 9.0;
  278. var maxHeight = Math.min(160, availableHeight);
  279. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  280. if (availableHeight < availableWidth / aspectRatio) {
  281. availableWidth = Math.floor(availableHeight * aspectRatio);
  282. }
  283. // size videos so that while keeping AR and max height, we have a nice fit
  284. $('#remoteVideos').height(availableHeight+26); // add the 2*18px-padding-top border used for highlighting shadow.
  285. $('#remoteVideos>span').width(availableWidth);
  286. $('#remoteVideos>span').height(availableHeight);
  287. }
  288. $(document).ready(function () {
  289. $('#nickinput').keydown(function(event) {
  290. if (event.keyCode == 13) {
  291. event.preventDefault();
  292. var val = this.value;
  293. this.value = '';
  294. if (!nickname) {
  295. nickname = val;
  296. $('#nickname').css({visibility:"hidden"});
  297. $('#chatconversation').css({visibility:'visible'});
  298. $('#usermsg').css({visibility:'visible'});
  299. $('#usermsg').focus();
  300. return;
  301. }
  302. }
  303. });
  304. $('#usermsg').keydown(function(event) {
  305. if (event.keyCode == 13) {
  306. event.preventDefault();
  307. var message = this.value;
  308. $('#usermsg').val('').trigger('autosize.resize');
  309. this.focus();
  310. connection.emuc.sendMessage(message, nickname);
  311. }
  312. });
  313. $('#usermsg').autosize();
  314. resizeLarge();
  315. $(window).resize(function () {
  316. resizeLarge();
  317. });
  318. if (!$('#settings').is(':visible')) {
  319. console.log('init');
  320. init();
  321. } else {
  322. loginInfo.onsubmit = function (e) {
  323. if (e.preventDefault) e.preventDefault();
  324. $('#settings').hide();
  325. init();
  326. };
  327. }
  328. });
  329. $(window).bind('unload', function () {
  330. if (connection && connection.connected) {
  331. // ensure signout
  332. $.ajax({
  333. type: 'POST',
  334. url: config.bosh,
  335. async: false,
  336. cache: false,
  337. contentType: 'application/xml',
  338. 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>",
  339. success: function (data) {
  340. console.log('signed out');
  341. console.log(data);
  342. },
  343. error: function (XMLHttpRequest, textStatus, errorThrown) {
  344. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  345. }
  346. });
  347. }
  348. });
  349. function dump(elem, filename){
  350. elem = elem.parentNode;
  351. elem.download = filename || 'xmpplog.json';
  352. elem.href = 'data:application/json;charset=utf-8,\n';
  353. var data = {};
  354. data.time = new Date();
  355. data.url = window.location.href;
  356. data.ua = navigator.userAgent;
  357. if (connection.logger) {
  358. data.xmpp = connection.logger.log;
  359. }
  360. if (connection.jingle) {
  361. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  362. var session = connection.jingle.sessions[sid];
  363. if (session.peerconnection && session.peerconnection.updateLog) {
  364. // FIXME: should probably be a .dump call
  365. data["jingle_" + session.sid] = session.peerconnection.updateLog;
  366. }
  367. });
  368. }
  369. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  370. return false;
  371. }
  372. function updateChatConversation(nick, message)
  373. {
  374. var divClassName = '';
  375. if (nickname == nick)
  376. divClassName = "localuser";
  377. else
  378. divClassName = "remoteuser";
  379. $('#chatconversation').append('<div class="' + divClassName + '"><b>' + nick + ': </b>' + message + '</div>');
  380. $('#chatconversation').animate({ scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  381. }
  382. /*
  383. * Changes the style class of the element given by id.
  384. */
  385. function buttonClick(id, classname) {
  386. $(id).toggleClass(classname); // add the class to the clicked element
  387. }
  388. /*
  389. * Opens the lock room dialog.
  390. */
  391. function openLockDialog() {
  392. // Only the focus is able to set a shared key.
  393. if (focus == null) {
  394. if (sharedKey)
  395. $.prompt("This conversation is currently protected by a shared secret key.",
  396. {
  397. title: "Secrect key",
  398. persistent: false
  399. });
  400. else
  401. $.prompt("This conversation isn't currently protected by a secret key. Only the owner of the conference could set a shared key.",
  402. {
  403. title: "Secrect key",
  404. persistent: false
  405. });
  406. }
  407. else {
  408. if (sharedKey)
  409. $.prompt("Are you sure you would like to remove your secret key?",
  410. {
  411. title: "Remove secrect key",
  412. persistent: false,
  413. buttons: { "Remove": true, "Cancel": false},
  414. defaultButton: 1,
  415. submit: function(e,v,m,f){
  416. if(v)
  417. {
  418. setSharedKey('');
  419. lockRoom();
  420. }
  421. }
  422. });
  423. else
  424. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  425. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  426. {
  427. persistent: false,
  428. buttons: { "Save": true , "Cancel": false},
  429. defaultButton: 1,
  430. loaded: function(event) {
  431. document.getElementById('lockKey').focus();
  432. },
  433. submit: function(e,v,m,f){
  434. if(v)
  435. {
  436. var lockKey = document.getElementById('lockKey');
  437. if (lockKey.value)
  438. {
  439. console.log("LOCK KEY", lockKey.value);
  440. setSharedKey(lockKey.value);
  441. lockRoom(true);
  442. }
  443. }
  444. }
  445. });
  446. }
  447. }
  448. /*
  449. * Opens the invite link dialog.
  450. */
  451. function openLinkDialog() {
  452. $.prompt('<input id="inviteLinkRef" type="text" value="' + roomUrl + '" onclick="this.select();">',
  453. {
  454. title: "Share this link with everyone you want to invite",
  455. persistent: false,
  456. buttons: { "Cancel": false},
  457. loaded: function(event) {
  458. document.getElementById('inviteLinkRef').select();
  459. }
  460. });
  461. }
  462. /*
  463. * Locks / unlocks the room.
  464. */
  465. function lockRoom(lock) {
  466. connection.emuc.lockRoom(sharedKey);
  467. updateLockButton();
  468. }
  469. /*
  470. * Sets the shared key.
  471. */
  472. function setSharedKey(sKey) {
  473. sharedKey = sKey;
  474. }
  475. /*
  476. * Updates the lock button state.
  477. */
  478. function updateLockButton() {
  479. buttonClick("#lockIcon", "fa fa-unlock fa-lg fa fa-lock fa-lg");
  480. }
  481. /*
  482. * Opens / closes the chat area.
  483. */
  484. function openChat() {
  485. var chatspace = $('#chatspace');
  486. var videospace = $('#videospace');
  487. var chatspaceWidth = chatspace.width();
  488. if (chatspace.css("opacity") == 1) {
  489. chatspace.animate({opacity: 0}, "fast");
  490. chatspace.animate({width: 0}, "slow");
  491. videospace.animate({right: 0, width:"100%"}, "slow");
  492. }
  493. else {
  494. chatspace.animate({width:"20%"}, "slow");
  495. chatspace.animate({opacity: 1}, "slow");
  496. videospace.animate({right:chatspaceWidth, width:"80%"}, "slow");
  497. }
  498. // Request the focus in the nickname field or the chat input field.
  499. if ($('#nickinput').is(':visible'))
  500. $('#nickinput').focus();
  501. else
  502. $('#usermsg').focus();
  503. }
  504. /*
  505. * Shows the call main toolbar.
  506. */
  507. function showToolbar() {
  508. $('#toolbar').css({visibility:"visible"});
  509. }
  510. /*
  511. * Updates the room invite url.
  512. */
  513. function updateRoomUrl(newRoomUrl) {
  514. roomUrl = newRoomUrl;
  515. }
  516. /*
  517. * Warning to the user that the conference window is about to be closed.
  518. */
  519. function closePageWarning() {
  520. if (focus != null)
  521. return "You are the owner of this conference call and you are about to end it.";
  522. else
  523. return "You are about to leave this conversation.";
  524. }