Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

app.js 37KB

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