You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 36KB

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