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 38KB

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