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

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