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.

conference.js 37KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import {openConnection} from './connection';
  3. //FIXME:
  4. import createRoomLocker from './modules/UI/authentication/RoomLocker';
  5. //FIXME:
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import ConnectionQuality from './modules/connectionquality/connectionquality';
  8. import CQEvents from './service/connectionquality/CQEvents';
  9. import UIEvents from './service/UI/UIEvents';
  10. const ConnectionEvents = JitsiMeetJS.events.connection;
  11. const ConnectionErrors = JitsiMeetJS.errors.connection;
  12. const ConferenceEvents = JitsiMeetJS.events.conference;
  13. const ConferenceErrors = JitsiMeetJS.errors.conference;
  14. const TrackEvents = JitsiMeetJS.events.track;
  15. const TrackErrors = JitsiMeetJS.errors.track;
  16. let room, connection, localAudio, localVideo, roomLocker;
  17. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/LargeVideo";
  18. /**
  19. * Open Connection. When authentication failed it shows auth dialog.
  20. * @param roomName the room name to use
  21. * @returns Promise<JitsiConnection>
  22. */
  23. function connect(roomName) {
  24. return openConnection({retry: true, roomName: roomName})
  25. .catch(function (err) {
  26. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  27. APP.UI.notifyTokenAuthFailed();
  28. } else {
  29. APP.UI.notifyConnectionFailed(err);
  30. }
  31. throw err;
  32. });
  33. }
  34. /**
  35. * Share email with other users.
  36. * @param emailCommand the email command
  37. * @param {string} email new email
  38. */
  39. function sendEmail (emailCommand, email) {
  40. room.sendCommand(emailCommand, {
  41. value: email,
  42. attributes: {
  43. id: room.myUserId()
  44. }
  45. });
  46. }
  47. /**
  48. * Get user nickname by user id.
  49. * @param {string} id user id
  50. * @returns {string?} user nickname or undefined if user is unknown.
  51. */
  52. function getDisplayName (id) {
  53. if (APP.conference.isLocalId(id)) {
  54. return APP.settings.getDisplayName();
  55. }
  56. let participant = room.getParticipantById(id);
  57. if (participant && participant.getDisplayName()) {
  58. return participant.getDisplayName();
  59. }
  60. }
  61. /**
  62. * Mute or unmute local audio stream if it exists.
  63. * @param {boolean} muted if audio stream should be muted or unmuted.
  64. * @param {boolean} indicates if this local audio mute was a result of user
  65. * interaction
  66. *
  67. */
  68. function muteLocalAudio (muted, userInteraction) {
  69. if (!localAudio) {
  70. return;
  71. }
  72. if (muted) {
  73. localAudio.mute().then(function(value) {},
  74. function(value) {
  75. console.warn('Audio Mute was rejected:', value);
  76. }
  77. );
  78. } else {
  79. localAudio.unmute().then(function(value) {},
  80. function(value) {
  81. console.warn('Audio unmute was rejected:', value);
  82. }
  83. );
  84. }
  85. }
  86. /**
  87. * Mute or unmute local video stream if it exists.
  88. * @param {boolean} muted if video stream should be muted or unmuted.
  89. */
  90. function muteLocalVideo (muted) {
  91. if (!localVideo) {
  92. return;
  93. }
  94. if (muted) {
  95. localVideo.mute().then(function(value) {},
  96. function(value) {
  97. console.warn('Video mute was rejected:', value);
  98. }
  99. );
  100. } else {
  101. localVideo.unmute().then(function(value) {},
  102. function(value) {
  103. console.warn('Video unmute was rejected:', value);
  104. }
  105. );
  106. }
  107. }
  108. /**
  109. * Disconnect from the conference and optionally request user feedback.
  110. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  111. */
  112. function hangup (requestFeedback = false) {
  113. let promise = Promise.resolve();
  114. if (requestFeedback) {
  115. promise = APP.UI.requestFeedback();
  116. }
  117. promise.then(function () {
  118. connection.disconnect();
  119. if (!config.enableWelcomePage) {
  120. return;
  121. }
  122. // redirect to welcome page
  123. setTimeout(() => {
  124. APP.settings.setWelcomePageEnabled(true);
  125. window.location.pathname = "/";
  126. }, 3000);
  127. }, function (err) {
  128. console.error('Failed to hangup the call:', err);
  129. });
  130. }
  131. /**
  132. * Create local tracks of specified types.
  133. * @param {string[]} devices required track types ('audio', 'video' etc.)
  134. * @returns {Promise<JitsiLocalTrack[]>}
  135. */
  136. function createLocalTracks (...devices) {
  137. return JitsiMeetJS.createLocalTracks({
  138. // copy array to avoid mutations inside library
  139. devices: devices.slice(0),
  140. resolution: config.resolution,
  141. cameraDeviceId: APP.settings.getCameraDeviceId(),
  142. micDeviceId: APP.settings.getMicDeviceId(),
  143. // adds any ff fake device settings if any
  144. firefox_fake_device: config.firefox_fake_device
  145. }).catch(function (err) {
  146. console.error('failed to create local tracks', ...devices, err);
  147. return Promise.reject(err);
  148. });
  149. }
  150. class ConferenceConnector {
  151. constructor(resolve, reject) {
  152. this._resolve = resolve;
  153. this._reject = reject;
  154. this.reconnectTimeout = null;
  155. room.on(ConferenceEvents.CONFERENCE_JOINED,
  156. this._handleConferenceJoined.bind(this));
  157. room.on(ConferenceEvents.CONFERENCE_FAILED,
  158. this._onConferenceFailed.bind(this));
  159. room.on(ConferenceEvents.CONFERENCE_ERROR,
  160. this._onConferenceError.bind(this));
  161. }
  162. _handleConferenceFailed(err, msg) {
  163. this._unsubscribe();
  164. this._reject(err);
  165. }
  166. _onConferenceFailed(err, ...params) {
  167. console.error('CONFERENCE FAILED:', err, ...params);
  168. switch (err) {
  169. // room is locked by the password
  170. case ConferenceErrors.PASSWORD_REQUIRED:
  171. APP.UI.markRoomLocked(true);
  172. roomLocker.requirePassword().then(function () {
  173. room.join(roomLocker.password);
  174. });
  175. break;
  176. case ConferenceErrors.CONNECTION_ERROR:
  177. {
  178. let [msg] = params;
  179. APP.UI.notifyConnectionFailed(msg);
  180. }
  181. break;
  182. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  183. APP.UI.notifyBridgeDown();
  184. break;
  185. // not enough rights to create conference
  186. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  187. // schedule reconnect to check if someone else created the room
  188. this.reconnectTimeout = setTimeout(function () {
  189. room.join();
  190. }, 5000);
  191. // notify user that auth is required
  192. AuthHandler.requireAuth(room, roomLocker.password);
  193. break;
  194. case ConferenceErrors.RESERVATION_ERROR:
  195. {
  196. let [code, msg] = params;
  197. APP.UI.notifyReservationError(code, msg);
  198. }
  199. break;
  200. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  201. APP.UI.notifyGracefulShutdown();
  202. break;
  203. case ConferenceErrors.JINGLE_FATAL_ERROR:
  204. APP.UI.notifyInternalError();
  205. break;
  206. case ConferenceErrors.CONFERENCE_DESTROYED:
  207. {
  208. let [reason] = params;
  209. APP.UI.hideStats();
  210. APP.UI.notifyConferenceDestroyed(reason);
  211. }
  212. break;
  213. case ConferenceErrors.FOCUS_DISCONNECTED:
  214. {
  215. let [focus, retrySec] = params;
  216. APP.UI.notifyFocusDisconnected(focus, retrySec);
  217. }
  218. break;
  219. case ConferenceErrors.FOCUS_LEFT:
  220. room.leave().then(() => connection.disconnect());
  221. APP.UI.notifyFocusLeft();
  222. break;
  223. case ConferenceErrors.CONFERENCE_MAX_USERS:
  224. connection.disconnect();
  225. APP.UI.notifyMaxUsersLimitReached();
  226. break;
  227. default:
  228. this._handleConferenceFailed(err, ...params);
  229. }
  230. }
  231. _onConferenceError(err, ...params) {
  232. console.error('CONFERENCE Error:', err, params);
  233. switch (err) {
  234. case ConferenceErrors.CHAT_ERROR:
  235. {
  236. let [code, msg] = params;
  237. APP.UI.showChatError(code, msg);
  238. }
  239. break;
  240. default:
  241. console.error("Unknown error.");
  242. }
  243. }
  244. _unsubscribe() {
  245. room.off(
  246. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  247. room.off(
  248. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  249. if (this.reconnectTimeout !== null) {
  250. clearTimeout(this.reconnectTimeout);
  251. }
  252. AuthHandler.closeAuth();
  253. }
  254. _handleConferenceJoined() {
  255. this._unsubscribe();
  256. this._resolve();
  257. }
  258. connect() {
  259. room.join();
  260. }
  261. }
  262. export default {
  263. localId: undefined,
  264. isModerator: false,
  265. audioMuted: false,
  266. videoMuted: false,
  267. isSharingScreen: false,
  268. isDesktopSharingEnabled: false,
  269. /**
  270. * Open new connection and join to the conference.
  271. * @param {object} options
  272. * @param {string} roomName name of the conference
  273. * @returns {Promise}
  274. */
  275. init(options) {
  276. this.roomName = options.roomName;
  277. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  278. // attaches global error handler, if there is already one, respect it
  279. if(JitsiMeetJS.getGlobalOnErrorHandler){
  280. var oldOnErrorHandler = window.onerror;
  281. window.onerror = function (message, source, lineno, colno, error) {
  282. JitsiMeetJS.getGlobalOnErrorHandler(
  283. message, source, lineno, colno, error);
  284. if(oldOnErrorHandler)
  285. oldOnErrorHandler(message, source, lineno, colno, error);
  286. };
  287. }
  288. return JitsiMeetJS.init(config).then(() => {
  289. return Promise.all([
  290. // try to retrieve audio and video
  291. createLocalTracks('audio', 'video')
  292. // if failed then try to retrieve only audio
  293. .catch(() => createLocalTracks('audio'))
  294. // if audio also failed then just return empty array
  295. .catch(() => []),
  296. connect(options.roomName)
  297. ]);
  298. }).then(([tracks, con]) => {
  299. console.log('initialized with %s local tracks', tracks.length);
  300. APP.connection = connection = con;
  301. this._createRoom(tracks);
  302. this.isDesktopSharingEnabled =
  303. JitsiMeetJS.isDesktopSharingEnabled();
  304. // update list of available devices
  305. if (JitsiMeetJS.isDeviceListAvailable() &&
  306. JitsiMeetJS.isDeviceChangeAvailable()) {
  307. JitsiMeetJS.enumerateDevices(
  308. devices => APP.UI.onAvailableDevicesChanged(devices)
  309. );
  310. }
  311. // XXX The API will take care of disconnecting from the XMPP server
  312. // (and, thus, leaving the room) on unload.
  313. return new Promise((resolve, reject) => {
  314. (new ConferenceConnector(resolve, reject)).connect();
  315. });
  316. });
  317. },
  318. /**
  319. * Check if id is id of the local user.
  320. * @param {string} id id to check
  321. * @returns {boolean}
  322. */
  323. isLocalId (id) {
  324. return this.localId === id;
  325. },
  326. /**
  327. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  328. * @param mute true for mute and false for unmute.
  329. */
  330. muteAudio (mute) {
  331. muteLocalAudio(mute);
  332. },
  333. /**
  334. * Returns whether local audio is muted or not.
  335. * @returns {boolean}
  336. */
  337. isLocalAudioMuted() {
  338. return this.audioMuted;
  339. },
  340. /**
  341. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  342. */
  343. toggleAudioMuted () {
  344. this.muteAudio(!this.audioMuted);
  345. },
  346. /**
  347. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  348. * @param mute true for mute and false for unmute.
  349. */
  350. muteVideo (mute) {
  351. muteLocalVideo(mute);
  352. },
  353. /**
  354. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  355. */
  356. toggleVideoMuted () {
  357. this.muteVideo(!this.videoMuted);
  358. },
  359. /**
  360. * Retrieve list of conference participants (without local user).
  361. * @returns {JitsiParticipant[]}
  362. */
  363. listMembers () {
  364. return room.getParticipants();
  365. },
  366. /**
  367. * Retrieve list of ids of conference participants (without local user).
  368. * @returns {string[]}
  369. */
  370. listMembersIds () {
  371. return room.getParticipants().map(p => p.getId());
  372. },
  373. /**
  374. * Checks whether the participant identified by id is a moderator.
  375. * @id id to search for participant
  376. * @return {boolean} whether the participant is moderator
  377. */
  378. isParticipantModerator (id) {
  379. let user = room.getParticipantById(id);
  380. return user && user.isModerator();
  381. },
  382. /**
  383. * Check if SIP is supported.
  384. * @returns {boolean}
  385. */
  386. sipGatewayEnabled () {
  387. return room.isSIPCallingSupported();
  388. },
  389. get membersCount () {
  390. return room.getParticipants().length + 1;
  391. },
  392. /**
  393. * Returns true if the callstats integration is enabled, otherwise returns
  394. * false.
  395. *
  396. * @returns true if the callstats integration is enabled, otherwise returns
  397. * false.
  398. */
  399. isCallstatsEnabled () {
  400. return room.isCallstatsEnabled();
  401. },
  402. /**
  403. * Sends the given feedback through CallStats if enabled.
  404. *
  405. * @param overallFeedback an integer between 1 and 5 indicating the
  406. * user feedback
  407. * @param detailedFeedback detailed feedback from the user. Not yet used
  408. */
  409. sendFeedback (overallFeedback, detailedFeedback) {
  410. return room.sendFeedback (overallFeedback, detailedFeedback);
  411. },
  412. // used by torture currently
  413. isJoined () {
  414. return this._room
  415. && this._room.isJoined();
  416. },
  417. getConnectionState () {
  418. return this._room
  419. && this._room.getConnectionState();
  420. },
  421. getMyUserId () {
  422. return this._room
  423. && this._room.myUserId();
  424. },
  425. /**
  426. * Will be filled with values only when config.debug is enabled.
  427. * Its used by torture to check audio levels.
  428. */
  429. audioLevelsMap: {},
  430. /**
  431. * Returns the stored audio level (stored only if config.debug is enabled)
  432. * @param id the id for the user audio level to return (the id value is
  433. * returned for the participant using getMyUserId() method)
  434. */
  435. getPeerSSRCAudioLevel (id) {
  436. return this.audioLevelsMap[id];
  437. },
  438. /**
  439. * Will check for number of remote particiapnts that have at least one
  440. * remote track.
  441. * @return {boolean} whether we have enough participants with remote streams
  442. */
  443. checkEnoughParticipants (number) {
  444. var participants = this._room.getParticipants();
  445. var foundParticipants = 0;
  446. for (var i = 0; i < participants.length; i += 1) {
  447. if (participants[i].getTracks().length > 0) {
  448. foundParticipants++;
  449. }
  450. }
  451. return foundParticipants >= number;
  452. },
  453. /**
  454. * Returns the stats.
  455. */
  456. getStats() {
  457. return ConnectionQuality.getStats();
  458. },
  459. // end used by torture
  460. getLogs () {
  461. return room.getLogs();
  462. },
  463. /**
  464. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  465. * desire to keep room private to this instance and (2) the need of other
  466. * modules to send and receive commands to and from participants.
  467. * Eventually, this instance remains in control with respect to the
  468. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  469. * JitsiConference) is to be used in the implementation of the Command(s)
  470. * API of this instance.
  471. */
  472. commands: {
  473. /**
  474. * Known custom conference commands.
  475. */
  476. defaults: {
  477. CONNECTION_QUALITY: "stats",
  478. EMAIL: "email",
  479. ETHERPAD: "etherpad",
  480. SHARED_VIDEO: "shared-video",
  481. CUSTOM_ROLE: "custom-role"
  482. },
  483. /**
  484. * Receives notifications from other participants about commands aka
  485. * custom events (sent by sendCommand or sendCommandOnce methods).
  486. * @param command {String} the name of the command
  487. * @param handler {Function} handler for the command
  488. */
  489. addCommandListener () {
  490. room.addCommandListener.apply(room, arguments);
  491. },
  492. /**
  493. * Removes command.
  494. * @param name {String} the name of the command.
  495. */
  496. removeCommand () {
  497. room.removeCommand.apply(room, arguments);
  498. },
  499. /**
  500. * Sends command.
  501. * @param name {String} the name of the command.
  502. * @param values {Object} with keys and values that will be sent.
  503. */
  504. sendCommand () {
  505. room.sendCommand.apply(room, arguments);
  506. },
  507. /**
  508. * Sends command one time.
  509. * @param name {String} the name of the command.
  510. * @param values {Object} with keys and values that will be sent.
  511. */
  512. sendCommandOnce () {
  513. room.sendCommandOnce.apply(room, arguments);
  514. }
  515. },
  516. _createRoom (localTracks) {
  517. room = connection.initJitsiConference(APP.conference.roomName,
  518. this._getConferenceOptions());
  519. this.localId = room.myUserId();
  520. localTracks.forEach((track) => {
  521. if (track.isAudioTrack()) {
  522. this.useAudioStream(track);
  523. } else if (track.isVideoTrack()) {
  524. this.useVideoStream(track);
  525. }
  526. });
  527. roomLocker = createRoomLocker(room);
  528. this._room = room; // FIXME do not use this
  529. let email = APP.settings.getEmail();
  530. email && sendEmail(this.commands.defaults.EMAIL, email);
  531. let nick = APP.settings.getDisplayName();
  532. if (config.useNicks && !nick) {
  533. nick = APP.UI.askForNickname();
  534. APP.settings.setDisplayName(nick);
  535. }
  536. nick && room.setDisplayName(nick);
  537. this._setupListeners();
  538. },
  539. _getConferenceOptions() {
  540. let options = config;
  541. if(config.enableRecording && !config.recordingType) {
  542. options.recordingType = (config.hosts &&
  543. (typeof config.hosts.jirecon != "undefined"))?
  544. "jirecon" : "colibri";
  545. }
  546. return options;
  547. },
  548. /**
  549. * Start using provided video stream.
  550. * Stops previous video stream.
  551. * @param {JitsiLocalTrack} [stream] new stream to use or null
  552. * @returns {Promise}
  553. */
  554. useVideoStream (stream) {
  555. let promise = Promise.resolve();
  556. if (localVideo) {
  557. // this calls room.removeTrack internally
  558. // so we don't need to remove it manually
  559. promise = localVideo.dispose();
  560. }
  561. localVideo = stream;
  562. return promise.then(function () {
  563. if (stream) {
  564. return room.addTrack(stream);
  565. }
  566. }).then(() => {
  567. if (stream) {
  568. this.videoMuted = stream.isMuted();
  569. this.isSharingScreen = stream.videoType === 'desktop';
  570. APP.UI.addLocalStream(stream);
  571. } else {
  572. this.videoMuted = false;
  573. this.isSharingScreen = false;
  574. }
  575. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  576. APP.UI.updateDesktopSharingButtons();
  577. });
  578. },
  579. /**
  580. * Start using provided audio stream.
  581. * Stops previous audio stream.
  582. * @param {JitsiLocalTrack} [stream] new stream to use or null
  583. * @returns {Promise}
  584. */
  585. useAudioStream (stream) {
  586. let promise = Promise.resolve();
  587. if (localAudio) {
  588. // this calls room.removeTrack internally
  589. // so we don't need to remove it manually
  590. promise = localAudio.dispose();
  591. }
  592. localAudio = stream;
  593. return promise.then(function () {
  594. if (stream) {
  595. return room.addTrack(stream);
  596. }
  597. }).then(() => {
  598. if (stream) {
  599. this.audioMuted = stream.isMuted();
  600. APP.UI.addLocalStream(stream);
  601. } else {
  602. this.audioMuted = false;
  603. }
  604. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  605. });
  606. },
  607. videoSwitchInProgress: false,
  608. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  609. if (this.videoSwitchInProgress) {
  610. console.warn("Switch in progress.");
  611. return;
  612. }
  613. if (!this.isDesktopSharingEnabled) {
  614. console.warn("Cannot toggle screen sharing: not supported.");
  615. return;
  616. }
  617. this.videoSwitchInProgress = true;
  618. if (shareScreen) {
  619. createLocalTracks('desktop').then(([stream]) => {
  620. stream.on(
  621. TrackEvents.LOCAL_TRACK_STOPPED,
  622. () => {
  623. // if stream was stopped during screensharing session
  624. // then we should switch to video
  625. // otherwise we stopped it because we already switched
  626. // to video, so nothing to do here
  627. if (this.isSharingScreen) {
  628. this.toggleScreenSharing(false);
  629. }
  630. }
  631. );
  632. return this.useVideoStream(stream);
  633. }).then(() => {
  634. this.videoSwitchInProgress = false;
  635. console.log('sharing local desktop');
  636. }).catch((err) => {
  637. this.videoSwitchInProgress = false;
  638. this.toggleScreenSharing(false);
  639. if(err === TrackErrors.CHROME_EXTENSION_USER_CANCELED)
  640. return;
  641. console.error('failed to share local desktop', err);
  642. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  643. APP.UI.showExtensionRequiredDialog(
  644. config.desktopSharingFirefoxExtensionURL
  645. );
  646. return;
  647. }
  648. // Handling:
  649. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  650. // TrackErrors.GENERAL
  651. // and any other
  652. let dialogTxt = APP.translation
  653. .generateTranslationHTML("dialog.failtoinstall");
  654. let dialogTitle = APP.translation
  655. .generateTranslationHTML("dialog.error");
  656. APP.UI.messageHandler.openDialog(
  657. dialogTitle,
  658. dialogTxt,
  659. false
  660. );
  661. });
  662. } else {
  663. createLocalTracks('video').then(
  664. ([stream]) => this.useVideoStream(stream)
  665. ).then(() => {
  666. this.videoSwitchInProgress = false;
  667. console.log('sharing local video');
  668. }).catch((err) => {
  669. this.useVideoStream(null);
  670. this.videoSwitchInProgress = false;
  671. console.error('failed to share local video', err);
  672. });
  673. }
  674. },
  675. /**
  676. * Setup interaction between conference and UI.
  677. */
  678. _setupListeners () {
  679. // add local streams when joined to the conference
  680. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  681. APP.UI.mucJoined();
  682. });
  683. room.on(
  684. ConferenceEvents.AUTH_STATUS_CHANGED,
  685. function (authEnabled, authLogin) {
  686. APP.UI.updateAuthInfo(authEnabled, authLogin);
  687. }
  688. );
  689. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  690. console.log('USER %s connnected', id, user);
  691. APP.API.notifyUserJoined(id);
  692. APP.UI.addUser(id, user.getDisplayName());
  693. // chek the roles for the new user and reflect them
  694. APP.UI.updateUserRole(user);
  695. });
  696. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  697. console.log('USER %s LEFT', id, user);
  698. APP.API.notifyUserLeft(id);
  699. APP.UI.removeUser(id, user.getDisplayName());
  700. APP.UI.stopSharedVideo(id);
  701. });
  702. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  703. if (this.isLocalId(id)) {
  704. console.info(`My role changed, new role: ${role}`);
  705. this.isModerator = room.isModerator();
  706. APP.UI.updateLocalRole(room.isModerator());
  707. } else {
  708. let user = room.getParticipantById(id);
  709. if (user) {
  710. APP.UI.updateUserRole(user);
  711. }
  712. }
  713. });
  714. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  715. if(!track || track.isLocal())
  716. return;
  717. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  718. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  719. });
  720. APP.UI.addRemoteStream(track);
  721. });
  722. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  723. if(!track || track.isLocal())
  724. return;
  725. APP.UI.removeRemoteStream(track);
  726. });
  727. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  728. if(!track)
  729. return;
  730. const handler = (track.getType() === "audio")?
  731. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  732. let id;
  733. const mute = track.isMuted();
  734. if(track.isLocal()){
  735. id = this.localId;
  736. if(track.getType() === "audio") {
  737. this.audioMuted = mute;
  738. } else {
  739. this.videoMuted = mute;
  740. }
  741. } else {
  742. id = track.getParticipantId();
  743. }
  744. handler(id , mute);
  745. });
  746. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  747. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  748. lvl = 0;
  749. }
  750. if(config.debug)
  751. {
  752. this.audioLevelsMap[id] = lvl;
  753. console.log("AudioLevel:" + id + "/" + lvl);
  754. }
  755. APP.UI.setAudioLevel(id, lvl);
  756. });
  757. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  758. //FIXME
  759. if (config.muteLocalVideoIfNotInLastN) {
  760. // TODO mute or unmute if required
  761. // mark video on UI
  762. // APP.UI.markVideoMuted(true/false);
  763. }
  764. });
  765. room.on(
  766. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  767. APP.UI.handleLastNEndpoints(ids, enteringIds);
  768. });
  769. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  770. APP.UI.markDominantSpeaker(id);
  771. });
  772. if (!interfaceConfig.filmStripOnly) {
  773. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  774. APP.UI.markVideoInterrupted(true);
  775. });
  776. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  777. APP.UI.markVideoInterrupted(false);
  778. });
  779. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  780. let nick = getDisplayName(id);
  781. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  782. APP.UI.addMessage(id, nick, text, ts);
  783. });
  784. }
  785. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  786. APP.API.notifyDisplayNameChanged(id, displayName);
  787. APP.UI.changeDisplayName(id, displayName);
  788. });
  789. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  790. console.log("Received recorder status change: ", status, error);
  791. if(status == "error") {
  792. console.error(error);
  793. return;
  794. }
  795. APP.UI.updateRecordingState(status);
  796. });
  797. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  798. APP.UI.updateUserStatus(id, status);
  799. });
  800. room.on(ConferenceEvents.KICKED, () => {
  801. APP.UI.hideStats();
  802. APP.UI.notifyKicked();
  803. // FIXME close
  804. });
  805. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  806. APP.UI.updateDTMFSupport(isDTMFSupported);
  807. });
  808. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  809. if (room.isModerator()) {
  810. let promise = roomLocker.isLocked
  811. ? roomLocker.askToUnlock()
  812. : roomLocker.askToLock();
  813. promise.then(() => {
  814. APP.UI.markRoomLocked(roomLocker.isLocked);
  815. });
  816. } else {
  817. roomLocker.notifyModeratorRequired();
  818. }
  819. });
  820. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  821. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  822. if (!interfaceConfig.filmStripOnly) {
  823. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  824. APP.API.notifySendingChatMessage(message);
  825. room.sendTextMessage(message);
  826. });
  827. }
  828. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  829. ConnectionQuality.updateLocalStats(stats);
  830. });
  831. ConnectionQuality.addListener(
  832. CQEvents.LOCALSTATS_UPDATED,
  833. (percent, stats) => {
  834. APP.UI.updateLocalStats(percent, stats);
  835. // send local stats to other users
  836. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  837. {
  838. children: ConnectionQuality.convertToMUCStats(stats),
  839. attributes: {
  840. xmlns: 'http://jitsi.org/jitmeet/stats'
  841. }
  842. });
  843. }
  844. );
  845. // listen to remote stats
  846. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  847. (values, from) => {
  848. ConnectionQuality.updateRemoteStats(from, values);
  849. });
  850. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  851. (id, percent, stats) => {
  852. APP.UI.updateRemoteStats(id, percent, stats);
  853. });
  854. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  855. APP.UI.initEtherpad(value);
  856. });
  857. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  858. email = email.trim();
  859. if (email === APP.settings.getEmail()) {
  860. return;
  861. }
  862. APP.settings.setEmail(email);
  863. APP.UI.setUserAvatar(room.myUserId(), email);
  864. sendEmail(this.commands.defaults.EMAIL, email);
  865. });
  866. room.addCommandListener(this.commands.defaults.EMAIL, (data) => {
  867. APP.UI.setUserAvatar(data.attributes.id, data.value);
  868. });
  869. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  870. nickname = nickname.trim();
  871. if (nickname === APP.settings.getDisplayName()) {
  872. return;
  873. }
  874. APP.settings.setDisplayName(nickname);
  875. room.setDisplayName(nickname);
  876. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  877. });
  878. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  879. (startAudioMuted, startVideoMuted) => {
  880. room.setStartMutedPolicy({
  881. audio: startAudioMuted,
  882. video: startVideoMuted
  883. });
  884. }
  885. );
  886. room.on(
  887. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  888. ({ audio, video }) => {
  889. APP.UI.onStartMutedChanged(audio, video);
  890. }
  891. );
  892. room.on(ConferenceEvents.STARTED_MUTED, () => {
  893. (room.isStartAudioMuted() || room.isStartVideoMuted())
  894. && APP.UI.notifyInitiallyMuted();
  895. });
  896. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  897. APP.UI.inviteParticipants(
  898. roomUrl,
  899. APP.conference.roomName,
  900. roomLocker.password,
  901. APP.settings.getDisplayName()
  902. );
  903. });
  904. room.on(
  905. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  906. APP.UI.updateDevicesAvailability(id, devices);
  907. }
  908. );
  909. // call hangup
  910. APP.UI.addListener(UIEvents.HANGUP, () => {
  911. hangup(true);
  912. });
  913. // logout
  914. APP.UI.addListener(UIEvents.LOGOUT, () => {
  915. AuthHandler.logout(room).then(function (url) {
  916. if (url) {
  917. window.location.href = url;
  918. } else {
  919. hangup(true);
  920. }
  921. });
  922. });
  923. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  924. room.dial(sipNumber);
  925. });
  926. // Starts or stops the recording for the conference.
  927. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  928. room.toggleRecording(options);
  929. });
  930. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  931. room.setSubject(topic);
  932. });
  933. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  934. APP.UI.setSubject(subject);
  935. });
  936. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  937. room.kickParticipant(id);
  938. });
  939. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  940. room.muteParticipant(id);
  941. });
  942. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  943. AuthHandler.authenticate(room);
  944. });
  945. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  946. room.selectParticipant(id);
  947. });
  948. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  949. var smallVideoId = smallVideo.getId();
  950. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  951. && !APP.conference.isLocalId(smallVideoId))
  952. if (isPinned)
  953. room.pinParticipant(smallVideoId);
  954. // When the library starts supporting multiple pins we would
  955. // pass the isPinned parameter together with the identifier,
  956. // but currently we send null to indicate that we unpin the
  957. // last pinned.
  958. else
  959. room.pinParticipant(null);
  960. });
  961. APP.UI.addListener(
  962. UIEvents.VIDEO_DEVICE_CHANGED,
  963. (cameraDeviceId) => {
  964. APP.settings.setCameraDeviceId(cameraDeviceId);
  965. createLocalTracks('video').then(([stream]) => {
  966. this.useVideoStream(stream);
  967. console.log('switched local video device');
  968. });
  969. }
  970. );
  971. APP.UI.addListener(
  972. UIEvents.AUDIO_DEVICE_CHANGED,
  973. (micDeviceId) => {
  974. APP.settings.setMicDeviceId(micDeviceId);
  975. createLocalTracks('audio').then(([stream]) => {
  976. this.useAudioStream(stream);
  977. console.log('switched local audio device');
  978. });
  979. }
  980. );
  981. APP.UI.addListener(
  982. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  983. );
  984. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  985. (url, state, time, volume) => {
  986. // send start and stop commands once, and remove any updates
  987. // that had left
  988. if (state === 'stop' || state === 'start' || state === 'playing') {
  989. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  990. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  991. value: url,
  992. attributes: {
  993. state: state,
  994. time: time,
  995. volume: volume
  996. }
  997. });
  998. }
  999. else {
  1000. // in case of paused, in order to allow late users to join
  1001. // paused
  1002. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1003. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1004. value: url,
  1005. attributes: {
  1006. state: state,
  1007. time: time,
  1008. volume: volume
  1009. }
  1010. });
  1011. }
  1012. });
  1013. room.addCommandListener(
  1014. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1015. if (attributes.state === 'stop') {
  1016. APP.UI.stopSharedVideo(id, attributes);
  1017. } else if (attributes.state === 'start') {
  1018. APP.UI.showSharedVideo(id, value, attributes);
  1019. } else if (attributes.state === 'playing'
  1020. || attributes.state === 'pause') {
  1021. APP.UI.updateSharedVideo(id, value, attributes);
  1022. }
  1023. });
  1024. }
  1025. };