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.

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