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.

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