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

app.js 36KB

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