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