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

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