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.

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