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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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. 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('joined.muc', function (event, jid, info) {
  422. });
  423. $(document).bind('presence.muc', function (event, jid, info, pres) {
  424. //check if the video bridge is available
  425. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  426. bridgeIsDown = true;
  427. UI.messageHandler.showError("Error",
  428. "Jitsi Videobridge is currently unavailable. Please try again later!");
  429. }
  430. if (info.isFocus)
  431. {
  432. return;
  433. }
  434. // Remove old ssrcs coming from the jid
  435. Object.keys(ssrc2jid).forEach(function (ssrc) {
  436. if (ssrc2jid[ssrc] == jid) {
  437. delete ssrc2jid[ssrc];
  438. delete ssrc2videoType[ssrc];
  439. }
  440. });
  441. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  442. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  443. var ssrcV = ssrc.getAttribute('ssrc');
  444. ssrc2jid[ssrcV] = jid;
  445. notReceivedSSRCs.push(ssrcV);
  446. var type = ssrc.getAttribute('type');
  447. ssrc2videoType[ssrcV] = type;
  448. // might need to update the direction if participant just went from sendrecv to recvonly
  449. if (type === 'video' || type === 'screen') {
  450. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  451. switch (ssrc.getAttribute('direction')) {
  452. case 'sendrecv':
  453. el.show();
  454. break;
  455. case 'recvonly':
  456. el.hide();
  457. // FIXME: Check if we have to change large video
  458. //VideoLayout.updateLargeVideo(el);
  459. break;
  460. }
  461. }
  462. });
  463. var displayName = !config.displayJids
  464. ? info.displayName : Strophe.getResourceFromJid(jid);
  465. if (displayName && displayName.length > 0)
  466. $(document).trigger('displaynamechanged',
  467. [jid, displayName]);
  468. /*if (focus !== null && info.displayName !== null) {
  469. focus.setEndpointDisplayName(jid, info.displayName);
  470. }*/
  471. //check if the video bridge is available
  472. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  473. bridgeIsDown = true;
  474. UI.messageHandler.showError("Error",
  475. "Jitsi Videobridge is currently unavailable. Please try again later!");
  476. }
  477. var id = $(pres).find('>userID').text();
  478. var email = $(pres).find('>email');
  479. if(email.length > 0) {
  480. id = email.text();
  481. }
  482. UI.setUserAvatar(jid, id);
  483. });
  484. $(document).bind('kicked.muc', function (event, jid) {
  485. console.info(jid + " has been kicked from MUC!");
  486. if (connection.emuc.myroomjid === jid) {
  487. sessionTerminated = true;
  488. disposeConference(false);
  489. connection.emuc.doLeave();
  490. UI.messageHandler.openMessageDialog("Session Terminated",
  491. "Ouch! You have been kicked out of the meet!");
  492. }
  493. });
  494. $(document).bind('passwordrequired.main', function (event) {
  495. console.log('password is required');
  496. UI.messageHandler.openTwoButtonDialog(null,
  497. '<h2>Password required</h2>' +
  498. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  499. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  500. true,
  501. "Ok",
  502. function (e, v, m, f) {
  503. if (v) {
  504. var username = document.getElementById('passwordrequired.username');
  505. var password = document.getElementById('passwordrequired.password');
  506. if (username.value !== null && password.value != null) {
  507. connect(username.value, password.value);
  508. }
  509. }
  510. },
  511. function (event) {
  512. document.getElementById('passwordrequired.username').focus();
  513. }
  514. );
  515. });
  516. /**
  517. * Checks if video identified by given src is desktop stream.
  518. * @param videoSrc eg.
  519. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  520. * @returns {boolean}
  521. */
  522. function isVideoSrcDesktop(jid) {
  523. // FIXME: fix this mapping mess...
  524. // figure out if large video is desktop stream or just a camera
  525. if(!jid)
  526. return false;
  527. var isDesktop = false;
  528. if (connection.emuc.myroomjid &&
  529. Strophe.getResourceFromJid(connection.emuc.myroomjid) === jid) {
  530. // local video
  531. isDesktop = isUsingScreenStream;
  532. } else {
  533. // Do we have associations...
  534. var videoSsrc = jid2Ssrc[jid];
  535. if (videoSsrc) {
  536. var videoType = ssrc2videoType[videoSsrc];
  537. if (videoType) {
  538. // Finally there...
  539. isDesktop = videoType === 'screen';
  540. } else {
  541. console.error("No video type for ssrc: " + videoSsrc);
  542. }
  543. } else {
  544. console.error("No ssrc for jid: " + jid);
  545. }
  546. }
  547. return isDesktop;
  548. }
  549. function getConferenceHandler() {
  550. return activecall;
  551. }
  552. /**
  553. * Mutes/unmutes the local video.
  554. *
  555. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  556. * @param options an object which specifies optional arguments such as the
  557. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  558. * specifies whether the method was initiated in response to a user command (in
  559. * contrast to an automatic decision taken by the application logic)
  560. */
  561. function setVideoMute(mute, options) {
  562. if (connection && connection.jingle.localVideo) {
  563. var session = getConferenceHandler();
  564. if (session) {
  565. session.setVideoMute(
  566. mute,
  567. function (mute) {
  568. var video = $('#video');
  569. var communicativeClass = "icon-camera";
  570. var muteClass = "icon-camera icon-camera-disabled";
  571. if (mute) {
  572. video.removeClass(communicativeClass);
  573. video.addClass(muteClass);
  574. } else {
  575. video.removeClass(muteClass);
  576. video.addClass(communicativeClass);
  577. }
  578. connection.emuc.addVideoInfoToPresence(mute);
  579. connection.emuc.sendPresence();
  580. },
  581. options);
  582. }
  583. }
  584. }
  585. $(document).on('inlastnchanged', function (event, oldValue, newValue) {
  586. if (config.muteLocalVideoIfNotInLastN) {
  587. setVideoMute(!newValue, { 'byUser': false });
  588. }
  589. });
  590. /**
  591. * Mutes/unmutes the local video.
  592. */
  593. function toggleVideo() {
  594. buttonClick("#video", "icon-camera icon-camera-disabled");
  595. if (connection && connection.jingle.localVideo) {
  596. var session = getConferenceHandler();
  597. if (session) {
  598. setVideoMute(!session.isVideoMute());
  599. }
  600. }
  601. }
  602. /**
  603. * Mutes / unmutes audio for the local participant.
  604. */
  605. function toggleAudio() {
  606. setAudioMuted(!isAudioMuted());
  607. }
  608. /**
  609. * Sets muted audio state for the local participant.
  610. */
  611. function setAudioMuted(mute) {
  612. if (!(connection && connection.jingle.localAudio)) {
  613. preMuted = mute;
  614. // We still click the button.
  615. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  616. return;
  617. }
  618. if (forceMuted && !mute) {
  619. console.info("Asking focus for unmute");
  620. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  621. // FIXME: wait for result before resetting muted status
  622. forceMuted = false;
  623. }
  624. if (mute == isAudioMuted()) {
  625. // Nothing to do
  626. return;
  627. }
  628. // It is not clear what is the right way to handle multiple tracks.
  629. // So at least make sure that they are all muted or all unmuted and
  630. // that we send presence just once.
  631. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  632. if (localAudioTracks.length > 0) {
  633. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  634. localAudioTracks[idx].enabled = !mute;
  635. }
  636. }
  637. // isMuted is the opposite of audioEnabled
  638. connection.emuc.addAudioInfoToPresence(mute);
  639. connection.emuc.sendPresence();
  640. UI.showLocalAudioIndicator(mute);
  641. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  642. }
  643. /**
  644. * Checks whether the audio is muted or not.
  645. * @returns {boolean} true if audio is muted and false if not.
  646. */
  647. function isAudioMuted()
  648. {
  649. var localAudio = connection.jingle.localAudio;
  650. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  651. if(localAudio.getAudioTracks()[idx].enabled === true)
  652. return false;
  653. }
  654. return true;
  655. }
  656. /**
  657. * Returns an array of the video horizontal and vertical indents,
  658. * so that if fits its parent.
  659. *
  660. * @return an array with 2 elements, the horizontal indent and the vertical
  661. * indent
  662. */
  663. function getCameraVideoPosition(videoWidth,
  664. videoHeight,
  665. videoSpaceWidth,
  666. videoSpaceHeight) {
  667. // Parent height isn't completely calculated when we position the video in
  668. // full screen mode and this is why we use the screen height in this case.
  669. // Need to think it further at some point and implement it properly.
  670. var isFullScreen = document.fullScreen ||
  671. document.mozFullScreen ||
  672. document.webkitIsFullScreen;
  673. if (isFullScreen)
  674. videoSpaceHeight = window.innerHeight;
  675. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  676. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  677. return [horizontalIndent, verticalIndent];
  678. }
  679. /**
  680. * Returns an array of the video horizontal and vertical indents.
  681. * Centers horizontally and top aligns vertically.
  682. *
  683. * @return an array with 2 elements, the horizontal indent and the vertical
  684. * indent
  685. */
  686. function getDesktopVideoPosition(videoWidth,
  687. videoHeight,
  688. videoSpaceWidth,
  689. videoSpaceHeight) {
  690. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  691. var verticalIndent = 0;// Top aligned
  692. return [horizontalIndent, verticalIndent];
  693. }
  694. /**
  695. * Returns an array of the video dimensions, so that it covers the screen.
  696. * It leaves no empty areas, but some parts of the video might not be visible.
  697. *
  698. * @return an array with 2 elements, the video width and the video height
  699. */
  700. function getCameraVideoSize(videoWidth,
  701. videoHeight,
  702. videoSpaceWidth,
  703. videoSpaceHeight) {
  704. if (!videoWidth)
  705. videoWidth = currentVideoWidth;
  706. if (!videoHeight)
  707. videoHeight = currentVideoHeight;
  708. var aspectRatio = videoWidth / videoHeight;
  709. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  710. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  711. if (availableWidth / aspectRatio < videoSpaceHeight) {
  712. availableHeight = videoSpaceHeight;
  713. availableWidth = availableHeight * aspectRatio;
  714. }
  715. if (availableHeight * aspectRatio < videoSpaceWidth) {
  716. availableWidth = videoSpaceWidth;
  717. availableHeight = availableWidth / aspectRatio;
  718. }
  719. return [availableWidth, availableHeight];
  720. }
  721. $(document).ready(function () {
  722. if(APIConnector.isEnabled())
  723. APIConnector.init();
  724. UI.start();
  725. statistics.start();
  726. Moderator.init();
  727. // Set default desktop sharing method
  728. setDesktopSharing(config.desktopSharing);
  729. // Initialize Chrome extension inline installs
  730. if (config.chromeExtensionId) {
  731. initInlineInstalls();
  732. }
  733. // By default we use camera
  734. getVideoSize = getCameraVideoSize;
  735. getVideoPosition = getCameraVideoPosition;
  736. });
  737. $(window).bind('beforeunload', function () {
  738. if (connection && connection.connected) {
  739. // ensure signout
  740. $.ajax({
  741. type: 'POST',
  742. url: config.bosh,
  743. async: false,
  744. cache: false,
  745. contentType: 'application/xml',
  746. data: "<body rid='" + (connection.rid || connection._proto.rid)
  747. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  748. + (connection.sid || connection._proto.sid)
  749. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  750. success: function (data) {
  751. console.log('signed out');
  752. console.log(data);
  753. },
  754. error: function (XMLHttpRequest, textStatus, errorThrown) {
  755. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  756. }
  757. });
  758. }
  759. disposeConference(true);
  760. if(APIConnector.isEnabled())
  761. APIConnector.dispose();
  762. });
  763. function disposeConference(onUnload) {
  764. UI.onDisposeConference(onUnload);
  765. var handler = getConferenceHandler();
  766. if (handler && handler.peerconnection) {
  767. // FIXME: probably removing streams is not required and close() should
  768. // be enough
  769. if (connection.jingle.localAudio) {
  770. handler.peerconnection.removeStream(connection.jingle.localAudio, onUnload);
  771. }
  772. if (connection.jingle.localVideo) {
  773. handler.peerconnection.removeStream(connection.jingle.localVideo, onUnload);
  774. }
  775. handler.peerconnection.close();
  776. }
  777. statistics.onDisposeConference(onUnload);
  778. activecall = null;
  779. }
  780. function dump(elem, filename) {
  781. elem = elem.parentNode;
  782. elem.download = filename || 'meetlog.json';
  783. elem.href = 'data:application/json;charset=utf-8,\n';
  784. var data = populateData();
  785. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  786. return false;
  787. }
  788. /**
  789. * Populates the log data
  790. */
  791. function populateData() {
  792. var data = {};
  793. if (connection.jingle) {
  794. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  795. var session = connection.jingle.sessions[sid];
  796. if (session.peerconnection && session.peerconnection.updateLog) {
  797. // FIXME: should probably be a .dump call
  798. data["jingle_" + session.sid] = {
  799. updateLog: session.peerconnection.updateLog,
  800. stats: session.peerconnection.stats,
  801. url: window.location.href
  802. };
  803. }
  804. });
  805. }
  806. var metadata = {};
  807. metadata.time = new Date();
  808. metadata.url = window.location.href;
  809. metadata.ua = navigator.userAgent;
  810. if (connection.logger) {
  811. metadata.xmpp = connection.logger.log;
  812. }
  813. data.metadata = metadata;
  814. return data;
  815. }
  816. /**
  817. * Changes the style class of the element given by id.
  818. */
  819. function buttonClick(id, classname) {
  820. $(id).toggleClass(classname); // add the class to the clicked element
  821. }
  822. /**
  823. * Warning to the user that the conference window is about to be closed.
  824. */
  825. function closePageWarning() {
  826. /*
  827. FIXME: do we need a warning when the focus is a server-side one now ?
  828. if (focus !== null)
  829. return "You are the owner of this conference call and"
  830. + " you are about to end it.";
  831. else*/
  832. return "You are about to leave this conversation.";
  833. }
  834. $(document).bind('error.jingle',
  835. function (event, session, error)
  836. {
  837. console.error("Jingle error", error);
  838. }
  839. );
  840. $(document).bind('fatalError.jingle',
  841. function (event, session, error)
  842. {
  843. sessionTerminated = true;
  844. connection.emuc.doLeave();
  845. UI.messageHandler.showError( "Sorry",
  846. "Internal application error[setRemoteDescription]");
  847. }
  848. );
  849. function callSipButtonClicked()
  850. {
  851. var defaultNumber
  852. = config.defaultSipNumber ? config.defaultSipNumber : '';
  853. UI.messageHandler.openTwoButtonDialog(null,
  854. '<h2>Enter SIP number</h2>' +
  855. '<input id="sipNumber" type="text"' +
  856. ' value="' + defaultNumber + '" autofocus>',
  857. false,
  858. "Dial",
  859. function (e, v, m, f) {
  860. if (v) {
  861. var numberInput = document.getElementById('sipNumber');
  862. if (numberInput.value) {
  863. connection.rayo.dial(
  864. numberInput.value, 'fromnumber', roomName);
  865. }
  866. }
  867. },
  868. function (event) {
  869. document.getElementById('sipNumber').focus();
  870. }
  871. );
  872. }
  873. function hangup() {
  874. disposeConference();
  875. sessionTerminated = true;
  876. connection.emuc.doLeave();
  877. if(config.enableWelcomePage)
  878. {
  879. setTimeout(function()
  880. {
  881. window.localStorage.welcomePageDisabled = false;
  882. window.location.pathname = "/";
  883. }, 10000);
  884. }
  885. messageHandler.openDialog(
  886. "Session Terminated",
  887. "You hung up the call",
  888. true,
  889. { "Join again": true },
  890. function(event, value, message, formVals)
  891. {
  892. window.location.reload();
  893. return false;
  894. }
  895. );
  896. }