You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 42KB

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