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

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