選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conference.js 48KB

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