You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 51KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  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. if (v) {
  753. var lockKey = document.getElementById('lockKey');
  754. if (lockKey.value !== null) {
  755. setSharedKey(lockKey.value);
  756. connection.emuc.doJoin(jid, lockKey.value);
  757. }
  758. }
  759. },
  760. function (event) {
  761. document.getElementById('lockKey').focus();
  762. }
  763. );
  764. });
  765. $(document).bind('passwordrequired.main', function (event) {
  766. console.log('password is required');
  767. messageHandler.openTwoButtonDialog(null,
  768. '<h2>Password required</h2>' +
  769. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  770. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  771. true,
  772. "Ok",
  773. function (e, v, m, f) {
  774. if (v) {
  775. var username = document.getElementById('passwordrequired.username');
  776. var password = document.getElementById('passwordrequired.password');
  777. if (username.value !== null && password.value != null) {
  778. connect(username.value, password.value);
  779. }
  780. }
  781. },
  782. function (event) {
  783. document.getElementById('passwordrequired.username').focus();
  784. }
  785. );
  786. });
  787. /**
  788. * Checks if video identified by given src is desktop stream.
  789. * @param videoSrc eg.
  790. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  791. * @returns {boolean}
  792. */
  793. function isVideoSrcDesktop(videoSrc) {
  794. // FIXME: fix this mapping mess...
  795. // figure out if large video is desktop stream or just a camera
  796. var isDesktop = false;
  797. if (localVideoSrc === videoSrc) {
  798. // local video
  799. isDesktop = isUsingScreenStream;
  800. } else {
  801. // Do we have associations...
  802. var videoSsrc = videoSrcToSsrc[videoSrc];
  803. if (videoSsrc) {
  804. var videoType = ssrc2videoType[videoSsrc];
  805. if (videoType) {
  806. // Finally there...
  807. isDesktop = videoType === 'screen';
  808. } else {
  809. console.error("No video type for ssrc: " + videoSsrc);
  810. }
  811. } else {
  812. console.error("No ssrc for src: " + videoSrc);
  813. }
  814. }
  815. return isDesktop;
  816. }
  817. function getConferenceHandler() {
  818. return focus ? focus : activecall;
  819. }
  820. function toggleVideo() {
  821. buttonClick("#video", "icon-camera icon-camera-disabled");
  822. if (!(connection && connection.jingle.localVideo))
  823. return;
  824. var sess = getConferenceHandler();
  825. if (sess) {
  826. sess.toggleVideoMute(
  827. function (isMuted) {
  828. if (isMuted) {
  829. $('#video').removeClass("icon-camera");
  830. $('#video').addClass("icon-camera icon-camera-disabled");
  831. } else {
  832. $('#video').removeClass("icon-camera icon-camera-disabled");
  833. $('#video').addClass("icon-camera");
  834. }
  835. connection.emuc.addVideoInfoToPresence(isMuted);
  836. connection.emuc.sendPresence();
  837. }
  838. );
  839. }
  840. }
  841. /**
  842. * Mutes / unmutes audio for the local participant.
  843. */
  844. function toggleAudio() {
  845. if (!(connection && connection.jingle.localAudio)) {
  846. // We still click the button.
  847. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  848. return;
  849. }
  850. // It is not clear what is the right way to handle multiple tracks.
  851. // So at least make sure that they are all muted or all unmuted and
  852. // that we send presence just once.
  853. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  854. if (localAudioTracks.length > 0) {
  855. var audioEnabled = localAudioTracks[0].enabled;
  856. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  857. localAudioTracks[idx].enabled = !audioEnabled;
  858. }
  859. // isMuted is the opposite of audioEnabled
  860. connection.emuc.addAudioInfoToPresence(audioEnabled);
  861. connection.emuc.sendPresence();
  862. VideoLayout.showLocalAudioIndicator(audioEnabled);
  863. }
  864. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  865. }
  866. /**
  867. * Checks whether the audio is muted or not.
  868. * @returns {boolean} true if audio is muted and false if not.
  869. */
  870. function isAudioMuted()
  871. {
  872. var localAudio = connection.jingle.localAudio;
  873. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  874. if(localAudio.getAudioTracks()[idx].enabled === true)
  875. return false;
  876. }
  877. return true;
  878. }
  879. // Starts or stops the recording for the conference.
  880. function toggleRecording() {
  881. if (focus === null || focus.confid === null) {
  882. console.log('non-focus, or conference not yet organized: not enabling recording');
  883. return;
  884. }
  885. if (!recordingToken)
  886. {
  887. messageHandler.openTwoButtonDialog(null,
  888. '<h2>Enter recording token</h2>' +
  889. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  890. false,
  891. "Save",
  892. function (e, v, m, f) {
  893. if (v) {
  894. var token = document.getElementById('recordingToken');
  895. if (token.value) {
  896. setRecordingToken(Util.escapeHtml(token.value));
  897. toggleRecording();
  898. }
  899. }
  900. },
  901. function (event) {
  902. document.getElementById('recordingToken').focus();
  903. }
  904. );
  905. return;
  906. }
  907. var oldState = focus.recordingEnabled;
  908. Toolbar.toggleRecordingButtonState();
  909. focus.setRecording(!oldState,
  910. recordingToken,
  911. function (state) {
  912. console.log("New recording state: ", state);
  913. if (state == oldState) //failed to change, reset the token because it might have been wrong
  914. {
  915. Toolbar.toggleRecordingButtonState();
  916. setRecordingToken(null);
  917. }
  918. }
  919. );
  920. }
  921. /**
  922. * Returns an array of the video horizontal and vertical indents,
  923. * so that if fits its parent.
  924. *
  925. * @return an array with 2 elements, the horizontal indent and the vertical
  926. * indent
  927. */
  928. function getCameraVideoPosition(videoWidth,
  929. videoHeight,
  930. videoSpaceWidth,
  931. videoSpaceHeight) {
  932. // Parent height isn't completely calculated when we position the video in
  933. // full screen mode and this is why we use the screen height in this case.
  934. // Need to think it further at some point and implement it properly.
  935. var isFullScreen = document.fullScreen ||
  936. document.mozFullScreen ||
  937. document.webkitIsFullScreen;
  938. if (isFullScreen)
  939. videoSpaceHeight = window.innerHeight;
  940. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  941. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  942. return [horizontalIndent, verticalIndent];
  943. }
  944. /**
  945. * Returns an array of the video horizontal and vertical indents.
  946. * Centers horizontally and top aligns vertically.
  947. *
  948. * @return an array with 2 elements, the horizontal indent and the vertical
  949. * indent
  950. */
  951. function getDesktopVideoPosition(videoWidth,
  952. videoHeight,
  953. videoSpaceWidth,
  954. videoSpaceHeight) {
  955. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  956. var verticalIndent = 0;// Top aligned
  957. return [horizontalIndent, verticalIndent];
  958. }
  959. /**
  960. * Returns an array of the video dimensions, so that it covers the screen.
  961. * It leaves no empty areas, but some parts of the video might not be visible.
  962. *
  963. * @return an array with 2 elements, the video width and the video height
  964. */
  965. function getCameraVideoSize(videoWidth,
  966. videoHeight,
  967. videoSpaceWidth,
  968. videoSpaceHeight) {
  969. if (!videoWidth)
  970. videoWidth = currentVideoWidth;
  971. if (!videoHeight)
  972. videoHeight = currentVideoHeight;
  973. var aspectRatio = videoWidth / videoHeight;
  974. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  975. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  976. if (availableWidth / aspectRatio < videoSpaceHeight) {
  977. availableHeight = videoSpaceHeight;
  978. availableWidth = availableHeight * aspectRatio;
  979. }
  980. if (availableHeight * aspectRatio < videoSpaceWidth) {
  981. availableWidth = videoSpaceWidth;
  982. availableHeight = availableWidth / aspectRatio;
  983. }
  984. return [availableWidth, availableHeight];
  985. }
  986. $(document).ready(function () {
  987. document.title = brand.appName;
  988. if(APIConnector.isEnabled())
  989. APIConnector.init();
  990. if(config.enableWelcomePage && window.location.pathname == "/" &&
  991. (!window.localStorage.welcomePageDisabled
  992. || window.localStorage.welcomePageDisabled == "false"))
  993. {
  994. $("#videoconference_page").hide();
  995. $("#domain_name").text(
  996. window.location.protocol + "//" + window.location.host + "/");
  997. $("span[name='appName']").text(brand.appName);
  998. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  999. var leftWatermarkDiv
  1000. = $("#welcome_page_header div[class='watermark leftwatermark']");
  1001. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  1002. {
  1003. leftWatermarkDiv.css({display: 'block'});
  1004. leftWatermarkDiv.parent().get(0).href
  1005. = interfaceConfig.JITSI_WATERMARK_LINK;
  1006. }
  1007. }
  1008. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1009. var rightWatermarkDiv
  1010. = $("#welcome_page_header div[class='watermark rightwatermark']");
  1011. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  1012. rightWatermarkDiv.css({display: 'block'});
  1013. rightWatermarkDiv.parent().get(0).href
  1014. = interfaceConfig.BRAND_WATERMARK_LINK;
  1015. rightWatermarkDiv.get(0).style.backgroundImage
  1016. = "url(images/rightwatermark.png)";
  1017. }
  1018. }
  1019. if (interfaceConfig.SHOW_POWERED_BY) {
  1020. $("#welcome_page_header>a[class='poweredby']")
  1021. .css({display: 'block'});
  1022. }
  1023. function enter_room()
  1024. {
  1025. var val = $("#enter_room_field").val();
  1026. if(!val) {
  1027. val = $("#enter_room_field").attr("room_name");
  1028. }
  1029. if (val) {
  1030. window.location.pathname = "/" + val;
  1031. }
  1032. }
  1033. $("#enter_room_button").click(function()
  1034. {
  1035. enter_room();
  1036. });
  1037. $("#enter_room_field").keydown(function (event) {
  1038. if (event.keyCode === 13 /* enter */) {
  1039. enter_room();
  1040. }
  1041. });
  1042. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  1043. var updateTimeout;
  1044. var animateTimeout;
  1045. $("#reload_roomname").click(function () {
  1046. clearTimeout(updateTimeout);
  1047. clearTimeout(animateTimeout);
  1048. update_roomname();
  1049. });
  1050. $("#reload_roomname").show();
  1051. function animate(word) {
  1052. var currentVal = $("#enter_room_field").attr("placeholder");
  1053. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  1054. animateTimeout = setTimeout(function() {
  1055. animate(word.substring(1, word.length))
  1056. }, 70);
  1057. }
  1058. function update_roomname()
  1059. {
  1060. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1061. $("#enter_room_field").attr("room_name", word);
  1062. $("#enter_room_field").attr("placeholder", "");
  1063. clearTimeout(animateTimeout);
  1064. animate(word);
  1065. updateTimeout = setTimeout(update_roomname, 10000);
  1066. }
  1067. update_roomname();
  1068. }
  1069. $("#disable_welcome").click(function () {
  1070. window.localStorage.welcomePageDisabled
  1071. = $("#disable_welcome").is(":checked");
  1072. });
  1073. return;
  1074. }
  1075. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1076. var leftWatermarkDiv
  1077. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1078. leftWatermarkDiv.css({display: 'block'});
  1079. leftWatermarkDiv.parent().get(0).href
  1080. = interfaceConfig.JITSI_WATERMARK_LINK;
  1081. }
  1082. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1083. var rightWatermarkDiv
  1084. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1085. rightWatermarkDiv.css({display: 'block'});
  1086. rightWatermarkDiv.parent().get(0).href
  1087. = interfaceConfig.BRAND_WATERMARK_LINK;
  1088. rightWatermarkDiv.get(0).style.backgroundImage
  1089. = "url(images/rightwatermark.png)";
  1090. }
  1091. if (interfaceConfig.SHOW_POWERED_BY) {
  1092. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1093. }
  1094. $("#welcome_page").hide();
  1095. Chat.init();
  1096. $('body').popover({ selector: '[data-toggle=popover]',
  1097. trigger: 'click hover',
  1098. content: function() {
  1099. return this.getAttribute("content") +
  1100. KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
  1101. }
  1102. });
  1103. // Set the defaults for prompt dialogs.
  1104. jQuery.prompt.setDefaults({persistent: false});
  1105. // Set default desktop sharing method
  1106. setDesktopSharing(config.desktopSharing);
  1107. // Initialize Chrome extension inline installs
  1108. if (config.chromeExtensionId) {
  1109. initInlineInstalls();
  1110. }
  1111. // By default we use camera
  1112. getVideoSize = getCameraVideoSize;
  1113. getVideoPosition = getCameraVideoPosition;
  1114. VideoLayout.resizeLargeVideoContainer();
  1115. $(window).resize(function () {
  1116. VideoLayout.resizeLargeVideoContainer();
  1117. VideoLayout.positionLarge();
  1118. });
  1119. // Listen for large video size updates
  1120. document.getElementById('largeVideo')
  1121. .addEventListener('loadedmetadata', function (e) {
  1122. currentVideoWidth = this.videoWidth;
  1123. currentVideoHeight = this.videoHeight;
  1124. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  1125. });
  1126. if (!$('#settings').is(':visible')) {
  1127. console.log('init');
  1128. init();
  1129. } else {
  1130. loginInfo.onsubmit = function (e) {
  1131. if (e.preventDefault) e.preventDefault();
  1132. $('#settings').hide();
  1133. init();
  1134. };
  1135. }
  1136. });
  1137. $(window).bind('beforeunload', function () {
  1138. if (connection && connection.connected) {
  1139. // ensure signout
  1140. $.ajax({
  1141. type: 'POST',
  1142. url: config.bosh,
  1143. async: false,
  1144. cache: false,
  1145. contentType: 'application/xml',
  1146. data: "<body rid='" + (connection.rid || connection._proto.rid)
  1147. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  1148. + (connection.sid || connection._proto.sid)
  1149. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1150. success: function (data) {
  1151. console.log('signed out');
  1152. console.log(data);
  1153. },
  1154. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1155. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1156. }
  1157. });
  1158. }
  1159. disposeConference(true);
  1160. if(APIConnector.isEnabled())
  1161. APIConnector.dispose();
  1162. });
  1163. function disposeConference(onUnload) {
  1164. var handler = getConferenceHandler();
  1165. if (handler && handler.peerconnection) {
  1166. // FIXME: probably removing streams is not required and close() should
  1167. // be enough
  1168. if (connection.jingle.localAudio) {
  1169. handler.peerconnection.removeStream(connection.jingle.localAudio);
  1170. }
  1171. if (connection.jingle.localVideo) {
  1172. handler.peerconnection.removeStream(connection.jingle.localVideo);
  1173. }
  1174. handler.peerconnection.close();
  1175. }
  1176. stopRTPStatsCollector();
  1177. if(onUnload) {
  1178. stopLocalRtpStatsCollector();
  1179. }
  1180. focus = null;
  1181. activecall = null;
  1182. }
  1183. function dump(elem, filename) {
  1184. elem = elem.parentNode;
  1185. elem.download = filename || 'meetlog.json';
  1186. elem.href = 'data:application/json;charset=utf-8,\n';
  1187. var data = populateData();
  1188. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1189. return false;
  1190. }
  1191. /**
  1192. * Populates the log data
  1193. */
  1194. function populateData() {
  1195. var data = {};
  1196. if (connection.jingle) {
  1197. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1198. var session = connection.jingle.sessions[sid];
  1199. if (session.peerconnection && session.peerconnection.updateLog) {
  1200. // FIXME: should probably be a .dump call
  1201. data["jingle_" + session.sid] = {
  1202. updateLog: session.peerconnection.updateLog,
  1203. stats: session.peerconnection.stats,
  1204. url: window.location.href
  1205. };
  1206. }
  1207. });
  1208. }
  1209. var metadata = {};
  1210. metadata.time = new Date();
  1211. metadata.url = window.location.href;
  1212. metadata.ua = navigator.userAgent;
  1213. if (connection.logger) {
  1214. metadata.xmpp = connection.logger.log;
  1215. }
  1216. data.metadata = metadata;
  1217. return data;
  1218. }
  1219. /**
  1220. * Changes the style class of the element given by id.
  1221. */
  1222. function buttonClick(id, classname) {
  1223. $(id).toggleClass(classname); // add the class to the clicked element
  1224. }
  1225. /**
  1226. * Locks / unlocks the room.
  1227. */
  1228. function lockRoom(lock) {
  1229. if (lock)
  1230. connection.emuc.lockRoom(sharedKey);
  1231. else
  1232. connection.emuc.lockRoom('');
  1233. Toolbar.updateLockButton();
  1234. }
  1235. /**
  1236. * Sets the shared key.
  1237. */
  1238. function setSharedKey(sKey) {
  1239. sharedKey = sKey;
  1240. }
  1241. function setRecordingToken(token) {
  1242. recordingToken = token;
  1243. }
  1244. /**
  1245. * Updates the room invite url.
  1246. */
  1247. function updateRoomUrl(newRoomUrl) {
  1248. roomUrl = newRoomUrl;
  1249. // If the invite dialog has been already opened we update the information.
  1250. var inviteLink = document.getElementById('inviteLinkRef');
  1251. if (inviteLink) {
  1252. inviteLink.value = roomUrl;
  1253. inviteLink.select();
  1254. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1255. }
  1256. }
  1257. /**
  1258. * Warning to the user that the conference window is about to be closed.
  1259. */
  1260. function closePageWarning() {
  1261. if (focus !== null)
  1262. return "You are the owner of this conference call and"
  1263. + " you are about to end it.";
  1264. else
  1265. return "You are about to leave this conversation.";
  1266. }
  1267. /**
  1268. * Resizes and repositions videos in full screen mode.
  1269. */
  1270. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1271. function () {
  1272. VideoLayout.resizeLargeVideoContainer();
  1273. VideoLayout.positionLarge();
  1274. isFullScreen = document.fullScreen ||
  1275. document.mozFullScreen ||
  1276. document.webkitIsFullScreen;
  1277. if (isFullScreen) {
  1278. setView("fullscreen");
  1279. }
  1280. else {
  1281. setView("default");
  1282. }
  1283. }
  1284. );
  1285. /**
  1286. * Sets the current view.
  1287. */
  1288. function setView(viewName) {
  1289. // if (viewName == "fullscreen") {
  1290. // document.getElementById('videolayout_fullscreen').disabled = false;
  1291. // document.getElementById('videolayout_default').disabled = true;
  1292. // }
  1293. // else {
  1294. // document.getElementById('videolayout_default').disabled = false;
  1295. // document.getElementById('videolayout_fullscreen').disabled = true;
  1296. // }
  1297. }
  1298. function hangUp() {
  1299. if (connection && connection.connected) {
  1300. // ensure signout
  1301. $.ajax({
  1302. type: 'POST',
  1303. url: config.bosh,
  1304. async: false,
  1305. cache: false,
  1306. contentType: 'application/xml',
  1307. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1308. success: function (data) {
  1309. console.log('signed out');
  1310. console.log(data);
  1311. },
  1312. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1313. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1314. }
  1315. });
  1316. }
  1317. disposeConference(true);
  1318. }
  1319. $(document).bind('fatalError.jingle',
  1320. function (event, session, error)
  1321. {
  1322. sessionTerminated = true;
  1323. connection.emuc.doLeave();
  1324. messageHandler.showError( "Sorry",
  1325. "Your browser version is too old. Please update and try again...");
  1326. }
  1327. );
  1328. function onSelectedEndpointChanged(userJid)
  1329. {
  1330. console.log('selected endpoint changed: ', userJid);
  1331. if (_dataChannels && _dataChannels.length != 0)
  1332. {
  1333. _dataChannels.some(function (dataChannel) {
  1334. if (dataChannel.readyState == 'open')
  1335. {
  1336. dataChannel.send(JSON.stringify({
  1337. 'colibriClass': 'SelectedEndpointChangedEvent',
  1338. 'selectedEndpoint': (!userJid || userJid == null)
  1339. ? null : Strophe.getResourceFromJid(userJid)
  1340. }));
  1341. return true;
  1342. }
  1343. });
  1344. }
  1345. }
  1346. $(document).bind("selectedendpointchanged", function(event, userJid) {
  1347. onSelectedEndpointChanged(userJid);
  1348. });
  1349. function callSipButtonClicked()
  1350. {
  1351. var defaultNumber
  1352. = config.defaultSipNumber ? config.defaultSipNumber : '';
  1353. messageHandler.openTwoButtonDialog(null,
  1354. '<h2>Enter SIP number</h2>' +
  1355. '<input id="sipNumber" type="text"' +
  1356. ' value="' + defaultNumber + '" autofocus>',
  1357. false,
  1358. "Dial",
  1359. function (e, v, m, f) {
  1360. if (v) {
  1361. var numberInput = document.getElementById('sipNumber');
  1362. if (numberInput.value) {
  1363. connection.rayo.dial(
  1364. numberInput.value, 'fromnumber', roomName);
  1365. }
  1366. }
  1367. },
  1368. function (event) {
  1369. document.getElementById('sipNumber').focus();
  1370. }
  1371. );
  1372. }
  1373. function hangup() {
  1374. disposeConference();
  1375. sessionTerminated = true;
  1376. connection.emuc.doLeave();
  1377. if(config.enableWelcomePage)
  1378. {
  1379. setTimeout(function()
  1380. {
  1381. window.localStorage.welcomePageDisabled = false;
  1382. window.location.pathname = "/";
  1383. }, 10000);
  1384. }
  1385. $.prompt("Session Terminated",
  1386. {
  1387. title: "You hung up the call",
  1388. persistent: true,
  1389. buttons: {
  1390. "Join again": true
  1391. },
  1392. closeText: '',
  1393. submit: function(event, value, message, formVals)
  1394. {
  1395. window.location.reload();
  1396. return false;
  1397. }
  1398. }
  1399. );
  1400. }