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 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. var ssrc2jid = {};
  11. var localVideoSrc = null;
  12. var preziPlayer = null;
  13. /* window.onbeforeunload = closePageWarning; */
  14. function init() {
  15. RTC = setupRTC();
  16. if (RTC === null) {
  17. window.location.href = 'webrtcrequired.html';
  18. return;
  19. } else if (RTC.browser != 'chrome') {
  20. window.location.href = 'chromeonly.html';
  21. return;
  22. }
  23. RTCPeerconnection = TraceablePeerConnection;
  24. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  25. if (connection.disco) {
  26. // for chrome, add multistream cap
  27. }
  28. connection.jingle.pc_constraints = RTC.pc_constraints;
  29. if (config.useIPv6) {
  30. // https://code.google.com/p/webrtc/issues/detail?id=2828
  31. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  32. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  33. }
  34. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  35. connection.connect(jid, document.getElementById('password').value, function (status) {
  36. if (status == Strophe.Status.CONNECTED) {
  37. console.log('connected');
  38. if (config.useStunTurn) {
  39. connection.jingle.getStunAndTurnCredentials();
  40. }
  41. if (RTC.browser == 'firefox') {
  42. getUserMediaWithConstraints(['audio']);
  43. } else {
  44. getUserMediaWithConstraints(['audio', 'video'], config.resolution || '360');
  45. }
  46. document.getElementById('connect').disabled = true;
  47. } else {
  48. console.log('status', status);
  49. }
  50. });
  51. }
  52. function doJoin() {
  53. var roomnode = null;
  54. var path = window.location.pathname;
  55. var roomjid;
  56. // determinde the room node from the url
  57. // TODO: just the roomnode or the whole bare jid?
  58. if (config.getroomnode && typeof config.getroomnode === 'function') {
  59. // custom function might be responsible for doing the pushstate
  60. roomnode = config.getroomnode(path);
  61. } else {
  62. /* fall back to default strategy
  63. * this is making assumptions about how the URL->room mapping happens.
  64. * It currently assumes deployment at root, with a rewrite like the
  65. * following one (for nginx):
  66. location ~ ^/([a-zA-Z0-9]+)$ {
  67. rewrite ^/(.*)$ / break;
  68. }
  69. */
  70. if (path.length > 1) {
  71. roomnode = path.substr(1).toLowerCase();
  72. } else {
  73. roomnode = Math.random().toString(36).substr(2, 20);
  74. window.history.pushState('VideoChat', 'Room: ' + roomnode, window.location.pathname + roomnode);
  75. }
  76. }
  77. roomjid = roomnode + '@' + config.hosts.muc;
  78. if (config.useNicks) {
  79. var nick = window.prompt('Your nickname (optional)');
  80. if (nick) {
  81. roomjid += '/' + nick;
  82. } else {
  83. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  84. }
  85. } else {
  86. roomjid += '/' + Strophe.getNodeFromJid(connection.jid).substr(0,8);
  87. }
  88. connection.emuc.doJoin(roomjid);
  89. }
  90. $(document).bind('mediaready.jingle', function (event, stream) {
  91. connection.jingle.localStream = stream;
  92. RTC.attachMediaStream($('#localVideo'), stream);
  93. document.getElementById('localVideo').autoplay = true;
  94. document.getElementById('localVideo').volume = 0;
  95. localVideoSrc = document.getElementById('localVideo').src;
  96. updateLargeVideo(localVideoSrc, true, 0);
  97. $('#localVideo').click(function () {
  98. updateLargeVideo($(this).attr('src'), true, 0);
  99. $('video').each(function (idx, el) {
  100. if (el.id.indexOf('mixedmslabel') != -1) {
  101. el.volume = 0;
  102. el.volume = 1;
  103. }
  104. });
  105. });
  106. doJoin();
  107. });
  108. $(document).bind('mediafailure.jingle', function () {
  109. // FIXME
  110. });
  111. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  112. function waitForRemoteVideo(selector, sid) {
  113. var sess = connection.jingle.sessions[sid];
  114. videoTracks = data.stream.getVideoTracks();
  115. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  116. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  117. $(document).trigger('callactive.jingle', [selector, sid]);
  118. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  119. } else {
  120. setTimeout(function () { waitForRemoteVideo(selector, sid); }, 100);
  121. }
  122. }
  123. var sess = connection.jingle.sessions[sid];
  124. // look up an associated JID for a stream id
  125. if (data.stream.id.indexOf('mixedmslabel') == -1) {
  126. var ssrclines = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  127. ssrclines = ssrclines.filter(function (line) {
  128. return line.indexOf('mslabel:' + data.stream.label) != -1;
  129. });
  130. if (ssrclines.length) {
  131. thessrc = ssrclines[0].substring(7).split(' ')[0];
  132. // ok to overwrite the one from focus? might save work in colibri.js
  133. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  134. if (ssrc2jid[thessrc]) {
  135. data.peerjid = ssrc2jid[thessrc];
  136. }
  137. }
  138. }
  139. var container;
  140. var remotes = document.getElementById('remoteVideos');
  141. if (data.peerjid) {
  142. container = document.getElementById('participant_' + Strophe.getResourceFromJid(data.peerjid));
  143. if (!container) {
  144. console.warn('no container for', data.peerjid);
  145. // create for now...
  146. // FIXME: should be removed
  147. container = addRemoteVideoContainer('participant_' + Strophe.getResourceFromJid(data.peerjid));
  148. } else {
  149. //console.log('found container for', data.peerjid);
  150. }
  151. } else {
  152. if (data.stream.id != 'mixedmslabel') {
  153. console.warn('can not associate stream', data.stream.id, 'with a participant');
  154. }
  155. // FIXME: for the mixed ms we dont need a video -- currently
  156. container = document.createElement('span');
  157. container.className = 'videocontainer';
  158. remotes.appendChild(container);
  159. }
  160. var vid = document.createElement('video');
  161. var id = 'remoteVideo_' + sid + '_' + data.stream.id;
  162. vid.id = id;
  163. vid.autoplay = true;
  164. vid.oncontextmenu = function () { return false; };
  165. container.appendChild(vid);
  166. // TODO: make mixedstream display:none via css?
  167. if (id.indexOf('mixedmslabel') != -1) {
  168. container.id = 'mixedstream';
  169. $(container).hide();
  170. }
  171. var sel = $('#' + id);
  172. sel.hide();
  173. RTC.attachMediaStream(sel, data.stream);
  174. waitForRemoteVideo(sel, sid);
  175. data.stream.onended = function () {
  176. console.log('stream ended', this.id);
  177. var src = $('#' + id).attr('src');
  178. if (src === $('#largeVideo').attr('src')) {
  179. // this is currently displayed as large
  180. // pick the last visible video in the row
  181. // if nobody else is left, this picks the local video
  182. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video').get(0);
  183. // mute if localvideo
  184. var isLocalVideo = false;
  185. if (pick) {
  186. if (pick.src === localVideoSrc)
  187. isLocalVideo = true;
  188. updateLargeVideo(pick.src, isLocalVideo, pick.volume);
  189. }
  190. }
  191. $('#' + id).parent().remove();
  192. resizeThumbnails();
  193. };
  194. sel.click(
  195. function () {
  196. updateLargeVideo($(this).attr('src'), false, 1);
  197. }
  198. );
  199. });
  200. $(document).bind('callincoming.jingle', function (event, sid) {
  201. var sess = connection.jingle.sessions[sid];
  202. // TODO: check affiliation and/or role
  203. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  204. sess.usedrip = true; // not-so-naive trickle ice
  205. sess.sendAnswer();
  206. sess.accept();
  207. });
  208. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  209. if (videoelem.attr('id').indexOf('mixedmslabel') == -1) {
  210. // ignore mixedmslabela0 and v0
  211. videoelem.show();
  212. resizeThumbnails();
  213. updateLargeVideo(videoelem.attr('src'), false, 1);
  214. showFocusIndicator();
  215. }
  216. });
  217. $(document).bind('callterminated.jingle', function (event, sid, reason) {
  218. // FIXME
  219. });
  220. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  221. // put our ssrcs into presence so other clients can identify our stream
  222. var sess = connection.jingle.sessions[sid];
  223. var newssrcs = {};
  224. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  225. localSDP.media.forEach(function (media) {
  226. var type = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  227. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  228. // assumes a single local ssrc
  229. newssrcs[type] = ssrc;
  230. });
  231. console.log('new ssrcs', newssrcs);
  232. var i = 0;
  233. Object.keys(newssrcs).forEach(function (mtype) {
  234. i++;
  235. connection.emuc.addMediaToPresence(i, mtype, newssrcs[mtype]);
  236. });
  237. connection.emuc.sendPresence();
  238. });
  239. $(document).bind('joined.muc', function (event, jid, info) {
  240. updateRoomUrl(window.location.href);
  241. document.getElementById('localNick').appendChild(
  242. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (you)')
  243. );
  244. if (Object.keys(connection.emuc.members).length < 1) {
  245. focus = new ColibriFocus(connection, config.hosts.bridge);
  246. }
  247. // Once we've joined the muc show the toolbar
  248. showToolbar();
  249. });
  250. $(document).bind('entered.muc', function (event, jid, info, pres) {
  251. console.log('entered', jid, info);
  252. console.log(focus);
  253. var container = addRemoteVideoContainer('participant_' + Strophe.getResourceFromJid(jid));
  254. var nickfield = document.createElement('span');
  255. nickfield.appendChild(document.createTextNode(Strophe.getResourceFromJid(jid)));
  256. container.appendChild(nickfield);
  257. resizeThumbnails();
  258. if (focus !== null) {
  259. // FIXME: this should prepare the video
  260. if (focus.confid === null) {
  261. console.log('make new conference with', jid);
  262. focus.makeConference(Object.keys(connection.emuc.members));
  263. } else {
  264. console.log('invite', jid, 'into conference');
  265. focus.addNewParticipant(jid);
  266. }
  267. }
  268. else if (sharedKey) {
  269. updateLockButton();
  270. }
  271. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  272. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  273. ssrc2jid[ssrc.getAttribute('ssrc')] = jid;
  274. });
  275. });
  276. $(document).bind('left.muc', function (event, jid) {
  277. console.log('left', jid);
  278. connection.jingle.terminateByJid(jid);
  279. var container = document.getElementById('participant_' + Strophe.getResourceFromJid(jid));
  280. if (container) {
  281. // hide here, wait for video to close before removing
  282. $(container).hide();
  283. resizeThumbnails();
  284. }
  285. if (Object.keys(connection.emuc.members).length === 0) {
  286. console.log('everyone left');
  287. if (focus !== null) {
  288. // FIXME: closing the connection is a hack to avoid some
  289. // problemswith reinit
  290. if (focus.peerconnection !== null) {
  291. focus.peerconnection.close();
  292. }
  293. focus = new ColibriFocus(connection, config.hosts.bridge);
  294. }
  295. }
  296. if (connection.emuc.getPrezi(jid)) {
  297. $(document).trigger('presentationremoved.muc', [jid, connection.emuc.getPrezi(jid)]);
  298. }
  299. });
  300. $(document).bind('presence.muc', function (event, jid, info, pres) {
  301. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  302. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  303. ssrc2jid[ssrc.getAttribute('ssrc')] = jid;
  304. });
  305. });
  306. $(document).bind('passwordrequired.muc', function (event, jid) {
  307. console.log('on password required', jid);
  308. $.prompt('<h2>Password required</h2>' +
  309. '<input id="lockKey" type="text" placeholder="shared key" autofocus>',
  310. {
  311. persistent: true,
  312. buttons: { "Ok": true , "Cancel": false},
  313. defaultButton: 1,
  314. loaded: function(event) {
  315. document.getElementById('lockKey').focus();
  316. },
  317. submit: function(e,v,m,f){
  318. if(v)
  319. {
  320. var lockKey = document.getElementById('lockKey');
  321. if (lockKey.value != null)
  322. {
  323. setSharedKey(lockKey);
  324. connection.emuc.doJoin(jid, lockKey.value);
  325. }
  326. }
  327. }
  328. });
  329. });
  330. /*
  331. * Presentation has been removed.
  332. */
  333. $(document).bind('presentationremoved.muc', function(event, jid, presUrl) {
  334. console.log('presentation removed', presUrl);
  335. var presId = getPresentationId(presUrl);
  336. setPresentationVisible(false);
  337. $('#participant_' + Strophe.getResourceFromJid(jid) + '_' + presId).remove();
  338. $('#presentation>iframe').remove();
  339. if (preziPlayer != null) {
  340. preziPlayer.destroy();
  341. preziPlayer = null;
  342. }
  343. });
  344. /*
  345. * Presentation has been added.
  346. */
  347. $(document).bind('presentationadded.muc', function (event, jid, presUrl, currentSlide) {
  348. console.log("presentation added", presUrl);
  349. var presId = getPresentationId(presUrl);
  350. var elementId = 'participant_' + Strophe.getResourceFromJid(jid) + '_' + presId;
  351. var container = addRemoteVideoContainer(elementId);
  352. resizeThumbnails();
  353. var controlsEnabled = false;
  354. if (jid === connection.emuc.myroomjid)
  355. controlsEnabled = true;
  356. setPresentationVisible(true);
  357. $('#largeVideoContainer').hover(
  358. function (event) {
  359. if ($('#largeVideo').css('visibility') == 'hidden')
  360. $('#reloadPresentation').css({display:'inline-block'});
  361. },
  362. function (event) {
  363. if ($('#largeVideo').css('visibility') == 'visible')
  364. $('#reloadPresentation').css({display:'none'});
  365. else {
  366. var e = event.toElement || event.relatedTarget;
  367. while(e && e.parentNode && e.parentNode != window) {
  368. if (e.parentNode == this || e == this) {
  369. return false;
  370. }
  371. e = e.parentNode;
  372. }
  373. $('#reloadPresentation').css({display:'none'});
  374. }
  375. });
  376. preziPlayer = new PreziPlayer(
  377. 'presentation',
  378. {preziId: presId,
  379. width: $('#largeVideoContainer').width(),
  380. height: $('#largeVideoContainer').height(),
  381. controls: controlsEnabled,
  382. debug: true
  383. });
  384. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  385. // $('#presentation>iframe').load(function (){
  386. // console.log("IFRAME LOADED!!!!!!!!!!!!!!!!");
  387. // });
  388. // $('#presentation>iframe').ready(function (){
  389. // console.log("IFRAME READY!!!!!!!!!!!!!!!!");
  390. // });
  391. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  392. console.log("prezi status", event.value);
  393. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  394. if (jid != connection.emuc.myroomjid)
  395. preziPlayer.flyToStep(currentSlide);
  396. }
  397. });
  398. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  399. console.log("event value", event.value);
  400. connection.emuc.addCurrentSlideToPresence(event.value);
  401. connection.emuc.sendPresence();
  402. });
  403. $("#" + elementId).css('background-image','url(../images/avatarprezi.png)');
  404. $("#" + elementId).click(
  405. function () {
  406. setPresentationVisible(true);
  407. }
  408. );
  409. });
  410. /*
  411. * Indicates presentation slide change.
  412. */
  413. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  414. if (preziPlayer) {
  415. preziPlayer.flyToStep(current);
  416. }
  417. });
  418. /**
  419. * Returns the presentation id from the given url.
  420. */
  421. function getPresentationId (presUrl) {
  422. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  423. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  424. }
  425. /*
  426. * Reloads the current presentation.
  427. */
  428. function reloadPresentation() {
  429. var iframe = document.getElementById(preziPlayer.options.preziId);
  430. iframe.src = iframe.src;
  431. }
  432. /*
  433. * Shows/hides a presentation.
  434. */
  435. function setPresentationVisible(visible) {
  436. if (visible) {
  437. $('#largeVideo').fadeOut(300, function () {
  438. $('#largeVideo').css({visibility:'hidden'});
  439. $('#presentation>iframe').fadeIn(300, function() {
  440. $('#presentation>iframe').css({opacity:'1'});
  441. });
  442. });
  443. }
  444. else {
  445. if ($('#presentation>iframe')) {
  446. $('#presentation>iframe').fadeOut(300, function () {
  447. $('#presentation>iframe').css({opacity:'0'});
  448. $('#largeVideo').fadeIn(300, function() {
  449. $('#largeVideo').css({visibility:'visible'});
  450. });
  451. });
  452. }
  453. }
  454. }
  455. /**
  456. * Updates the large video with the given new video source.
  457. */
  458. function updateLargeVideo(newSrc, localVideo, vol) {
  459. console.log('hover in', newSrc);
  460. setPresentationVisible(false);
  461. if ($('#largeVideo').attr('src') != newSrc) {
  462. document.getElementById('largeVideo').volume = vol;
  463. $('#largeVideo').fadeOut(300, function () {
  464. $(this).attr('src', newSrc);
  465. var videoTransform = document.getElementById('largeVideo').style.webkitTransform;
  466. if (localVideo && videoTransform != 'scaleX(-1)') {
  467. document.getElementById('largeVideo').style.webkitTransform = "scaleX(-1)";
  468. }
  469. else if (!localVideo && videoTransform == 'scaleX(-1)') {
  470. document.getElementById('largeVideo').style.webkitTransform = "none";
  471. }
  472. $(this).fadeIn(300);
  473. });
  474. }
  475. }
  476. function toggleVideo() {
  477. if (!(connection && connection.jingle.localStream)) return;
  478. for (var idx = 0; idx < connection.jingle.localStream.getVideoTracks().length; idx++) {
  479. connection.jingle.localStream.getVideoTracks()[idx].enabled = !connection.jingle.localStream.getVideoTracks()[idx].enabled;
  480. }
  481. }
  482. function toggleAudio() {
  483. if (!(connection && connection.jingle.localStream)) return;
  484. for (var idx = 0; idx < connection.jingle.localStream.getAudioTracks().length; idx++) {
  485. connection.jingle.localStream.getAudioTracks()[idx].enabled = !connection.jingle.localStream.getAudioTracks()[idx].enabled;
  486. }
  487. }
  488. function resizeLarge() {
  489. var availableHeight = window.innerHeight;
  490. var chatspaceWidth = $('#chatspace').width();
  491. var numvids = $('#remoteVideos>video:visible').length;
  492. if (numvids < 5)
  493. availableHeight -= 100; // min thumbnail height for up to 4 videos
  494. else
  495. availableHeight -= 50; // min thumbnail height for more than 5 videos
  496. availableHeight -= 79; // padding + link ontop
  497. var availableWidth = window.innerWidth - chatspaceWidth;
  498. var aspectRatio = 16.0 / 9.0;
  499. if (availableHeight < availableWidth / aspectRatio) {
  500. availableWidth = Math.floor(availableHeight * aspectRatio);
  501. }
  502. if (availableWidth < 0 || availableHeight < 0) return;
  503. $('#largeVideo').parent().width(availableWidth);
  504. $('#largeVideo').parent().height(availableWidth / aspectRatio);
  505. if ($('#presentation>iframe')) {
  506. $('#presentation>iframe').width(availableWidth);
  507. $('#presentation>iframe').height(availableWidth / aspectRatio);
  508. }
  509. resizeThumbnails();
  510. }
  511. function resizeThumbnails() {
  512. // Calculate the available height, which is the inner window height minus 39px for the header
  513. // minus 4px for the delimiter lines on the top and bottom of the large video,
  514. // minus the 36px space inside the remoteVideos container used for highlighting shadow.
  515. var availableHeight = window.innerHeight - $('#largeVideo').height() - 79;
  516. var numvids = $('#remoteVideos>span:visible').length;
  517. var chatWidth = $('#chatspace').width();
  518. // Remove the 1px borders arround videos and the chat width.
  519. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids - chatWidth - 50;
  520. var availableWidth = availableWinWidth / numvids;
  521. var aspectRatio = 16.0 / 9.0;
  522. var maxHeight = Math.min(160, availableHeight);
  523. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  524. if (availableHeight < availableWidth / aspectRatio) {
  525. availableWidth = Math.floor(availableHeight * aspectRatio);
  526. }
  527. // size videos so that while keeping AR and max height, we have a nice fit
  528. $('#remoteVideos').height(availableHeight+26); // add the 2*18px-padding-top border used for highlighting shadow.
  529. $('#remoteVideos>span').width(availableWidth);
  530. $('#remoteVideos>span').height(availableHeight);
  531. }
  532. $(document).ready(function () {
  533. $('#nickinput').keydown(function(event) {
  534. if (event.keyCode == 13) {
  535. event.preventDefault();
  536. var val = this.value;
  537. this.value = '';
  538. if (!nickname) {
  539. nickname = val;
  540. $('#nickname').css({visibility:"hidden"});
  541. $('#chatconversation').css({visibility:'visible'});
  542. $('#usermsg').css({visibility:'visible'});
  543. $('#usermsg').focus();
  544. return;
  545. }
  546. }
  547. });
  548. $('#usermsg').keydown(function(event) {
  549. if (event.keyCode == 13) {
  550. event.preventDefault();
  551. var message = this.value;
  552. $('#usermsg').val('').trigger('autosize.resize');
  553. this.focus();
  554. connection.emuc.sendMessage(message, nickname);
  555. }
  556. });
  557. $('#usermsg').autosize();
  558. // Set the defaults for prompt dialogs.
  559. jQuery.prompt.setDefaults({persistent: false});
  560. resizeLarge();
  561. $(window).resize(function () {
  562. resizeLarge();
  563. });
  564. if (!$('#settings').is(':visible')) {
  565. console.log('init');
  566. init();
  567. } else {
  568. loginInfo.onsubmit = function (e) {
  569. if (e.preventDefault) e.preventDefault();
  570. $('#settings').hide();
  571. init();
  572. };
  573. }
  574. });
  575. $(window).bind('beforeunload', function () {
  576. if (connection && connection.connected) {
  577. // ensure signout
  578. $.ajax({
  579. type: 'POST',
  580. url: config.bosh,
  581. async: false,
  582. cache: false,
  583. contentType: 'application/xml',
  584. 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>",
  585. success: function (data) {
  586. console.log('signed out');
  587. console.log(data);
  588. },
  589. error: function (XMLHttpRequest, textStatus, errorThrown) {
  590. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  591. }
  592. });
  593. }
  594. });
  595. function dump(elem, filename){
  596. elem = elem.parentNode;
  597. elem.download = filename || 'meetlog.json';
  598. elem.href = 'data:application/json;charset=utf-8,\n';
  599. var data = {};
  600. if (connection.jingle) {
  601. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  602. var session = connection.jingle.sessions[sid];
  603. if (session.peerconnection && session.peerconnection.updateLog) {
  604. // FIXME: should probably be a .dump call
  605. data["jingle_" + session.sid] = {
  606. updateLog: session.peerconnection.updateLog,
  607. url: window.location.href}
  608. ;
  609. }
  610. });
  611. }
  612. metadata = {};
  613. metadata.time = new Date();
  614. metadata.url = window.location.href;
  615. metadata.ua = navigator.userAgent;
  616. if (connection.logger) {
  617. metadata.xmpp = connection.logger.log;
  618. }
  619. data.metadata = metadata;
  620. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  621. return false;
  622. }
  623. /*
  624. * Appends the given message to the chat conversation.
  625. */
  626. function updateChatConversation(nick, message)
  627. {
  628. var divClassName = '';
  629. if (nickname == nick)
  630. divClassName = "localuser";
  631. else
  632. divClassName = "remoteuser";
  633. $('#chatconversation').append('<div class="' + divClassName + '"><b>' + nick + ': </b>' + message + '</div>');
  634. $('#chatconversation').animate({ scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  635. }
  636. /*
  637. * Changes the style class of the element given by id.
  638. */
  639. function buttonClick(id, classname) {
  640. $(id).toggleClass(classname); // add the class to the clicked element
  641. }
  642. /*
  643. * Opens the lock room dialog.
  644. */
  645. function openLockDialog() {
  646. // Only the focus is able to set a shared key.
  647. if (focus == null) {
  648. if (sharedKey)
  649. $.prompt("This conversation is currently protected by a shared secret key.",
  650. {
  651. title: "Secrect key",
  652. persistent: false
  653. });
  654. else
  655. $.prompt("This conversation isn't currently protected by a secret key. Only the owner of the conference could set a shared key.",
  656. {
  657. title: "Secrect key",
  658. persistent: false
  659. });
  660. }
  661. else {
  662. if (sharedKey)
  663. $.prompt("Are you sure you would like to remove your secret key?",
  664. {
  665. title: "Remove secrect key",
  666. persistent: false,
  667. buttons: { "Remove": true, "Cancel": false},
  668. defaultButton: 1,
  669. submit: function(e,v,m,f){
  670. if(v)
  671. {
  672. setSharedKey('');
  673. lockRoom(false);
  674. }
  675. }
  676. });
  677. else
  678. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  679. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  680. {
  681. persistent: false,
  682. buttons: { "Save": true , "Cancel": false},
  683. defaultButton: 1,
  684. loaded: function(event) {
  685. document.getElementById('lockKey').focus();
  686. },
  687. submit: function(e,v,m,f){
  688. if(v)
  689. {
  690. var lockKey = document.getElementById('lockKey');
  691. if (lockKey.value)
  692. {
  693. setSharedKey(lockKey.value);
  694. lockRoom(true);
  695. }
  696. }
  697. }
  698. });
  699. }
  700. }
  701. /*
  702. * Opens the invite link dialog.
  703. */
  704. function openLinkDialog() {
  705. $.prompt('<input id="inviteLinkRef" type="text" value="' + roomUrl + '" onclick="this.select();">',
  706. {
  707. title: "Share this link with everyone you want to invite",
  708. persistent: false,
  709. buttons: { "Cancel": false},
  710. loaded: function(event) {
  711. document.getElementById('inviteLinkRef').select();
  712. }
  713. });
  714. }
  715. /*
  716. * Opens the settings dialog.
  717. */
  718. function openSettingsDialog() {
  719. $.prompt('<h2>Configure your conference</h2>' +
  720. '<input type="checkbox" id="initMuted"> Participants join muted<br/>' +
  721. '<input type="checkbox" id="requireNicknames"> Require nicknames<br/><br/>' +
  722. 'Set a secrect key to lock your room: <input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  723. {
  724. persistent: false,
  725. buttons: { "Save": true , "Cancel": false},
  726. defaultButton: 1,
  727. loaded: function(event) {
  728. document.getElementById('lockKey').focus();
  729. },
  730. submit: function(e,v,m,f){
  731. if(v)
  732. {
  733. if ($('#initMuted').is(":checked"))
  734. {
  735. // it is checked
  736. }
  737. if ($('#requireNicknames').is(":checked"))
  738. {
  739. // it is checked
  740. }
  741. /*
  742. var lockKey = document.getElementById('lockKey');
  743. if (lockKey.value)
  744. {
  745. setSharedKey(lockKey.value);
  746. lockRoom(true);
  747. }
  748. */
  749. }
  750. }
  751. });
  752. }
  753. /*
  754. * Opens the Prezi dialog, from which the user could choose a presentation to load.
  755. */
  756. function openPreziDialog() {
  757. var myprezi = connection.emuc.getPrezi(connection.emuc.myroomjid);
  758. if (myprezi) {
  759. $.prompt("Are you sure you would like to remove your Prezi?",
  760. {
  761. title: "Remove Prezi",
  762. buttons: { "Remove": true, "Cancel": false},
  763. defaultButton: 1,
  764. submit: function(e,v,m,f){
  765. if(v)
  766. {
  767. connection.emuc.removePreziFromPresence();
  768. connection.emuc.sendPresence();
  769. }
  770. }
  771. });
  772. }
  773. else if (preziPlayer != null) {
  774. $.prompt("Another participant is already sharing a Prezi. This conference allows only one Prezi at a time.",
  775. {
  776. title: "Share a Prezi",
  777. buttons: { "Ok": true},
  778. defaultButton: 0,
  779. submit: function(e,v,m,f){
  780. $.prompt.close();
  781. }
  782. });
  783. }
  784. else {
  785. var openPreziState = {
  786. state0: {
  787. html: '<h2>Share a Prezi</h2>' +
  788. '<input id="preziUrl" type="text" placeholder="e.g. http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  789. persistent: false,
  790. buttons: { "Share": true , "Cancel": false},
  791. defaultButton: 1,
  792. submit: function(e,v,m,f){
  793. e.preventDefault();
  794. if(v)
  795. {
  796. var preziUrl = document.getElementById('preziUrl');
  797. if (preziUrl.value)
  798. {
  799. if (preziUrl.value.indexOf('http://prezi.com/') != 0
  800. && preziUrl.value.indexOf('https://prezi.com/') != 0)
  801. {
  802. $.prompt.goToState('state1');
  803. return false;
  804. }
  805. else {
  806. var presIdTmp = preziUrl.value.substring(preziUrl.value.indexOf("prezi.com/") + 10);
  807. if (presIdTmp.indexOf('/') < 2) {
  808. $.prompt.goToState('state1');
  809. return false;
  810. }
  811. else {
  812. connection.emuc.addPreziToPresence(preziUrl.value, 0);
  813. connection.emuc.sendPresence();
  814. $.prompt.close();
  815. }
  816. }
  817. }
  818. }
  819. else
  820. $.prompt.close();
  821. }
  822. },
  823. state1: {
  824. html: '<h2>Share a Prezi</h2>' +
  825. 'Please provide a correct prezi link.',
  826. persistent: false,
  827. buttons: { "Back": true, "Cancel": false },
  828. defaultButton: 1,
  829. submit:function(e,v,m,f) {
  830. e.preventDefault();
  831. if(v==0)
  832. $.prompt.close();
  833. else
  834. $.prompt.goToState('state0');
  835. }
  836. }
  837. };
  838. var myPrompt = jQuery.prompt(openPreziState);
  839. myPrompt.on('impromptu:loaded', function(e) {
  840. document.getElementById('preziUrl').focus();
  841. });
  842. myPrompt.on('impromptu:statechanged', function(e) {
  843. document.getElementById('preziUrl').focus();
  844. });
  845. }
  846. }
  847. /*
  848. * Locks / unlocks the room.
  849. */
  850. function lockRoom(lock) {
  851. if (lock)
  852. connection.emuc.lockRoom(sharedKey);
  853. else
  854. connection.emuc.lockRoom('');
  855. updateLockButton();
  856. }
  857. /*
  858. * Sets the shared key.
  859. */
  860. function setSharedKey(sKey) {
  861. sharedKey = sKey;
  862. }
  863. /*
  864. * Updates the lock button state.
  865. */
  866. function updateLockButton() {
  867. buttonClick("#lockIcon", "fa fa-unlock fa-lg fa fa-lock fa-lg");
  868. }
  869. /*
  870. * Opens / closes the chat area.
  871. */
  872. function openChat() {
  873. var chatspace = $('#chatspace');
  874. var videospace = $('#videospace');
  875. var onAnimationProgress = function () {
  876. resizeLarge();
  877. videospace.css({right:chatspace.width()});
  878. };
  879. if (chatspace.css("opacity") == 1) {
  880. chatspace.animate({width: 0, opacity: 0}, {duration: 1000, progress: onAnimationProgress});
  881. }
  882. else {
  883. chatspace.animate({width:"20%", opacity: 1}, {duration: 1000, progress: onAnimationProgress});
  884. }
  885. // Request the focus in the nickname field or the chat input field.
  886. if ($('#nickinput').is(':visible'))
  887. $('#nickinput').focus();
  888. else
  889. $('#usermsg').focus();
  890. }
  891. /*
  892. * Shows the call main toolbar.
  893. */
  894. function showToolbar() {
  895. $('#toolbar').css({visibility:"visible"});
  896. if (focus != null)
  897. {
  898. // TODO: Enable settings functionality. Need to uncomment the settings button in index.html.
  899. // $('#settingsButton').css({visibility:"visible"});
  900. }
  901. }
  902. /*
  903. * Updates the room invite url.
  904. */
  905. function updateRoomUrl(newRoomUrl) {
  906. roomUrl = newRoomUrl;
  907. }
  908. /*
  909. * Warning to the user that the conference window is about to be closed.
  910. */
  911. function closePageWarning() {
  912. if (focus != null)
  913. return "You are the owner of this conference call and you are about to end it.";
  914. else
  915. return "You are about to leave this conversation.";
  916. }
  917. /*
  918. * Shows a visual indicator for the focus of the conference.
  919. * Currently if we're not the owner of the conference we obtain the focus
  920. * from the connection.jingle.sessions.
  921. */
  922. function showFocusIndicator() {
  923. if (focus != null) {
  924. var localVideoToolbar = document.getElementById('localVideoToolbar');
  925. if (localVideoToolbar.childNodes.length === 0)
  926. {
  927. createFocusIndicatorElement(localVideoToolbar);
  928. }
  929. }
  930. else if (Object.keys(connection.jingle.sessions).length > 0) {
  931. // If we're only a participant the focus will be the only session we have.
  932. var session = connection.jingle.sessions[Object.keys(connection.jingle.sessions)[0]];
  933. var focusId = 'participant_' + Strophe.getResourceFromJid(session.peerjid);
  934. var focusContainer = document.getElementById(focusId);
  935. var indicatorSpan = $('#' + focusId + ' .focusindicator');
  936. if (!indicatorSpan || indicatorSpan.length == 0) {
  937. indicatorSpan = document.createElement('span');
  938. indicatorSpan.className = 'focusindicator';
  939. focusContainer.appendChild(indicatorSpan);
  940. createFocusIndicatorElement(indicatorSpan);
  941. }
  942. }
  943. }
  944. function addRemoteVideoContainer(id) {
  945. var container = document.createElement('span');
  946. container.id = id;
  947. container.className = 'videocontainer';
  948. var remotes = document.getElementById('remoteVideos');
  949. remotes.appendChild(container);
  950. return container;
  951. }
  952. /*
  953. * Creates the element indicating the focus of the conference.
  954. */
  955. function createFocusIndicatorElement(parentElement) {
  956. var focusIndicator = document.createElement('i');
  957. focusIndicator.className = 'fa fa-star';
  958. focusIndicator.title = "The owner of this conference"
  959. parentElement.appendChild(focusIndicator);
  960. }