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.

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