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

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