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. container.onclick = function (event) {
  271. VideoLayout.handleVideoThumbClicked(
  272. $('#' + container.id + '>video').get(0).src);
  273. event.preventDefault();
  274. return false;
  275. };
  276. // Add hover handler
  277. $(container).hover(
  278. function() {
  279. VideoLayout.showDisplayName(container.id, true);
  280. },
  281. function() {
  282. var videoSrc = null;
  283. if ($('#' + container.id + '>video')
  284. && $('#' + container.id + '>video').length > 0) {
  285. videoSrc = $('#' + container.id + '>video').get(0).src;
  286. }
  287. // If the video has been "pinned" by the user we want to keep the
  288. // display name on place.
  289. if (!VideoLayout.isLargeVideoVisible()
  290. || videoSrc !== $('#largeVideo').attr('src'))
  291. VideoLayout.showDisplayName(container.id, false);
  292. }
  293. );
  294. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  295. if (isVideo &&
  296. data.peerjid && sess.peerjid === data.peerjid &&
  297. data.stream.getVideoTracks().length === 0 &&
  298. connection.jingle.localVideo.getVideoTracks().length > 0) {
  299. //
  300. window.setTimeout(function () {
  301. sendKeyframe(sess.peerconnection);
  302. }, 3000);
  303. }
  304. });
  305. /**
  306. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  307. * @param videoSrc the video "src" identifier.
  308. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  309. * belongs.
  310. */
  311. function getJidFromVideoSrc(videoSrc)
  312. {
  313. if (videoSrc === localVideoSrc)
  314. return connection.emuc.myroomjid;
  315. var ssrc = videoSrcToSsrc[videoSrc];
  316. if (!ssrc)
  317. {
  318. return null;
  319. }
  320. return ssrc2jid[ssrc];
  321. }
  322. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  323. function sendKeyframe(pc) {
  324. console.log('sendkeyframe', pc.iceConnectionState);
  325. if (pc.iceConnectionState !== 'connected') return; // safe...
  326. pc.setRemoteDescription(
  327. pc.remoteDescription,
  328. function () {
  329. pc.createAnswer(
  330. function (modifiedAnswer) {
  331. pc.setLocalDescription(
  332. modifiedAnswer,
  333. function () {
  334. // noop
  335. },
  336. function (error) {
  337. console.log('triggerKeyframe setLocalDescription failed', error);
  338. }
  339. );
  340. },
  341. function (error) {
  342. console.log('triggerKeyframe createAnswer failed', error);
  343. }
  344. );
  345. },
  346. function (error) {
  347. console.log('triggerKeyframe setRemoteDescription failed', error);
  348. }
  349. );
  350. }
  351. // Really mute video, i.e. dont even send black frames
  352. function muteVideo(pc, unmute) {
  353. // FIXME: this probably needs another of those lovely state safeguards...
  354. // which checks for iceconn == connected and sigstate == stable
  355. pc.setRemoteDescription(pc.remoteDescription,
  356. function () {
  357. pc.createAnswer(
  358. function (answer) {
  359. var sdp = new SDP(answer.sdp);
  360. if (sdp.media.length > 1) {
  361. if (unmute)
  362. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  363. else
  364. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  365. sdp.raw = sdp.session + sdp.media.join('');
  366. answer.sdp = sdp.raw;
  367. }
  368. pc.setLocalDescription(answer,
  369. function () {
  370. console.log('mute SLD ok');
  371. },
  372. function (error) {
  373. console.log('mute SLD error');
  374. }
  375. );
  376. },
  377. function (error) {
  378. console.log(error);
  379. }
  380. );
  381. },
  382. function (error) {
  383. console.log('muteVideo SRD error');
  384. }
  385. );
  386. }
  387. /**
  388. * Callback called by {@link StatsCollector} in intervals supplied to it's
  389. * constructor.
  390. * @param statsCollector {@link StatsCollector} source of the event.
  391. */
  392. function statsUpdated(statsCollector)
  393. {
  394. Object.keys(statsCollector.jid2stats).forEach(function (jid)
  395. {
  396. var peerStats = statsCollector.jid2stats[jid];
  397. Object.keys(peerStats.ssrc2AudioLevel).forEach(function (ssrc)
  398. {
  399. // console.info(jid + " audio level: " +
  400. // peerStats.ssrc2AudioLevel[ssrc] + " of ssrc: " + ssrc);
  401. });
  402. });
  403. }
  404. /**
  405. * Callback called by {@link LocalStatsCollector} in intervals supplied to it's
  406. * constructor.
  407. * @param statsCollector {@link LocalStatsCollector} source of the event.
  408. */
  409. function localStatsUpdated(statsCollector)
  410. {
  411. // console.info("Local audio level: " + statsCollector.audioLevel);
  412. }
  413. /**
  414. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  415. */
  416. function startRtpStatsCollector()
  417. {
  418. if (config.enableRtpStats && !statsCollector)
  419. {
  420. statsCollector = new StatsCollector(
  421. getConferenceHandler().peerconnection, 200, statsUpdated);
  422. stopLocalRtpStatsCollector();
  423. statsCollector.start();
  424. }
  425. }
  426. /**
  427. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  428. * @param stream the stream that will be used for collecting statistics.
  429. */
  430. function startLocalRtpStatsCollector(stream)
  431. {
  432. if(config.enableRtpStats)
  433. {
  434. localStatsCollector = new LocalStatsCollector(stream, 200, localStatsUpdated);
  435. localStatsCollector.start();
  436. }
  437. }
  438. /**
  439. * Stops the {@link LocalStatsCollector}.
  440. */
  441. function stopLocalRtpStatsCollector()
  442. {
  443. if(localStatsCollector)
  444. {
  445. localStatsCollector.stop();
  446. localStatsCollector = null;
  447. }
  448. }
  449. $(document).bind('callincoming.jingle', function (event, sid) {
  450. var sess = connection.jingle.sessions[sid];
  451. // TODO: do we check activecall == null?
  452. activecall = sess;
  453. startRtpStatsCollector();
  454. // Bind data channel listener in case we're a regular participant
  455. if (config.openSctp)
  456. {
  457. bindDataChannelListener(sess.peerconnection);
  458. }
  459. // TODO: check affiliation and/or role
  460. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  461. sess.usedrip = true; // not-so-naive trickle ice
  462. sess.sendAnswer();
  463. sess.accept();
  464. });
  465. $(document).bind('conferenceCreated.jingle', function (event, focus)
  466. {
  467. startRtpStatsCollector();
  468. });
  469. $(document).bind('conferenceCreated.jingle', function (event, focus)
  470. {
  471. // Bind data channel listener in case we're the focus
  472. if (config.openSctp)
  473. {
  474. bindDataChannelListener(focus.peerconnection);
  475. }
  476. });
  477. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  478. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  479. // ignore mixedmslabela0 and v0
  480. videoelem.show();
  481. VideoLayout.resizeThumbnails();
  482. // Update the large video to the last added video only if there's no
  483. // current active or focused speaker.
  484. if (!focusedVideoSrc && !VideoLayout.getActiveSpeakerResourceJid())
  485. VideoLayout.updateLargeVideo(videoelem.attr('src'), 1);
  486. VideoLayout.showFocusIndicator();
  487. }
  488. });
  489. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  490. // Leave the room if my call has been remotely terminated.
  491. if (connection.emuc.joined && focus == null && reason === 'kick') {
  492. sessionTerminated = true;
  493. connection.emuc.doLeave();
  494. openMessageDialog( "Session Terminated",
  495. "Ouch! You have been kicked out of the meet!");
  496. }
  497. });
  498. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  499. // put our ssrcs into presence so other clients can identify our stream
  500. var sess = connection.jingle.sessions[sid];
  501. var newssrcs = {};
  502. var directions = {};
  503. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  504. localSDP.media.forEach(function (media) {
  505. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  506. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  507. // assumes a single local ssrc
  508. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  509. newssrcs[type] = ssrc;
  510. directions[type] = (
  511. SDPUtil.find_line(media, 'a=sendrecv') ||
  512. SDPUtil.find_line(media, 'a=recvonly') ||
  513. SDPUtil.find_line(media, 'a=sendonly') ||
  514. SDPUtil.find_line(media, 'a=inactive') ||
  515. 'a=sendrecv').substr(2);
  516. }
  517. });
  518. console.log('new ssrcs', newssrcs);
  519. // Have to clear presence map to get rid of removed streams
  520. connection.emuc.clearPresenceMedia();
  521. var i = 0;
  522. Object.keys(newssrcs).forEach(function (mtype) {
  523. i++;
  524. var type = mtype;
  525. // Change video type to screen
  526. if (mtype === 'video' && isUsingScreenStream) {
  527. type = 'screen';
  528. }
  529. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  530. });
  531. if (i > 0) {
  532. connection.emuc.sendPresence();
  533. }
  534. });
  535. $(document).bind('joined.muc', function (event, jid, info) {
  536. updateRoomUrl(window.location.href);
  537. document.getElementById('localNick').appendChild(
  538. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  539. );
  540. if (Object.keys(connection.emuc.members).length < 1) {
  541. focus = new ColibriFocus(connection, config.hosts.bridge);
  542. }
  543. if (focus && config.etherpad_base) {
  544. Etherpad.init();
  545. }
  546. VideoLayout.showFocusIndicator();
  547. // Once we've joined the muc show the toolbar
  548. Toolbar.showToolbar();
  549. var displayName = '';
  550. if (info.displayName)
  551. displayName = info.displayName + ' (me)';
  552. VideoLayout.setDisplayName('localVideoContainer', displayName);
  553. });
  554. $(document).bind('entered.muc', function (event, jid, info, pres) {
  555. console.log('entered', jid, info);
  556. console.log('is focus?' + focus ? 'true' : 'false');
  557. // Add Peer's container
  558. VideoLayout.ensurePeerContainerExists(jid);
  559. if (focus !== null) {
  560. // FIXME: this should prepare the video
  561. if (focus.confid === null) {
  562. console.log('make new conference with', jid);
  563. focus.makeConference(Object.keys(connection.emuc.members));
  564. } else {
  565. console.log('invite', jid, 'into conference');
  566. focus.addNewParticipant(jid);
  567. }
  568. }
  569. else if (sharedKey) {
  570. Toolbar.updateLockButton();
  571. }
  572. });
  573. $(document).bind('left.muc', function (event, jid) {
  574. console.log('left.muc', jid);
  575. // Need to call this with a slight delay, otherwise the element couldn't be
  576. // found for some reason.
  577. window.setTimeout(function () {
  578. var container = document.getElementById(
  579. 'participant_' + Strophe.getResourceFromJid(jid));
  580. if (container) {
  581. // hide here, wait for video to close before removing
  582. $(container).hide();
  583. VideoLayout.resizeThumbnails();
  584. }
  585. }, 10);
  586. // Unlock large video
  587. if (focusedVideoSrc)
  588. {
  589. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  590. {
  591. console.info("Focused video owner has left the conference");
  592. focusedVideoSrc = null;
  593. }
  594. }
  595. connection.jingle.terminateByJid(jid);
  596. if (focus == null
  597. // I shouldn't be the one that left to enter here.
  598. && jid !== connection.emuc.myroomjid
  599. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  600. // If our session has been terminated for some reason
  601. // (kicked, hangup), don't try to become the focus
  602. && !sessionTerminated) {
  603. console.log('welcome to our new focus... myself');
  604. focus = new ColibriFocus(connection, config.hosts.bridge);
  605. if (Object.keys(connection.emuc.members).length > 0) {
  606. focus.makeConference(Object.keys(connection.emuc.members));
  607. }
  608. $(document).trigger('focusechanged.muc', [focus]);
  609. }
  610. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  611. console.log('everyone left');
  612. // FIXME: closing the connection is a hack to avoid some
  613. // problemswith reinit
  614. disposeConference();
  615. focus = new ColibriFocus(connection, config.hosts.bridge);
  616. }
  617. if (connection.emuc.getPrezi(jid)) {
  618. $(document).trigger('presentationremoved.muc',
  619. [jid, connection.emuc.getPrezi(jid)]);
  620. }
  621. });
  622. $(document).bind('presence.muc', function (event, jid, info, pres) {
  623. // Remove old ssrcs coming from the jid
  624. Object.keys(ssrc2jid).forEach(function (ssrc) {
  625. if (ssrc2jid[ssrc] == jid) {
  626. delete ssrc2jid[ssrc];
  627. }
  628. if (ssrc2videoType == jid) {
  629. delete ssrc2videoType[ssrc];
  630. }
  631. });
  632. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  633. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  634. var ssrcV = ssrc.getAttribute('ssrc');
  635. ssrc2jid[ssrcV] = jid;
  636. var type = ssrc.getAttribute('type');
  637. ssrc2videoType[ssrcV] = type;
  638. // might need to update the direction if participant just went from sendrecv to recvonly
  639. if (type === 'video' || type === 'screen') {
  640. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  641. switch (ssrc.getAttribute('direction')) {
  642. case 'sendrecv':
  643. el.show();
  644. break;
  645. case 'recvonly':
  646. el.hide();
  647. // FIXME: Check if we have to change large video
  648. //VideoLayout.checkChangeLargeVideo(el);
  649. break;
  650. }
  651. }
  652. });
  653. if (jid === connection.emuc.myroomjid) {
  654. VideoLayout.setDisplayName('localVideoContainer',
  655. info.displayName);
  656. } else {
  657. VideoLayout.ensurePeerContainerExists(jid);
  658. VideoLayout.setDisplayName(
  659. 'participant_' + Strophe.getResourceFromJid(jid),
  660. info.displayName);
  661. }
  662. });
  663. $(document).bind('passwordrequired.muc', function (event, jid) {
  664. console.log('on password required', jid);
  665. $.prompt('<h2>Password required</h2>' +
  666. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  667. persistent: true,
  668. buttons: { "Ok": true, "Cancel": false},
  669. defaultButton: 1,
  670. loaded: function (event) {
  671. document.getElementById('lockKey').focus();
  672. },
  673. submit: function (e, v, m, f) {
  674. if (v) {
  675. var lockKey = document.getElementById('lockKey');
  676. if (lockKey.value !== null) {
  677. setSharedKey(lockKey.value);
  678. connection.emuc.doJoin(jid, lockKey.value);
  679. }
  680. }
  681. }
  682. });
  683. });
  684. /**
  685. * Checks if video identified by given src is desktop stream.
  686. * @param videoSrc eg.
  687. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  688. * @returns {boolean}
  689. */
  690. function isVideoSrcDesktop(videoSrc) {
  691. // FIXME: fix this mapping mess...
  692. // figure out if large video is desktop stream or just a camera
  693. var isDesktop = false;
  694. if (localVideoSrc === videoSrc) {
  695. // local video
  696. isDesktop = isUsingScreenStream;
  697. } else {
  698. // Do we have associations...
  699. var videoSsrc = videoSrcToSsrc[videoSrc];
  700. if (videoSsrc) {
  701. var videoType = ssrc2videoType[videoSsrc];
  702. if (videoType) {
  703. // Finally there...
  704. isDesktop = videoType === 'screen';
  705. } else {
  706. console.error("No video type for ssrc: " + videoSsrc);
  707. }
  708. } else {
  709. console.error("No ssrc for src: " + videoSrc);
  710. }
  711. }
  712. return isDesktop;
  713. }
  714. function getConferenceHandler() {
  715. return focus ? focus : activecall;
  716. }
  717. function toggleVideo() {
  718. if (!(connection && connection.jingle.localVideo))
  719. return;
  720. var sess = getConferenceHandler();
  721. if (sess) {
  722. sess.toggleVideoMute(
  723. function (isMuted) {
  724. if (isMuted) {
  725. $('#video').removeClass("icon-camera");
  726. $('#video').addClass("icon-camera icon-camera-disabled");
  727. } else {
  728. $('#video').removeClass("icon-camera icon-camera-disabled");
  729. $('#video').addClass("icon-camera");
  730. }
  731. }
  732. );
  733. }
  734. sess = focus || activecall;
  735. if (!sess) {
  736. return;
  737. }
  738. sess.pendingop = ismuted ? 'unmute' : 'mute';
  739. // connection.emuc.addVideoInfoToPresence(!ismuted);
  740. // connection.emuc.sendPresence();
  741. sess.modifySources();
  742. }
  743. /**
  744. * Mutes / unmutes audio for the local participant.
  745. */
  746. function toggleAudio() {
  747. if (!(connection && connection.jingle.localAudio)) {
  748. preMuted = true;
  749. // We still click the button.
  750. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  751. return;
  752. }
  753. var localAudio = connection.jingle.localAudio;
  754. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  755. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  756. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  757. // isMuted is the opposite of audioEnabled
  758. connection.emuc.addAudioInfoToPresence(audioEnabled);
  759. connection.emuc.sendPresence();
  760. }
  761. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  762. }
  763. /**
  764. * Returns an array of the video horizontal and vertical indents,
  765. * so that if fits its parent.
  766. *
  767. * @return an array with 2 elements, the horizontal indent and the vertical
  768. * indent
  769. */
  770. function getCameraVideoPosition(videoWidth,
  771. videoHeight,
  772. videoSpaceWidth,
  773. videoSpaceHeight) {
  774. // Parent height isn't completely calculated when we position the video in
  775. // full screen mode and this is why we use the screen height in this case.
  776. // Need to think it further at some point and implement it properly.
  777. var isFullScreen = document.fullScreen ||
  778. document.mozFullScreen ||
  779. document.webkitIsFullScreen;
  780. if (isFullScreen)
  781. videoSpaceHeight = window.innerHeight;
  782. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  783. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  784. return [horizontalIndent, verticalIndent];
  785. }
  786. /**
  787. * Returns an array of the video horizontal and vertical indents.
  788. * Centers horizontally and top aligns vertically.
  789. *
  790. * @return an array with 2 elements, the horizontal indent and the vertical
  791. * indent
  792. */
  793. function getDesktopVideoPosition(videoWidth,
  794. videoHeight,
  795. videoSpaceWidth,
  796. videoSpaceHeight) {
  797. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  798. var verticalIndent = 0;// Top aligned
  799. return [horizontalIndent, verticalIndent];
  800. }
  801. /**
  802. * Returns an array of the video dimensions, so that it covers the screen.
  803. * It leaves no empty areas, but some parts of the video might not be visible.
  804. *
  805. * @return an array with 2 elements, the video width and the video height
  806. */
  807. function getCameraVideoSize(videoWidth,
  808. videoHeight,
  809. videoSpaceWidth,
  810. videoSpaceHeight) {
  811. if (!videoWidth)
  812. videoWidth = currentVideoWidth;
  813. if (!videoHeight)
  814. videoHeight = currentVideoHeight;
  815. var aspectRatio = videoWidth / videoHeight;
  816. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  817. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  818. if (availableWidth / aspectRatio < videoSpaceHeight) {
  819. availableHeight = videoSpaceHeight;
  820. availableWidth = availableHeight * aspectRatio;
  821. }
  822. if (availableHeight * aspectRatio < videoSpaceWidth) {
  823. availableWidth = videoSpaceWidth;
  824. availableHeight = availableWidth / aspectRatio;
  825. }
  826. return [availableWidth, availableHeight];
  827. }
  828. $(document).ready(function () {
  829. Chat.init();
  830. $('body').popover({ selector: '[data-toggle=popover]',
  831. trigger: 'click hover'});
  832. // Set the defaults for prompt dialogs.
  833. jQuery.prompt.setDefaults({persistent: false});
  834. // Set default desktop sharing method
  835. setDesktopSharing(config.desktopSharing);
  836. // Initialize Chrome extension inline installs
  837. if (config.chromeExtensionId) {
  838. initInlineInstalls();
  839. }
  840. // By default we use camera
  841. getVideoSize = getCameraVideoSize;
  842. getVideoPosition = getCameraVideoPosition;
  843. VideoLayout.resizeLargeVideoContainer();
  844. $(window).resize(function () {
  845. VideoLayout.resizeLargeVideoContainer();
  846. VideoLayout.positionLarge();
  847. });
  848. // Listen for large video size updates
  849. document.getElementById('largeVideo')
  850. .addEventListener('loadedmetadata', function (e) {
  851. currentVideoWidth = this.videoWidth;
  852. currentVideoHeight = this.videoHeight;
  853. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  854. });
  855. if (!$('#settings').is(':visible')) {
  856. console.log('init');
  857. init();
  858. } else {
  859. loginInfo.onsubmit = function (e) {
  860. if (e.preventDefault) e.preventDefault();
  861. $('#settings').hide();
  862. init();
  863. };
  864. }
  865. });
  866. $(window).bind('beforeunload', function () {
  867. if (connection && connection.connected) {
  868. // ensure signout
  869. $.ajax({
  870. type: 'POST',
  871. url: config.bosh,
  872. async: false,
  873. cache: false,
  874. contentType: 'application/xml',
  875. 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>",
  876. success: function (data) {
  877. console.log('signed out');
  878. console.log(data);
  879. },
  880. error: function (XMLHttpRequest, textStatus, errorThrown) {
  881. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  882. }
  883. });
  884. }
  885. disposeConference(true);
  886. });
  887. function disposeConference(onUnload) {
  888. var handler = getConferenceHandler();
  889. if (handler && handler.peerconnection) {
  890. // FIXME: probably removing streams is not required and close() should be enough
  891. if (connection.jingle.localAudio) {
  892. handler.peerconnection.removeStream(connection.jingle.localAudio);
  893. }
  894. if (connection.jingle.localVideo) {
  895. handler.peerconnection.removeStream(connection.jingle.localVideo);
  896. }
  897. handler.peerconnection.close();
  898. }
  899. if (statsCollector)
  900. {
  901. statsCollector.stop();
  902. statsCollector = null;
  903. }
  904. if(!onUnload) {
  905. startLocalRtpStatsCollector(connection.jingle.localAudio);
  906. }
  907. else
  908. {
  909. stopLocalRtpStatsCollector();
  910. }
  911. focus = null;
  912. activecall = null;
  913. }
  914. function dump(elem, filename) {
  915. elem = elem.parentNode;
  916. elem.download = filename || 'meetlog.json';
  917. elem.href = 'data:application/json;charset=utf-8,\n';
  918. var data = {};
  919. if (connection.jingle) {
  920. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  921. var session = connection.jingle.sessions[sid];
  922. if (session.peerconnection && session.peerconnection.updateLog) {
  923. // FIXME: should probably be a .dump call
  924. data["jingle_" + session.sid] = {
  925. updateLog: session.peerconnection.updateLog,
  926. stats: session.peerconnection.stats,
  927. url: window.location.href
  928. };
  929. }
  930. });
  931. }
  932. metadata = {};
  933. metadata.time = new Date();
  934. metadata.url = window.location.href;
  935. metadata.ua = navigator.userAgent;
  936. if (connection.logger) {
  937. metadata.xmpp = connection.logger.log;
  938. }
  939. data.metadata = metadata;
  940. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  941. return false;
  942. }
  943. /**
  944. * Changes the style class of the element given by id.
  945. */
  946. function buttonClick(id, classname) {
  947. $(id).toggleClass(classname); // add the class to the clicked element
  948. }
  949. /**
  950. * Shows a message to the user.
  951. *
  952. * @param titleString the title of the message
  953. * @param messageString the text of the message
  954. */
  955. function openMessageDialog(titleString, messageString) {
  956. $.prompt(messageString,
  957. {
  958. title: titleString,
  959. persistent: false
  960. }
  961. );
  962. }
  963. /**
  964. * Locks / unlocks the room.
  965. */
  966. function lockRoom(lock) {
  967. if (lock)
  968. connection.emuc.lockRoom(sharedKey);
  969. else
  970. connection.emuc.lockRoom('');
  971. Toolbar.updateLockButton();
  972. }
  973. /**
  974. * Sets the shared key.
  975. */
  976. function setSharedKey(sKey) {
  977. sharedKey = sKey;
  978. }
  979. /**
  980. * Updates the room invite url.
  981. */
  982. function updateRoomUrl(newRoomUrl) {
  983. roomUrl = newRoomUrl;
  984. // If the invite dialog has been already opened we update the information.
  985. var inviteLink = document.getElementById('inviteLinkRef');
  986. if (inviteLink) {
  987. inviteLink.value = roomUrl;
  988. inviteLink.select();
  989. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  990. }
  991. }
  992. /**
  993. * Warning to the user that the conference window is about to be closed.
  994. */
  995. function closePageWarning() {
  996. if (focus !== null)
  997. return "You are the owner of this conference call and"
  998. + " you are about to end it.";
  999. else
  1000. return "You are about to leave this conversation.";
  1001. }
  1002. /**
  1003. * Resizes and repositions videos in full screen mode.
  1004. */
  1005. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1006. function () {
  1007. VideoLayout.resizeLargeVideoContainer();
  1008. VideoLayout.positionLarge();
  1009. isFullScreen = document.fullScreen ||
  1010. document.mozFullScreen ||
  1011. document.webkitIsFullScreen;
  1012. if (isFullScreen) {
  1013. setView("fullscreen");
  1014. }
  1015. else {
  1016. setView("default");
  1017. }
  1018. }
  1019. );
  1020. /**
  1021. * Sets the current view.
  1022. */
  1023. function setView(viewName) {
  1024. // if (viewName == "fullscreen") {
  1025. // document.getElementById('videolayout_fullscreen').disabled = false;
  1026. // document.getElementById('videolayout_default').disabled = true;
  1027. // }
  1028. // else {
  1029. // document.getElementById('videolayout_default').disabled = false;
  1030. // document.getElementById('videolayout_fullscreen').disabled = true;
  1031. // }
  1032. }
  1033. $(document).bind('fatalError.jingle',
  1034. function (event, session, error)
  1035. {
  1036. sessionTerminated = true;
  1037. connection.emuc.doLeave();
  1038. openMessageDialog( "Sorry",
  1039. "Your browser version is too old. Please update and try again...");
  1040. }
  1041. );