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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var authenticatedUser = false;
  5. /* Initial "authentication required" dialog */
  6. var authDialog = null;
  7. /* Loop retry ID that wits for other user to create the room */
  8. var authRetryId = null;
  9. var activecall = null;
  10. var nickname = null;
  11. var focusMucJid = null;
  12. var roomName = null;
  13. var ssrc2jid = {};
  14. var bridgeIsDown = false;
  15. //TODO: this array must be removed when firefox implement multistream support
  16. var notReceivedSSRCs = [];
  17. var jid2Ssrc = {};
  18. /**
  19. * Indicates whether ssrc is camera video or desktop stream.
  20. * FIXME: remove those maps
  21. */
  22. var ssrc2videoType = {};
  23. /**
  24. * Currently focused video "src"(displayed in large video).
  25. * @type {String}
  26. */
  27. var focusedVideoInfo = null;
  28. var mutedAudios = {};
  29. /**
  30. * Remembers if we were muted by the focus.
  31. * @type {boolean}
  32. */
  33. var forceMuted = false;
  34. /**
  35. * Indicates if we have muted our audio before the conference has started.
  36. * @type {boolean}
  37. */
  38. var preMuted = false;
  39. var localVideoSrc = null;
  40. var flipXLocalVideo = true;
  41. var isFullScreen = false;
  42. var currentVideoWidth = null;
  43. var currentVideoHeight = null;
  44. /**
  45. * Method used to calculate large video size.
  46. * @type {function ()}
  47. */
  48. var getVideoSize;
  49. /**
  50. * Method used to get large video position.
  51. * @type {function ()}
  52. */
  53. var getVideoPosition;
  54. /* window.onbeforeunload = closePageWarning; */
  55. var sessionTerminated = false;
  56. function init() {
  57. RTC.addStreamListener(maybeDoJoin, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  58. RTC.start();
  59. var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
  60. connect(jid);
  61. }
  62. function connect(jid, password) {
  63. var localAudio, localVideo;
  64. if (connection && connection.jingle) {
  65. localAudio = connection.jingle.localAudio;
  66. localVideo = connection.jingle.localVideo;
  67. }
  68. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  69. var settings = UI.getSettings();
  70. var email = settings.email;
  71. var displayName = settings.displayName;
  72. if(email) {
  73. connection.emuc.addEmailToPresence(email);
  74. } else {
  75. connection.emuc.addUserIdToPresence(settings.uid);
  76. }
  77. if(displayName) {
  78. connection.emuc.addDisplayNameToPresence(displayName);
  79. }
  80. if (connection.disco) {
  81. // for chrome, add multistream cap
  82. }
  83. connection.jingle.pc_constraints = RTC.getPCConstraints();
  84. if (config.useIPv6) {
  85. // https://code.google.com/p/webrtc/issues/detail?id=2828
  86. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  87. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  88. }
  89. if (localAudio) connection.jingle.localAudio = localAudio;
  90. if (localVideo) connection.jingle.localVideo = localVideo;
  91. if(!password)
  92. password = document.getElementById('password').value;
  93. var anonymousConnectionFailed = false;
  94. connection.connect(jid, password, function (status, msg) {
  95. console.log('Strophe status changed to', Strophe.getStatusString(status));
  96. if (status === Strophe.Status.CONNECTED) {
  97. if (config.useStunTurn) {
  98. connection.jingle.getStunAndTurnCredentials();
  99. }
  100. document.getElementById('connect').disabled = true;
  101. console.info("My Jabber ID: " + connection.jid);
  102. if(password)
  103. authenticatedUser = true;
  104. maybeDoJoin();
  105. } else if (status === Strophe.Status.CONNFAIL) {
  106. if(msg === 'x-strophe-bad-non-anon-jid') {
  107. anonymousConnectionFailed = true;
  108. }
  109. } else if (status === Strophe.Status.DISCONNECTED) {
  110. if(anonymousConnectionFailed) {
  111. // prompt user for username and password
  112. $(document).trigger('passwordrequired.main');
  113. }
  114. } else if (status === Strophe.Status.AUTHFAIL) {
  115. // wrong password or username, prompt user
  116. $(document).trigger('passwordrequired.main');
  117. }
  118. });
  119. }
  120. function maybeDoJoin() {
  121. if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
  122. && (connection.jingle.localAudio || connection.jingle.localVideo)) {
  123. doJoin();
  124. }
  125. }
  126. function doJoin() {
  127. if (!roomName) {
  128. UI.generateRoomName();
  129. }
  130. Moderator.allocateConferenceFocus(
  131. roomName, doJoinAfterFocus);
  132. }
  133. function doJoinAfterFocus() {
  134. // Close authentication dialog if opened
  135. if (authDialog) {
  136. UI.messageHandler.closeDialog();
  137. authDialog = null;
  138. }
  139. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  140. if (authRetryId) {
  141. window.clearTimeout(authRetryId);
  142. authRetryId = null;
  143. }
  144. var roomjid;
  145. roomjid = roomName;
  146. if (config.useNicks) {
  147. var nick = window.prompt('Your nickname (optional)');
  148. if (nick) {
  149. roomjid += '/' + nick;
  150. } else {
  151. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  152. }
  153. } else {
  154. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  155. if(!authenticatedUser)
  156. tmpJid = tmpJid.substr(0, 8);
  157. roomjid += '/' + tmpJid;
  158. }
  159. connection.emuc.doJoin(roomjid);
  160. }
  161. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  162. // XXX(gp) so, every call to this function is *always* preceded by a call
  163. // to the RTC.attachMediaStream() function but that call is *not* followed
  164. // by an update to the videoSrcToSsrc map!
  165. //
  166. // The above way of doing things results in video SRCs that don't correspond
  167. // to any SSRC for a short period of time (to be more precise, for as long
  168. // the waitForRemoteVideo takes to complete). This causes problems (see
  169. // bellow).
  170. //
  171. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  172. // a second time in here and only then update the videoSrcToSsrc map? Why
  173. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  174. // is called the first time? I actually do that in the lastN changed event
  175. // handler because the "orphan" video SRC is causing troubles there. The
  176. // purpose of this method would then be to fire the "videoactive.jingle".
  177. //
  178. // Food for though I guess :-)
  179. if (selector.removed || !selector.parent().is(":visible")) {
  180. console.warn("Media removed before had started", selector);
  181. return;
  182. }
  183. if (stream.id === 'mixedmslabel') return;
  184. if (selector[0].currentTime > 0) {
  185. var videoStream = simulcast.getReceivingVideoStream(stream);
  186. RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  187. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  188. // in order to get rid of too many maps
  189. if (ssrc && jid) {
  190. jid2Ssrc[Strophe.getResourceFromJid(jid)] = ssrc;
  191. } else {
  192. console.warn("No ssrc given for jid", jid);
  193. }
  194. $(document).trigger('videoactive.jingle', [selector]);
  195. } else {
  196. setTimeout(function () {
  197. waitForRemoteVideo(selector, ssrc, stream, jid);
  198. }, 250);
  199. }
  200. }
  201. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  202. waitForPresence(data, sid);
  203. });
  204. function waitForPresence(data, sid) {
  205. var sess = connection.jingle.sessions[sid];
  206. var thessrc;
  207. // look up an associated JID for a stream id
  208. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  209. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  210. var ssrclines
  211. = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  212. ssrclines = ssrclines.filter(function (line) {
  213. // NOTE(gp) previously we filtered on the mslabel, but that property
  214. // is not always present.
  215. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  216. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  217. });
  218. if (ssrclines.length) {
  219. thessrc = ssrclines[0].substring(7).split(' ')[0];
  220. // We signal our streams (through Jingle to the focus) before we set
  221. // our presence (through which peers associate remote streams to
  222. // jids). So, it might arrive that a remote stream is added but
  223. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  224. // successfully set. Here we wait for up to a second for the
  225. // presence to arrive.
  226. if (!ssrc2jid[thessrc]) {
  227. // TODO(gp) limit wait duration to 1 sec.
  228. setTimeout(function(d, s) {
  229. return function() {
  230. waitForPresence(d, s);
  231. }
  232. }(data, sid), 250);
  233. return;
  234. }
  235. // ok to overwrite the one from focus? might save work in colibri.js
  236. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  237. if (ssrc2jid[thessrc]) {
  238. data.peerjid = ssrc2jid[thessrc];
  239. }
  240. }
  241. }
  242. //TODO: this code should be removed when firefox implement multistream support
  243. if(RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  244. {
  245. if((notReceivedSSRCs.length == 0) ||
  246. !ssrc2jid[notReceivedSSRCs[notReceivedSSRCs.length - 1]])
  247. {
  248. // TODO(gp) limit wait duration to 1 sec.
  249. setTimeout(function(d, s) {
  250. return function() {
  251. waitForPresence(d, s);
  252. }
  253. }(data, sid), 250);
  254. return;
  255. }
  256. thessrc = notReceivedSSRCs.pop();
  257. if (ssrc2jid[thessrc]) {
  258. data.peerjid = ssrc2jid[thessrc];
  259. }
  260. }
  261. RTC.createRemoteStream(data, sid, thessrc);
  262. var isVideo = data.stream.getVideoTracks().length > 0;
  263. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  264. if (isVideo &&
  265. data.peerjid && sess.peerjid === data.peerjid &&
  266. data.stream.getVideoTracks().length === 0 &&
  267. connection.jingle.localVideo.getVideoTracks().length > 0) {
  268. //
  269. window.setTimeout(function () {
  270. sendKeyframe(sess.peerconnection);
  271. }, 3000);
  272. }
  273. }
  274. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  275. function sendKeyframe(pc) {
  276. console.log('sendkeyframe', pc.iceConnectionState);
  277. if (pc.iceConnectionState !== 'connected') return; // safe...
  278. pc.setRemoteDescription(
  279. pc.remoteDescription,
  280. function () {
  281. pc.createAnswer(
  282. function (modifiedAnswer) {
  283. pc.setLocalDescription(
  284. modifiedAnswer,
  285. function () {
  286. // noop
  287. },
  288. function (error) {
  289. console.log('triggerKeyframe setLocalDescription failed', error);
  290. UI.messageHandler.showError();
  291. }
  292. );
  293. },
  294. function (error) {
  295. console.log('triggerKeyframe createAnswer failed', error);
  296. UI.messageHandler.showError();
  297. }
  298. );
  299. },
  300. function (error) {
  301. console.log('triggerKeyframe setRemoteDescription failed', error);
  302. UI.messageHandler.showError();
  303. }
  304. );
  305. }
  306. // Really mute video, i.e. dont even send black frames
  307. function muteVideo(pc, unmute) {
  308. // FIXME: this probably needs another of those lovely state safeguards...
  309. // which checks for iceconn == connected and sigstate == stable
  310. pc.setRemoteDescription(pc.remoteDescription,
  311. function () {
  312. pc.createAnswer(
  313. function (answer) {
  314. var sdp = new SDP(answer.sdp);
  315. if (sdp.media.length > 1) {
  316. if (unmute)
  317. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  318. else
  319. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  320. sdp.raw = sdp.session + sdp.media.join('');
  321. answer.sdp = sdp.raw;
  322. }
  323. pc.setLocalDescription(answer,
  324. function () {
  325. console.log('mute SLD ok');
  326. },
  327. function (error) {
  328. console.log('mute SLD error');
  329. UI.messageHandler.showError('Error',
  330. 'Oops! Something went wrong and we failed to ' +
  331. 'mute! (SLD Failure)');
  332. }
  333. );
  334. },
  335. function (error) {
  336. console.log(error);
  337. UI.messageHandler.showError();
  338. }
  339. );
  340. },
  341. function (error) {
  342. console.log('muteVideo SRD error');
  343. UI.messageHandler.showError('Error',
  344. 'Oops! Something went wrong and we failed to stop video!' +
  345. '(SRD Failure)');
  346. }
  347. );
  348. }
  349. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  350. // put our ssrcs into presence so other clients can identify our stream
  351. var sess = connection.jingle.sessions[sid];
  352. var newssrcs = [];
  353. var media = simulcast.parseMedia(sess.peerconnection.localDescription);
  354. media.forEach(function (media) {
  355. if(Object.keys(media.sources).length > 0) {
  356. // TODO(gp) maybe exclude FID streams?
  357. Object.keys(media.sources).forEach(function (ssrc) {
  358. newssrcs.push({
  359. 'ssrc': ssrc,
  360. 'type': media.type,
  361. 'direction': media.direction
  362. });
  363. });
  364. }
  365. else if(sess.localStreamsSSRC && sess.localStreamsSSRC[media.type])
  366. {
  367. newssrcs.push({
  368. 'ssrc': sess.localStreamsSSRC[media.type],
  369. 'type': media.type,
  370. 'direction': media.direction
  371. });
  372. }
  373. });
  374. console.log('new ssrcs', newssrcs);
  375. // Have to clear presence map to get rid of removed streams
  376. connection.emuc.clearPresenceMedia();
  377. if (newssrcs.length > 0) {
  378. for (var i = 1; i <= newssrcs.length; i ++) {
  379. // Change video type to screen
  380. if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
  381. newssrcs[i-1].type = 'screen';
  382. }
  383. connection.emuc.addMediaToPresence(i,
  384. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  385. }
  386. connection.emuc.sendPresence();
  387. }
  388. });
  389. $(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
  390. switch (session.peerconnection.iceConnectionState) {
  391. case 'checking':
  392. session.timeChecking = (new Date()).getTime();
  393. session.firstconnect = true;
  394. break;
  395. case 'completed': // on caller side
  396. case 'connected':
  397. if (session.firstconnect) {
  398. session.firstconnect = false;
  399. var metadata = {};
  400. metadata.setupTime = (new Date()).getTime() - session.timeChecking;
  401. session.peerconnection.getStats(function (res) {
  402. if(res && res.result) {
  403. res.result().forEach(function (report) {
  404. if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
  405. metadata.localCandidateType = report.stat('googLocalCandidateType');
  406. metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
  407. // log pair as well so we can get nice pie charts
  408. metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
  409. if (report.stat('googRemoteAddress').indexOf('[') === 0) {
  410. metadata.ipv6 = true;
  411. }
  412. }
  413. });
  414. trackUsage('iceConnected', metadata);
  415. }
  416. });
  417. }
  418. break;
  419. }
  420. });
  421. $(document).bind('presence.muc', function (event, jid, info, pres) {
  422. //check if the video bridge is available
  423. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  424. bridgeIsDown = true;
  425. UI.messageHandler.showError("Error",
  426. "Jitsi Videobridge is currently unavailable. Please try again later!");
  427. }
  428. if (info.isFocus)
  429. {
  430. return;
  431. }
  432. // Remove old ssrcs coming from the jid
  433. Object.keys(ssrc2jid).forEach(function (ssrc) {
  434. if (ssrc2jid[ssrc] == jid) {
  435. delete ssrc2jid[ssrc];
  436. delete ssrc2videoType[ssrc];
  437. }
  438. });
  439. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  440. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  441. var ssrcV = ssrc.getAttribute('ssrc');
  442. ssrc2jid[ssrcV] = jid;
  443. notReceivedSSRCs.push(ssrcV);
  444. var type = ssrc.getAttribute('type');
  445. ssrc2videoType[ssrcV] = type;
  446. // might need to update the direction if participant just went from sendrecv to recvonly
  447. if (type === 'video' || type === 'screen') {
  448. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  449. switch (ssrc.getAttribute('direction')) {
  450. case 'sendrecv':
  451. el.show();
  452. break;
  453. case 'recvonly':
  454. el.hide();
  455. // FIXME: Check if we have to change large video
  456. //VideoLayout.updateLargeVideo(el);
  457. break;
  458. }
  459. }
  460. });
  461. var displayName = !config.displayJids
  462. ? info.displayName : Strophe.getResourceFromJid(jid);
  463. if (displayName && displayName.length > 0)
  464. $(document).trigger('displaynamechanged',
  465. [jid, displayName]);
  466. /*if (focus !== null && info.displayName !== null) {
  467. focus.setEndpointDisplayName(jid, info.displayName);
  468. }*/
  469. //check if the video bridge is available
  470. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  471. bridgeIsDown = true;
  472. UI.messageHandler.showError("Error",
  473. "Jitsi Videobridge is currently unavailable. Please try again later!");
  474. }
  475. var id = $(pres).find('>userID').text();
  476. var email = $(pres).find('>email');
  477. if(email.length > 0) {
  478. id = email.text();
  479. }
  480. UI.setUserAvatar(jid, id);
  481. });
  482. $(document).bind('kicked.muc', function (event, jid) {
  483. console.info(jid + " has been kicked from MUC!");
  484. if (connection.emuc.myroomjid === jid) {
  485. sessionTerminated = true;
  486. disposeConference(false);
  487. connection.emuc.doLeave();
  488. UI.messageHandler.openMessageDialog("Session Terminated",
  489. "Ouch! You have been kicked out of the meet!");
  490. }
  491. });
  492. $(document).bind('passwordrequired.main', function (event) {
  493. console.log('password is required');
  494. UI.messageHandler.openTwoButtonDialog(null,
  495. '<h2>Password required</h2>' +
  496. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  497. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  498. true,
  499. "Ok",
  500. function (e, v, m, f) {
  501. if (v) {
  502. var username = document.getElementById('passwordrequired.username');
  503. var password = document.getElementById('passwordrequired.password');
  504. if (username.value !== null && password.value != null) {
  505. connect(username.value, password.value);
  506. }
  507. }
  508. },
  509. function (event) {
  510. document.getElementById('passwordrequired.username').focus();
  511. }
  512. );
  513. });
  514. /**
  515. * Checks if video identified by given src is desktop stream.
  516. * @param videoSrc eg.
  517. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  518. * @returns {boolean}
  519. */
  520. function isVideoSrcDesktop(jid) {
  521. // FIXME: fix this mapping mess...
  522. // figure out if large video is desktop stream or just a camera
  523. if(!jid)
  524. return false;
  525. var isDesktop = false;
  526. if (connection.emuc.myroomjid &&
  527. Strophe.getResourceFromJid(connection.emuc.myroomjid) === jid) {
  528. // local video
  529. isDesktop = isUsingScreenStream;
  530. } else {
  531. // Do we have associations...
  532. var videoSsrc = jid2Ssrc[jid];
  533. if (videoSsrc) {
  534. var videoType = ssrc2videoType[videoSsrc];
  535. if (videoType) {
  536. // Finally there...
  537. isDesktop = videoType === 'screen';
  538. } else {
  539. console.error("No video type for ssrc: " + videoSsrc);
  540. }
  541. } else {
  542. console.error("No ssrc for jid: " + jid);
  543. }
  544. }
  545. return isDesktop;
  546. }
  547. function getConferenceHandler() {
  548. return activecall;
  549. }
  550. /**
  551. * Mutes/unmutes the local video.
  552. *
  553. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  554. * @param options an object which specifies optional arguments such as the
  555. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  556. * specifies whether the method was initiated in response to a user command (in
  557. * contrast to an automatic decision taken by the application logic)
  558. */
  559. function setVideoMute(mute, options) {
  560. if (connection && connection.jingle.localVideo) {
  561. var session = getConferenceHandler();
  562. if (session) {
  563. session.setVideoMute(
  564. mute,
  565. function (mute) {
  566. var video = $('#video');
  567. var communicativeClass = "icon-camera";
  568. var muteClass = "icon-camera icon-camera-disabled";
  569. if (mute) {
  570. video.removeClass(communicativeClass);
  571. video.addClass(muteClass);
  572. } else {
  573. video.removeClass(muteClass);
  574. video.addClass(communicativeClass);
  575. }
  576. connection.emuc.addVideoInfoToPresence(mute);
  577. connection.emuc.sendPresence();
  578. },
  579. options);
  580. }
  581. }
  582. }
  583. $(document).on('inlastnchanged', function (event, oldValue, newValue) {
  584. if (config.muteLocalVideoIfNotInLastN) {
  585. setVideoMute(!newValue, { 'byUser': false });
  586. }
  587. });
  588. /**
  589. * Mutes/unmutes the local video.
  590. */
  591. function toggleVideo() {
  592. buttonClick("#video", "icon-camera icon-camera-disabled");
  593. if (connection && connection.jingle.localVideo) {
  594. var session = getConferenceHandler();
  595. if (session) {
  596. setVideoMute(!session.isVideoMute());
  597. }
  598. }
  599. }
  600. /**
  601. * Mutes / unmutes audio for the local participant.
  602. */
  603. function toggleAudio() {
  604. setAudioMuted(!isAudioMuted());
  605. }
  606. /**
  607. * Sets muted audio state for the local participant.
  608. */
  609. function setAudioMuted(mute) {
  610. if (!(connection && connection.jingle.localAudio)) {
  611. preMuted = mute;
  612. // We still click the button.
  613. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  614. return;
  615. }
  616. if (forceMuted && !mute) {
  617. console.info("Asking focus for unmute");
  618. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  619. // FIXME: wait for result before resetting muted status
  620. forceMuted = false;
  621. }
  622. if (mute == isAudioMuted()) {
  623. // Nothing to do
  624. return;
  625. }
  626. // It is not clear what is the right way to handle multiple tracks.
  627. // So at least make sure that they are all muted or all unmuted and
  628. // that we send presence just once.
  629. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  630. if (localAudioTracks.length > 0) {
  631. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  632. localAudioTracks[idx].enabled = !mute;
  633. }
  634. }
  635. // isMuted is the opposite of audioEnabled
  636. connection.emuc.addAudioInfoToPresence(mute);
  637. connection.emuc.sendPresence();
  638. UI.showLocalAudioIndicator(mute);
  639. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  640. }
  641. /**
  642. * Checks whether the audio is muted or not.
  643. * @returns {boolean} true if audio is muted and false if not.
  644. */
  645. function isAudioMuted()
  646. {
  647. var localAudio = connection.jingle.localAudio;
  648. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  649. if(localAudio.getAudioTracks()[idx].enabled === true)
  650. return false;
  651. }
  652. return true;
  653. }
  654. $(document).ready(function () {
  655. if(APIConnector.isEnabled())
  656. APIConnector.init();
  657. UI.start();
  658. statistics.start();
  659. Moderator.init();
  660. // Set default desktop sharing method
  661. setDesktopSharing(config.desktopSharing);
  662. // Initialize Chrome extension inline installs
  663. if (config.chromeExtensionId) {
  664. initInlineInstalls();
  665. }
  666. });
  667. $(window).bind('beforeunload', function () {
  668. if (connection && connection.connected) {
  669. // ensure signout
  670. $.ajax({
  671. type: 'POST',
  672. url: config.bosh,
  673. async: false,
  674. cache: false,
  675. contentType: 'application/xml',
  676. data: "<body rid='" + (connection.rid || connection._proto.rid)
  677. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  678. + (connection.sid || connection._proto.sid)
  679. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  680. success: function (data) {
  681. console.log('signed out');
  682. console.log(data);
  683. },
  684. error: function (XMLHttpRequest, textStatus, errorThrown) {
  685. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  686. }
  687. });
  688. }
  689. disposeConference(true);
  690. if(APIConnector.isEnabled())
  691. APIConnector.dispose();
  692. });
  693. function disposeConference(onUnload) {
  694. UI.onDisposeConference(onUnload);
  695. var handler = getConferenceHandler();
  696. if (handler && handler.peerconnection) {
  697. // FIXME: probably removing streams is not required and close() should
  698. // be enough
  699. if (connection.jingle.localAudio) {
  700. handler.peerconnection.removeStream(connection.jingle.localAudio, onUnload);
  701. }
  702. if (connection.jingle.localVideo) {
  703. handler.peerconnection.removeStream(connection.jingle.localVideo, onUnload);
  704. }
  705. handler.peerconnection.close();
  706. }
  707. statistics.onDisposeConference(onUnload);
  708. activecall = null;
  709. }
  710. function dump(elem, filename) {
  711. elem = elem.parentNode;
  712. elem.download = filename || 'meetlog.json';
  713. elem.href = 'data:application/json;charset=utf-8,\n';
  714. var data = populateData();
  715. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  716. return false;
  717. }
  718. /**
  719. * Populates the log data
  720. */
  721. function populateData() {
  722. var data = {};
  723. if (connection.jingle) {
  724. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  725. var session = connection.jingle.sessions[sid];
  726. if (session.peerconnection && session.peerconnection.updateLog) {
  727. // FIXME: should probably be a .dump call
  728. data["jingle_" + session.sid] = {
  729. updateLog: session.peerconnection.updateLog,
  730. stats: session.peerconnection.stats,
  731. url: window.location.href
  732. };
  733. }
  734. });
  735. }
  736. var metadata = {};
  737. metadata.time = new Date();
  738. metadata.url = window.location.href;
  739. metadata.ua = navigator.userAgent;
  740. if (connection.logger) {
  741. metadata.xmpp = connection.logger.log;
  742. }
  743. data.metadata = metadata;
  744. return data;
  745. }
  746. /**
  747. * Changes the style class of the element given by id.
  748. */
  749. function buttonClick(id, classname) {
  750. $(id).toggleClass(classname); // add the class to the clicked element
  751. }