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.

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