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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  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. var oldOnUnhandledRejection = window.onunhandledrejection;
  308. window.onunhandledrejection = function(event) {
  309. JitsiMeetJS.getGlobalOnErrorHandler(
  310. null, null, null, null, event.reason);
  311. if(oldOnUnhandledRejection)
  312. oldOnUnhandledRejection(event);
  313. };
  314. }
  315. return JitsiMeetJS.init(config).then(() => {
  316. return Promise.all([
  317. // try to retrieve audio and video
  318. createLocalTracks('audio', 'video')
  319. // if failed then try to retrieve only audio
  320. .catch(() => createLocalTracks('audio'))
  321. // if audio also failed then just return empty array
  322. .catch(() => []),
  323. connect(options.roomName)
  324. ]);
  325. }).then(([tracks, con]) => {
  326. console.log('initialized with %s local tracks', tracks.length);
  327. APP.connection = connection = con;
  328. this._createRoom(tracks);
  329. this.isDesktopSharingEnabled =
  330. JitsiMeetJS.isDesktopSharingEnabled();
  331. // update list of available devices
  332. if (JitsiMeetJS.isDeviceListAvailable() &&
  333. JitsiMeetJS.isDeviceChangeAvailable()) {
  334. JitsiMeetJS.enumerateDevices(
  335. devices => APP.UI.onAvailableDevicesChanged(devices)
  336. );
  337. }
  338. if (config.iAmRecorder)
  339. this.recorder = new Recorder();
  340. // XXX The API will take care of disconnecting from the XMPP server
  341. // (and, thus, leaving the room) on unload.
  342. return new Promise((resolve, reject) => {
  343. (new ConferenceConnector(resolve, reject)).connect();
  344. });
  345. });
  346. },
  347. /**
  348. * Check if id is id of the local user.
  349. * @param {string} id id to check
  350. * @returns {boolean}
  351. */
  352. isLocalId (id) {
  353. return this.localId === id;
  354. },
  355. /**
  356. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  357. * @param mute true for mute and false for unmute.
  358. */
  359. muteAudio (mute) {
  360. muteLocalAudio(mute);
  361. },
  362. /**
  363. * Returns whether local audio is muted or not.
  364. * @returns {boolean}
  365. */
  366. isLocalAudioMuted() {
  367. return this.audioMuted;
  368. },
  369. /**
  370. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  371. */
  372. toggleAudioMuted () {
  373. this.muteAudio(!this.audioMuted);
  374. },
  375. /**
  376. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  377. * @param mute true for mute and false for unmute.
  378. */
  379. muteVideo (mute) {
  380. muteLocalVideo(mute);
  381. },
  382. /**
  383. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  384. */
  385. toggleVideoMuted () {
  386. this.muteVideo(!this.videoMuted);
  387. },
  388. /**
  389. * Retrieve list of conference participants (without local user).
  390. * @returns {JitsiParticipant[]}
  391. */
  392. listMembers () {
  393. return room.getParticipants();
  394. },
  395. /**
  396. * Retrieve list of ids of conference participants (without local user).
  397. * @returns {string[]}
  398. */
  399. listMembersIds () {
  400. return room.getParticipants().map(p => p.getId());
  401. },
  402. /**
  403. * Checks whether the participant identified by id is a moderator.
  404. * @id id to search for participant
  405. * @return {boolean} whether the participant is moderator
  406. */
  407. isParticipantModerator (id) {
  408. let user = room.getParticipantById(id);
  409. return user && user.isModerator();
  410. },
  411. /**
  412. * Check if SIP is supported.
  413. * @returns {boolean}
  414. */
  415. sipGatewayEnabled () {
  416. return room.isSIPCallingSupported();
  417. },
  418. get membersCount () {
  419. return room.getParticipants().length + 1;
  420. },
  421. /**
  422. * Returns true if the callstats integration is enabled, otherwise returns
  423. * false.
  424. *
  425. * @returns true if the callstats integration is enabled, otherwise returns
  426. * false.
  427. */
  428. isCallstatsEnabled () {
  429. return room.isCallstatsEnabled();
  430. },
  431. /**
  432. * Sends the given feedback through CallStats if enabled.
  433. *
  434. * @param overallFeedback an integer between 1 and 5 indicating the
  435. * user feedback
  436. * @param detailedFeedback detailed feedback from the user. Not yet used
  437. */
  438. sendFeedback (overallFeedback, detailedFeedback) {
  439. return room.sendFeedback (overallFeedback, detailedFeedback);
  440. },
  441. // used by torture currently
  442. isJoined () {
  443. return this._room
  444. && this._room.isJoined();
  445. },
  446. getConnectionState () {
  447. return this._room
  448. && this._room.getConnectionState();
  449. },
  450. getMyUserId () {
  451. return this._room
  452. && this._room.myUserId();
  453. },
  454. /**
  455. * Indicates if recording is supported in this conference.
  456. */
  457. isRecordingSupported() {
  458. return this._room && this._room.isRecordingSupported();
  459. },
  460. /**
  461. * Returns the recording state or undefined if the room is not defined.
  462. */
  463. getRecordingState() {
  464. return (this._room) ? this._room.getRecordingState() : undefined;
  465. },
  466. /**
  467. * Will be filled with values only when config.debug is enabled.
  468. * Its used by torture to check audio levels.
  469. */
  470. audioLevelsMap: {},
  471. /**
  472. * Returns the stored audio level (stored only if config.debug is enabled)
  473. * @param id the id for the user audio level to return (the id value is
  474. * returned for the participant using getMyUserId() method)
  475. */
  476. getPeerSSRCAudioLevel (id) {
  477. return this.audioLevelsMap[id];
  478. },
  479. /**
  480. * @return {number} the number of participants in the conference with at
  481. * least one track.
  482. */
  483. getNumberOfParticipantsWithTracks() {
  484. return this._room.getParticipants()
  485. .filter((p) => p.getTracks().length > 0)
  486. .length;
  487. },
  488. /**
  489. * Returns the stats.
  490. */
  491. getStats() {
  492. return ConnectionQuality.getStats();
  493. },
  494. // end used by torture
  495. getLogs () {
  496. return room.getLogs();
  497. },
  498. /**
  499. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  500. * desire to keep room private to this instance and (2) the need of other
  501. * modules to send and receive commands to and from participants.
  502. * Eventually, this instance remains in control with respect to the
  503. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  504. * JitsiConference) is to be used in the implementation of the Command(s)
  505. * API of this instance.
  506. */
  507. commands: {
  508. /**
  509. * Known custom conference commands.
  510. */
  511. defaults: {
  512. CONNECTION_QUALITY: "stats",
  513. EMAIL: "email",
  514. ETHERPAD: "etherpad",
  515. SHARED_VIDEO: "shared-video",
  516. CUSTOM_ROLE: "custom-role"
  517. },
  518. /**
  519. * Receives notifications from other participants about commands aka
  520. * custom events (sent by sendCommand or sendCommandOnce methods).
  521. * @param command {String} the name of the command
  522. * @param handler {Function} handler for the command
  523. */
  524. addCommandListener () {
  525. room.addCommandListener.apply(room, arguments);
  526. },
  527. /**
  528. * Removes command.
  529. * @param name {String} the name of the command.
  530. */
  531. removeCommand () {
  532. room.removeCommand.apply(room, arguments);
  533. },
  534. /**
  535. * Sends command.
  536. * @param name {String} the name of the command.
  537. * @param values {Object} with keys and values that will be sent.
  538. */
  539. sendCommand () {
  540. room.sendCommand.apply(room, arguments);
  541. },
  542. /**
  543. * Sends command one time.
  544. * @param name {String} the name of the command.
  545. * @param values {Object} with keys and values that will be sent.
  546. */
  547. sendCommandOnce () {
  548. room.sendCommandOnce.apply(room, arguments);
  549. }
  550. },
  551. _createRoom (localTracks) {
  552. room = connection.initJitsiConference(APP.conference.roomName,
  553. this._getConferenceOptions());
  554. this.localId = room.myUserId();
  555. localTracks.forEach((track) => {
  556. if (track.isAudioTrack()) {
  557. this.useAudioStream(track);
  558. } else if (track.isVideoTrack()) {
  559. this.useVideoStream(track);
  560. } else {
  561. console.error(
  562. "Ignored not an audio nor a video track: ", track);
  563. }
  564. });
  565. roomLocker = createRoomLocker(room);
  566. this._room = room; // FIXME do not use this
  567. let email = APP.settings.getEmail();
  568. email && sendEmail(this.commands.defaults.EMAIL, email);
  569. let nick = APP.settings.getDisplayName();
  570. if (config.useNicks && !nick) {
  571. nick = APP.UI.askForNickname();
  572. APP.settings.setDisplayName(nick);
  573. }
  574. nick && room.setDisplayName(nick);
  575. this._setupListeners();
  576. },
  577. _getConferenceOptions() {
  578. let options = config;
  579. if(config.enableRecording && !config.recordingType) {
  580. options.recordingType = (config.hosts &&
  581. (typeof config.hosts.jirecon != "undefined"))?
  582. "jirecon" : "colibri";
  583. }
  584. return options;
  585. },
  586. /**
  587. * Start using provided video stream.
  588. * Stops previous video stream.
  589. * @param {JitsiLocalTrack} [stream] new stream to use or null
  590. * @returns {Promise}
  591. */
  592. useVideoStream (stream) {
  593. let promise = Promise.resolve();
  594. if (localVideo) {
  595. // this calls room.removeTrack internally
  596. // so we don't need to remove it manually
  597. promise = localVideo.dispose();
  598. }
  599. localVideo = stream;
  600. return promise.then(function () {
  601. if (stream) {
  602. return room.addTrack(stream);
  603. }
  604. }).then(() => {
  605. if (stream) {
  606. this.videoMuted = stream.isMuted();
  607. this.isSharingScreen = stream.videoType === 'desktop';
  608. APP.UI.addLocalStream(stream);
  609. } else {
  610. this.videoMuted = false;
  611. this.isSharingScreen = false;
  612. }
  613. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  614. APP.UI.updateDesktopSharingButtons();
  615. });
  616. },
  617. /**
  618. * Start using provided audio stream.
  619. * Stops previous audio stream.
  620. * @param {JitsiLocalTrack} [stream] new stream to use or null
  621. * @returns {Promise}
  622. */
  623. useAudioStream (stream) {
  624. let promise = Promise.resolve();
  625. if (localAudio) {
  626. // this calls room.removeTrack internally
  627. // so we don't need to remove it manually
  628. promise = localAudio.dispose();
  629. }
  630. localAudio = stream;
  631. return promise.then(function () {
  632. if (stream) {
  633. return room.addTrack(stream);
  634. }
  635. }).then(() => {
  636. if (stream) {
  637. this.audioMuted = stream.isMuted();
  638. APP.UI.addLocalStream(stream);
  639. } else {
  640. this.audioMuted = false;
  641. }
  642. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  643. });
  644. },
  645. videoSwitchInProgress: false,
  646. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  647. if (this.videoSwitchInProgress) {
  648. console.warn("Switch in progress.");
  649. return;
  650. }
  651. if (!this.isDesktopSharingEnabled) {
  652. console.warn("Cannot toggle screen sharing: not supported.");
  653. return;
  654. }
  655. this.videoSwitchInProgress = true;
  656. if (shareScreen) {
  657. createLocalTracks('desktop').then(([stream]) => {
  658. stream.on(
  659. TrackEvents.LOCAL_TRACK_STOPPED,
  660. () => {
  661. // if stream was stopped during screensharing session
  662. // then we should switch to video
  663. // otherwise we stopped it because we already switched
  664. // to video, so nothing to do here
  665. if (this.isSharingScreen) {
  666. this.toggleScreenSharing(false);
  667. }
  668. }
  669. );
  670. return this.useVideoStream(stream);
  671. }).then(() => {
  672. this.videoSwitchInProgress = false;
  673. console.log('sharing local desktop');
  674. }).catch((err) => {
  675. this.videoSwitchInProgress = false;
  676. this.toggleScreenSharing(false);
  677. if(err === TrackErrors.CHROME_EXTENSION_USER_CANCELED)
  678. return;
  679. console.error('failed to share local desktop', err);
  680. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  681. APP.UI.showExtensionRequiredDialog(
  682. config.desktopSharingFirefoxExtensionURL
  683. );
  684. return;
  685. }
  686. // Handling:
  687. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  688. // TrackErrors.GENERAL
  689. // and any other
  690. let dialogTxt = APP.translation
  691. .generateTranslationHTML("dialog.failtoinstall");
  692. let dialogTitle = APP.translation
  693. .generateTranslationHTML("dialog.error");
  694. APP.UI.messageHandler.openDialog(
  695. dialogTitle,
  696. dialogTxt,
  697. false
  698. );
  699. });
  700. } else {
  701. createLocalTracks('video').then(
  702. ([stream]) => this.useVideoStream(stream)
  703. ).then(() => {
  704. this.videoSwitchInProgress = false;
  705. console.log('sharing local video');
  706. }).catch((err) => {
  707. this.useVideoStream(null);
  708. this.videoSwitchInProgress = false;
  709. console.error('failed to share local video', err);
  710. });
  711. }
  712. },
  713. /**
  714. * Setup interaction between conference and UI.
  715. */
  716. _setupListeners () {
  717. // add local streams when joined to the conference
  718. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  719. APP.UI.mucJoined();
  720. });
  721. room.on(
  722. ConferenceEvents.AUTH_STATUS_CHANGED,
  723. function (authEnabled, authLogin) {
  724. APP.UI.updateAuthInfo(authEnabled, authLogin);
  725. }
  726. );
  727. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  728. if (user.isHidden())
  729. return;
  730. console.log('USER %s connnected', id, user);
  731. APP.API.notifyUserJoined(id);
  732. APP.UI.addUser(id, user.getDisplayName());
  733. // check the roles for the new user and reflect them
  734. APP.UI.updateUserRole(user);
  735. });
  736. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  737. console.log('USER %s LEFT', id, user);
  738. APP.API.notifyUserLeft(id);
  739. APP.UI.removeUser(id, user.getDisplayName());
  740. APP.UI.onSharedVideoStop(id);
  741. });
  742. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  743. if (this.isLocalId(id)) {
  744. console.info(`My role changed, new role: ${role}`);
  745. this.isModerator = room.isModerator();
  746. APP.UI.updateLocalRole(room.isModerator());
  747. } else {
  748. let user = room.getParticipantById(id);
  749. if (user) {
  750. APP.UI.updateUserRole(user);
  751. }
  752. }
  753. });
  754. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  755. if(!track || track.isLocal())
  756. return;
  757. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  758. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  759. });
  760. APP.UI.addRemoteStream(track);
  761. });
  762. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  763. if(!track || track.isLocal())
  764. return;
  765. APP.UI.removeRemoteStream(track);
  766. });
  767. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  768. if(!track)
  769. return;
  770. const handler = (track.getType() === "audio")?
  771. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  772. let id;
  773. const mute = track.isMuted();
  774. if(track.isLocal()){
  775. id = this.localId;
  776. if(track.getType() === "audio") {
  777. this.audioMuted = mute;
  778. } else {
  779. this.videoMuted = mute;
  780. }
  781. } else {
  782. id = track.getParticipantId();
  783. }
  784. handler(id , mute);
  785. });
  786. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  787. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  788. lvl = 0;
  789. }
  790. if(config.debug)
  791. {
  792. this.audioLevelsMap[id] = lvl;
  793. console.log("AudioLevel:" + id + "/" + lvl);
  794. }
  795. APP.UI.setAudioLevel(id, lvl);
  796. });
  797. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  798. //FIXME
  799. if (config.muteLocalVideoIfNotInLastN) {
  800. // TODO mute or unmute if required
  801. // mark video on UI
  802. // APP.UI.markVideoMuted(true/false);
  803. }
  804. });
  805. room.on(
  806. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  807. APP.UI.handleLastNEndpoints(ids, enteringIds);
  808. });
  809. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  810. APP.UI.markDominantSpeaker(id);
  811. });
  812. if (!interfaceConfig.filmStripOnly) {
  813. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  814. APP.UI.markVideoInterrupted(true);
  815. });
  816. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  817. APP.UI.markVideoInterrupted(false);
  818. });
  819. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  820. let nick = getDisplayName(id);
  821. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  822. APP.UI.addMessage(id, nick, text, ts);
  823. });
  824. }
  825. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  826. APP.API.notifyDisplayNameChanged(id, displayName);
  827. APP.UI.changeDisplayName(id, displayName);
  828. });
  829. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  830. console.log("Received recorder status change: ", status, error);
  831. APP.UI.updateRecordingState(status);
  832. });
  833. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  834. APP.UI.updateUserStatus(id, status);
  835. });
  836. room.on(ConferenceEvents.KICKED, () => {
  837. APP.UI.hideStats();
  838. APP.UI.notifyKicked();
  839. // FIXME close
  840. });
  841. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  842. APP.UI.updateDTMFSupport(isDTMFSupported);
  843. });
  844. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  845. if (room.isModerator()) {
  846. let promise = roomLocker.isLocked
  847. ? roomLocker.askToUnlock()
  848. : roomLocker.askToLock();
  849. promise.then(() => {
  850. APP.UI.markRoomLocked(roomLocker.isLocked);
  851. });
  852. } else {
  853. roomLocker.notifyModeratorRequired();
  854. }
  855. });
  856. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  857. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  858. if (!interfaceConfig.filmStripOnly) {
  859. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  860. APP.API.notifySendingChatMessage(message);
  861. room.sendTextMessage(message);
  862. });
  863. }
  864. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  865. ConnectionQuality.updateLocalStats(stats);
  866. });
  867. ConnectionQuality.addListener(
  868. CQEvents.LOCALSTATS_UPDATED,
  869. (percent, stats) => {
  870. APP.UI.updateLocalStats(percent, stats);
  871. // send local stats to other users
  872. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  873. {
  874. children: ConnectionQuality.convertToMUCStats(stats),
  875. attributes: {
  876. xmlns: 'http://jitsi.org/jitmeet/stats'
  877. }
  878. });
  879. }
  880. );
  881. // listen to remote stats
  882. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  883. (values, from) => {
  884. ConnectionQuality.updateRemoteStats(from, values);
  885. });
  886. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  887. (id, percent, stats) => {
  888. APP.UI.updateRemoteStats(id, percent, stats);
  889. });
  890. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  891. APP.UI.initEtherpad(value);
  892. });
  893. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  894. email = email.trim();
  895. if (email === APP.settings.getEmail()) {
  896. return;
  897. }
  898. APP.settings.setEmail(email);
  899. APP.UI.setUserAvatar(room.myUserId(), email);
  900. sendEmail(this.commands.defaults.EMAIL, email);
  901. });
  902. room.addCommandListener(this.commands.defaults.EMAIL, (data) => {
  903. APP.UI.setUserAvatar(data.attributes.id, data.value);
  904. });
  905. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  906. nickname = nickname.trim();
  907. if (nickname === APP.settings.getDisplayName()) {
  908. return;
  909. }
  910. APP.settings.setDisplayName(nickname);
  911. room.setDisplayName(nickname);
  912. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  913. });
  914. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  915. (startAudioMuted, startVideoMuted) => {
  916. room.setStartMutedPolicy({
  917. audio: startAudioMuted,
  918. video: startVideoMuted
  919. });
  920. }
  921. );
  922. room.on(
  923. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  924. ({ audio, video }) => {
  925. APP.UI.onStartMutedChanged(audio, video);
  926. }
  927. );
  928. room.on(ConferenceEvents.STARTED_MUTED, () => {
  929. (room.isStartAudioMuted() || room.isStartVideoMuted())
  930. && APP.UI.notifyInitiallyMuted();
  931. });
  932. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  933. APP.UI.inviteParticipants(
  934. roomUrl,
  935. APP.conference.roomName,
  936. roomLocker.password,
  937. APP.settings.getDisplayName()
  938. );
  939. });
  940. room.on(
  941. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  942. APP.UI.updateDevicesAvailability(id, devices);
  943. }
  944. );
  945. // call hangup
  946. APP.UI.addListener(UIEvents.HANGUP, () => {
  947. hangup(true);
  948. });
  949. // logout
  950. APP.UI.addListener(UIEvents.LOGOUT, () => {
  951. AuthHandler.logout(room).then(function (url) {
  952. if (url) {
  953. window.location.href = url;
  954. } else {
  955. hangup(true);
  956. }
  957. });
  958. });
  959. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  960. room.dial(sipNumber);
  961. });
  962. // Starts or stops the recording for the conference.
  963. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  964. room.toggleRecording(options);
  965. });
  966. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  967. room.setSubject(topic);
  968. });
  969. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  970. APP.UI.setSubject(subject);
  971. });
  972. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  973. room.kickParticipant(id);
  974. });
  975. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  976. room.muteParticipant(id);
  977. });
  978. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  979. AuthHandler.authenticate(room);
  980. });
  981. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  982. room.selectParticipant(id);
  983. });
  984. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  985. var smallVideoId = smallVideo.getId();
  986. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  987. && !APP.conference.isLocalId(smallVideoId))
  988. if (isPinned)
  989. room.pinParticipant(smallVideoId);
  990. // When the library starts supporting multiple pins we would
  991. // pass the isPinned parameter together with the identifier,
  992. // but currently we send null to indicate that we unpin the
  993. // last pinned.
  994. else
  995. room.pinParticipant(null);
  996. });
  997. APP.UI.addListener(
  998. UIEvents.VIDEO_DEVICE_CHANGED,
  999. (cameraDeviceId) => {
  1000. APP.settings.setCameraDeviceId(cameraDeviceId);
  1001. createLocalTracks('video').then(([stream]) => {
  1002. this.useVideoStream(stream);
  1003. console.log('switched local video device');
  1004. });
  1005. }
  1006. );
  1007. APP.UI.addListener(
  1008. UIEvents.AUDIO_DEVICE_CHANGED,
  1009. (micDeviceId) => {
  1010. APP.settings.setMicDeviceId(micDeviceId);
  1011. createLocalTracks('audio').then(([stream]) => {
  1012. this.useAudioStream(stream);
  1013. console.log('switched local audio device');
  1014. });
  1015. }
  1016. );
  1017. APP.UI.addListener(
  1018. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1019. (audioOutputDeviceId) => {
  1020. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1021. .then(() => console.log('changed audio output device'))
  1022. .catch((err) => {
  1023. console.error('failed to set audio output device', err);
  1024. });
  1025. }
  1026. );
  1027. APP.UI.addListener(
  1028. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1029. );
  1030. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1031. (url, state, time, isMuted, volume) => {
  1032. // send start and stop commands once, and remove any updates
  1033. // that had left
  1034. if (state === 'stop' || state === 'start' || state === 'playing') {
  1035. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1036. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1037. value: url,
  1038. attributes: {
  1039. state: state,
  1040. time: time,
  1041. muted: isMuted,
  1042. volume: volume
  1043. }
  1044. });
  1045. }
  1046. else {
  1047. // in case of paused, in order to allow late users to join
  1048. // paused
  1049. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1050. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1051. value: url,
  1052. attributes: {
  1053. state: state,
  1054. time: time,
  1055. muted: isMuted,
  1056. volume: volume
  1057. }
  1058. });
  1059. }
  1060. });
  1061. room.addCommandListener(
  1062. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1063. if (attributes.state === 'stop') {
  1064. APP.UI.onSharedVideoStop(id, attributes);
  1065. }
  1066. else if (attributes.state === 'start') {
  1067. APP.UI.onSharedVideoStart(id, value, attributes);
  1068. }
  1069. else if (attributes.state === 'playing'
  1070. || attributes.state === 'pause') {
  1071. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1072. }
  1073. });
  1074. },
  1075. /**
  1076. * Adss any room listener.
  1077. * @param eventName one of the ConferenceEvents
  1078. * @param callBack the function to be called when the event occurs
  1079. */
  1080. addConferenceListener(eventName, callBack) {
  1081. room.on(eventName, callBack);
  1082. }
  1083. };