Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

app.js 25KB

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