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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. showFocusIndicator();
  272. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  273. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  274. ssrc2jid[ssrc.getAttribute('ssrc')] = jid;
  275. });
  276. });
  277. $(document).bind('left.muc', function (event, jid) {
  278. console.log('left', jid);
  279. connection.jingle.terminateByJid(jid);
  280. var container = document.getElementById('participant_' + Strophe.getResourceFromJid(jid));
  281. if (container) {
  282. // hide here, wait for video to close before removing
  283. $(container).hide();
  284. resizeThumbnails();
  285. }
  286. if (Object.keys(connection.emuc.members).length === 0) {
  287. console.log('everyone left');
  288. if (focus !== null) {
  289. // FIXME: closing the connection is a hack to avoid some
  290. // problemswith reinit
  291. if (focus.peerconnection !== null) {
  292. focus.peerconnection.close();
  293. }
  294. focus = new ColibriFocus(connection, config.hosts.bridge);
  295. }
  296. }
  297. if (connection.emuc.getPrezi(jid)) {
  298. $(document).trigger('presentationremoved.muc', [jid, connection.emuc.getPrezi(jid)]);
  299. }
  300. });
  301. $(document).bind('presence.muc', function (event, jid, info, pres) {
  302. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  303. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  304. ssrc2jid[ssrc.getAttribute('ssrc')] = jid;
  305. });
  306. });
  307. $(document).bind('passwordrequired.muc', function (event, jid) {
  308. console.log('on password required', jid);
  309. $.prompt('<h2>Password required</h2>' +
  310. '<input id="lockKey" type="text" placeholder="shared key" autofocus>',
  311. {
  312. persistent: true,
  313. buttons: { "Ok": true , "Cancel": false},
  314. defaultButton: 1,
  315. loaded: function(event) {
  316. document.getElementById('lockKey').focus();
  317. },
  318. submit: function(e,v,m,f){
  319. if(v)
  320. {
  321. var lockKey = document.getElementById('lockKey');
  322. if (lockKey.value != null)
  323. {
  324. setSharedKey(lockKey);
  325. connection.emuc.doJoin(jid, lockKey.value);
  326. }
  327. }
  328. }
  329. });
  330. });
  331. /*
  332. * Presentation has been removed.
  333. */
  334. $(document).bind('presentationremoved.muc', function(event, jid, presUrl) {
  335. console.log('presentation removed', presUrl);
  336. var presId = getPresentationId(presUrl);
  337. setPresentationVisible(false);
  338. $('#participant_' + Strophe.getResourceFromJid(jid) + '_' + presId).remove();
  339. $('#presentation>iframe').remove();
  340. if (preziPlayer != null) {
  341. preziPlayer.destroy();
  342. preziPlayer = null;
  343. }
  344. });
  345. /*
  346. * Presentation has been added.
  347. */
  348. $(document).bind('presentationadded.muc', function (event, jid, presUrl, currentSlide) {
  349. console.log("presentation added", presUrl);
  350. var presId = getPresentationId(presUrl);
  351. var elementId = 'participant_' + Strophe.getResourceFromJid(jid) + '_' + presId;
  352. var container = addRemoteVideoContainer(elementId);
  353. resizeThumbnails();
  354. var controlsEnabled = false;
  355. if (jid === connection.emuc.myroomjid)
  356. controlsEnabled = true;
  357. setPresentationVisible(true);
  358. $('#largeVideoContainer').hover(
  359. function (event) {
  360. if ($('#largeVideo').css('visibility') == 'hidden')
  361. $('#reloadPresentation').css({display:'inline-block'});
  362. },
  363. function (event) {
  364. if ($('#largeVideo').css('visibility') == 'visible')
  365. $('#reloadPresentation').css({display:'none'});
  366. else {
  367. var e = event.toElement || event.relatedTarget;
  368. while(e && e.parentNode && e.parentNode != window) {
  369. if (e.parentNode == this || e == this) {
  370. return false;
  371. }
  372. e = e.parentNode;
  373. }
  374. $('#reloadPresentation').css({display:'none'});
  375. }
  376. });
  377. preziPlayer = new PreziPlayer(
  378. 'presentation',
  379. {preziId: presId,
  380. width: $('#largeVideoContainer').width(),
  381. height: $('#largeVideoContainer').height(),
  382. controls: controlsEnabled,
  383. debug: true
  384. });
  385. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  386. // $('#presentation>iframe').load(function (){
  387. // console.log("IFRAME LOADED!!!!!!!!!!!!!!!!");
  388. // });
  389. // $('#presentation>iframe').ready(function (){
  390. // console.log("IFRAME READY!!!!!!!!!!!!!!!!");
  391. // });
  392. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  393. console.log("prezi status", event.value);
  394. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  395. if (jid != connection.emuc.myroomjid)
  396. preziPlayer.flyToStep(currentSlide);
  397. }
  398. });
  399. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  400. console.log("event value", event.value);
  401. connection.emuc.addCurrentSlideToPresence(event.value);
  402. connection.emuc.sendPresence();
  403. });
  404. $("#" + elementId).css('background-image','url(../images/avatarprezi.png)');
  405. $("#" + elementId).click(
  406. function () {
  407. setPresentationVisible(true);
  408. }
  409. );
  410. });
  411. /*
  412. * Indicates presentation slide change.
  413. */
  414. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  415. if (preziPlayer) {
  416. preziPlayer.flyToStep(current);
  417. }
  418. });
  419. /**
  420. * Returns the presentation id from the given url.
  421. */
  422. function getPresentationId (presUrl) {
  423. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  424. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  425. }
  426. /*
  427. * Reloads the current presentation.
  428. */
  429. function reloadPresentation() {
  430. var iframe = document.getElementById(preziPlayer.options.preziId);
  431. iframe.src = iframe.src;
  432. }
  433. /*
  434. * Shows/hides a presentation.
  435. */
  436. function setPresentationVisible(visible) {
  437. if (visible) {
  438. $('#largeVideo').fadeOut(300, function () {
  439. $('#largeVideo').css({visibility:'hidden'});
  440. $('#presentation>iframe').fadeIn(300, function() {
  441. $('#presentation>iframe').css({opacity:'1'});
  442. });
  443. });
  444. }
  445. else {
  446. if ($('#presentation>iframe')) {
  447. $('#presentation>iframe').fadeOut(300, function () {
  448. $('#presentation>iframe').css({opacity:'0'});
  449. $('#largeVideo').fadeIn(300, function() {
  450. $('#largeVideo').css({visibility:'visible'});
  451. });
  452. });
  453. }
  454. }
  455. }
  456. /**
  457. * Updates the large video with the given new video source.
  458. */
  459. function updateLargeVideo(newSrc, localVideo, vol) {
  460. console.log('hover in', newSrc);
  461. setPresentationVisible(false);
  462. if ($('#largeVideo').attr('src') != newSrc) {
  463. document.getElementById('largeVideo').volume = vol;
  464. $('#largeVideo').fadeOut(300, function () {
  465. $(this).attr('src', newSrc);
  466. var videoTransform = document.getElementById('largeVideo').style.webkitTransform;
  467. if (localVideo && videoTransform != 'scaleX(-1)') {
  468. document.getElementById('largeVideo').style.webkitTransform = "scaleX(-1)";
  469. }
  470. else if (!localVideo && videoTransform == 'scaleX(-1)') {
  471. document.getElementById('largeVideo').style.webkitTransform = "none";
  472. }
  473. $(this).fadeIn(300);
  474. });
  475. }
  476. }
  477. function toggleVideo() {
  478. if (!(connection && connection.jingle.localStream)) return;
  479. for (var idx = 0; idx < connection.jingle.localStream.getVideoTracks().length; idx++) {
  480. connection.jingle.localStream.getVideoTracks()[idx].enabled = !connection.jingle.localStream.getVideoTracks()[idx].enabled;
  481. }
  482. }
  483. function toggleAudio() {
  484. if (!(connection && connection.jingle.localStream)) return;
  485. for (var idx = 0; idx < connection.jingle.localStream.getAudioTracks().length; idx++) {
  486. connection.jingle.localStream.getAudioTracks()[idx].enabled = !connection.jingle.localStream.getAudioTracks()[idx].enabled;
  487. }
  488. }
  489. function resizeLarge() {
  490. var availableHeight = window.innerHeight;
  491. var chatspaceWidth = $('#chatspace').width();
  492. var numvids = $('#remoteVideos>video:visible').length;
  493. if (numvids < 5)
  494. availableHeight -= 100; // min thumbnail height for up to 4 videos
  495. else
  496. availableHeight -= 50; // min thumbnail height for more than 5 videos
  497. availableHeight -= 79; // padding + link ontop
  498. var availableWidth = window.innerWidth - chatspaceWidth;
  499. var aspectRatio = 16.0 / 9.0;
  500. if (availableHeight < availableWidth / aspectRatio) {
  501. availableWidth = Math.floor(availableHeight * aspectRatio);
  502. }
  503. if (availableWidth < 0 || availableHeight < 0) return;
  504. $('#largeVideo').parent().width(availableWidth);
  505. $('#largeVideo').parent().height(availableWidth / aspectRatio);
  506. $('#presentation>iframe').width(availableWidth);
  507. $('#presentation>iframe').height(availableWidth / aspectRatio);
  508. resizeThumbnails();
  509. }
  510. function resizeThumbnails() {
  511. // Calculate the available height, which is the inner window height minus 39px for the header
  512. // minus 4px for the delimiter lines on the top and bottom of the large video,
  513. // minus the 36px space inside the remoteVideos container used for highlighting shadow.
  514. var availableHeight = window.innerHeight - $('#largeVideo').height() - 79;
  515. var numvids = $('#remoteVideos>span:visible').length;
  516. // Remove the 1px borders arround videos.
  517. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids - 50;
  518. var availableWidth = availableWinWidth / numvids;
  519. var aspectRatio = 16.0 / 9.0;
  520. var maxHeight = Math.min(160, availableHeight);
  521. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  522. if (availableHeight < availableWidth / aspectRatio) {
  523. availableWidth = Math.floor(availableHeight * aspectRatio);
  524. }
  525. // size videos so that while keeping AR and max height, we have a nice fit
  526. $('#remoteVideos').height(availableHeight+26); // add the 2*18px-padding-top border used for highlighting shadow.
  527. $('#remoteVideos>span').width(availableWidth);
  528. $('#remoteVideos>span').height(availableHeight);
  529. }
  530. $(document).ready(function () {
  531. $('#nickinput').keydown(function(event) {
  532. if (event.keyCode == 13) {
  533. event.preventDefault();
  534. var val = this.value;
  535. this.value = '';
  536. if (!nickname) {
  537. nickname = val;
  538. $('#nickname').css({visibility:"hidden"});
  539. $('#chatconversation').css({visibility:'visible'});
  540. $('#usermsg').css({visibility:'visible'});
  541. $('#usermsg').focus();
  542. return;
  543. }
  544. }
  545. });
  546. $('#usermsg').keydown(function(event) {
  547. if (event.keyCode == 13) {
  548. event.preventDefault();
  549. var message = this.value;
  550. $('#usermsg').val('').trigger('autosize.resize');
  551. this.focus();
  552. connection.emuc.sendMessage(message, nickname);
  553. }
  554. });
  555. $('#usermsg').autosize();
  556. // Set the defaults for prompt dialogs.
  557. jQuery.prompt.setDefaults({persistent: false});
  558. resizeLarge();
  559. $(window).resize(function () {
  560. resizeLarge();
  561. });
  562. if (!$('#settings').is(':visible')) {
  563. console.log('init');
  564. init();
  565. } else {
  566. loginInfo.onsubmit = function (e) {
  567. if (e.preventDefault) e.preventDefault();
  568. $('#settings').hide();
  569. init();
  570. };
  571. }
  572. });
  573. $(window).bind('beforeunload', function () {
  574. if (connection && connection.connected) {
  575. // ensure signout
  576. $.ajax({
  577. type: 'POST',
  578. url: config.bosh,
  579. async: false,
  580. cache: false,
  581. contentType: 'application/xml',
  582. 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>",
  583. success: function (data) {
  584. console.log('signed out');
  585. console.log(data);
  586. },
  587. error: function (XMLHttpRequest, textStatus, errorThrown) {
  588. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  589. }
  590. });
  591. }
  592. });
  593. function dump(elem, filename){
  594. elem = elem.parentNode;
  595. elem.download = filename || 'meetlog.json';
  596. elem.href = 'data:application/json;charset=utf-8,\n';
  597. var data = {};
  598. if (connection.jingle) {
  599. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  600. var session = connection.jingle.sessions[sid];
  601. if (session.peerconnection && session.peerconnection.updateLog) {
  602. // FIXME: should probably be a .dump call
  603. data["jingle_" + session.sid] = {
  604. updateLog: session.peerconnection.updateLog,
  605. url: window.location.href}
  606. ;
  607. }
  608. });
  609. }
  610. metadata = {};
  611. metadata.time = new Date();
  612. metadata.url = window.location.href;
  613. metadata.ua = navigator.userAgent;
  614. if (connection.logger) {
  615. metadata.xmpp = connection.logger.log;
  616. }
  617. data.metadata = metadata;
  618. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  619. return false;
  620. }
  621. /*
  622. * Appends the given message to the chat conversation.
  623. */
  624. function updateChatConversation(nick, message)
  625. {
  626. var divClassName = '';
  627. if (nickname == nick)
  628. divClassName = "localuser";
  629. else
  630. divClassName = "remoteuser";
  631. $('#chatconversation').append('<div class="' + divClassName + '"><b>' + nick + ': </b>' + message + '</div>');
  632. $('#chatconversation').animate({ scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  633. }
  634. /*
  635. * Changes the style class of the element given by id.
  636. */
  637. function buttonClick(id, classname) {
  638. $(id).toggleClass(classname); // add the class to the clicked element
  639. }
  640. /*
  641. * Opens the lock room dialog.
  642. */
  643. function openLockDialog() {
  644. // Only the focus is able to set a shared key.
  645. if (focus == null) {
  646. if (sharedKey)
  647. $.prompt("This conversation is currently protected by a shared secret key.",
  648. {
  649. title: "Secrect key",
  650. persistent: false
  651. });
  652. else
  653. $.prompt("This conversation isn't currently protected by a secret key. Only the owner of the conference could set a shared key.",
  654. {
  655. title: "Secrect key",
  656. persistent: false
  657. });
  658. }
  659. else {
  660. if (sharedKey)
  661. $.prompt("Are you sure you would like to remove your secret key?",
  662. {
  663. title: "Remove secrect key",
  664. persistent: false,
  665. buttons: { "Remove": true, "Cancel": false},
  666. defaultButton: 1,
  667. submit: function(e,v,m,f){
  668. if(v)
  669. {
  670. setSharedKey('');
  671. lockRoom(false);
  672. }
  673. }
  674. });
  675. else
  676. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  677. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  678. {
  679. persistent: false,
  680. buttons: { "Save": true , "Cancel": false},
  681. defaultButton: 1,
  682. loaded: function(event) {
  683. document.getElementById('lockKey').focus();
  684. },
  685. submit: function(e,v,m,f){
  686. if(v)
  687. {
  688. var lockKey = document.getElementById('lockKey');
  689. if (lockKey.value)
  690. {
  691. setSharedKey(lockKey.value);
  692. lockRoom(true);
  693. }
  694. }
  695. }
  696. });
  697. }
  698. }
  699. /*
  700. * Opens the invite link dialog.
  701. */
  702. function openLinkDialog() {
  703. $.prompt('<input id="inviteLinkRef" type="text" value="' + roomUrl + '" onclick="this.select();">',
  704. {
  705. title: "Share this link with everyone you want to invite",
  706. persistent: false,
  707. buttons: { "Cancel": false},
  708. loaded: function(event) {
  709. document.getElementById('inviteLinkRef').select();
  710. }
  711. });
  712. }
  713. /*
  714. * Opens the settings dialog.
  715. */
  716. function openSettingsDialog() {
  717. $.prompt('<h2>Configure your conference</h2>' +
  718. '<input type="checkbox" id="initMuted"> Participants join muted<br/>' +
  719. '<input type="checkbox" id="requireNicknames"> Require nicknames<br/><br/>' +
  720. 'Set a secrect key to lock your room: <input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  721. {
  722. persistent: false,
  723. buttons: { "Save": true , "Cancel": false},
  724. defaultButton: 1,
  725. loaded: function(event) {
  726. document.getElementById('lockKey').focus();
  727. },
  728. submit: function(e,v,m,f){
  729. if(v)
  730. {
  731. if ($('#initMuted').is(":checked"))
  732. {
  733. // it is checked
  734. }
  735. if ($('#requireNicknames').is(":checked"))
  736. {
  737. // it is checked
  738. }
  739. /*
  740. var lockKey = document.getElementById('lockKey');
  741. if (lockKey.value)
  742. {
  743. setSharedKey(lockKey.value);
  744. lockRoom(true);
  745. }
  746. */
  747. }
  748. }
  749. });
  750. }
  751. /*
  752. * Opens the Prezi dialog, from which the user could choose a presentation to load.
  753. */
  754. function openPreziDialog() {
  755. var myprezi = connection.emuc.getPrezi(connection.emuc.myroomjid);
  756. if (myprezi) {
  757. $.prompt("Are you sure you would like to remove your Prezi?",
  758. {
  759. title: "Remove Prezi",
  760. buttons: { "Remove": true, "Cancel": false},
  761. defaultButton: 1,
  762. submit: function(e,v,m,f){
  763. if(v)
  764. {
  765. connection.emuc.removePreziFromPresence();
  766. connection.emuc.sendPresence();
  767. }
  768. }
  769. });
  770. }
  771. else if (preziPlayer != null) {
  772. $.prompt("Another participant is already sharing a Prezi. This conference allows only one Prezi at a time.",
  773. {
  774. title: "Share a Prezi",
  775. buttons: { "Ok": true},
  776. defaultButton: 0,
  777. submit: function(e,v,m,f){
  778. $.prompt.close();
  779. }
  780. });
  781. }
  782. else {
  783. var openPreziState = {
  784. state0: {
  785. html: '<h2>Share a Prezi</h2>' +
  786. '<input id="preziUrl" type="text" placeholder="e.g. http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  787. persistent: false,
  788. buttons: { "Share": true , "Cancel": false},
  789. defaultButton: 1,
  790. submit: function(e,v,m,f){
  791. e.preventDefault();
  792. if(v)
  793. {
  794. var preziUrl = document.getElementById('preziUrl');
  795. if (preziUrl.value)
  796. {
  797. if (preziUrl.value.indexOf('http://prezi.com/') != 0
  798. && preziUrl.value.indexOf('https://prezi.com/') != 0)
  799. {
  800. $.prompt.goToState('state1');
  801. return false;
  802. }
  803. else {
  804. var presIdTmp = preziUrl.value.substring(preziUrl.value.indexOf("prezi.com/") + 10);
  805. if (presIdTmp.indexOf('/') < 2) {
  806. $.prompt.goToState('state1');
  807. return false;
  808. }
  809. else {
  810. connection.emuc.addPreziToPresence(preziUrl.value, 0);
  811. connection.emuc.sendPresence();
  812. $.prompt.close();
  813. }
  814. }
  815. }
  816. }
  817. else
  818. $.prompt.close();
  819. }
  820. },
  821. state1: {
  822. html: '<h2>Share a Prezi</h2>' +
  823. 'Please provide a correct prezi link.',
  824. persistent: false,
  825. buttons: { "Back": true, "Cancel": false },
  826. defaultButton: 1,
  827. submit:function(e,v,m,f) {
  828. e.preventDefault();
  829. if(v==0)
  830. $.prompt.close();
  831. else
  832. $.prompt.goToState('state0');
  833. }
  834. }
  835. };
  836. var myPrompt = jQuery.prompt(openPreziState);
  837. myPrompt.on('impromptu:loaded', function(e) {
  838. document.getElementById('preziUrl').focus();
  839. });
  840. myPrompt.on('impromptu:statechanged', function(e) {
  841. document.getElementById('preziUrl').focus();
  842. });
  843. }
  844. }
  845. /*
  846. * Locks / unlocks the room.
  847. */
  848. function lockRoom(lock) {
  849. if (lock)
  850. connection.emuc.lockRoom(sharedKey);
  851. else
  852. connection.emuc.lockRoom('');
  853. updateLockButton();
  854. }
  855. /*
  856. * Sets the shared key.
  857. */
  858. function setSharedKey(sKey) {
  859. sharedKey = sKey;
  860. }
  861. /*
  862. * Updates the lock button state.
  863. */
  864. function updateLockButton() {
  865. buttonClick("#lockIcon", "fa fa-unlock fa-lg fa fa-lock fa-lg");
  866. }
  867. /*
  868. * Opens / closes the chat area.
  869. */
  870. function openChat() {
  871. var chatspace = $('#chatspace');
  872. var videospace = $('#videospace');
  873. var chatspaceWidth = chatspace.width();
  874. if (chatspace.css("opacity") == 1) {
  875. chatspace.animate({opacity: 0}, "fast");
  876. chatspace.animate({width: 0}, "slow");
  877. videospace.animate({right: 0, width:"100%"}, "slow");
  878. }
  879. else {
  880. chatspace.animate({width:"20%"}, "slow");
  881. chatspace.animate({opacity: 1}, "slow");
  882. videospace.animate({right:chatspaceWidth, width:"80%"}, "slow");
  883. }
  884. // Request the focus in the nickname field or the chat input field.
  885. if ($('#nickinput').is(':visible'))
  886. $('#nickinput').focus();
  887. else
  888. $('#usermsg').focus();
  889. }
  890. /*
  891. * Shows the call main toolbar.
  892. */
  893. function showToolbar() {
  894. $('#toolbar').css({visibility:"visible"});
  895. if (focus != null)
  896. {
  897. // TODO: Enable settings functionality. Need to uncomment the settings button in index.html.
  898. // $('#settingsButton').css({visibility:"visible"});
  899. }
  900. }
  901. /*
  902. * Updates the room invite url.
  903. */
  904. function updateRoomUrl(newRoomUrl) {
  905. roomUrl = newRoomUrl;
  906. }
  907. /*
  908. * Warning to the user that the conference window is about to be closed.
  909. */
  910. function closePageWarning() {
  911. if (focus != null)
  912. return "You are the owner of this conference call and you are about to end it.";
  913. else
  914. return "You are about to leave this conversation.";
  915. }
  916. /*
  917. * Shows a visual indicator for the focus of the conference.
  918. * Currently if we're not the owner of the conference we obtain the focus
  919. * from the connection.jingle.sessions.
  920. */
  921. function showFocusIndicator() {
  922. if (focus != null) {
  923. var localVideoToolbar = document.getElementById('localVideoToolbar');
  924. if (localVideoToolbar.childNodes.length === 0)
  925. {
  926. createFocusIndicatorElement(localVideoToolbar);
  927. }
  928. }
  929. else if (Object.keys(connection.jingle.sessions).length > 0) {
  930. // If we're only a participant the focus will be the only session we have.
  931. var session = connection.jingle.sessions[Object.keys(connection.jingle.sessions)[0]];
  932. var focusId = 'participant_' + Strophe.getResourceFromJid(session.peerjid);
  933. var focusContainer = document.getElementById(focusId);
  934. var indicatorSpan = $('#' + focusId + ' .focusindicator');
  935. if (!indicatorSpan || indicatorSpan.length == 0) {
  936. indicatorSpan = document.createElement('span');
  937. indicatorSpan.className = 'focusindicator';
  938. focusContainer.appendChild(indicatorSpan);
  939. createFocusIndicatorElement(indicatorSpan);
  940. }
  941. }
  942. }
  943. function addRemoteVideoContainer(id) {
  944. var container = document.createElement('span');
  945. container.id = id;
  946. container.className = 'videocontainer';
  947. var remotes = document.getElementById('remoteVideos');
  948. remotes.appendChild(container);
  949. return container;
  950. }
  951. /*
  952. * Creates the element indicating the focus of the conference.
  953. */
  954. function createFocusIndicatorElement(parentElement) {
  955. var focusIndicator = document.createElement('i');
  956. focusIndicator.className = 'fa fa-star';
  957. focusIndicator.title = "The owner of this conference"
  958. parentElement.appendChild(focusIndicator);
  959. }