Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conference.js 51KB

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