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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var authenticatedUser = false;
  5. var authenticationWindow = null;
  6. var activecall = null;
  7. var RTC = null;
  8. var nickname = null;
  9. var sharedKey = '';
  10. var focusMucJid = null;
  11. var roomUrl = null;
  12. var roomName = null;
  13. var ssrc2jid = {};
  14. var mediaStreams = {};
  15. var bridgeIsDown = false;
  16. //TODO: this array must be removed when firefox implement multistream support
  17. var notReceivedSSRCs = [];
  18. var jid2Ssrc = {};
  19. /**
  20. * The stats collector that process stats data and triggers updates to app.js.
  21. * @type {StatsCollector}
  22. */
  23. var statsCollector = null;
  24. /**
  25. * The stats collector for the local stream.
  26. * @type {LocalStatsCollector}
  27. */
  28. var localStatsCollector = null;
  29. /**
  30. * Indicates whether ssrc is camera video or desktop stream.
  31. * FIXME: remove those maps
  32. */
  33. var ssrc2videoType = {};
  34. /**
  35. * Currently focused video "src"(displayed in large video).
  36. * @type {String}
  37. */
  38. var focusedVideoInfo = null;
  39. var mutedAudios = {};
  40. /**
  41. * Remembers if we were muted by the focus.
  42. * @type {boolean}
  43. */
  44. var forceMuted = false;
  45. /**
  46. * Indicates if we have muted our audio before the conference has started.
  47. * @type {boolean}
  48. */
  49. var preMuted = false;
  50. var localVideoSrc = null;
  51. var flipXLocalVideo = true;
  52. var isFullScreen = false;
  53. var currentVideoWidth = null;
  54. var currentVideoHeight = null;
  55. /**
  56. * Method used to calculate large video size.
  57. * @type {function ()}
  58. */
  59. var getVideoSize;
  60. /**
  61. * Method used to get large video position.
  62. * @type {function ()}
  63. */
  64. var getVideoPosition;
  65. /* window.onbeforeunload = closePageWarning; */
  66. var sessionTerminated = false;
  67. function init() {
  68. Toolbar.setupButtonsFromConfig();
  69. RTC = setupRTC();
  70. if (RTC === null) {
  71. window.location.href = 'webrtcrequired.html';
  72. return;
  73. } else if (RTC.browser !== 'chrome' &&
  74. config.enableFirefoxSupport !== true) {
  75. window.location.href = 'chromeonly.html';
  76. return;
  77. }
  78. obtainAudioAndVideoPermissions(function (stream) {
  79. var audioStream, videoStream;
  80. if(window.webkitMediaStream)
  81. {
  82. var audioStream = new webkitMediaStream();
  83. var videoStream = new webkitMediaStream();
  84. var audioTracks = stream.getAudioTracks();
  85. var videoTracks = stream.getVideoTracks();
  86. for (var i = 0; i < audioTracks.length; i++) {
  87. audioStream.addTrack(audioTracks[i]);
  88. }
  89. for (i = 0; i < videoTracks.length; i++) {
  90. videoStream.addTrack(videoTracks[i]);
  91. }
  92. VideoLayout.changeLocalAudio(audioStream);
  93. startLocalRtpStatsCollector(audioStream);
  94. VideoLayout.changeLocalVideo(videoStream, true);
  95. }
  96. else
  97. {
  98. VideoLayout.changeLocalStream(stream);
  99. startLocalRtpStatsCollector(stream);
  100. }
  101. maybeDoJoin();
  102. });
  103. var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
  104. connect(jid);
  105. }
  106. function connect(jid, password) {
  107. var localAudio, localVideo;
  108. if (connection && connection.jingle) {
  109. localAudio = connection.jingle.localAudio;
  110. localVideo = connection.jingle.localVideo;
  111. }
  112. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  113. var email = SettingsMenu.getEmail();
  114. var displayName = SettingsMenu.getDisplayName();
  115. if(email) {
  116. connection.emuc.addEmailToPresence(email);
  117. } else {
  118. connection.emuc.addUserIdToPresence(SettingsMenu.getUID());
  119. }
  120. if(displayName) {
  121. connection.emuc.addDisplayNameToPresence(displayName);
  122. }
  123. if (connection.disco) {
  124. // for chrome, add multistream cap
  125. }
  126. connection.jingle.pc_constraints = RTC.pc_constraints;
  127. if (config.useIPv6) {
  128. // https://code.google.com/p/webrtc/issues/detail?id=2828
  129. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  130. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  131. }
  132. if (localAudio) connection.jingle.localAudio = localAudio;
  133. if (localVideo) connection.jingle.localVideo = localVideo;
  134. if(!password)
  135. password = document.getElementById('password').value;
  136. var anonymousConnectionFailed = false;
  137. connection.connect(jid, password, function (status, msg) {
  138. console.log('Strophe status changed to', Strophe.getStatusString(status));
  139. if (status === Strophe.Status.CONNECTED) {
  140. if (config.useStunTurn) {
  141. connection.jingle.getStunAndTurnCredentials();
  142. }
  143. document.getElementById('connect').disabled = true;
  144. console.info("My Jabber ID: " + connection.jid);
  145. if(password)
  146. authenticatedUser = true;
  147. maybeDoJoin();
  148. } else if (status === Strophe.Status.CONNFAIL) {
  149. if(msg === 'x-strophe-bad-non-anon-jid') {
  150. anonymousConnectionFailed = true;
  151. }
  152. } else if (status === Strophe.Status.DISCONNECTED) {
  153. if(anonymousConnectionFailed) {
  154. // prompt user for username and password
  155. $(document).trigger('passwordrequired.main');
  156. }
  157. } else if (status === Strophe.Status.AUTHFAIL) {
  158. // wrong password or username, prompt user
  159. $(document).trigger('passwordrequired.main');
  160. }
  161. });
  162. }
  163. /**
  164. * We ask for audio and video combined stream in order to get permissions and
  165. * not to ask twice.
  166. */
  167. function obtainAudioAndVideoPermissions(callback) {
  168. // Get AV
  169. var cb = function (stream) {
  170. console.log('got', stream, stream.getAudioTracks().length, stream.getVideoTracks().length);
  171. callback(stream);
  172. trackUsage('localMedia', {
  173. audio: stream.getAudioTracks().length,
  174. video: stream.getVideoTracks().length
  175. });
  176. }
  177. getUserMediaWithConstraints(
  178. ['audio', 'video'],
  179. cb,
  180. function (error) {
  181. console.error('failed to obtain audio/video stream - trying audio only', error);
  182. getUserMediaWithConstraints(
  183. ['audio'],
  184. cb,
  185. function (error) {
  186. console.error('failed to obtain audio/video stream - stop', error);
  187. trackUsage('localMediaError', {
  188. media: error.media || 'video',
  189. name : error.name
  190. });
  191. messageHandler.showError("Error",
  192. "Failed to obtain permissions to use the local microphone" +
  193. "and/or camera.");
  194. }
  195. );
  196. },
  197. config.resolution || '360');
  198. }
  199. function maybeDoJoin() {
  200. if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
  201. && (connection.jingle.localAudio || connection.jingle.localVideo)) {
  202. doJoin();
  203. }
  204. }
  205. function generateRoomName() {
  206. var roomnode = null;
  207. var path = window.location.pathname;
  208. // determinde the room node from the url
  209. // TODO: just the roomnode or the whole bare jid?
  210. if (config.getroomnode && typeof config.getroomnode === 'function') {
  211. // custom function might be responsible for doing the pushstate
  212. roomnode = config.getroomnode(path);
  213. } else {
  214. /* fall back to default strategy
  215. * this is making assumptions about how the URL->room mapping happens.
  216. * It currently assumes deployment at root, with a rewrite like the
  217. * following one (for nginx):
  218. location ~ ^/([a-zA-Z0-9]+)$ {
  219. rewrite ^/(.*)$ / break;
  220. }
  221. */
  222. if (path.length > 1) {
  223. roomnode = path.substr(1).toLowerCase();
  224. } else {
  225. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  226. roomnode = word.toLowerCase();
  227. window.history.pushState('VideoChat',
  228. 'Room: ' + word, window.location.pathname + word);
  229. }
  230. }
  231. roomName = roomnode + '@' + config.hosts.muc;
  232. }
  233. function doJoin() {
  234. if (!roomName) {
  235. generateRoomName();
  236. }
  237. Moderator.allocateConferenceFocus(
  238. roomName, doJoinAfterFocus);
  239. }
  240. function doJoinAfterFocus() {
  241. var roomjid;
  242. roomjid = roomName;
  243. if (config.useNicks) {
  244. var nick = window.prompt('Your nickname (optional)');
  245. if (nick) {
  246. roomjid += '/' + nick;
  247. } else {
  248. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  249. }
  250. } else {
  251. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  252. if(!authenticatedUser)
  253. tmpJid = tmpJid.substr(0, 8);
  254. roomjid += '/' + tmpJid;
  255. }
  256. connection.emuc.doJoin(roomjid);
  257. }
  258. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  259. // XXX(gp) so, every call to this function is *always* preceded by a call
  260. // to the RTC.attachMediaStream() function but that call is *not* followed
  261. // by an update to the videoSrcToSsrc map!
  262. //
  263. // The above way of doing things results in video SRCs that don't correspond
  264. // to any SSRC for a short period of time (to be more precise, for as long
  265. // the waitForRemoteVideo takes to complete). This causes problems (see
  266. // bellow).
  267. //
  268. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  269. // a second time in here and only then update the videoSrcToSsrc map? Why
  270. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  271. // is called the first time? I actually do that in the lastN changed event
  272. // handler because the "orphan" video SRC is causing troubles there. The
  273. // purpose of this method would then be to fire the "videoactive.jingle".
  274. //
  275. // Food for though I guess :-)
  276. if (selector.removed || !selector.parent().is(":visible")) {
  277. console.warn("Media removed before had started", selector);
  278. return;
  279. }
  280. if (stream.id === 'mixedmslabel') return;
  281. if (selector[0].currentTime > 0) {
  282. var videoStream = simulcast.getReceivingVideoStream(stream);
  283. RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  284. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  285. // in order to get rid of too many maps
  286. if (ssrc && jid) {
  287. jid2Ssrc[Strophe.getResourceFromJid(jid)] = ssrc;
  288. } else {
  289. console.warn("No ssrc given for jid", jid);
  290. // messageHandler.showError('Warning', 'No ssrc was given for the video.');
  291. }
  292. $(document).trigger('videoactive.jingle', [selector]);
  293. } else {
  294. setTimeout(function () {
  295. waitForRemoteVideo(selector, ssrc, stream, jid);
  296. }, 250);
  297. }
  298. }
  299. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  300. waitForPresence(data, sid);
  301. });
  302. function waitForPresence(data, sid) {
  303. var sess = connection.jingle.sessions[sid];
  304. var thessrc;
  305. // look up an associated JID for a stream id
  306. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  307. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  308. var ssrclines
  309. = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  310. ssrclines = ssrclines.filter(function (line) {
  311. // NOTE(gp) previously we filtered on the mslabel, but that property
  312. // is not always present.
  313. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  314. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  315. });
  316. if (ssrclines.length) {
  317. thessrc = ssrclines[0].substring(7).split(' ')[0];
  318. // We signal our streams (through Jingle to the focus) before we set
  319. // our presence (through which peers associate remote streams to
  320. // jids). So, it might arrive that a remote stream is added but
  321. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  322. // successfully set. Here we wait for up to a second for the
  323. // presence to arrive.
  324. if (!ssrc2jid[thessrc]) {
  325. // TODO(gp) limit wait duration to 1 sec.
  326. setTimeout(function(d, s) {
  327. return function() {
  328. waitForPresence(d, s);
  329. }
  330. }(data, sid), 250);
  331. return;
  332. }
  333. // ok to overwrite the one from focus? might save work in colibri.js
  334. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  335. if (ssrc2jid[thessrc]) {
  336. data.peerjid = ssrc2jid[thessrc];
  337. }
  338. }
  339. }
  340. //TODO: this code should be removed when firefox implement multistream support
  341. if(RTC.browser == "firefox")
  342. {
  343. if((notReceivedSSRCs.length == 0) ||
  344. !ssrc2jid[notReceivedSSRCs[notReceivedSSRCs.length - 1]])
  345. {
  346. // TODO(gp) limit wait duration to 1 sec.
  347. setTimeout(function(d, s) {
  348. return function() {
  349. waitForPresence(d, s);
  350. }
  351. }(data, sid), 250);
  352. return;
  353. }
  354. thessrc = notReceivedSSRCs.pop();
  355. if (ssrc2jid[thessrc]) {
  356. data.peerjid = ssrc2jid[thessrc];
  357. }
  358. }
  359. // NOTE(gp) now that we have simulcast, a media stream can have more than 1
  360. // ssrc. We should probably take that into account in our MediaStream
  361. // wrapper.
  362. var mediaStream = new MediaStream(data, sid, thessrc);
  363. var jid = data.peerjid || connection.emuc.myroomjid;
  364. if(!mediaStreams[jid]) {
  365. mediaStreams[jid] = {};
  366. }
  367. mediaStreams[jid][mediaStream.type] = mediaStream;
  368. var container;
  369. var remotes = document.getElementById('remoteVideos');
  370. if (data.peerjid) {
  371. VideoLayout.ensurePeerContainerExists(data.peerjid);
  372. container = document.getElementById(
  373. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  374. } else {
  375. if (data.stream.id !== 'mixedmslabel'
  376. // FIXME: default stream is added always with new focus
  377. // (to be investigated)
  378. && data.stream.id !== 'default') {
  379. console.error('can not associate stream',
  380. data.stream.id,
  381. 'with a participant');
  382. // We don't want to add it here since it will cause troubles
  383. return;
  384. }
  385. // FIXME: for the mixed ms we dont need a video -- currently
  386. container = document.createElement('span');
  387. container.id = 'mixedstream';
  388. container.className = 'videocontainer';
  389. remotes.appendChild(container);
  390. Util.playSoundNotification('userJoined');
  391. }
  392. var isVideo = data.stream.getVideoTracks().length > 0;
  393. if (container) {
  394. VideoLayout.addRemoteStreamElement( container,
  395. sid,
  396. data.stream,
  397. data.peerjid,
  398. thessrc);
  399. }
  400. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  401. if (isVideo &&
  402. data.peerjid && sess.peerjid === data.peerjid &&
  403. data.stream.getVideoTracks().length === 0 &&
  404. connection.jingle.localVideo.getVideoTracks().length > 0) {
  405. //
  406. window.setTimeout(function () {
  407. sendKeyframe(sess.peerconnection);
  408. }, 3000);
  409. }
  410. }
  411. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  412. function sendKeyframe(pc) {
  413. console.log('sendkeyframe', pc.iceConnectionState);
  414. if (pc.iceConnectionState !== 'connected') return; // safe...
  415. pc.setRemoteDescription(
  416. pc.remoteDescription,
  417. function () {
  418. pc.createAnswer(
  419. function (modifiedAnswer) {
  420. pc.setLocalDescription(
  421. modifiedAnswer,
  422. function () {
  423. // noop
  424. },
  425. function (error) {
  426. console.log('triggerKeyframe setLocalDescription failed', error);
  427. messageHandler.showError();
  428. }
  429. );
  430. },
  431. function (error) {
  432. console.log('triggerKeyframe createAnswer failed', error);
  433. messageHandler.showError();
  434. }
  435. );
  436. },
  437. function (error) {
  438. console.log('triggerKeyframe setRemoteDescription failed', error);
  439. messageHandler.showError();
  440. }
  441. );
  442. }
  443. // Really mute video, i.e. dont even send black frames
  444. function muteVideo(pc, unmute) {
  445. // FIXME: this probably needs another of those lovely state safeguards...
  446. // which checks for iceconn == connected and sigstate == stable
  447. pc.setRemoteDescription(pc.remoteDescription,
  448. function () {
  449. pc.createAnswer(
  450. function (answer) {
  451. var sdp = new SDP(answer.sdp);
  452. if (sdp.media.length > 1) {
  453. if (unmute)
  454. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  455. else
  456. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  457. sdp.raw = sdp.session + sdp.media.join('');
  458. answer.sdp = sdp.raw;
  459. }
  460. pc.setLocalDescription(answer,
  461. function () {
  462. console.log('mute SLD ok');
  463. },
  464. function (error) {
  465. console.log('mute SLD error');
  466. messageHandler.showError('Error',
  467. 'Oops! Something went wrong and we failed to ' +
  468. 'mute! (SLD Failure)');
  469. }
  470. );
  471. },
  472. function (error) {
  473. console.log(error);
  474. messageHandler.showError();
  475. }
  476. );
  477. },
  478. function (error) {
  479. console.log('muteVideo SRD error');
  480. messageHandler.showError('Error',
  481. 'Oops! Something went wrong and we failed to stop video!' +
  482. '(SRD Failure)');
  483. }
  484. );
  485. }
  486. /**
  487. * Callback for audio levels changed.
  488. * @param jid JID of the user
  489. * @param audioLevel the audio level value
  490. */
  491. function audioLevelUpdated(jid, audioLevel)
  492. {
  493. var resourceJid;
  494. if(jid === LocalStatsCollector.LOCAL_JID)
  495. {
  496. resourceJid = AudioLevels.LOCAL_LEVEL;
  497. if(isAudioMuted())
  498. {
  499. audioLevel = 0;
  500. }
  501. }
  502. else
  503. {
  504. resourceJid = Strophe.getResourceFromJid(jid);
  505. }
  506. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  507. }
  508. /**
  509. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  510. */
  511. function startRtpStatsCollector()
  512. {
  513. stopRTPStatsCollector();
  514. if (config.enableRtpStats)
  515. {
  516. statsCollector = new StatsCollector(
  517. getConferenceHandler().peerconnection, 200, audioLevelUpdated, 2000,
  518. ConnectionQuality.updateLocalStats);
  519. statsCollector.start();
  520. }
  521. }
  522. /**
  523. * Stops the {@link StatsCollector}.
  524. */
  525. function stopRTPStatsCollector()
  526. {
  527. if (statsCollector)
  528. {
  529. statsCollector.stop();
  530. statsCollector = null;
  531. ConnectionQuality.stopSendingStats();
  532. }
  533. }
  534. /**
  535. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  536. * @param stream the stream that will be used for collecting statistics.
  537. */
  538. function startLocalRtpStatsCollector(stream)
  539. {
  540. if(config.enableRtpStats)
  541. {
  542. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  543. localStatsCollector.start();
  544. }
  545. }
  546. /**
  547. * Stops the {@link LocalStatsCollector}.
  548. */
  549. function stopLocalRtpStatsCollector()
  550. {
  551. if(localStatsCollector)
  552. {
  553. localStatsCollector.stop();
  554. localStatsCollector = null;
  555. }
  556. }
  557. $(document).bind('callincoming.jingle', function (event, sid) {
  558. var sess = connection.jingle.sessions[sid];
  559. // TODO: do we check activecall == null?
  560. activecall = sess;
  561. startRtpStatsCollector();
  562. // Bind data channel listener in case we're a regular participant
  563. if (config.openSctp)
  564. {
  565. bindDataChannelListener(sess.peerconnection);
  566. }
  567. // TODO: check affiliation and/or role
  568. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  569. sess.usedrip = true; // not-so-naive trickle ice
  570. sess.sendAnswer();
  571. sess.accept();
  572. });
  573. $(document).bind('conferenceCreated.jingle', function (event, focus)
  574. {
  575. startRtpStatsCollector();
  576. });
  577. $(document).bind('conferenceCreated.jingle', function (event, focus)
  578. {
  579. // Bind data channel listener in case we're the focus
  580. if (config.openSctp)
  581. {
  582. bindDataChannelListener(focus.peerconnection);
  583. }
  584. });
  585. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  586. // put our ssrcs into presence so other clients can identify our stream
  587. var sess = connection.jingle.sessions[sid];
  588. var newssrcs = [];
  589. var media = simulcast.parseMedia(sess.peerconnection.localDescription);
  590. media.forEach(function (media) {
  591. if(Object.keys(media.sources).length > 0) {
  592. // TODO(gp) maybe exclude FID streams?
  593. Object.keys(media.sources).forEach(function (ssrc) {
  594. newssrcs.push({
  595. 'ssrc': ssrc,
  596. 'type': media.type,
  597. 'direction': media.direction
  598. });
  599. });
  600. }
  601. else if(sess.localStreamsSSRC && sess.localStreamsSSRC[media.type])
  602. {
  603. newssrcs.push({
  604. 'ssrc': sess.localStreamsSSRC[media.type],
  605. 'type': media.type,
  606. 'direction': media.direction
  607. });
  608. }
  609. });
  610. console.log('new ssrcs', newssrcs);
  611. // Have to clear presence map to get rid of removed streams
  612. connection.emuc.clearPresenceMedia();
  613. if (newssrcs.length > 0) {
  614. for (var i = 1; i <= newssrcs.length; i ++) {
  615. // Change video type to screen
  616. if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
  617. newssrcs[i-1].type = 'screen';
  618. }
  619. connection.emuc.addMediaToPresence(i,
  620. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  621. }
  622. connection.emuc.sendPresence();
  623. }
  624. });
  625. $(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
  626. switch (session.peerconnection.iceConnectionState) {
  627. case 'checking':
  628. session.timeChecking = (new Date()).getTime();
  629. session.firstconnect = true;
  630. break;
  631. case 'completed': // on caller side
  632. case 'connected':
  633. if (session.firstconnect) {
  634. session.firstconnect = false;
  635. var metadata = {};
  636. metadata.setupTime = (new Date()).getTime() - session.timeChecking;
  637. session.peerconnection.getStats(function (res) {
  638. if(res && res.result) {
  639. res.result().forEach(function (report) {
  640. if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
  641. metadata.localCandidateType = report.stat('googLocalCandidateType');
  642. metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
  643. // log pair as well so we can get nice pie charts
  644. metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
  645. if (report.stat('googRemoteAddress').indexOf('[') === 0) {
  646. metadata.ipv6 = true;
  647. }
  648. }
  649. });
  650. trackUsage('iceConnected', metadata);
  651. }
  652. });
  653. }
  654. break;
  655. }
  656. });
  657. $(document).bind('joined.muc', function (event, jid, info) {
  658. updateRoomUrl(window.location.href);
  659. document.getElementById('localNick').appendChild(
  660. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  661. );
  662. // Add myself to the contact list.
  663. ContactList.addContact(jid, SettingsMenu.getEmail() || SettingsMenu.getUID());
  664. // Once we've joined the muc show the toolbar
  665. ToolbarToggler.showToolbar();
  666. // Show authenticate button if needed
  667. Toolbar.showAuthenticateButton(
  668. Moderator.isExternalAuthEnabled() && !Moderator.isModerator());
  669. var displayName = !config.displayJids
  670. ? info.displayName : Strophe.getResourceFromJid(jid);
  671. if (displayName)
  672. $(document).trigger('displaynamechanged',
  673. ['localVideoContainer', displayName + ' (me)']);
  674. });
  675. $(document).bind('entered.muc', function (event, jid, info, pres) {
  676. console.log('entered', jid, info);
  677. if (info.isFocus)
  678. {
  679. focusMucJid = jid;
  680. console.info("Ignore focus: " + jid +", real JID: " + info.jid);
  681. return;
  682. }
  683. messageHandler.notify(info.displayName || 'Somebody',
  684. 'connected',
  685. 'connected');
  686. // Add Peer's container
  687. var id = $(pres).find('>userID').text();
  688. var email = $(pres).find('>email');
  689. if(email.length > 0) {
  690. id = email.text();
  691. }
  692. VideoLayout.ensurePeerContainerExists(jid,id);
  693. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantJoined"))
  694. {
  695. APIConnector.triggerEvent("participantJoined",{jid: jid});
  696. }
  697. /*if (focus !== null) {
  698. // FIXME: this should prepare the video
  699. if (focus.confid === null) {
  700. console.log('make new conference with', jid);
  701. focus.makeConference(Object.keys(connection.emuc.members),
  702. function(error) {
  703. connection.emuc.addBridgeIsDownToPresence();
  704. connection.emuc.sendPresence();
  705. }
  706. );
  707. Toolbar.showRecordingButton(true);
  708. } else {
  709. console.log('invite', jid, 'into conference');
  710. focus.addNewParticipant(jid);
  711. }
  712. }*/
  713. });
  714. $(document).bind('left.muc', function (event, jid) {
  715. console.log('left.muc', jid);
  716. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  717. '>.displayname').text();
  718. messageHandler.notify(displayName || 'Somebody',
  719. 'disconnected',
  720. 'disconnected');
  721. // Need to call this with a slight delay, otherwise the element couldn't be
  722. // found for some reason.
  723. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  724. window.setTimeout(function () {
  725. var container = document.getElementById(
  726. 'participant_' + Strophe.getResourceFromJid(jid));
  727. if (container) {
  728. ContactList.removeContact(jid);
  729. VideoLayout.removeConnectionIndicator(jid);
  730. // hide here, wait for video to close before removing
  731. $(container).hide();
  732. VideoLayout.resizeThumbnails();
  733. }
  734. }, 10);
  735. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantLeft"))
  736. {
  737. APIConnector.triggerEvent("participantLeft",{jid: jid});
  738. }
  739. delete jid2Ssrc[jid];
  740. // Unlock large video
  741. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  742. {
  743. console.info("Focused video owner has left the conference");
  744. focusedVideoInfo = null;
  745. }
  746. connection.jingle.terminateByJid(jid);
  747. if (connection.emuc.getPrezi(jid)) {
  748. $(document).trigger('presentationremoved.muc',
  749. [jid, connection.emuc.getPrezi(jid)]);
  750. }
  751. });
  752. $(document).bind('presence.muc', function (event, jid, info, pres) {
  753. //check if the video bridge is available
  754. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  755. bridgeIsDown = true;
  756. messageHandler.showError("Error",
  757. "Jitsi Videobridge is currently unavailable. Please try again later!");
  758. }
  759. if (info.isFocus)
  760. {
  761. return;
  762. }
  763. // Remove old ssrcs coming from the jid
  764. Object.keys(ssrc2jid).forEach(function (ssrc) {
  765. if (ssrc2jid[ssrc] == jid) {
  766. delete ssrc2jid[ssrc];
  767. delete ssrc2videoType[ssrc];
  768. }
  769. });
  770. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  771. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  772. var ssrcV = ssrc.getAttribute('ssrc');
  773. ssrc2jid[ssrcV] = jid;
  774. notReceivedSSRCs.push(ssrcV);
  775. var type = ssrc.getAttribute('type');
  776. ssrc2videoType[ssrcV] = type;
  777. // might need to update the direction if participant just went from sendrecv to recvonly
  778. if (type === 'video' || type === 'screen') {
  779. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  780. switch (ssrc.getAttribute('direction')) {
  781. case 'sendrecv':
  782. el.show();
  783. break;
  784. case 'recvonly':
  785. el.hide();
  786. // FIXME: Check if we have to change large video
  787. //VideoLayout.updateLargeVideo(el);
  788. break;
  789. }
  790. }
  791. });
  792. var displayName = !config.displayJids
  793. ? info.displayName : Strophe.getResourceFromJid(jid);
  794. if (displayName && displayName.length > 0)
  795. $(document).trigger('displaynamechanged',
  796. [jid, displayName]);
  797. /*if (focus !== null && info.displayName !== null) {
  798. focus.setEndpointDisplayName(jid, info.displayName);
  799. }*/
  800. //check if the video bridge is available
  801. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  802. bridgeIsDown = true;
  803. messageHandler.showError("Error",
  804. "Jitsi Videobridge is currently unavailable. Please try again later!");
  805. }
  806. var id = $(pres).find('>userID').text();
  807. var email = $(pres).find('>email');
  808. if(email.length > 0) {
  809. id = email.text();
  810. }
  811. Avatar.setUserAvatar(jid, id);
  812. });
  813. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  814. VideoLayout.setPresenceStatus(
  815. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  816. });
  817. $(document).bind('kicked.muc', function (event, jid) {
  818. console.info(jid + " has been kicked from MUC!");
  819. if (connection.emuc.myroomjid === jid) {
  820. sessionTerminated = true;
  821. disposeConference(false);
  822. connection.emuc.doLeave();
  823. messageHandler.openMessageDialog("Session Terminated",
  824. "Ouch! You have been kicked out of the meet!");
  825. }
  826. });
  827. $(document).bind('role.changed.muc', function (event, jid, member, pres) {
  828. console.info("Role changed for " + jid + ", new role: " + member.role);
  829. VideoLayout.showModeratorIndicator();
  830. if (member.role === 'moderator') {
  831. var displayName = member.displayName;
  832. if (!displayName) {
  833. displayName = 'Somebody';
  834. }
  835. messageHandler.notify(
  836. displayName,
  837. 'connected',
  838. 'Moderator rights granted to ' + displayName + '!');
  839. }
  840. }
  841. );
  842. $(document).bind('local.role.changed.muc', function (event, jid, info, pres) {
  843. console.info("My role changed, new role: " + info.role);
  844. var isModerator = Moderator.isModerator();
  845. VideoLayout.showModeratorIndicator();
  846. Toolbar.showAuthenticateButton(
  847. Moderator.isExternalAuthEnabled() && !isModerator);
  848. if (isModerator) {
  849. if (authenticationWindow) {
  850. authenticationWindow.close();
  851. authenticationWindow = null;
  852. }
  853. messageHandler.notify(
  854. 'Me', 'connected', 'Moderator rights granted !');
  855. }
  856. }
  857. );
  858. $(document).bind('passwordrequired.muc', function (event, jid) {
  859. console.log('on password required', jid);
  860. // password is required
  861. Toolbar.lockLockButton();
  862. messageHandler.openTwoButtonDialog(null,
  863. '<h2>Password required</h2>' +
  864. '<input id="lockKey" type="text" placeholder="password" autofocus>',
  865. true,
  866. "Ok",
  867. function (e, v, m, f) {},
  868. function (event) {
  869. document.getElementById('lockKey').focus();
  870. },
  871. function (e, v, m, f) {
  872. if (v) {
  873. var lockKey = document.getElementById('lockKey');
  874. if (lockKey.value !== null) {
  875. setSharedKey(lockKey.value);
  876. connection.emuc.doJoin(jid, lockKey.value);
  877. }
  878. }
  879. }
  880. );
  881. });
  882. $(document).bind('passwordrequired.main', function (event) {
  883. console.log('password is required');
  884. messageHandler.openTwoButtonDialog(null,
  885. '<h2>Password required</h2>' +
  886. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  887. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  888. true,
  889. "Ok",
  890. function (e, v, m, f) {
  891. if (v) {
  892. var username = document.getElementById('passwordrequired.username');
  893. var password = document.getElementById('passwordrequired.password');
  894. if (username.value !== null && password.value != null) {
  895. connect(username.value, password.value);
  896. }
  897. }
  898. },
  899. function (event) {
  900. document.getElementById('passwordrequired.username').focus();
  901. }
  902. );
  903. });
  904. $(document).bind('auth_required.moderator', function () {
  905. // extract room name from 'room@muc.server.net'
  906. var room = roomName.substr(0, roomName.indexOf('@'));
  907. messageHandler.openDialog(
  908. 'Stop',
  909. 'Authentication is required to create room:<br/>' + room,
  910. true,
  911. {
  912. Authenticate: 'authNow',
  913. Close: 'close'
  914. },
  915. function (onSubmitEvent, submitValue) {
  916. console.info('On submit: ' + submitValue, submitValue);
  917. if (submitValue === 'authNow') {
  918. authenticateClicked();
  919. } else {
  920. Toolbar.showAuthenticateButton(true);
  921. }
  922. }
  923. );
  924. });
  925. function authenticateClicked() {
  926. // Get authentication URL
  927. Moderator.getAuthUrl(function (url) {
  928. // Open popup with authentication URL
  929. authenticationWindow = messageHandler.openCenteredPopup(
  930. url, 500, 400,
  931. function () {
  932. // On popup closed - retry room allocation
  933. Moderator.allocateConferenceFocus(
  934. roomName, doJoinAfterFocus);
  935. authenticationWindow = null;
  936. });
  937. if (!authenticationWindow) {
  938. Toolbar.showAuthenticateButton(true);
  939. messageHandler.openMessageDialog(
  940. null, "Your browser is blocking popup windows from this site." +
  941. " Please enable popups in your browser security settings" +
  942. " and try again.");
  943. }
  944. });
  945. };
  946. /**
  947. * Checks if video identified by given src is desktop stream.
  948. * @param videoSrc eg.
  949. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  950. * @returns {boolean}
  951. */
  952. function isVideoSrcDesktop(jid) {
  953. // FIXME: fix this mapping mess...
  954. // figure out if large video is desktop stream or just a camera
  955. if(!jid)
  956. return false;
  957. var isDesktop = false;
  958. if (connection.emuc.myroomjid &&
  959. Strophe.getResourceFromJid(connection.emuc.myroomjid) === jid) {
  960. // local video
  961. isDesktop = isUsingScreenStream;
  962. } else {
  963. // Do we have associations...
  964. var videoSsrc = jid2Ssrc[jid];
  965. if (videoSsrc) {
  966. var videoType = ssrc2videoType[videoSsrc];
  967. if (videoType) {
  968. // Finally there...
  969. isDesktop = videoType === 'screen';
  970. } else {
  971. console.error("No video type for ssrc: " + videoSsrc);
  972. }
  973. } else {
  974. console.error("No ssrc for jid: " + jid);
  975. }
  976. }
  977. return isDesktop;
  978. }
  979. function getConferenceHandler() {
  980. return activecall;
  981. }
  982. /**
  983. * Mutes/unmutes the local video.
  984. *
  985. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  986. * @param options an object which specifies optional arguments such as the
  987. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  988. * specifies whether the method was initiated in response to a user command (in
  989. * contrast to an automatic decision taken by the application logic)
  990. */
  991. function setVideoMute(mute, options) {
  992. if (connection && connection.jingle.localVideo) {
  993. var session = getConferenceHandler();
  994. if (session) {
  995. session.setVideoMute(
  996. mute,
  997. function (mute) {
  998. var video = $('#video');
  999. var communicativeClass = "icon-camera";
  1000. var muteClass = "icon-camera icon-camera-disabled";
  1001. if (mute) {
  1002. video.removeClass(communicativeClass);
  1003. video.addClass(muteClass);
  1004. } else {
  1005. video.removeClass(muteClass);
  1006. video.addClass(communicativeClass);
  1007. }
  1008. connection.emuc.addVideoInfoToPresence(mute);
  1009. connection.emuc.sendPresence();
  1010. },
  1011. options);
  1012. }
  1013. }
  1014. }
  1015. $(document).on('inlastnchanged', function (event, oldValue, newValue) {
  1016. if (config.muteLocalVideoIfNotInLastN) {
  1017. setVideoMute(!newValue, { 'byUser': false });
  1018. }
  1019. });
  1020. /**
  1021. * Mutes/unmutes the local video.
  1022. */
  1023. function toggleVideo() {
  1024. buttonClick("#video", "icon-camera icon-camera-disabled");
  1025. if (connection && connection.jingle.localVideo) {
  1026. var session = getConferenceHandler();
  1027. if (session) {
  1028. setVideoMute(!session.isVideoMute());
  1029. }
  1030. }
  1031. }
  1032. /**
  1033. * Mutes / unmutes audio for the local participant.
  1034. */
  1035. function toggleAudio() {
  1036. setAudioMuted(!isAudioMuted());
  1037. }
  1038. /**
  1039. * Sets muted audio state for the local participant.
  1040. */
  1041. function setAudioMuted(mute) {
  1042. if (!(connection && connection.jingle.localAudio)) {
  1043. preMuted = mute;
  1044. // We still click the button.
  1045. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1046. return;
  1047. }
  1048. if (forceMuted && !mute) {
  1049. console.info("Asking focus for unmute");
  1050. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  1051. // FIXME: wait for result before resetting muted status
  1052. forceMuted = false;
  1053. }
  1054. if (mute == isAudioMuted()) {
  1055. // Nothing to do
  1056. return;
  1057. }
  1058. // It is not clear what is the right way to handle multiple tracks.
  1059. // So at least make sure that they are all muted or all unmuted and
  1060. // that we send presence just once.
  1061. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  1062. if (localAudioTracks.length > 0) {
  1063. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  1064. localAudioTracks[idx].enabled = !mute;
  1065. }
  1066. }
  1067. // isMuted is the opposite of audioEnabled
  1068. connection.emuc.addAudioInfoToPresence(mute);
  1069. connection.emuc.sendPresence();
  1070. VideoLayout.showLocalAudioIndicator(mute);
  1071. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1072. }
  1073. /**
  1074. * Checks whether the audio is muted or not.
  1075. * @returns {boolean} true if audio is muted and false if not.
  1076. */
  1077. function isAudioMuted()
  1078. {
  1079. var localAudio = connection.jingle.localAudio;
  1080. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  1081. if(localAudio.getAudioTracks()[idx].enabled === true)
  1082. return false;
  1083. }
  1084. return true;
  1085. }
  1086. // Starts or stops the recording for the conference.
  1087. function toggleRecording() {
  1088. Recording.toggleRecording();
  1089. }
  1090. /**
  1091. * Returns an array of the video horizontal and vertical indents,
  1092. * so that if fits its parent.
  1093. *
  1094. * @return an array with 2 elements, the horizontal indent and the vertical
  1095. * indent
  1096. */
  1097. function getCameraVideoPosition(videoWidth,
  1098. videoHeight,
  1099. videoSpaceWidth,
  1100. videoSpaceHeight) {
  1101. // Parent height isn't completely calculated when we position the video in
  1102. // full screen mode and this is why we use the screen height in this case.
  1103. // Need to think it further at some point and implement it properly.
  1104. var isFullScreen = document.fullScreen ||
  1105. document.mozFullScreen ||
  1106. document.webkitIsFullScreen;
  1107. if (isFullScreen)
  1108. videoSpaceHeight = window.innerHeight;
  1109. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  1110. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  1111. return [horizontalIndent, verticalIndent];
  1112. }
  1113. /**
  1114. * Returns an array of the video horizontal and vertical indents.
  1115. * Centers horizontally and top aligns vertically.
  1116. *
  1117. * @return an array with 2 elements, the horizontal indent and the vertical
  1118. * indent
  1119. */
  1120. function getDesktopVideoPosition(videoWidth,
  1121. videoHeight,
  1122. videoSpaceWidth,
  1123. videoSpaceHeight) {
  1124. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  1125. var verticalIndent = 0;// Top aligned
  1126. return [horizontalIndent, verticalIndent];
  1127. }
  1128. /**
  1129. * Returns an array of the video dimensions, so that it covers the screen.
  1130. * It leaves no empty areas, but some parts of the video might not be visible.
  1131. *
  1132. * @return an array with 2 elements, the video width and the video height
  1133. */
  1134. function getCameraVideoSize(videoWidth,
  1135. videoHeight,
  1136. videoSpaceWidth,
  1137. videoSpaceHeight) {
  1138. if (!videoWidth)
  1139. videoWidth = currentVideoWidth;
  1140. if (!videoHeight)
  1141. videoHeight = currentVideoHeight;
  1142. var aspectRatio = videoWidth / videoHeight;
  1143. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  1144. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  1145. if (availableWidth / aspectRatio < videoSpaceHeight) {
  1146. availableHeight = videoSpaceHeight;
  1147. availableWidth = availableHeight * aspectRatio;
  1148. }
  1149. if (availableHeight * aspectRatio < videoSpaceWidth) {
  1150. availableWidth = videoSpaceWidth;
  1151. availableHeight = availableWidth / aspectRatio;
  1152. }
  1153. return [availableWidth, availableHeight];
  1154. }
  1155. $(document).ready(function () {
  1156. document.title = interfaceConfig.APP_NAME;
  1157. if(APIConnector.isEnabled())
  1158. APIConnector.init();
  1159. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1160. (!window.localStorage.welcomePageDisabled
  1161. || window.localStorage.welcomePageDisabled == "false"))
  1162. {
  1163. $("#videoconference_page").hide();
  1164. $("#domain_name").text(
  1165. window.location.protocol + "//" + window.location.host + "/");
  1166. $("span[name='appName']").text(interfaceConfig.APP_NAME);
  1167. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1168. var leftWatermarkDiv
  1169. = $("#welcome_page_header div[class='watermark leftwatermark']");
  1170. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  1171. {
  1172. leftWatermarkDiv.css({display: 'block'});
  1173. leftWatermarkDiv.parent().get(0).href
  1174. = interfaceConfig.JITSI_WATERMARK_LINK;
  1175. }
  1176. }
  1177. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1178. var rightWatermarkDiv
  1179. = $("#welcome_page_header div[class='watermark rightwatermark']");
  1180. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  1181. rightWatermarkDiv.css({display: 'block'});
  1182. rightWatermarkDiv.parent().get(0).href
  1183. = interfaceConfig.BRAND_WATERMARK_LINK;
  1184. rightWatermarkDiv.get(0).style.backgroundImage
  1185. = "url(images/rightwatermark.png)";
  1186. }
  1187. }
  1188. if (interfaceConfig.SHOW_POWERED_BY) {
  1189. $("#welcome_page_header>a[class='poweredby']")
  1190. .css({display: 'block'});
  1191. }
  1192. function enter_room()
  1193. {
  1194. var val = $("#enter_room_field").val();
  1195. if(!val) {
  1196. val = $("#enter_room_field").attr("room_name");
  1197. }
  1198. if (val) {
  1199. window.location.pathname = "/" + val;
  1200. }
  1201. }
  1202. $("#enter_room_button").click(function()
  1203. {
  1204. enter_room();
  1205. });
  1206. $("#enter_room_field").keydown(function (event) {
  1207. if (event.keyCode === 13 /* enter */) {
  1208. enter_room();
  1209. }
  1210. });
  1211. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  1212. var updateTimeout;
  1213. var animateTimeout;
  1214. $("#reload_roomname").click(function () {
  1215. clearTimeout(updateTimeout);
  1216. clearTimeout(animateTimeout);
  1217. update_roomname();
  1218. });
  1219. $("#reload_roomname").show();
  1220. function animate(word) {
  1221. var currentVal = $("#enter_room_field").attr("placeholder");
  1222. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  1223. animateTimeout = setTimeout(function() {
  1224. animate(word.substring(1, word.length))
  1225. }, 70);
  1226. }
  1227. function update_roomname()
  1228. {
  1229. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1230. $("#enter_room_field").attr("room_name", word);
  1231. $("#enter_room_field").attr("placeholder", "");
  1232. clearTimeout(animateTimeout);
  1233. animate(word);
  1234. updateTimeout = setTimeout(update_roomname, 10000);
  1235. }
  1236. update_roomname();
  1237. }
  1238. $("#disable_welcome").click(function () {
  1239. window.localStorage.welcomePageDisabled
  1240. = $("#disable_welcome").is(":checked");
  1241. });
  1242. return;
  1243. }
  1244. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1245. var leftWatermarkDiv
  1246. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1247. leftWatermarkDiv.css({display: 'block'});
  1248. leftWatermarkDiv.parent().get(0).href
  1249. = interfaceConfig.JITSI_WATERMARK_LINK;
  1250. }
  1251. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1252. var rightWatermarkDiv
  1253. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1254. rightWatermarkDiv.css({display: 'block'});
  1255. rightWatermarkDiv.parent().get(0).href
  1256. = interfaceConfig.BRAND_WATERMARK_LINK;
  1257. rightWatermarkDiv.get(0).style.backgroundImage
  1258. = "url(images/rightwatermark.png)";
  1259. }
  1260. if (interfaceConfig.SHOW_POWERED_BY) {
  1261. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1262. }
  1263. $("#welcome_page").hide();
  1264. Chat.init();
  1265. $('body').popover({ selector: '[data-toggle=popover]',
  1266. trigger: 'click hover',
  1267. content: function() {
  1268. return this.getAttribute("content") +
  1269. KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
  1270. }
  1271. });
  1272. Moderator.init();
  1273. // Set the defaults for prompt dialogs.
  1274. jQuery.prompt.setDefaults({persistent: false});
  1275. // Set default desktop sharing method
  1276. setDesktopSharing(config.desktopSharing);
  1277. // Initialize Chrome extension inline installs
  1278. if (config.chromeExtensionId) {
  1279. initInlineInstalls();
  1280. }
  1281. // By default we use camera
  1282. getVideoSize = getCameraVideoSize;
  1283. getVideoPosition = getCameraVideoPosition;
  1284. VideoLayout.resizeLargeVideoContainer();
  1285. $(window).resize(function () {
  1286. VideoLayout.resizeLargeVideoContainer();
  1287. VideoLayout.positionLarge();
  1288. });
  1289. // Listen for large video size updates
  1290. document.getElementById('largeVideo')
  1291. .addEventListener('loadedmetadata', function (e) {
  1292. currentVideoWidth = this.videoWidth;
  1293. currentVideoHeight = this.videoHeight;
  1294. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  1295. });
  1296. document.getElementById('largeVideo').volume = 0;
  1297. if (!$('#settings').is(':visible')) {
  1298. console.log('init');
  1299. init();
  1300. } else {
  1301. loginInfo.onsubmit = function (e) {
  1302. if (e.preventDefault) e.preventDefault();
  1303. $('#settings').hide();
  1304. init();
  1305. };
  1306. }
  1307. toastr.options = {
  1308. "closeButton": true,
  1309. "debug": false,
  1310. "positionClass": "notification-bottom-right",
  1311. "onclick": null,
  1312. "showDuration": "300",
  1313. "hideDuration": "1000",
  1314. "timeOut": "2000",
  1315. "extendedTimeOut": "1000",
  1316. "showEasing": "swing",
  1317. "hideEasing": "linear",
  1318. "showMethod": "fadeIn",
  1319. "hideMethod": "fadeOut",
  1320. "reposition": function() {
  1321. if(PanelToggler.isVisible()) {
  1322. $("#toast-container").addClass("notification-bottom-right-center");
  1323. } else {
  1324. $("#toast-container").removeClass("notification-bottom-right-center");
  1325. }
  1326. },
  1327. "newestOnTop": false
  1328. };
  1329. $('#settingsmenu>input').keyup(function(event){
  1330. if(event.keyCode === 13) {//enter
  1331. SettingsMenu.update();
  1332. }
  1333. })
  1334. });
  1335. $(window).bind('beforeunload', function () {
  1336. if (connection && connection.connected) {
  1337. // ensure signout
  1338. $.ajax({
  1339. type: 'POST',
  1340. url: config.bosh,
  1341. async: false,
  1342. cache: false,
  1343. contentType: 'application/xml',
  1344. data: "<body rid='" + (connection.rid || connection._proto.rid)
  1345. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  1346. + (connection.sid || connection._proto.sid)
  1347. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1348. success: function (data) {
  1349. console.log('signed out');
  1350. console.log(data);
  1351. },
  1352. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1353. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1354. }
  1355. });
  1356. }
  1357. disposeConference(true);
  1358. if(APIConnector.isEnabled())
  1359. APIConnector.dispose();
  1360. });
  1361. function disposeConference(onUnload) {
  1362. Toolbar.showAuthenticateButton(false);
  1363. var handler = getConferenceHandler();
  1364. if (handler && handler.peerconnection) {
  1365. // FIXME: probably removing streams is not required and close() should
  1366. // be enough
  1367. if (connection.jingle.localAudio) {
  1368. handler.peerconnection.removeStream(connection.jingle.localAudio, onUnload);
  1369. }
  1370. if (connection.jingle.localVideo) {
  1371. handler.peerconnection.removeStream(connection.jingle.localVideo, onUnload);
  1372. }
  1373. handler.peerconnection.close();
  1374. }
  1375. stopRTPStatsCollector();
  1376. if(onUnload) {
  1377. stopLocalRtpStatsCollector();
  1378. }
  1379. activecall = null;
  1380. }
  1381. function dump(elem, filename) {
  1382. elem = elem.parentNode;
  1383. elem.download = filename || 'meetlog.json';
  1384. elem.href = 'data:application/json;charset=utf-8,\n';
  1385. var data = populateData();
  1386. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1387. return false;
  1388. }
  1389. /**
  1390. * Populates the log data
  1391. */
  1392. function populateData() {
  1393. var data = {};
  1394. if (connection.jingle) {
  1395. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1396. var session = connection.jingle.sessions[sid];
  1397. if (session.peerconnection && session.peerconnection.updateLog) {
  1398. // FIXME: should probably be a .dump call
  1399. data["jingle_" + session.sid] = {
  1400. updateLog: session.peerconnection.updateLog,
  1401. stats: session.peerconnection.stats,
  1402. url: window.location.href
  1403. };
  1404. }
  1405. });
  1406. }
  1407. var metadata = {};
  1408. metadata.time = new Date();
  1409. metadata.url = window.location.href;
  1410. metadata.ua = navigator.userAgent;
  1411. if (connection.logger) {
  1412. metadata.xmpp = connection.logger.log;
  1413. }
  1414. data.metadata = metadata;
  1415. return data;
  1416. }
  1417. /**
  1418. * Changes the style class of the element given by id.
  1419. */
  1420. function buttonClick(id, classname) {
  1421. $(id).toggleClass(classname); // add the class to the clicked element
  1422. }
  1423. /**
  1424. * Locks / unlocks the room.
  1425. */
  1426. function lockRoom(lock) {
  1427. if (lock)
  1428. connection.emuc.lockRoom(sharedKey);
  1429. else
  1430. connection.emuc.lockRoom('');
  1431. }
  1432. /**
  1433. * Sets the shared key.
  1434. */
  1435. function setSharedKey(sKey) {
  1436. sharedKey = sKey;
  1437. }
  1438. /**
  1439. * Updates the room invite url.
  1440. */
  1441. function updateRoomUrl(newRoomUrl) {
  1442. roomUrl = newRoomUrl;
  1443. // If the invite dialog has been already opened we update the information.
  1444. var inviteLink = document.getElementById('inviteLinkRef');
  1445. if (inviteLink) {
  1446. inviteLink.value = roomUrl;
  1447. inviteLink.select();
  1448. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1449. }
  1450. }
  1451. /**
  1452. * Warning to the user that the conference window is about to be closed.
  1453. */
  1454. function closePageWarning() {
  1455. /*
  1456. FIXME: do we need a warning when the focus is a server-side one now ?
  1457. if (focus !== null)
  1458. return "You are the owner of this conference call and"
  1459. + " you are about to end it.";
  1460. else*/
  1461. return "You are about to leave this conversation.";
  1462. }
  1463. /**
  1464. * Resizes and repositions videos in full screen mode.
  1465. */
  1466. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1467. function () {
  1468. VideoLayout.resizeLargeVideoContainer();
  1469. VideoLayout.positionLarge();
  1470. isFullScreen = document.fullScreen ||
  1471. document.mozFullScreen ||
  1472. document.webkitIsFullScreen;
  1473. if (isFullScreen) {
  1474. setView("fullscreen");
  1475. }
  1476. else {
  1477. setView("default");
  1478. }
  1479. }
  1480. );
  1481. /**
  1482. * Sets the current view.
  1483. */
  1484. function setView(viewName) {
  1485. // if (viewName == "fullscreen") {
  1486. // document.getElementById('videolayout_fullscreen').disabled = false;
  1487. // document.getElementById('videolayout_default').disabled = true;
  1488. // }
  1489. // else {
  1490. // document.getElementById('videolayout_default').disabled = false;
  1491. // document.getElementById('videolayout_fullscreen').disabled = true;
  1492. // }
  1493. }
  1494. $(document).bind('error.jingle',
  1495. function (event, session, error)
  1496. {
  1497. console.error("Jingle error", error);
  1498. }
  1499. );
  1500. $(document).bind('fatalError.jingle',
  1501. function (event, session, error)
  1502. {
  1503. sessionTerminated = true;
  1504. connection.emuc.doLeave();
  1505. messageHandler.showError( "Sorry",
  1506. "Internal application error[setRemoteDescription]");
  1507. }
  1508. );
  1509. function onSelectedEndpointChanged(userJid)
  1510. {
  1511. console.log('selected endpoint changed: ', userJid);
  1512. if (_dataChannels && _dataChannels.length != 0)
  1513. {
  1514. _dataChannels.some(function (dataChannel) {
  1515. if (dataChannel.readyState == 'open')
  1516. {
  1517. dataChannel.send(JSON.stringify({
  1518. 'colibriClass': 'SelectedEndpointChangedEvent',
  1519. 'selectedEndpoint': (!userJid || userJid == null)
  1520. ? null : userJid
  1521. }));
  1522. return true;
  1523. }
  1524. });
  1525. }
  1526. }
  1527. $(document).bind("selectedendpointchanged", function(event, userJid) {
  1528. onSelectedEndpointChanged(userJid);
  1529. });
  1530. function onPinnedEndpointChanged(userJid)
  1531. {
  1532. console.log('pinned endpoint changed: ', userJid);
  1533. if (_dataChannels && _dataChannels.length != 0)
  1534. {
  1535. _dataChannels.some(function (dataChannel) {
  1536. if (dataChannel.readyState == 'open')
  1537. {
  1538. dataChannel.send(JSON.stringify({
  1539. 'colibriClass': 'PinnedEndpointChangedEvent',
  1540. 'pinnedEndpoint': (!userJid || userJid == null)
  1541. ? null : Strophe.getResourceFromJid(userJid)
  1542. }));
  1543. return true;
  1544. }
  1545. });
  1546. }
  1547. }
  1548. $(document).bind("pinnedendpointchanged", function(event, userJid) {
  1549. onPinnedEndpointChanged(userJid);
  1550. });
  1551. function callSipButtonClicked()
  1552. {
  1553. var defaultNumber
  1554. = config.defaultSipNumber ? config.defaultSipNumber : '';
  1555. messageHandler.openTwoButtonDialog(null,
  1556. '<h2>Enter SIP number</h2>' +
  1557. '<input id="sipNumber" type="text"' +
  1558. ' value="' + defaultNumber + '" autofocus>',
  1559. false,
  1560. "Dial",
  1561. function (e, v, m, f) {
  1562. if (v) {
  1563. var numberInput = document.getElementById('sipNumber');
  1564. if (numberInput.value) {
  1565. connection.rayo.dial(
  1566. numberInput.value, 'fromnumber', roomName);
  1567. }
  1568. }
  1569. },
  1570. function (event) {
  1571. document.getElementById('sipNumber').focus();
  1572. }
  1573. );
  1574. }
  1575. function hangup() {
  1576. disposeConference();
  1577. sessionTerminated = true;
  1578. connection.emuc.doLeave();
  1579. if(config.enableWelcomePage)
  1580. {
  1581. setTimeout(function()
  1582. {
  1583. window.localStorage.welcomePageDisabled = false;
  1584. window.location.pathname = "/";
  1585. }, 10000);
  1586. }
  1587. $.prompt("Session Terminated",
  1588. {
  1589. title: "You hung up the call",
  1590. persistent: true,
  1591. buttons: {
  1592. "Join again": true
  1593. },
  1594. closeText: '',
  1595. submit: function(event, value, message, formVals)
  1596. {
  1597. window.location.reload();
  1598. return false;
  1599. }
  1600. }
  1601. );
  1602. }
  1603. $(document).on('videomuted.muc', function(event, jid, value) {
  1604. if(mediaStreams[jid] && mediaStreams[jid][MediaStream.VIDEO_TYPE]) {
  1605. var stream = mediaStreams[jid][MediaStream.VIDEO_TYPE];
  1606. var isMuted = (value === "true");
  1607. if (isMuted != stream.muted) {
  1608. stream.muted = isMuted;
  1609. Avatar.showUserAvatar(jid, isMuted);
  1610. }
  1611. }
  1612. });