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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  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. // FIXME: default stream is added always with new focus
  313. // (to be investigated)
  314. && data.stream.id !== 'default') {
  315. console.error('can not associate stream',
  316. data.stream.id,
  317. 'with a participant');
  318. // We don't want to add it here since it will cause troubles
  319. return;
  320. }
  321. // FIXME: for the mixed ms we dont need a video -- currently
  322. container = document.createElement('span');
  323. container.id = 'mixedstream';
  324. container.className = 'videocontainer';
  325. remotes.appendChild(container);
  326. Util.playSoundNotification('userJoined');
  327. }
  328. var isVideo = data.stream.getVideoTracks().length > 0;
  329. if (container) {
  330. VideoLayout.addRemoteStreamElement( container,
  331. sid,
  332. data.stream,
  333. data.peerjid,
  334. thessrc);
  335. }
  336. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  337. if (isVideo &&
  338. data.peerjid && sess.peerjid === data.peerjid &&
  339. data.stream.getVideoTracks().length === 0 &&
  340. connection.jingle.localVideo.getVideoTracks().length > 0) {
  341. //
  342. window.setTimeout(function () {
  343. sendKeyframe(sess.peerconnection);
  344. }, 3000);
  345. }
  346. }
  347. /**
  348. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  349. * @param videoSrc the video "src" identifier.
  350. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  351. * belongs.
  352. */
  353. function getJidFromVideoSrc(videoSrc)
  354. {
  355. if (videoSrc === localVideoSrc)
  356. return connection.emuc.myroomjid;
  357. var ssrc = videoSrcToSsrc[videoSrc];
  358. if (!ssrc)
  359. {
  360. return null;
  361. }
  362. return ssrc2jid[ssrc];
  363. }
  364. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  365. function sendKeyframe(pc) {
  366. console.log('sendkeyframe', pc.iceConnectionState);
  367. if (pc.iceConnectionState !== 'connected') return; // safe...
  368. pc.setRemoteDescription(
  369. pc.remoteDescription,
  370. function () {
  371. pc.createAnswer(
  372. function (modifiedAnswer) {
  373. pc.setLocalDescription(
  374. modifiedAnswer,
  375. function () {
  376. // noop
  377. },
  378. function (error) {
  379. console.log('triggerKeyframe setLocalDescription failed', error);
  380. messageHandler.showError();
  381. }
  382. );
  383. },
  384. function (error) {
  385. console.log('triggerKeyframe createAnswer failed', error);
  386. messageHandler.showError();
  387. }
  388. );
  389. },
  390. function (error) {
  391. console.log('triggerKeyframe setRemoteDescription failed', error);
  392. messageHandler.showError();
  393. }
  394. );
  395. }
  396. // Really mute video, i.e. dont even send black frames
  397. function muteVideo(pc, unmute) {
  398. // FIXME: this probably needs another of those lovely state safeguards...
  399. // which checks for iceconn == connected and sigstate == stable
  400. pc.setRemoteDescription(pc.remoteDescription,
  401. function () {
  402. pc.createAnswer(
  403. function (answer) {
  404. var sdp = new SDP(answer.sdp);
  405. if (sdp.media.length > 1) {
  406. if (unmute)
  407. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  408. else
  409. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  410. sdp.raw = sdp.session + sdp.media.join('');
  411. answer.sdp = sdp.raw;
  412. }
  413. pc.setLocalDescription(answer,
  414. function () {
  415. console.log('mute SLD ok');
  416. },
  417. function (error) {
  418. console.log('mute SLD error');
  419. messageHandler.showError('Error',
  420. 'Oops! Something went wrong and we failed to ' +
  421. 'mute! (SLD Failure)');
  422. }
  423. );
  424. },
  425. function (error) {
  426. console.log(error);
  427. messageHandler.showError();
  428. }
  429. );
  430. },
  431. function (error) {
  432. console.log('muteVideo SRD error');
  433. messageHandler.showError('Error',
  434. 'Oops! Something went wrong and we failed to stop video!' +
  435. '(SRD Failure)');
  436. }
  437. );
  438. }
  439. /**
  440. * Callback for audio levels changed.
  441. * @param jid JID of the user
  442. * @param audioLevel the audio level value
  443. */
  444. function audioLevelUpdated(jid, audioLevel)
  445. {
  446. var resourceJid;
  447. if(jid === LocalStatsCollector.LOCAL_JID)
  448. {
  449. resourceJid = AudioLevels.LOCAL_LEVEL;
  450. if(isAudioMuted())
  451. {
  452. audioLevel = 0;
  453. }
  454. }
  455. else
  456. {
  457. resourceJid = Strophe.getResourceFromJid(jid);
  458. }
  459. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  460. }
  461. /**
  462. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  463. */
  464. function startRtpStatsCollector()
  465. {
  466. stopRTPStatsCollector();
  467. if (config.enableRtpStats)
  468. {
  469. statsCollector = new StatsCollector(
  470. getConferenceHandler().peerconnection, 200, audioLevelUpdated, 2000,
  471. ConnectionQuality.updateLocalStats);
  472. statsCollector.start();
  473. }
  474. }
  475. /**
  476. * Stops the {@link StatsCollector}.
  477. */
  478. function stopRTPStatsCollector()
  479. {
  480. if (statsCollector)
  481. {
  482. statsCollector.stop();
  483. statsCollector = null;
  484. ConnectionQuality.stopSendingStats();
  485. }
  486. }
  487. /**
  488. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  489. * @param stream the stream that will be used for collecting statistics.
  490. */
  491. function startLocalRtpStatsCollector(stream)
  492. {
  493. if(config.enableRtpStats)
  494. {
  495. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  496. localStatsCollector.start();
  497. }
  498. }
  499. /**
  500. * Stops the {@link LocalStatsCollector}.
  501. */
  502. function stopLocalRtpStatsCollector()
  503. {
  504. if(localStatsCollector)
  505. {
  506. localStatsCollector.stop();
  507. localStatsCollector = null;
  508. }
  509. }
  510. $(document).bind('callincoming.jingle', function (event, sid) {
  511. var sess = connection.jingle.sessions[sid];
  512. // TODO: do we check activecall == null?
  513. activecall = sess;
  514. startRtpStatsCollector();
  515. // Bind data channel listener in case we're a regular participant
  516. if (config.openSctp)
  517. {
  518. bindDataChannelListener(sess.peerconnection);
  519. }
  520. // TODO: check affiliation and/or role
  521. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  522. sess.usedrip = true; // not-so-naive trickle ice
  523. sess.sendAnswer();
  524. sess.accept();
  525. });
  526. $(document).bind('conferenceCreated.jingle', function (event, focus)
  527. {
  528. startRtpStatsCollector();
  529. });
  530. $(document).bind('conferenceCreated.jingle', function (event, focus)
  531. {
  532. // Bind data channel listener in case we're the focus
  533. if (config.openSctp)
  534. {
  535. bindDataChannelListener(focus.peerconnection);
  536. }
  537. });
  538. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  539. // put our ssrcs into presence so other clients can identify our stream
  540. var sess = connection.jingle.sessions[sid];
  541. var newssrcs = [];
  542. var media = simulcast.parseMedia(sess.peerconnection.localDescription);
  543. media.forEach(function (media) {
  544. // TODO(gp) maybe exclude FID streams?
  545. Object.keys(media.sources).forEach(function(ssrc) {
  546. newssrcs.push({
  547. 'ssrc': ssrc,
  548. 'type': media.type,
  549. 'direction': media.direction
  550. });
  551. });
  552. });
  553. console.log('new ssrcs', newssrcs);
  554. // Have to clear presence map to get rid of removed streams
  555. connection.emuc.clearPresenceMedia();
  556. if (newssrcs.length > 0) {
  557. for (var i = 1; i <= newssrcs.length; i ++) {
  558. // Change video type to screen
  559. if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
  560. newssrcs[i-1].type = 'screen';
  561. }
  562. connection.emuc.addMediaToPresence(i,
  563. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  564. }
  565. connection.emuc.sendPresence();
  566. }
  567. });
  568. $(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
  569. switch (session.peerconnection.iceConnectionState) {
  570. case 'checking':
  571. session.timeChecking = (new Date()).getTime();
  572. session.firstconnect = true;
  573. break;
  574. case 'completed': // on caller side
  575. case 'connected':
  576. if (session.firstconnect) {
  577. session.firstconnect = false;
  578. var metadata = {};
  579. metadata.setupTime = (new Date()).getTime() - session.timeChecking;
  580. session.peerconnection.getStats(function (res) {
  581. res.result().forEach(function (report) {
  582. if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
  583. metadata.localCandidateType = report.stat('googLocalCandidateType');
  584. metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
  585. // log pair as well so we can get nice pie charts
  586. metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
  587. if (report.stat('googRemoteAddress').indexOf('[') === 0) {
  588. metadata.ipv6 = true;
  589. }
  590. }
  591. });
  592. trackUsage('iceConnected', metadata);
  593. });
  594. }
  595. break;
  596. }
  597. });
  598. $(document).bind('joined.muc', function (event, jid, info) {
  599. updateRoomUrl(window.location.href);
  600. document.getElementById('localNick').appendChild(
  601. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  602. );
  603. // Add myself to the contact list.
  604. ContactList.addContact(jid);
  605. // Once we've joined the muc show the toolbar
  606. ToolbarToggler.showToolbar();
  607. var displayName = !config.displayJids
  608. ? info.displayName : Strophe.getResourceFromJid(jid);
  609. if (displayName)
  610. $(document).trigger('displaynamechanged',
  611. ['localVideoContainer', displayName + ' (me)']);
  612. });
  613. $(document).bind('entered.muc', function (event, jid, info, pres) {
  614. console.log('entered', jid, info);
  615. messageHandler.notify(info.displayName || 'Somebody',
  616. 'connected',
  617. 'connected');
  618. if (Strophe.getResourceFromJid(jid).indexOf('focus') != -1)
  619. {
  620. focusJid = jid;
  621. console.info("Ignore focus " + jid);
  622. return;
  623. }
  624. // Add Peer's container
  625. VideoLayout.ensurePeerContainerExists(jid);
  626. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantJoined"))
  627. {
  628. APIConnector.triggerEvent("participantJoined",{jid: jid});
  629. }
  630. /*if (focus !== null) {
  631. // FIXME: this should prepare the video
  632. if (focus.confid === null) {
  633. console.log('make new conference with', jid);
  634. focus.makeConference(Object.keys(connection.emuc.members),
  635. function(error) {
  636. connection.emuc.addBridgeIsDownToPresence();
  637. connection.emuc.sendPresence();
  638. }
  639. );
  640. Toolbar.showRecordingButton(true);
  641. } else {
  642. console.log('invite', jid, 'into conference');
  643. focus.addNewParticipant(jid);
  644. }
  645. }*/
  646. });
  647. $(document).bind('left.muc', function (event, jid) {
  648. console.log('left.muc', jid);
  649. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  650. '>.displayname').text();
  651. messageHandler.notify(displayName || 'Somebody',
  652. 'disconnected',
  653. 'disconnected');
  654. // Need to call this with a slight delay, otherwise the element couldn't be
  655. // found for some reason.
  656. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  657. window.setTimeout(function () {
  658. var container = document.getElementById(
  659. 'participant_' + Strophe.getResourceFromJid(jid));
  660. if (container) {
  661. VideoLayout.removeConnectionIndicator(jid);
  662. // hide here, wait for video to close before removing
  663. $(container).hide();
  664. VideoLayout.resizeThumbnails();
  665. }
  666. }, 10);
  667. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantLeft"))
  668. {
  669. APIConnector.triggerEvent("participantLeft",{jid: jid});
  670. }
  671. // Unlock large video
  672. if (focusedVideoSrc)
  673. {
  674. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  675. {
  676. console.info("Focused video owner has left the conference");
  677. focusedVideoSrc = null;
  678. }
  679. }
  680. connection.jingle.terminateByJid(jid);
  681. if (connection.emuc.getPrezi(jid)) {
  682. $(document).trigger('presentationremoved.muc',
  683. [jid, connection.emuc.getPrezi(jid)]);
  684. }
  685. });
  686. $(document).bind('presence.muc', function (event, jid, info, pres) {
  687. // Remove old ssrcs coming from the jid
  688. Object.keys(ssrc2jid).forEach(function (ssrc) {
  689. if (ssrc2jid[ssrc] == jid) {
  690. delete ssrc2jid[ssrc];
  691. }
  692. if (ssrc2videoType[ssrc] == jid) {
  693. delete ssrc2videoType[ssrc];
  694. }
  695. });
  696. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  697. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  698. var ssrcV = ssrc.getAttribute('ssrc');
  699. ssrc2jid[ssrcV] = jid;
  700. var type = ssrc.getAttribute('type');
  701. ssrc2videoType[ssrcV] = type;
  702. // might need to update the direction if participant just went from sendrecv to recvonly
  703. if (type === 'video' || type === 'screen') {
  704. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  705. switch (ssrc.getAttribute('direction')) {
  706. case 'sendrecv':
  707. el.show();
  708. break;
  709. case 'recvonly':
  710. el.hide();
  711. // FIXME: Check if we have to change large video
  712. //VideoLayout.updateLargeVideo(el);
  713. break;
  714. }
  715. }
  716. });
  717. var displayName = !config.displayJids
  718. ? info.displayName : Strophe.getResourceFromJid(jid);
  719. if (displayName && displayName.length > 0)
  720. $(document).trigger('displaynamechanged',
  721. [jid, displayName]);
  722. if (Strophe.getResourceFromJid(jid).indexOf('focus') != -1)
  723. {
  724. console.info("Ignore focus");
  725. return;
  726. }
  727. /*if (focus !== null && info.displayName !== null) {
  728. focus.setEndpointDisplayName(jid, info.displayName);
  729. }*/
  730. //check if the video bridge is available
  731. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  732. bridgeIsDown = true;
  733. messageHandler.showError("Error",
  734. "Jitsi Videobridge is currently unavailable. Please try again later!");
  735. }
  736. });
  737. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  738. VideoLayout.setPresenceStatus(
  739. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  740. });
  741. $(document).bind('kicked.muc', function (event, jid) {
  742. console.info(jid + " has been kicked from MUC!");
  743. if (connection.emuc.myroomjid === jid) {
  744. sessionTerminated = true;
  745. disposeConference(false);
  746. connection.emuc.doLeave();
  747. messageHandler.openMessageDialog("Session Terminated",
  748. "Ouch! You have been kicked out of the meet!");
  749. }
  750. });
  751. $(document).bind('passwordrequired.muc', function (event, jid) {
  752. console.log('on password required', jid);
  753. // password is required
  754. Toolbar.lockLockButton();
  755. messageHandler.openTwoButtonDialog(null,
  756. '<h2>Password required</h2>' +
  757. '<input id="lockKey" type="text" placeholder="password" autofocus>',
  758. true,
  759. "Ok",
  760. function (e, v, m, f) {},
  761. function (event) {
  762. document.getElementById('lockKey').focus();
  763. },
  764. function (e, v, m, f) {
  765. if (v) {
  766. var lockKey = document.getElementById('lockKey');
  767. if (lockKey.value !== null) {
  768. setSharedKey(lockKey.value);
  769. connection.emuc.doJoin(jid, lockKey.value);
  770. }
  771. }
  772. }
  773. );
  774. });
  775. $(document).bind('passwordrequired.main', function (event) {
  776. console.log('password is required');
  777. messageHandler.openTwoButtonDialog(null,
  778. '<h2>Password required</h2>' +
  779. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  780. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  781. true,
  782. "Ok",
  783. function (e, v, m, f) {
  784. if (v) {
  785. var username = document.getElementById('passwordrequired.username');
  786. var password = document.getElementById('passwordrequired.password');
  787. if (username.value !== null && password.value != null) {
  788. connect(username.value, password.value);
  789. }
  790. }
  791. },
  792. function (event) {
  793. document.getElementById('passwordrequired.username').focus();
  794. }
  795. );
  796. });
  797. /**
  798. * Checks if video identified by given src is desktop stream.
  799. * @param videoSrc eg.
  800. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  801. * @returns {boolean}
  802. */
  803. function isVideoSrcDesktop(videoSrc) {
  804. // FIXME: fix this mapping mess...
  805. // figure out if large video is desktop stream or just a camera
  806. var isDesktop = false;
  807. if (localVideoSrc === videoSrc) {
  808. // local video
  809. isDesktop = isUsingScreenStream;
  810. } else {
  811. // Do we have associations...
  812. var videoSsrc = videoSrcToSsrc[videoSrc];
  813. if (videoSsrc) {
  814. var videoType = ssrc2videoType[videoSsrc];
  815. if (videoType) {
  816. // Finally there...
  817. isDesktop = videoType === 'screen';
  818. } else {
  819. console.error("No video type for ssrc: " + videoSsrc);
  820. }
  821. } else {
  822. console.error("No ssrc for src: " + videoSrc);
  823. }
  824. }
  825. return isDesktop;
  826. }
  827. function getConferenceHandler() {
  828. return activecall;
  829. }
  830. function toggleVideo() {
  831. buttonClick("#video", "icon-camera icon-camera-disabled");
  832. if (!(connection && connection.jingle.localVideo))
  833. return;
  834. var sess = getConferenceHandler();
  835. if (sess) {
  836. sess.toggleVideoMute(
  837. function (isMuted) {
  838. if (isMuted) {
  839. $('#video').removeClass("icon-camera");
  840. $('#video').addClass("icon-camera icon-camera-disabled");
  841. } else {
  842. $('#video').removeClass("icon-camera icon-camera-disabled");
  843. $('#video').addClass("icon-camera");
  844. }
  845. connection.emuc.addVideoInfoToPresence(isMuted);
  846. connection.emuc.sendPresence();
  847. }
  848. );
  849. }
  850. }
  851. /**
  852. * Mutes / unmutes audio for the local participant.
  853. */
  854. function toggleAudio() {
  855. if (!(connection && connection.jingle.localAudio)) {
  856. // We still click the button.
  857. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  858. return;
  859. }
  860. // It is not clear what is the right way to handle multiple tracks.
  861. // So at least make sure that they are all muted or all unmuted and
  862. // that we send presence just once.
  863. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  864. if (localAudioTracks.length > 0) {
  865. var audioEnabled = localAudioTracks[0].enabled;
  866. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  867. localAudioTracks[idx].enabled = !audioEnabled;
  868. }
  869. // isMuted is the opposite of audioEnabled
  870. connection.emuc.addAudioInfoToPresence(audioEnabled);
  871. connection.emuc.sendPresence();
  872. VideoLayout.showLocalAudioIndicator(audioEnabled);
  873. }
  874. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  875. }
  876. /**
  877. * Checks whether the audio is muted or not.
  878. * @returns {boolean} true if audio is muted and false if not.
  879. */
  880. function isAudioMuted()
  881. {
  882. var localAudio = connection.jingle.localAudio;
  883. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  884. if(localAudio.getAudioTracks()[idx].enabled === true)
  885. return false;
  886. }
  887. return true;
  888. }
  889. // Starts or stops the recording for the conference.
  890. function toggleRecording() {
  891. Recording.toggleRecording();
  892. }
  893. /**
  894. * Returns an array of the video horizontal and vertical indents,
  895. * so that if fits its parent.
  896. *
  897. * @return an array with 2 elements, the horizontal indent and the vertical
  898. * indent
  899. */
  900. function getCameraVideoPosition(videoWidth,
  901. videoHeight,
  902. videoSpaceWidth,
  903. videoSpaceHeight) {
  904. // Parent height isn't completely calculated when we position the video in
  905. // full screen mode and this is why we use the screen height in this case.
  906. // Need to think it further at some point and implement it properly.
  907. var isFullScreen = document.fullScreen ||
  908. document.mozFullScreen ||
  909. document.webkitIsFullScreen;
  910. if (isFullScreen)
  911. videoSpaceHeight = window.innerHeight;
  912. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  913. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  914. return [horizontalIndent, verticalIndent];
  915. }
  916. /**
  917. * Returns an array of the video horizontal and vertical indents.
  918. * Centers horizontally and top aligns vertically.
  919. *
  920. * @return an array with 2 elements, the horizontal indent and the vertical
  921. * indent
  922. */
  923. function getDesktopVideoPosition(videoWidth,
  924. videoHeight,
  925. videoSpaceWidth,
  926. videoSpaceHeight) {
  927. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  928. var verticalIndent = 0;// Top aligned
  929. return [horizontalIndent, verticalIndent];
  930. }
  931. /**
  932. * Returns an array of the video dimensions, so that it covers the screen.
  933. * It leaves no empty areas, but some parts of the video might not be visible.
  934. *
  935. * @return an array with 2 elements, the video width and the video height
  936. */
  937. function getCameraVideoSize(videoWidth,
  938. videoHeight,
  939. videoSpaceWidth,
  940. videoSpaceHeight) {
  941. if (!videoWidth)
  942. videoWidth = currentVideoWidth;
  943. if (!videoHeight)
  944. videoHeight = currentVideoHeight;
  945. var aspectRatio = videoWidth / videoHeight;
  946. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  947. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  948. if (availableWidth / aspectRatio < videoSpaceHeight) {
  949. availableHeight = videoSpaceHeight;
  950. availableWidth = availableHeight * aspectRatio;
  951. }
  952. if (availableHeight * aspectRatio < videoSpaceWidth) {
  953. availableWidth = videoSpaceWidth;
  954. availableHeight = availableWidth / aspectRatio;
  955. }
  956. return [availableWidth, availableHeight];
  957. }
  958. $(document).ready(function () {
  959. document.title = interfaceConfig.APP_NAME;
  960. if(APIConnector.isEnabled())
  961. APIConnector.init();
  962. if(config.enableWelcomePage && window.location.pathname == "/" &&
  963. (!window.localStorage.welcomePageDisabled
  964. || window.localStorage.welcomePageDisabled == "false"))
  965. {
  966. $("#videoconference_page").hide();
  967. $("#domain_name").text(
  968. window.location.protocol + "//" + window.location.host + "/");
  969. $("span[name='appName']").text(interfaceConfig.APP_NAME);
  970. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  971. var leftWatermarkDiv
  972. = $("#welcome_page_header div[class='watermark leftwatermark']");
  973. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  974. {
  975. leftWatermarkDiv.css({display: 'block'});
  976. leftWatermarkDiv.parent().get(0).href
  977. = interfaceConfig.JITSI_WATERMARK_LINK;
  978. }
  979. }
  980. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  981. var rightWatermarkDiv
  982. = $("#welcome_page_header div[class='watermark rightwatermark']");
  983. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  984. rightWatermarkDiv.css({display: 'block'});
  985. rightWatermarkDiv.parent().get(0).href
  986. = interfaceConfig.BRAND_WATERMARK_LINK;
  987. rightWatermarkDiv.get(0).style.backgroundImage
  988. = "url(images/rightwatermark.png)";
  989. }
  990. }
  991. if (interfaceConfig.SHOW_POWERED_BY) {
  992. $("#welcome_page_header>a[class='poweredby']")
  993. .css({display: 'block'});
  994. }
  995. function enter_room()
  996. {
  997. var val = $("#enter_room_field").val();
  998. if(!val) {
  999. val = $("#enter_room_field").attr("room_name");
  1000. }
  1001. if (val) {
  1002. window.location.pathname = "/" + val;
  1003. }
  1004. }
  1005. $("#enter_room_button").click(function()
  1006. {
  1007. enter_room();
  1008. });
  1009. $("#enter_room_field").keydown(function (event) {
  1010. if (event.keyCode === 13 /* enter */) {
  1011. enter_room();
  1012. }
  1013. });
  1014. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  1015. var updateTimeout;
  1016. var animateTimeout;
  1017. $("#reload_roomname").click(function () {
  1018. clearTimeout(updateTimeout);
  1019. clearTimeout(animateTimeout);
  1020. update_roomname();
  1021. });
  1022. $("#reload_roomname").show();
  1023. function animate(word) {
  1024. var currentVal = $("#enter_room_field").attr("placeholder");
  1025. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  1026. animateTimeout = setTimeout(function() {
  1027. animate(word.substring(1, word.length))
  1028. }, 70);
  1029. }
  1030. function update_roomname()
  1031. {
  1032. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1033. $("#enter_room_field").attr("room_name", word);
  1034. $("#enter_room_field").attr("placeholder", "");
  1035. clearTimeout(animateTimeout);
  1036. animate(word);
  1037. updateTimeout = setTimeout(update_roomname, 10000);
  1038. }
  1039. update_roomname();
  1040. }
  1041. $("#disable_welcome").click(function () {
  1042. window.localStorage.welcomePageDisabled
  1043. = $("#disable_welcome").is(":checked");
  1044. });
  1045. return;
  1046. }
  1047. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1048. var leftWatermarkDiv
  1049. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1050. leftWatermarkDiv.css({display: 'block'});
  1051. leftWatermarkDiv.parent().get(0).href
  1052. = interfaceConfig.JITSI_WATERMARK_LINK;
  1053. }
  1054. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1055. var rightWatermarkDiv
  1056. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1057. rightWatermarkDiv.css({display: 'block'});
  1058. rightWatermarkDiv.parent().get(0).href
  1059. = interfaceConfig.BRAND_WATERMARK_LINK;
  1060. rightWatermarkDiv.get(0).style.backgroundImage
  1061. = "url(images/rightwatermark.png)";
  1062. }
  1063. if (interfaceConfig.SHOW_POWERED_BY) {
  1064. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1065. }
  1066. $("#welcome_page").hide();
  1067. Chat.init();
  1068. $('body').popover({ selector: '[data-toggle=popover]',
  1069. trigger: 'click hover',
  1070. content: function() {
  1071. return this.getAttribute("content") +
  1072. KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
  1073. }
  1074. });
  1075. Moderator.init();
  1076. // Set the defaults for prompt dialogs.
  1077. jQuery.prompt.setDefaults({persistent: false});
  1078. // Set default desktop sharing method
  1079. setDesktopSharing(config.desktopSharing);
  1080. // Initialize Chrome extension inline installs
  1081. if (config.chromeExtensionId) {
  1082. initInlineInstalls();
  1083. }
  1084. // By default we use camera
  1085. getVideoSize = getCameraVideoSize;
  1086. getVideoPosition = getCameraVideoPosition;
  1087. VideoLayout.resizeLargeVideoContainer();
  1088. $(window).resize(function () {
  1089. VideoLayout.resizeLargeVideoContainer();
  1090. VideoLayout.positionLarge();
  1091. });
  1092. // Listen for large video size updates
  1093. document.getElementById('largeVideo')
  1094. .addEventListener('loadedmetadata', function (e) {
  1095. currentVideoWidth = this.videoWidth;
  1096. currentVideoHeight = this.videoHeight;
  1097. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  1098. });
  1099. if (!$('#settings').is(':visible')) {
  1100. console.log('init');
  1101. init();
  1102. } else {
  1103. loginInfo.onsubmit = function (e) {
  1104. if (e.preventDefault) e.preventDefault();
  1105. $('#settings').hide();
  1106. init();
  1107. };
  1108. }
  1109. toastr.options = {
  1110. "closeButton": true,
  1111. "debug": false,
  1112. "positionClass": "notification-bottom-right",
  1113. "onclick": null,
  1114. "showDuration": "300",
  1115. "hideDuration": "1000",
  1116. "timeOut": "2000",
  1117. "extendedTimeOut": "1000",
  1118. "showEasing": "swing",
  1119. "hideEasing": "linear",
  1120. "showMethod": "fadeIn",
  1121. "hideMethod": "fadeOut",
  1122. "reposition": function() {
  1123. if(Chat.isVisible() || ContactList.isVisible()) {
  1124. $("#toast-container").addClass("toast-bottom-right-center");
  1125. } else {
  1126. $("#toast-container").removeClass("toast-bottom-right-center");
  1127. }
  1128. },
  1129. "newestOnTop": false
  1130. }
  1131. });
  1132. $(window).bind('beforeunload', function () {
  1133. if (connection && connection.connected) {
  1134. // ensure signout
  1135. $.ajax({
  1136. type: 'POST',
  1137. url: config.bosh,
  1138. async: false,
  1139. cache: false,
  1140. contentType: 'application/xml',
  1141. data: "<body rid='" + (connection.rid || connection._proto.rid)
  1142. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  1143. + (connection.sid || connection._proto.sid)
  1144. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1145. success: function (data) {
  1146. console.log('signed out');
  1147. console.log(data);
  1148. },
  1149. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1150. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1151. }
  1152. });
  1153. }
  1154. disposeConference(true);
  1155. if(APIConnector.isEnabled())
  1156. APIConnector.dispose();
  1157. });
  1158. function disposeConference(onUnload) {
  1159. var handler = getConferenceHandler();
  1160. if (handler && handler.peerconnection) {
  1161. // FIXME: probably removing streams is not required and close() should
  1162. // be enough
  1163. if (connection.jingle.localAudio) {
  1164. handler.peerconnection.removeStream(connection.jingle.localAudio);
  1165. }
  1166. if (connection.jingle.localVideo) {
  1167. handler.peerconnection.removeStream(connection.jingle.localVideo);
  1168. }
  1169. handler.peerconnection.close();
  1170. }
  1171. stopRTPStatsCollector();
  1172. if(onUnload) {
  1173. stopLocalRtpStatsCollector();
  1174. }
  1175. activecall = null;
  1176. }
  1177. function dump(elem, filename) {
  1178. elem = elem.parentNode;
  1179. elem.download = filename || 'meetlog.json';
  1180. elem.href = 'data:application/json;charset=utf-8,\n';
  1181. var data = populateData();
  1182. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1183. return false;
  1184. }
  1185. /**
  1186. * Populates the log data
  1187. */
  1188. function populateData() {
  1189. var data = {};
  1190. if (connection.jingle) {
  1191. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1192. var session = connection.jingle.sessions[sid];
  1193. if (session.peerconnection && session.peerconnection.updateLog) {
  1194. // FIXME: should probably be a .dump call
  1195. data["jingle_" + session.sid] = {
  1196. updateLog: session.peerconnection.updateLog,
  1197. stats: session.peerconnection.stats,
  1198. url: window.location.href
  1199. };
  1200. }
  1201. });
  1202. }
  1203. var metadata = {};
  1204. metadata.time = new Date();
  1205. metadata.url = window.location.href;
  1206. metadata.ua = navigator.userAgent;
  1207. if (connection.logger) {
  1208. metadata.xmpp = connection.logger.log;
  1209. }
  1210. data.metadata = metadata;
  1211. return data;
  1212. }
  1213. /**
  1214. * Changes the style class of the element given by id.
  1215. */
  1216. function buttonClick(id, classname) {
  1217. $(id).toggleClass(classname); // add the class to the clicked element
  1218. }
  1219. /**
  1220. * Locks / unlocks the room.
  1221. */
  1222. function lockRoom(lock) {
  1223. if (lock)
  1224. connection.emuc.lockRoom(sharedKey);
  1225. else
  1226. connection.emuc.lockRoom('');
  1227. }
  1228. /**
  1229. * Sets the shared key.
  1230. */
  1231. function setSharedKey(sKey) {
  1232. sharedKey = sKey;
  1233. }
  1234. /**
  1235. * Updates the room invite url.
  1236. */
  1237. function updateRoomUrl(newRoomUrl) {
  1238. roomUrl = newRoomUrl;
  1239. // If the invite dialog has been already opened we update the information.
  1240. var inviteLink = document.getElementById('inviteLinkRef');
  1241. if (inviteLink) {
  1242. inviteLink.value = roomUrl;
  1243. inviteLink.select();
  1244. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1245. }
  1246. }
  1247. /**
  1248. * Warning to the user that the conference window is about to be closed.
  1249. */
  1250. function closePageWarning() {
  1251. /*
  1252. FIXME: do we need a warning when the focus is a server-side one now ?
  1253. if (focus !== null)
  1254. return "You are the owner of this conference call and"
  1255. + " you are about to end it.";
  1256. else*/
  1257. return "You are about to leave this conversation.";
  1258. }
  1259. /**
  1260. * Resizes and repositions videos in full screen mode.
  1261. */
  1262. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1263. function () {
  1264. VideoLayout.resizeLargeVideoContainer();
  1265. VideoLayout.positionLarge();
  1266. isFullScreen = document.fullScreen ||
  1267. document.mozFullScreen ||
  1268. document.webkitIsFullScreen;
  1269. if (isFullScreen) {
  1270. setView("fullscreen");
  1271. }
  1272. else {
  1273. setView("default");
  1274. }
  1275. }
  1276. );
  1277. /**
  1278. * Sets the current view.
  1279. */
  1280. function setView(viewName) {
  1281. // if (viewName == "fullscreen") {
  1282. // document.getElementById('videolayout_fullscreen').disabled = false;
  1283. // document.getElementById('videolayout_default').disabled = true;
  1284. // }
  1285. // else {
  1286. // document.getElementById('videolayout_default').disabled = false;
  1287. // document.getElementById('videolayout_fullscreen').disabled = true;
  1288. // }
  1289. }
  1290. $(document).bind('error.jingle',
  1291. function (event, session, error)
  1292. {
  1293. console.error("Jingle error", error);
  1294. }
  1295. );
  1296. $(document).bind('fatalError.jingle',
  1297. function (event, session, error)
  1298. {
  1299. sessionTerminated = true;
  1300. connection.emuc.doLeave();
  1301. messageHandler.showError( "Sorry",
  1302. "Your browser version is too old. Please update and try again...");
  1303. }
  1304. );
  1305. function onSelectedEndpointChanged(userJid)
  1306. {
  1307. console.log('selected endpoint changed: ', userJid);
  1308. if (_dataChannels && _dataChannels.length != 0)
  1309. {
  1310. _dataChannels.some(function (dataChannel) {
  1311. if (dataChannel.readyState == 'open')
  1312. {
  1313. dataChannel.send(JSON.stringify({
  1314. 'colibriClass': 'SelectedEndpointChangedEvent',
  1315. 'selectedEndpoint': (!userJid || userJid == null)
  1316. ? null : Strophe.getResourceFromJid(userJid)
  1317. }));
  1318. return true;
  1319. }
  1320. });
  1321. }
  1322. }
  1323. $(document).bind("selectedendpointchanged", function(event, userJid) {
  1324. onSelectedEndpointChanged(userJid);
  1325. });
  1326. function onPinnedEndpointChanged(userJid)
  1327. {
  1328. console.log('pinned endpoint changed: ', userJid);
  1329. if (_dataChannels && _dataChannels.length != 0)
  1330. {
  1331. _dataChannels.some(function (dataChannel) {
  1332. if (dataChannel.readyState == 'open')
  1333. {
  1334. dataChannel.send(JSON.stringify({
  1335. 'colibriClass': 'PinnedEndpointChangedEvent',
  1336. 'pinnedEndpoint': (!userJid || userJid == null)
  1337. ? null : Strophe.getResourceFromJid(userJid)
  1338. }));
  1339. return true;
  1340. }
  1341. });
  1342. }
  1343. }
  1344. $(document).bind("pinnedendpointchanged", function(event, userJid) {
  1345. onPinnedEndpointChanged(userJid);
  1346. });
  1347. function callSipButtonClicked()
  1348. {
  1349. var defaultNumber
  1350. = config.defaultSipNumber ? config.defaultSipNumber : '';
  1351. messageHandler.openTwoButtonDialog(null,
  1352. '<h2>Enter SIP number</h2>' +
  1353. '<input id="sipNumber" type="text"' +
  1354. ' value="' + defaultNumber + '" autofocus>',
  1355. false,
  1356. "Dial",
  1357. function (e, v, m, f) {
  1358. if (v) {
  1359. var numberInput = document.getElementById('sipNumber');
  1360. if (numberInput.value) {
  1361. connection.rayo.dial(
  1362. numberInput.value, 'fromnumber', roomName);
  1363. }
  1364. }
  1365. },
  1366. function (event) {
  1367. document.getElementById('sipNumber').focus();
  1368. }
  1369. );
  1370. }
  1371. function hangup() {
  1372. disposeConference();
  1373. sessionTerminated = true;
  1374. connection.emuc.doLeave();
  1375. if(config.enableWelcomePage)
  1376. {
  1377. setTimeout(function()
  1378. {
  1379. window.localStorage.welcomePageDisabled = false;
  1380. window.location.pathname = "/";
  1381. }, 10000);
  1382. }
  1383. $.prompt("Session Terminated",
  1384. {
  1385. title: "You hung up the call",
  1386. persistent: true,
  1387. buttons: {
  1388. "Join again": true
  1389. },
  1390. closeText: '',
  1391. submit: function(event, value, message, formVals)
  1392. {
  1393. window.location.reload();
  1394. return false;
  1395. }
  1396. }
  1397. );
  1398. }