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

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