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.

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