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.

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