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.

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