Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 58KB

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