Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 47KB

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