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.

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