You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 52KB

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