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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var focus = null;
  5. var activecall = null;
  6. var RTC = null;
  7. var nickname = null;
  8. var sharedKey = '';
  9. var roomUrl = null;
  10. var ssrc2jid = {};
  11. /**
  12. * The stats collector that process stats data and triggers updates to app.js.
  13. * @type {StatsCollector}
  14. */
  15. var statsCollector = null;
  16. /**
  17. * The stats collector for the local stream.
  18. * @type {LocalStatsCollector}
  19. */
  20. var localStatsCollector = null;
  21. /**
  22. * Indicates whether ssrc is camera video or desktop stream.
  23. * FIXME: remove those maps
  24. */
  25. var ssrc2videoType = {};
  26. var videoSrcToSsrc = {};
  27. /**
  28. * Currently focused video "src"(displayed in large video).
  29. * @type {String}
  30. */
  31. var focusedVideoSrc = null;
  32. var mutedAudios = {};
  33. var localVideoSrc = null;
  34. var flipXLocalVideo = true;
  35. var isFullScreen = false;
  36. var toolbarTimeout = null;
  37. var currentVideoWidth = null;
  38. var currentVideoHeight = null;
  39. /**
  40. * Method used to calculate large video size.
  41. * @type {function ()}
  42. */
  43. var getVideoSize;
  44. /**
  45. * Method used to get large video position.
  46. * @type {function ()}
  47. */
  48. var getVideoPosition;
  49. /* window.onbeforeunload = closePageWarning; */
  50. var sessionTerminated = false;
  51. function init() {
  52. RTC = setupRTC();
  53. if (RTC === null) {
  54. window.location.href = 'webrtcrequired.html';
  55. return;
  56. } else if (RTC.browser !== 'chrome') {
  57. window.location.href = 'chromeonly.html';
  58. return;
  59. }
  60. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  61. if (nickname) {
  62. connection.emuc.addDisplayNameToPresence(nickname);
  63. }
  64. if (connection.disco) {
  65. // for chrome, add multistream cap
  66. }
  67. connection.jingle.pc_constraints = RTC.pc_constraints;
  68. if (config.useIPv6) {
  69. // https://code.google.com/p/webrtc/issues/detail?id=2828
  70. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  71. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  72. }
  73. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  74. connection.connect(jid, document.getElementById('password').value, function (status) {
  75. if (status === Strophe.Status.CONNECTED) {
  76. console.log('connected');
  77. if (config.useStunTurn) {
  78. connection.jingle.getStunAndTurnCredentials();
  79. }
  80. obtainAudioAndVideoPermissions(function () {
  81. getUserMediaWithConstraints(['audio'], audioStreamReady,
  82. function (error) {
  83. console.error('failed to obtain audio stream - stop', error);
  84. });
  85. });
  86. document.getElementById('connect').disabled = true;
  87. } else {
  88. console.log('status', status);
  89. }
  90. });
  91. }
  92. /**
  93. * HTTPS only:
  94. * We first ask for audio and video combined stream in order to get permissions and not to ask twice.
  95. * Then we dispose the stream and continue with separate audio, video streams(required for desktop sharing).
  96. */
  97. function obtainAudioAndVideoPermissions(callback) {
  98. // This makes sense only on https sites otherwise we'll be asked for permissions every time
  99. if (location.protocol !== 'https:') {
  100. callback();
  101. return;
  102. }
  103. // Get AV
  104. getUserMediaWithConstraints(
  105. ['audio', 'video'],
  106. function (avStream) {
  107. avStream.stop();
  108. callback();
  109. },
  110. function (error) {
  111. console.error('failed to obtain audio/video stream - stop', error);
  112. });
  113. }
  114. function audioStreamReady(stream) {
  115. VideoLayout.changeLocalAudio(stream);
  116. startLocalRtpStatsCollector(stream);
  117. if (RTC.browser !== 'firefox') {
  118. getUserMediaWithConstraints(['video'],
  119. videoStreamReady,
  120. videoStreamFailed,
  121. config.resolution || '360');
  122. } else {
  123. doJoin();
  124. }
  125. }
  126. function videoStreamReady(stream) {
  127. VideoLayout.changeLocalVideo(stream, true);
  128. doJoin();
  129. }
  130. function videoStreamFailed(error) {
  131. console.warn("Failed to obtain video stream - continue anyway", error);
  132. doJoin();
  133. }
  134. function doJoin() {
  135. var roomnode = null;
  136. var path = window.location.pathname;
  137. var roomjid;
  138. // determinde the room node from the url
  139. // TODO: just the roomnode or the whole bare jid?
  140. if (config.getroomnode && typeof config.getroomnode === 'function') {
  141. // custom function might be responsible for doing the pushstate
  142. roomnode = config.getroomnode(path);
  143. } else {
  144. /* fall back to default strategy
  145. * this is making assumptions about how the URL->room mapping happens.
  146. * It currently assumes deployment at root, with a rewrite like the
  147. * following one (for nginx):
  148. location ~ ^/([a-zA-Z0-9]+)$ {
  149. rewrite ^/(.*)$ / break;
  150. }
  151. */
  152. if (path.length > 1) {
  153. roomnode = path.substr(1).toLowerCase();
  154. } else {
  155. roomnode = Math.random().toString(36).substr(2, 20);
  156. window.history.pushState('VideoChat',
  157. 'Room: ' + roomnode, window.location.pathname + roomnode);
  158. }
  159. }
  160. roomjid = roomnode + '@' + config.hosts.muc;
  161. if (config.useNicks) {
  162. var nick = window.prompt('Your nickname (optional)');
  163. if (nick) {
  164. roomjid += '/' + nick;
  165. } else {
  166. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  167. }
  168. } else {
  169. roomjid += '/' + Strophe.getNodeFromJid(connection.jid).substr(0, 8);
  170. }
  171. connection.emuc.doJoin(roomjid);
  172. }
  173. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  174. function waitForRemoteVideo(selector, sid, ssrc) {
  175. if (selector.removed) {
  176. console.warn("media removed before had started", selector);
  177. return;
  178. }
  179. var sess = connection.jingle.sessions[sid];
  180. if (data.stream.id === 'mixedmslabel') return;
  181. var videoTracks = data.stream.getVideoTracks();
  182. // console.log("waiting..", videoTracks, selector[0]);
  183. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  184. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  185. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  186. // in order to get rid of too many maps
  187. if (ssrc) {
  188. videoSrcToSsrc[sel.attr('src')] = ssrc;
  189. } else {
  190. console.warn("No ssrc given for video", sel);
  191. }
  192. $(document).trigger('callactive.jingle', [selector, sid]);
  193. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  194. } else {
  195. setTimeout(function () { waitForRemoteVideo(selector, sid, ssrc); }, 250);
  196. }
  197. }
  198. var sess = connection.jingle.sessions[sid];
  199. var thessrc;
  200. // look up an associated JID for a stream id
  201. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  202. var ssrclines = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  203. ssrclines = ssrclines.filter(function (line) {
  204. return line.indexOf('mslabel:' + data.stream.label) !== -1;
  205. });
  206. if (ssrclines.length) {
  207. thessrc = ssrclines[0].substring(7).split(' ')[0];
  208. // ok to overwrite the one from focus? might save work in colibri.js
  209. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  210. if (ssrc2jid[thessrc]) {
  211. data.peerjid = ssrc2jid[thessrc];
  212. }
  213. }
  214. }
  215. var container;
  216. var remotes = document.getElementById('remoteVideos');
  217. if (data.peerjid) {
  218. VideoLayout.ensurePeerContainerExists(data.peerjid);
  219. container = document.getElementById(
  220. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  221. } else {
  222. if (data.stream.id !== 'mixedmslabel') {
  223. console.error( 'can not associate stream',
  224. data.stream.id,
  225. 'with a participant');
  226. // We don't want to add it here since it will cause troubles
  227. return;
  228. }
  229. // FIXME: for the mixed ms we dont need a video -- currently
  230. container = document.createElement('span');
  231. container.className = 'videocontainer';
  232. remotes.appendChild(container);
  233. Util.playSoundNotification('userJoined');
  234. }
  235. var isVideo = data.stream.getVideoTracks().length > 0;
  236. var vid = isVideo ? document.createElement('video') : document.createElement('audio');
  237. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' + data.stream.id;
  238. vid.id = id;
  239. vid.autoplay = true;
  240. vid.oncontextmenu = function () { return false; };
  241. container.appendChild(vid);
  242. // TODO: make mixedstream display:none via css?
  243. if (id.indexOf('mixedmslabel') !== -1) {
  244. container.id = 'mixedstream';
  245. $(container).hide();
  246. }
  247. var sel = $('#' + id);
  248. sel.hide();
  249. RTC.attachMediaStream(sel, data.stream);
  250. if (isVideo) {
  251. waitForRemoteVideo(sel, sid, thessrc);
  252. }
  253. data.stream.onended = function () {
  254. console.log('stream ended', this.id);
  255. // Mark video as removed to cancel waiting loop(if video is removed before has started)
  256. sel.removed = true;
  257. sel.remove();
  258. var audioCount = $('#' + container.id + '>audio').length;
  259. var videoCount = $('#' + container.id + '>video').length;
  260. if (!audioCount && !videoCount) {
  261. console.log("Remove whole user", container.id);
  262. // Remove whole container
  263. container.remove();
  264. Util.playSoundNotification('userLeft');
  265. VideoLayout.resizeThumbnails();
  266. }
  267. VideoLayout.checkChangeLargeVideo(vid.src);
  268. };
  269. // Add click handler
  270. sel.click(function () {
  271. VideoLayout.handleVideoThumbClicked(vid.src);
  272. });
  273. // Add hover handler
  274. $(container).hover(
  275. function() {
  276. VideoLayout.showDisplayName(container.id, true);
  277. },
  278. function() {
  279. var videoSrc = null;
  280. if ($('#' + container.id + '>video')
  281. && $('#' + container.id + '>video').length > 0) {
  282. videoSrc = $('#' + container.id + '>video').get(0).src;
  283. }
  284. // If the video has been "pinned" by the user we want to keep the
  285. // display name on place.
  286. if (focusedVideoSrc && focusedVideoSrc !== videoSrc
  287. || (!focusedVideoSrc
  288. && container.id
  289. !== VideoLayout.getActiveSpeakerContainerId()))
  290. VideoLayout.showDisplayName(container.id, false);
  291. }
  292. );
  293. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  294. if (isVideo &&
  295. data.peerjid && sess.peerjid === data.peerjid &&
  296. data.stream.getVideoTracks().length === 0 &&
  297. connection.jingle.localVideo.getVideoTracks().length > 0) {
  298. //
  299. window.setTimeout(function () {
  300. sendKeyframe(sess.peerconnection);
  301. }, 3000);
  302. }
  303. });
  304. /**
  305. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  306. * @param videoSrc the video "src" identifier.
  307. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  308. * belongs.
  309. */
  310. function getJidFromVideoSrc(videoSrc)
  311. {
  312. if (videoSrc === localVideoSrc)
  313. return connection.emuc.myroomjid;
  314. var ssrc = videoSrcToSsrc[videoSrc];
  315. if (!ssrc)
  316. {
  317. return null;
  318. }
  319. return ssrc2jid[ssrc];
  320. }
  321. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  322. function sendKeyframe(pc) {
  323. console.log('sendkeyframe', pc.iceConnectionState);
  324. if (pc.iceConnectionState !== 'connected') return; // safe...
  325. pc.setRemoteDescription(
  326. pc.remoteDescription,
  327. function () {
  328. pc.createAnswer(
  329. function (modifiedAnswer) {
  330. pc.setLocalDescription(
  331. modifiedAnswer,
  332. function () {
  333. // noop
  334. },
  335. function (error) {
  336. console.log('triggerKeyframe setLocalDescription failed', error);
  337. }
  338. );
  339. },
  340. function (error) {
  341. console.log('triggerKeyframe createAnswer failed', error);
  342. }
  343. );
  344. },
  345. function (error) {
  346. console.log('triggerKeyframe setRemoteDescription failed', error);
  347. }
  348. );
  349. }
  350. // Really mute video, i.e. dont even send black frames
  351. function muteVideo(pc, unmute) {
  352. // FIXME: this probably needs another of those lovely state safeguards...
  353. // which checks for iceconn == connected and sigstate == stable
  354. pc.setRemoteDescription(pc.remoteDescription,
  355. function () {
  356. pc.createAnswer(
  357. function (answer) {
  358. var sdp = new SDP(answer.sdp);
  359. if (sdp.media.length > 1) {
  360. if (unmute)
  361. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  362. else
  363. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  364. sdp.raw = sdp.session + sdp.media.join('');
  365. answer.sdp = sdp.raw;
  366. }
  367. pc.setLocalDescription(answer,
  368. function () {
  369. console.log('mute SLD ok');
  370. },
  371. function (error) {
  372. console.log('mute SLD error');
  373. }
  374. );
  375. },
  376. function (error) {
  377. console.log(error);
  378. }
  379. );
  380. },
  381. function (error) {
  382. console.log('muteVideo SRD error');
  383. }
  384. );
  385. }
  386. /**
  387. * Callback called by {@link StatsCollector} in intervals supplied to it's
  388. * constructor.
  389. * @param statsCollector {@link StatsCollector} source of the event.
  390. */
  391. function statsUpdated(statsCollector)
  392. {
  393. Object.keys(statsCollector.jid2stats).forEach(function (jid)
  394. {
  395. var peerStats = statsCollector.jid2stats[jid];
  396. Object.keys(peerStats.ssrc2AudioLevel).forEach(function (ssrc)
  397. {
  398. console.info(jid + " audio level: " +
  399. peerStats.ssrc2AudioLevel[ssrc] + " of ssrc: " + ssrc);
  400. // VideoLayout.updateAudioLevel( Strophe.getResourceFromJid(jid),
  401. // peerStats.ssrc2AudioLevel[ssrc]);
  402. });
  403. });
  404. }
  405. /**
  406. * Callback called by {@link LocalStatsCollector} in intervals supplied to it's
  407. * constructor.
  408. * @param statsCollector {@link LocalStatsCollector} source of the event.
  409. */
  410. function localStatsUpdated(statsCollector)
  411. {
  412. console.info("Local audio level: " + statsCollector.audioLevel);
  413. }
  414. /**
  415. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  416. */
  417. function startRtpStatsCollector()
  418. {
  419. if (config.enableRtpStats && !statsCollector)
  420. {
  421. statsCollector = new StatsCollector(
  422. getConferenceHandler().peerconnection, 200, statsUpdated);
  423. stopLocalRtpStatsCollector();
  424. statsCollector.start();
  425. }
  426. }
  427. /**
  428. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  429. * @param stream the stream that will be used for collecting statistics.
  430. */
  431. function startLocalRtpStatsCollector(stream)
  432. {
  433. if(config.enableRtpStats)
  434. {
  435. localStatsCollector = new LocalStatsCollector(stream, 200, localStatsUpdated);
  436. localStatsCollector.start();
  437. }
  438. }
  439. /**
  440. * Stops the {@link LocalStatsCollector}.
  441. */
  442. function stopLocalRtpStatsCollector()
  443. {
  444. if(localStatsCollector)
  445. {
  446. localStatsCollector.stop();
  447. localStatsCollector = null;
  448. }
  449. }
  450. $(document).bind('callincoming.jingle', function (event, sid) {
  451. var sess = connection.jingle.sessions[sid];
  452. // TODO: do we check activecall == null?
  453. activecall = sess;
  454. startRtpStatsCollector();
  455. // Bind data channel listener in case we're a regular participant
  456. if (config.openSctp)
  457. {
  458. bindDataChannelListener(sess.peerconnection);
  459. }
  460. // TODO: check affiliation and/or role
  461. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  462. sess.usedrip = true; // not-so-naive trickle ice
  463. sess.sendAnswer();
  464. sess.accept();
  465. });
  466. $(document).bind('conferenceCreated.jingle', function (event, focus)
  467. {
  468. startRtpStatsCollector();
  469. });
  470. $(document).bind('conferenceCreated.jingle', function (event, focus)
  471. {
  472. // Bind data channel listener in case we're the focus
  473. if (config.openSctp)
  474. {
  475. bindDataChannelListener(focus.peerconnection);
  476. }
  477. });
  478. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  479. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  480. // ignore mixedmslabela0 and v0
  481. videoelem.show();
  482. VideoLayout.resizeThumbnails();
  483. if (!focusedVideoSrc)
  484. VideoLayout.updateLargeVideo(videoelem.attr('src'), 1);
  485. VideoLayout.showFocusIndicator();
  486. }
  487. });
  488. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  489. // Leave the room if my call has been remotely terminated.
  490. if (connection.emuc.joined && focus == null && reason === 'kick') {
  491. sessionTerminated = true;
  492. connection.emuc.doLeave();
  493. openMessageDialog( "Session Terminated",
  494. "Ouch! You have been kicked out of the meet!");
  495. }
  496. });
  497. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  498. // put our ssrcs into presence so other clients can identify our stream
  499. var sess = connection.jingle.sessions[sid];
  500. var newssrcs = {};
  501. var directions = {};
  502. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  503. localSDP.media.forEach(function (media) {
  504. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  505. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  506. // assumes a single local ssrc
  507. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  508. newssrcs[type] = ssrc;
  509. directions[type] = (
  510. SDPUtil.find_line(media, 'a=sendrecv') ||
  511. SDPUtil.find_line(media, 'a=recvonly') ||
  512. SDPUtil.find_line(media, 'a=sendonly') ||
  513. SDPUtil.find_line(media, 'a=inactive') ||
  514. 'a=sendrecv').substr(2);
  515. }
  516. });
  517. console.log('new ssrcs', newssrcs);
  518. // Have to clear presence map to get rid of removed streams
  519. connection.emuc.clearPresenceMedia();
  520. var i = 0;
  521. Object.keys(newssrcs).forEach(function (mtype) {
  522. i++;
  523. var type = mtype;
  524. // Change video type to screen
  525. if (mtype === 'video' && isUsingScreenStream) {
  526. type = 'screen';
  527. }
  528. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  529. });
  530. if (i > 0) {
  531. connection.emuc.sendPresence();
  532. }
  533. });
  534. $(document).bind('joined.muc', function (event, jid, info) {
  535. updateRoomUrl(window.location.href);
  536. document.getElementById('localNick').appendChild(
  537. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  538. );
  539. if (Object.keys(connection.emuc.members).length < 1) {
  540. focus = new ColibriFocus(connection, config.hosts.bridge);
  541. }
  542. if (focus && config.etherpad_base) {
  543. Etherpad.init();
  544. }
  545. VideoLayout.showFocusIndicator();
  546. // Once we've joined the muc show the toolbar
  547. Toolbar.showToolbar();
  548. var displayName = '';
  549. if (info.displayName)
  550. displayName = info.displayName + ' (me)';
  551. VideoLayout.setDisplayName('localVideoContainer', displayName);
  552. });
  553. $(document).bind('entered.muc', function (event, jid, info, pres) {
  554. console.log('entered', jid, info);
  555. console.log('is focus?' + focus ? 'true' : 'false');
  556. // Add Peer's container
  557. VideoLayout.ensurePeerContainerExists(jid);
  558. if (focus !== null) {
  559. // FIXME: this should prepare the video
  560. if (focus.confid === null) {
  561. console.log('make new conference with', jid);
  562. focus.makeConference(Object.keys(connection.emuc.members));
  563. } else {
  564. console.log('invite', jid, 'into conference');
  565. focus.addNewParticipant(jid);
  566. }
  567. }
  568. else if (sharedKey) {
  569. Toolbar.updateLockButton();
  570. }
  571. });
  572. $(document).bind('left.muc', function (event, jid) {
  573. console.log('left.muc', jid);
  574. // Need to call this with a slight delay, otherwise the element couldn't be
  575. // found for some reason.
  576. window.setTimeout(function () {
  577. var container = document.getElementById(
  578. 'participant_' + Strophe.getResourceFromJid(jid));
  579. if (container) {
  580. // hide here, wait for video to close before removing
  581. $(container).hide();
  582. VideoLayout.resizeThumbnails();
  583. }
  584. }, 10);
  585. // Unlock large video
  586. if (focusedVideoSrc)
  587. {
  588. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  589. {
  590. console.info("Focused video owner has left the conference");
  591. focusedVideoSrc = null;
  592. }
  593. }
  594. connection.jingle.terminateByJid(jid);
  595. if (focus == null
  596. // I shouldn't be the one that left to enter here.
  597. && jid !== connection.emuc.myroomjid
  598. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  599. // If our session has been terminated for some reason
  600. // (kicked, hangup), don't try to become the focus
  601. && !sessionTerminated) {
  602. console.log('welcome to our new focus... myself');
  603. focus = new ColibriFocus(connection, config.hosts.bridge);
  604. if (Object.keys(connection.emuc.members).length > 0) {
  605. focus.makeConference(Object.keys(connection.emuc.members));
  606. }
  607. $(document).trigger('focusechanged.muc', [focus]);
  608. }
  609. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  610. console.log('everyone left');
  611. // FIXME: closing the connection is a hack to avoid some
  612. // problemswith reinit
  613. disposeConference();
  614. focus = new ColibriFocus(connection, config.hosts.bridge);
  615. }
  616. if (connection.emuc.getPrezi(jid)) {
  617. $(document).trigger('presentationremoved.muc',
  618. [jid, connection.emuc.getPrezi(jid)]);
  619. }
  620. });
  621. $(document).bind('presence.muc', function (event, jid, info, pres) {
  622. // Remove old ssrcs coming from the jid
  623. Object.keys(ssrc2jid).forEach(function (ssrc) {
  624. if (ssrc2jid[ssrc] == jid) {
  625. delete ssrc2jid[ssrc];
  626. }
  627. if (ssrc2videoType == jid) {
  628. delete ssrc2videoType[ssrc];
  629. }
  630. });
  631. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  632. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  633. var ssrcV = ssrc.getAttribute('ssrc');
  634. ssrc2jid[ssrcV] = jid;
  635. var type = ssrc.getAttribute('type');
  636. ssrc2videoType[ssrcV] = type;
  637. // might need to update the direction if participant just went from sendrecv to recvonly
  638. if (type === 'video' || type === 'screen') {
  639. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  640. switch (ssrc.getAttribute('direction')) {
  641. case 'sendrecv':
  642. el.show();
  643. break;
  644. case 'recvonly':
  645. el.hide();
  646. // FIXME: Check if we have to change large video
  647. //VideoLayout.checkChangeLargeVideo(el);
  648. break;
  649. }
  650. }
  651. });
  652. if (info.displayName) {
  653. if (jid === connection.emuc.myroomjid) {
  654. VideoLayout.setDisplayName('localVideoContainer',
  655. info.displayName + ' (me)');
  656. } else {
  657. VideoLayout.ensurePeerContainerExists(jid);
  658. VideoLayout.setDisplayName(
  659. 'participant_' + Strophe.getResourceFromJid(jid),
  660. info.displayName);
  661. }
  662. }
  663. });
  664. $(document).bind('passwordrequired.muc', function (event, jid) {
  665. console.log('on password required', jid);
  666. $.prompt('<h2>Password required</h2>' +
  667. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  668. persistent: true,
  669. buttons: { "Ok": true, "Cancel": false},
  670. defaultButton: 1,
  671. loaded: function (event) {
  672. document.getElementById('lockKey').focus();
  673. },
  674. submit: function (e, v, m, f) {
  675. if (v) {
  676. var lockKey = document.getElementById('lockKey');
  677. if (lockKey.value !== null) {
  678. setSharedKey(lockKey.value);
  679. connection.emuc.doJoin(jid, lockKey.value);
  680. }
  681. }
  682. }
  683. });
  684. });
  685. /**
  686. * Checks if video identified by given src is desktop stream.
  687. * @param videoSrc eg.
  688. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  689. * @returns {boolean}
  690. */
  691. function isVideoSrcDesktop(videoSrc) {
  692. // FIXME: fix this mapping mess...
  693. // figure out if large video is desktop stream or just a camera
  694. var isDesktop = false;
  695. if (localVideoSrc === videoSrc) {
  696. // local video
  697. isDesktop = isUsingScreenStream;
  698. } else {
  699. // Do we have associations...
  700. var videoSsrc = videoSrcToSsrc[videoSrc];
  701. if (videoSsrc) {
  702. var videoType = ssrc2videoType[videoSsrc];
  703. if (videoType) {
  704. // Finally there...
  705. isDesktop = videoType === 'screen';
  706. } else {
  707. console.error("No video type for ssrc: " + videoSsrc);
  708. }
  709. } else {
  710. console.error("No ssrc for src: " + videoSrc);
  711. }
  712. }
  713. return isDesktop;
  714. }
  715. function getConferenceHandler() {
  716. return focus ? focus : activecall;
  717. }
  718. function toggleVideo() {
  719. if (!(connection && connection.jingle.localVideo))
  720. return;
  721. var sess = getConferenceHandler();
  722. if (sess) {
  723. sess.toggleVideoMute(
  724. function (isMuted) {
  725. if (isMuted) {
  726. $('#video').removeClass("icon-camera");
  727. $('#video').addClass("icon-camera icon-camera-disabled");
  728. } else {
  729. $('#video').removeClass("icon-camera icon-camera-disabled");
  730. $('#video').addClass("icon-camera");
  731. }
  732. }
  733. );
  734. }
  735. sess = focus || activecall;
  736. if (!sess) {
  737. return;
  738. }
  739. sess.pendingop = ismuted ? 'unmute' : 'mute';
  740. // connection.emuc.addVideoInfoToPresence(!ismuted);
  741. // connection.emuc.sendPresence();
  742. sess.modifySources();
  743. }
  744. /**
  745. * Mutes / unmutes audio for the local participant.
  746. */
  747. function toggleAudio() {
  748. if (!(connection && connection.jingle.localAudio)) {
  749. preMuted = true;
  750. // We still click the button.
  751. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  752. return;
  753. }
  754. var localAudio = connection.jingle.localAudio;
  755. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  756. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  757. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  758. // isMuted is the opposite of audioEnabled
  759. connection.emuc.addAudioInfoToPresence(audioEnabled);
  760. connection.emuc.sendPresence();
  761. }
  762. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  763. }
  764. /**
  765. * Returns an array of the video horizontal and vertical indents,
  766. * so that if fits its parent.
  767. *
  768. * @return an array with 2 elements, the horizontal indent and the vertical
  769. * indent
  770. */
  771. function getCameraVideoPosition(videoWidth,
  772. videoHeight,
  773. videoSpaceWidth,
  774. videoSpaceHeight) {
  775. // Parent height isn't completely calculated when we position the video in
  776. // full screen mode and this is why we use the screen height in this case.
  777. // Need to think it further at some point and implement it properly.
  778. var isFullScreen = document.fullScreen ||
  779. document.mozFullScreen ||
  780. document.webkitIsFullScreen;
  781. if (isFullScreen)
  782. videoSpaceHeight = window.innerHeight;
  783. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  784. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  785. return [horizontalIndent, verticalIndent];
  786. }
  787. /**
  788. * Returns an array of the video horizontal and vertical indents.
  789. * Centers horizontally and top aligns vertically.
  790. *
  791. * @return an array with 2 elements, the horizontal indent and the vertical
  792. * indent
  793. */
  794. function getDesktopVideoPosition(videoWidth,
  795. videoHeight,
  796. videoSpaceWidth,
  797. videoSpaceHeight) {
  798. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  799. var verticalIndent = 0;// Top aligned
  800. return [horizontalIndent, verticalIndent];
  801. }
  802. /**
  803. * Returns an array of the video dimensions, so that it covers the screen.
  804. * It leaves no empty areas, but some parts of the video might not be visible.
  805. *
  806. * @return an array with 2 elements, the video width and the video height
  807. */
  808. function getCameraVideoSize(videoWidth,
  809. videoHeight,
  810. videoSpaceWidth,
  811. videoSpaceHeight) {
  812. if (!videoWidth)
  813. videoWidth = currentVideoWidth;
  814. if (!videoHeight)
  815. videoHeight = currentVideoHeight;
  816. var aspectRatio = videoWidth / videoHeight;
  817. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  818. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  819. if (availableWidth / aspectRatio < videoSpaceHeight) {
  820. availableHeight = videoSpaceHeight;
  821. availableWidth = availableHeight * aspectRatio;
  822. }
  823. if (availableHeight * aspectRatio < videoSpaceWidth) {
  824. availableWidth = videoSpaceWidth;
  825. availableHeight = availableWidth / aspectRatio;
  826. }
  827. return [availableWidth, availableHeight];
  828. }
  829. $(document).ready(function () {
  830. Chat.init();
  831. $('body').popover({ selector: '[data-toggle=popover]',
  832. trigger: 'click hover'});
  833. // Set the defaults for prompt dialogs.
  834. jQuery.prompt.setDefaults({persistent: false});
  835. // Set default desktop sharing method
  836. setDesktopSharing(config.desktopSharing);
  837. // Initialize Chrome extension inline installs
  838. if (config.chromeExtensionId) {
  839. initInlineInstalls();
  840. }
  841. // By default we use camera
  842. getVideoSize = getCameraVideoSize;
  843. getVideoPosition = getCameraVideoPosition;
  844. VideoLayout.resizeLargeVideoContainer();
  845. $(window).resize(function () {
  846. VideoLayout.resizeLargeVideoContainer();
  847. VideoLayout.positionLarge();
  848. });
  849. // Listen for large video size updates
  850. document.getElementById('largeVideo')
  851. .addEventListener('loadedmetadata', function (e) {
  852. currentVideoWidth = this.videoWidth;
  853. currentVideoHeight = this.videoHeight;
  854. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  855. });
  856. if (!$('#settings').is(':visible')) {
  857. console.log('init');
  858. init();
  859. } else {
  860. loginInfo.onsubmit = function (e) {
  861. if (e.preventDefault) e.preventDefault();
  862. $('#settings').hide();
  863. init();
  864. };
  865. }
  866. });
  867. $(window).bind('beforeunload', function () {
  868. if (connection && connection.connected) {
  869. // ensure signout
  870. $.ajax({
  871. type: 'POST',
  872. url: config.bosh,
  873. async: false,
  874. cache: false,
  875. contentType: 'application/xml',
  876. 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>",
  877. success: function (data) {
  878. console.log('signed out');
  879. console.log(data);
  880. },
  881. error: function (XMLHttpRequest, textStatus, errorThrown) {
  882. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  883. }
  884. });
  885. }
  886. disposeConference(true);
  887. });
  888. function disposeConference(onUnload) {
  889. var handler = getConferenceHandler();
  890. if (handler && handler.peerconnection) {
  891. // FIXME: probably removing streams is not required and close() should be enough
  892. if (connection.jingle.localAudio) {
  893. handler.peerconnection.removeStream(connection.jingle.localAudio);
  894. }
  895. if (connection.jingle.localVideo) {
  896. handler.peerconnection.removeStream(connection.jingle.localVideo);
  897. }
  898. handler.peerconnection.close();
  899. }
  900. if (statsCollector)
  901. {
  902. statsCollector.stop();
  903. statsCollector = null;
  904. }
  905. if(!onUnload) {
  906. startLocalRtpStatsCollector(connection.jingle.localAudio);
  907. }
  908. else
  909. {
  910. stopLocalRtpStatsCollector();
  911. }
  912. focus = null;
  913. activecall = null;
  914. }
  915. function dump(elem, filename) {
  916. elem = elem.parentNode;
  917. elem.download = filename || 'meetlog.json';
  918. elem.href = 'data:application/json;charset=utf-8,\n';
  919. var data = {};
  920. if (connection.jingle) {
  921. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  922. var session = connection.jingle.sessions[sid];
  923. if (session.peerconnection && session.peerconnection.updateLog) {
  924. // FIXME: should probably be a .dump call
  925. data["jingle_" + session.sid] = {
  926. updateLog: session.peerconnection.updateLog,
  927. stats: session.peerconnection.stats,
  928. url: window.location.href
  929. };
  930. }
  931. });
  932. }
  933. metadata = {};
  934. metadata.time = new Date();
  935. metadata.url = window.location.href;
  936. metadata.ua = navigator.userAgent;
  937. if (connection.logger) {
  938. metadata.xmpp = connection.logger.log;
  939. }
  940. data.metadata = metadata;
  941. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  942. return false;
  943. }
  944. /**
  945. * Changes the style class of the element given by id.
  946. */
  947. function buttonClick(id, classname) {
  948. $(id).toggleClass(classname); // add the class to the clicked element
  949. }
  950. /**
  951. * Shows a message to the user.
  952. *
  953. * @param titleString the title of the message
  954. * @param messageString the text of the message
  955. */
  956. function openMessageDialog(titleString, messageString) {
  957. $.prompt(messageString,
  958. {
  959. title: titleString,
  960. persistent: false
  961. }
  962. );
  963. }
  964. /**
  965. * Locks / unlocks the room.
  966. */
  967. function lockRoom(lock) {
  968. if (lock)
  969. connection.emuc.lockRoom(sharedKey);
  970. else
  971. connection.emuc.lockRoom('');
  972. Toolbar.updateLockButton();
  973. }
  974. /**
  975. * Sets the shared key.
  976. */
  977. function setSharedKey(sKey) {
  978. sharedKey = sKey;
  979. }
  980. /**
  981. * Updates the room invite url.
  982. */
  983. function updateRoomUrl(newRoomUrl) {
  984. roomUrl = newRoomUrl;
  985. // If the invite dialog has been already opened we update the information.
  986. var inviteLink = document.getElementById('inviteLinkRef');
  987. if (inviteLink) {
  988. inviteLink.value = roomUrl;
  989. inviteLink.select();
  990. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  991. }
  992. }
  993. /**
  994. * Warning to the user that the conference window is about to be closed.
  995. */
  996. function closePageWarning() {
  997. if (focus !== null)
  998. return "You are the owner of this conference call and"
  999. + " you are about to end it.";
  1000. else
  1001. return "You are about to leave this conversation.";
  1002. }
  1003. /**
  1004. * Resizes and repositions videos in full screen mode.
  1005. */
  1006. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1007. function () {
  1008. VideoLayout.resizeLargeVideoContainer();
  1009. VideoLayout.positionLarge();
  1010. isFullScreen = document.fullScreen ||
  1011. document.mozFullScreen ||
  1012. document.webkitIsFullScreen;
  1013. if (isFullScreen) {
  1014. setView("fullscreen");
  1015. }
  1016. else {
  1017. setView("default");
  1018. }
  1019. }
  1020. );
  1021. /**
  1022. * Sets the current view.
  1023. */
  1024. function setView(viewName) {
  1025. // if (viewName == "fullscreen") {
  1026. // document.getElementById('videolayout_fullscreen').disabled = false;
  1027. // document.getElementById('videolayout_default').disabled = true;
  1028. // }
  1029. // else {
  1030. // document.getElementById('videolayout_default').disabled = false;
  1031. // document.getElementById('videolayout_fullscreen').disabled = true;
  1032. // }
  1033. }
  1034. $(document).bind('fatalError.jingle',
  1035. function (event, session, error)
  1036. {
  1037. sessionTerminated = true;
  1038. connection.emuc.doLeave();
  1039. openMessageDialog( "Sorry",
  1040. "Your browser version is too old. Please update and try again...");
  1041. }
  1042. );