Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

app.js 27KB

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