Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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