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

conference.js 60KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  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. /**
  616. * Checks whether or not our connection is currently in interrupted and
  617. * reconnect attempts are in progress.
  618. *
  619. * @returns {boolean} true if the connection is in interrupted state or
  620. * false otherwise.
  621. */
  622. isConnectionInterrupted () {
  623. return connectionIsInterrupted;
  624. },
  625. /**
  626. * Finds JitsiParticipant for given id.
  627. *
  628. * @param {string} id participant's identifier(MUC nickname).
  629. *
  630. * @returns {JitsiParticipant|null} participant instance for given id or
  631. * null if not found.
  632. */
  633. getParticipantById (id) {
  634. return room ? room.getParticipantById(id) : null;
  635. },
  636. /**
  637. * Checks whether the user identified by given id is currently connected.
  638. *
  639. * @param {string} id participant's identifier(MUC nickname)
  640. *
  641. * @returns {boolean|null} true if participant's connection is ok or false
  642. * if the user is having connectivity issues.
  643. */
  644. isParticipantConnectionActive (id) {
  645. let participant = this.getParticipantById(id);
  646. return participant ? participant.isConnectionActive() : null;
  647. },
  648. /**
  649. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  650. * the given <tt>id</tt>.
  651. *
  652. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  653. *
  654. * @return {string} the participant's display name or the default string if
  655. * absent.
  656. */
  657. getParticipantDisplayName (id) {
  658. let displayName = getDisplayName(id);
  659. if (displayName) {
  660. return displayName;
  661. } else {
  662. if (APP.conference.isLocalId(id)) {
  663. return APP.translation.generateTranslationHTML(
  664. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  665. } else {
  666. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  667. }
  668. }
  669. },
  670. getMyUserId () {
  671. return this._room
  672. && this._room.myUserId();
  673. },
  674. /**
  675. * Indicates if recording is supported in this conference.
  676. */
  677. isRecordingSupported() {
  678. return this._room && this._room.isRecordingSupported();
  679. },
  680. /**
  681. * Returns the recording state or undefined if the room is not defined.
  682. */
  683. getRecordingState() {
  684. return (this._room) ? this._room.getRecordingState() : undefined;
  685. },
  686. /**
  687. * Will be filled with values only when config.debug is enabled.
  688. * Its used by torture to check audio levels.
  689. */
  690. audioLevelsMap: {},
  691. /**
  692. * Returns the stored audio level (stored only if config.debug is enabled)
  693. * @param id the id for the user audio level to return (the id value is
  694. * returned for the participant using getMyUserId() method)
  695. */
  696. getPeerSSRCAudioLevel (id) {
  697. return this.audioLevelsMap[id];
  698. },
  699. /**
  700. * @return {number} the number of participants in the conference with at
  701. * least one track.
  702. */
  703. getNumberOfParticipantsWithTracks() {
  704. return this._room.getParticipants()
  705. .filter((p) => p.getTracks().length > 0)
  706. .length;
  707. },
  708. /**
  709. * Returns the stats.
  710. */
  711. getStats() {
  712. return ConnectionQuality.getStats();
  713. },
  714. // end used by torture
  715. getLogs () {
  716. return room.getLogs();
  717. },
  718. /**
  719. * Download logs, a function that can be called from console while
  720. * debugging.
  721. * @param filename (optional) specify target filename
  722. */
  723. saveLogs (filename = 'meetlog.json') {
  724. // this can be called from console and will not have reference to this
  725. // that's why we reference the global var
  726. let logs = APP.conference.getLogs();
  727. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  728. let elem = document.createElement('a');
  729. elem.download = filename;
  730. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  731. elem.dataset.downloadurl
  732. = ['text/json', elem.download, elem.href].join(':');
  733. elem.dispatchEvent(new MouseEvent('click', {
  734. view: window,
  735. bubbles: true,
  736. cancelable: false
  737. }));
  738. },
  739. /**
  740. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  741. * desire to keep room private to this instance and (2) the need of other
  742. * modules to send and receive commands to and from participants.
  743. * Eventually, this instance remains in control with respect to the
  744. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  745. * JitsiConference) is to be used in the implementation of the Command(s)
  746. * API of this instance.
  747. */
  748. commands: {
  749. /**
  750. * Known custom conference commands.
  751. */
  752. defaults: commands,
  753. /**
  754. * Receives notifications from other participants about commands aka
  755. * custom events (sent by sendCommand or sendCommandOnce methods).
  756. * @param command {String} the name of the command
  757. * @param handler {Function} handler for the command
  758. */
  759. addCommandListener () {
  760. room.addCommandListener.apply(room, arguments);
  761. },
  762. /**
  763. * Removes command.
  764. * @param name {String} the name of the command.
  765. */
  766. removeCommand () {
  767. room.removeCommand.apply(room, arguments);
  768. },
  769. /**
  770. * Sends command.
  771. * @param name {String} the name of the command.
  772. * @param values {Object} with keys and values that will be sent.
  773. */
  774. sendCommand () {
  775. room.sendCommand.apply(room, arguments);
  776. },
  777. /**
  778. * Sends command one time.
  779. * @param name {String} the name of the command.
  780. * @param values {Object} with keys and values that will be sent.
  781. */
  782. sendCommandOnce () {
  783. room.sendCommandOnce.apply(room, arguments);
  784. }
  785. },
  786. _createRoom (localTracks) {
  787. room = connection.initJitsiConference(APP.conference.roomName,
  788. this._getConferenceOptions());
  789. this._setLocalAudioVideoStreams(localTracks);
  790. roomLocker = createRoomLocker(room);
  791. this._room = room; // FIXME do not use this
  792. let email = APP.settings.getEmail();
  793. email && sendData(this.commands.defaults.EMAIL, email);
  794. let avatarUrl = APP.settings.getAvatarUrl();
  795. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  796. avatarUrl);
  797. !email && sendData(
  798. this.commands.defaults.AVATAR_ID, APP.settings.getAvatarId());
  799. let nick = APP.settings.getDisplayName();
  800. if (config.useNicks && !nick) {
  801. nick = APP.UI.askForNickname();
  802. APP.settings.setDisplayName(nick);
  803. }
  804. nick && room.setDisplayName(nick);
  805. this._setupListeners();
  806. },
  807. /**
  808. * Sets local video and audio streams.
  809. * @param {JitsiLocalTrack[]} tracks=[]
  810. * @returns {Promise[]}
  811. * @private
  812. */
  813. _setLocalAudioVideoStreams(tracks = []) {
  814. return tracks.map(track => {
  815. if (track.isAudioTrack()) {
  816. return this.useAudioStream(track);
  817. } else if (track.isVideoTrack()) {
  818. return this.useVideoStream(track);
  819. } else {
  820. console.error(
  821. "Ignored not an audio nor a video track: ", track);
  822. return Promise.resolve();
  823. }
  824. });
  825. },
  826. _getConferenceOptions() {
  827. let options = config;
  828. if(config.enableRecording && !config.recordingType) {
  829. options.recordingType = (config.hosts &&
  830. (typeof config.hosts.jirecon != "undefined"))?
  831. "jirecon" : "colibri";
  832. }
  833. return options;
  834. },
  835. /**
  836. * Start using provided video stream.
  837. * Stops previous video stream.
  838. * @param {JitsiLocalTrack} [stream] new stream to use or null
  839. * @returns {Promise}
  840. */
  841. useVideoStream (stream) {
  842. let promise = Promise.resolve();
  843. if (localVideo) {
  844. // this calls room.removeTrack internally
  845. // so we don't need to remove it manually
  846. promise = localVideo.dispose();
  847. }
  848. localVideo = stream;
  849. return promise.then(function () {
  850. if (stream) {
  851. return room.addTrack(stream);
  852. }
  853. }).then(() => {
  854. if (stream) {
  855. this.videoMuted = stream.isMuted();
  856. this.isSharingScreen = stream.videoType === 'desktop';
  857. APP.UI.addLocalStream(stream);
  858. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  859. } else {
  860. this.videoMuted = false;
  861. this.isSharingScreen = false;
  862. }
  863. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  864. APP.UI.updateDesktopSharingButtons();
  865. });
  866. },
  867. /**
  868. * Start using provided audio stream.
  869. * Stops previous audio stream.
  870. * @param {JitsiLocalTrack} [stream] new stream to use or null
  871. * @returns {Promise}
  872. */
  873. useAudioStream (stream) {
  874. let promise = Promise.resolve();
  875. if (localAudio) {
  876. // this calls room.removeTrack internally
  877. // so we don't need to remove it manually
  878. promise = localAudio.dispose();
  879. }
  880. localAudio = stream;
  881. return promise.then(function () {
  882. if (stream) {
  883. return room.addTrack(stream);
  884. }
  885. }).then(() => {
  886. if (stream) {
  887. this.audioMuted = stream.isMuted();
  888. APP.UI.addLocalStream(stream);
  889. } else {
  890. this.audioMuted = false;
  891. }
  892. APP.UI.enableMicrophoneButton();
  893. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  894. });
  895. },
  896. videoSwitchInProgress: false,
  897. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  898. if (this.videoSwitchInProgress) {
  899. console.warn("Switch in progress.");
  900. return;
  901. }
  902. if (!this.isDesktopSharingEnabled) {
  903. console.warn("Cannot toggle screen sharing: not supported.");
  904. return;
  905. }
  906. this.videoSwitchInProgress = true;
  907. let externalInstallation = false;
  908. if (shareScreen) {
  909. createLocalTracks({
  910. devices: ['desktop'],
  911. desktopSharingExtensionExternalInstallation: {
  912. interval: 500,
  913. checkAgain: () => {
  914. return DSExternalInstallationInProgress;
  915. },
  916. listener: (status, url) => {
  917. switch(status) {
  918. case "waitingForExtension":
  919. DSExternalInstallationInProgress = true;
  920. externalInstallation = true;
  921. APP.UI.showExtensionExternalInstallationDialog(
  922. url);
  923. break;
  924. case "extensionFound":
  925. if(externalInstallation) //close the dialog
  926. $.prompt.close();
  927. break;
  928. default:
  929. //Unknown status
  930. }
  931. }
  932. }
  933. }).then(([stream]) => {
  934. DSExternalInstallationInProgress = false;
  935. // close external installation dialog on success.
  936. if(externalInstallation)
  937. $.prompt.close();
  938. stream.on(
  939. TrackEvents.LOCAL_TRACK_STOPPED,
  940. () => {
  941. // if stream was stopped during screensharing session
  942. // then we should switch to video
  943. // otherwise we stopped it because we already switched
  944. // to video, so nothing to do here
  945. if (this.isSharingScreen) {
  946. this.toggleScreenSharing(false);
  947. }
  948. }
  949. );
  950. return this.useVideoStream(stream);
  951. }).then(() => {
  952. this.videoSwitchInProgress = false;
  953. JitsiMeetJS.analytics.sendEvent(
  954. 'conference.sharingDesktop.start');
  955. console.log('sharing local desktop');
  956. }).catch((err) => {
  957. // close external installation dialog to show the error.
  958. if(externalInstallation)
  959. $.prompt.close();
  960. this.videoSwitchInProgress = false;
  961. this.toggleScreenSharing(false);
  962. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  963. return;
  964. }
  965. console.error('failed to share local desktop', err);
  966. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  967. APP.UI.showExtensionRequiredDialog(
  968. config.desktopSharingFirefoxExtensionURL
  969. );
  970. return;
  971. }
  972. // Handling:
  973. // TrackErrors.PERMISSION_DENIED
  974. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  975. // TrackErrors.GENERAL
  976. // and any other
  977. let dialogTxt;
  978. let dialogTitle;
  979. if (err.name === TrackErrors.PERMISSION_DENIED) {
  980. dialogTxt = APP.translation.generateTranslationHTML(
  981. "dialog.screenSharingPermissionDeniedError");
  982. dialogTitle = APP.translation.generateTranslationHTML(
  983. "dialog.error");
  984. } else {
  985. dialogTxt = APP.translation.generateTranslationHTML(
  986. "dialog.failtoinstall");
  987. dialogTitle = APP.translation.generateTranslationHTML(
  988. "dialog.permissionDenied");
  989. }
  990. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  991. });
  992. } else {
  993. createLocalTracks({ devices: ['video'] }).then(
  994. ([stream]) => this.useVideoStream(stream)
  995. ).then(() => {
  996. this.videoSwitchInProgress = false;
  997. JitsiMeetJS.analytics.sendEvent(
  998. 'conference.sharingDesktop.stop');
  999. console.log('sharing local video');
  1000. }).catch((err) => {
  1001. this.useVideoStream(null);
  1002. this.videoSwitchInProgress = false;
  1003. console.error('failed to share local video', err);
  1004. });
  1005. }
  1006. },
  1007. /**
  1008. * Setup interaction between conference and UI.
  1009. */
  1010. _setupListeners () {
  1011. // add local streams when joined to the conference
  1012. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1013. APP.UI.mucJoined();
  1014. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1015. connectionIsInterrupted = false;
  1016. APP.UI.markVideoInterrupted(false);
  1017. });
  1018. room.on(
  1019. ConferenceEvents.AUTH_STATUS_CHANGED,
  1020. function (authEnabled, authLogin) {
  1021. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1022. }
  1023. );
  1024. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1025. if (user.isHidden())
  1026. return;
  1027. console.log('USER %s connnected', id, user);
  1028. APP.API.notifyUserJoined(id);
  1029. APP.UI.addUser(user);
  1030. // check the roles for the new user and reflect them
  1031. APP.UI.updateUserRole(user);
  1032. });
  1033. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1034. console.log('USER %s LEFT', id, user);
  1035. APP.API.notifyUserLeft(id);
  1036. APP.UI.removeUser(id, user.getDisplayName());
  1037. APP.UI.onSharedVideoStop(id);
  1038. });
  1039. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1040. if (this.isLocalId(id)) {
  1041. console.info(`My role changed, new role: ${role}`);
  1042. this.isModerator = room.isModerator();
  1043. APP.UI.updateLocalRole(room.isModerator());
  1044. } else {
  1045. let user = room.getParticipantById(id);
  1046. if (user) {
  1047. APP.UI.updateUserRole(user);
  1048. }
  1049. }
  1050. });
  1051. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1052. if(!track || track.isLocal())
  1053. return;
  1054. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1055. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1056. });
  1057. APP.UI.addRemoteStream(track);
  1058. });
  1059. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1060. if(!track || track.isLocal())
  1061. return;
  1062. APP.UI.removeRemoteStream(track);
  1063. });
  1064. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1065. if(!track)
  1066. return;
  1067. const handler = (track.getType() === "audio")?
  1068. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1069. let id;
  1070. const mute = track.isMuted();
  1071. if(track.isLocal()){
  1072. id = APP.conference.getMyUserId();
  1073. if(track.getType() === "audio") {
  1074. this.audioMuted = mute;
  1075. } else {
  1076. this.videoMuted = mute;
  1077. }
  1078. } else {
  1079. id = track.getParticipantId();
  1080. }
  1081. handler(id , mute);
  1082. });
  1083. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1084. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1085. lvl = 0;
  1086. }
  1087. if(config.debug)
  1088. {
  1089. this.audioLevelsMap[id] = lvl;
  1090. if(config.debugAudioLevels)
  1091. console.log("AudioLevel:" + id + "/" + lvl);
  1092. }
  1093. APP.UI.setAudioLevel(id, lvl);
  1094. });
  1095. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1096. //FIXME
  1097. if (config.muteLocalVideoIfNotInLastN) {
  1098. // TODO mute or unmute if required
  1099. // mark video on UI
  1100. // APP.UI.markVideoMuted(true/false);
  1101. }
  1102. });
  1103. room.on(
  1104. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1105. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1106. });
  1107. room.on(
  1108. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1109. (id, isActive) => {
  1110. APP.UI.participantConnectionStatusChanged(id, isActive);
  1111. });
  1112. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1113. if (this.isLocalId(id)) {
  1114. this.isDominantSpeaker = true;
  1115. this.setRaisedHand(false);
  1116. } else {
  1117. this.isDominantSpeaker = false;
  1118. var participant = room.getParticipantById(id);
  1119. if (participant) {
  1120. APP.UI.setRaisedHandStatus(participant, false);
  1121. }
  1122. }
  1123. APP.UI.markDominantSpeaker(id);
  1124. });
  1125. if (!interfaceConfig.filmStripOnly) {
  1126. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1127. APP.UI.markVideoInterrupted(true);
  1128. });
  1129. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1130. APP.UI.markVideoInterrupted(false);
  1131. });
  1132. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1133. let nick = getDisplayName(id);
  1134. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1135. APP.UI.addMessage(id, nick, text, ts);
  1136. });
  1137. }
  1138. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1139. connectionIsInterrupted = true;
  1140. ConnectionQuality.updateLocalConnectionQuality(0);
  1141. APP.UI.showLocalConnectionInterrupted(true);
  1142. });
  1143. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1144. connectionIsInterrupted = false;
  1145. APP.UI.showLocalConnectionInterrupted(false);
  1146. });
  1147. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1148. APP.API.notifyDisplayNameChanged(id, displayName);
  1149. APP.UI.changeDisplayName(id, displayName);
  1150. });
  1151. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1152. (participant, name, oldValue, newValue) => {
  1153. if (name === "raisedHand") {
  1154. APP.UI.setRaisedHandStatus(participant, newValue);
  1155. }
  1156. });
  1157. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1158. console.log("Received recorder status change: ", status, error);
  1159. APP.UI.updateRecordingState(status);
  1160. });
  1161. room.on(ConferenceEvents.LOCK_STATE_CHANGED, (state, error) => {
  1162. console.log("Received channel password lock change: ", state,
  1163. error);
  1164. APP.UI.markRoomLocked(state);
  1165. roomLocker.lockedElsewhere = state;
  1166. });
  1167. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1168. APP.UI.updateUserStatus(id, status);
  1169. });
  1170. room.on(ConferenceEvents.KICKED, () => {
  1171. APP.UI.hideStats();
  1172. APP.UI.notifyKicked();
  1173. // FIXME close
  1174. });
  1175. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1176. APP.UI.updateDTMFSupport(isDTMFSupported);
  1177. });
  1178. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1179. // Wait a little bit more just to be sure that we won't miss the
  1180. // extension installation
  1181. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1182. });
  1183. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1184. window.open(
  1185. url, "extension_store_window",
  1186. "resizable,scrollbars=yes,status=1");
  1187. });
  1188. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1189. if (room.isModerator()) {
  1190. let promise = roomLocker.isLocked
  1191. ? roomLocker.askToUnlock()
  1192. : roomLocker.askToLock();
  1193. promise.then(() => {
  1194. APP.UI.markRoomLocked(roomLocker.isLocked);
  1195. });
  1196. } else {
  1197. roomLocker.notifyModeratorRequired();
  1198. }
  1199. });
  1200. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1201. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1202. if (!interfaceConfig.filmStripOnly) {
  1203. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1204. APP.API.notifySendingChatMessage(message);
  1205. room.sendTextMessage(message);
  1206. });
  1207. }
  1208. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1209. ConnectionQuality.updateLocalStats(stats, connectionIsInterrupted);
  1210. });
  1211. ConnectionQuality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1212. (percent, stats) => {
  1213. APP.UI.updateLocalStats(percent, stats);
  1214. // Send only the data that remote participants care about.
  1215. let data = {
  1216. bitrate: stats.bitrate,
  1217. packetLoss: stats.packetLoss};
  1218. try {
  1219. room.broadcastEndpointMessage({
  1220. type: this.commands.defaults.CONNECTION_QUALITY,
  1221. values: data });
  1222. } catch (e) {
  1223. reportError(e);
  1224. }
  1225. });
  1226. room.on(ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1227. (participant, payload) => {
  1228. switch(payload.type) {
  1229. case this.commands.defaults.CONNECTION_QUALITY:
  1230. ConnectionQuality.updateRemoteStats(participant.getId(),
  1231. payload.values);
  1232. break;
  1233. default:
  1234. console.warn("Unknown datachannel message", payload);
  1235. }
  1236. });
  1237. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1238. (id, percent, stats) => {
  1239. APP.UI.updateRemoteStats(id, percent, stats);
  1240. });
  1241. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1242. APP.UI.initEtherpad(value);
  1243. });
  1244. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1245. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1246. APP.UI.setUserEmail(from, data.value);
  1247. });
  1248. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1249. (data, from) => {
  1250. APP.UI.setUserAvatarUrl(from, data.value);
  1251. });
  1252. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1253. (data, from) => {
  1254. APP.UI.setUserAvatarID(from, data.value);
  1255. });
  1256. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1257. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1258. (startAudioMuted, startVideoMuted) => {
  1259. room.setStartMutedPolicy({
  1260. audio: startAudioMuted,
  1261. video: startVideoMuted
  1262. });
  1263. }
  1264. );
  1265. room.on(
  1266. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1267. ({ audio, video }) => {
  1268. APP.UI.onStartMutedChanged(audio, video);
  1269. }
  1270. );
  1271. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1272. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1273. && APP.UI.notifyInitiallyMuted();
  1274. });
  1275. room.on(
  1276. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1277. APP.UI.updateDevicesAvailability(id, devices);
  1278. }
  1279. );
  1280. // call hangup
  1281. APP.UI.addListener(UIEvents.HANGUP, () => {
  1282. hangup(true);
  1283. });
  1284. // logout
  1285. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1286. AuthHandler.logout(room).then(function (url) {
  1287. if (url) {
  1288. window.location.href = url;
  1289. } else {
  1290. hangup(true);
  1291. }
  1292. });
  1293. });
  1294. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1295. room.dial(sipNumber);
  1296. });
  1297. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1298. (id, oldResolution, newResolution, delay) => {
  1299. var logObject = {
  1300. id: "resolution_change",
  1301. participant: id,
  1302. oldValue: oldResolution,
  1303. newValue: newResolution,
  1304. delay: delay
  1305. };
  1306. room.sendApplicationLog(JSON.stringify(logObject));
  1307. // We only care about the delay between simulcast streams.
  1308. // Longer delays will be caused by something else and will just
  1309. // poison the data.
  1310. if (delay < 2000) {
  1311. JitsiMeetJS.analytics.sendEvent('stream.switch.delay', delay);
  1312. }
  1313. });
  1314. // Starts or stops the recording for the conference.
  1315. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1316. room.toggleRecording(options);
  1317. });
  1318. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1319. room.setSubject(topic);
  1320. });
  1321. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1322. APP.UI.setSubject(subject);
  1323. });
  1324. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1325. room.kickParticipant(id);
  1326. });
  1327. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1328. room.muteParticipant(id);
  1329. });
  1330. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1331. AuthHandler.authenticate(room);
  1332. });
  1333. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1334. try {
  1335. // do not try to select participant if there is none (we are
  1336. // alone in the room), otherwise an error will be thrown cause
  1337. // reporting mechanism is not available (datachannels currently)
  1338. if (room.getParticipants().length === 0)
  1339. return;
  1340. room.selectParticipant(id);
  1341. } catch (e) {
  1342. JitsiMeetJS.analytics.sendEvent('selectParticipant.failed');
  1343. reportError(e);
  1344. }
  1345. });
  1346. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1347. var smallVideoId = smallVideo.getId();
  1348. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1349. // the participant is on the large video ?
  1350. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1351. && !APP.conference.isLocalId(smallVideoId)) {
  1352. // When the library starts supporting multiple pins we would
  1353. // pass the isPinned parameter together with the identifier,
  1354. // but currently we send null to indicate that we unpin the
  1355. // last pinned.
  1356. try {
  1357. room.pinParticipant(isPinned ? smallVideoId : null);
  1358. } catch (e) {
  1359. reportError(e);
  1360. }
  1361. }
  1362. });
  1363. APP.UI.addListener(
  1364. UIEvents.VIDEO_DEVICE_CHANGED,
  1365. (cameraDeviceId) => {
  1366. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1367. createLocalTracks({
  1368. devices: ['video'],
  1369. cameraDeviceId: cameraDeviceId,
  1370. micDeviceId: null
  1371. })
  1372. .then(([stream]) => {
  1373. this.useVideoStream(stream);
  1374. console.log('switched local video device');
  1375. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1376. })
  1377. .catch((err) => {
  1378. APP.UI.showDeviceErrorDialog(null, err);
  1379. APP.UI.setSelectedCameraFromSettings();
  1380. });
  1381. }
  1382. );
  1383. APP.UI.addListener(
  1384. UIEvents.AUDIO_DEVICE_CHANGED,
  1385. (micDeviceId) => {
  1386. JitsiMeetJS.analytics.sendEvent(
  1387. 'settings.changeDevice.audioIn');
  1388. createLocalTracks({
  1389. devices: ['audio'],
  1390. cameraDeviceId: null,
  1391. micDeviceId: micDeviceId
  1392. })
  1393. .then(([stream]) => {
  1394. this.useAudioStream(stream);
  1395. console.log('switched local audio device');
  1396. APP.settings.setMicDeviceId(micDeviceId, true);
  1397. })
  1398. .catch((err) => {
  1399. APP.UI.showDeviceErrorDialog(err, null);
  1400. APP.UI.setSelectedMicFromSettings();
  1401. });
  1402. }
  1403. );
  1404. APP.UI.addListener(
  1405. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1406. (audioOutputDeviceId) => {
  1407. JitsiMeetJS.analytics.sendEvent(
  1408. 'settings.changeDevice.audioOut');
  1409. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1410. .then(() => console.log('changed audio output device'))
  1411. .catch((err) => {
  1412. console.warn('Failed to change audio output device. ' +
  1413. 'Default or previously set audio output device ' +
  1414. 'will be used instead.', err);
  1415. APP.UI.setSelectedAudioOutputFromSettings();
  1416. });
  1417. }
  1418. );
  1419. APP.UI.addListener(
  1420. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1421. );
  1422. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1423. (url, state, time, isMuted, volume) => {
  1424. // send start and stop commands once, and remove any updates
  1425. // that had left
  1426. if (state === 'stop' || state === 'start' || state === 'playing') {
  1427. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1428. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1429. value: url,
  1430. attributes: {
  1431. state: state,
  1432. time: time,
  1433. muted: isMuted,
  1434. volume: volume
  1435. }
  1436. });
  1437. }
  1438. else {
  1439. // in case of paused, in order to allow late users to join
  1440. // paused
  1441. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1442. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1443. value: url,
  1444. attributes: {
  1445. state: state,
  1446. time: time,
  1447. muted: isMuted,
  1448. volume: volume
  1449. }
  1450. });
  1451. }
  1452. });
  1453. room.addCommandListener(
  1454. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1455. if (attributes.state === 'stop') {
  1456. APP.UI.onSharedVideoStop(id, attributes);
  1457. }
  1458. else if (attributes.state === 'start') {
  1459. APP.UI.onSharedVideoStart(id, value, attributes);
  1460. }
  1461. else if (attributes.state === 'playing'
  1462. || attributes.state === 'pause') {
  1463. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1464. }
  1465. });
  1466. },
  1467. /**
  1468. * Adds any room listener.
  1469. * @param eventName one of the ConferenceEvents
  1470. * @param callBack the function to be called when the event occurs
  1471. */
  1472. addConferenceListener(eventName, callBack) {
  1473. room.on(eventName, callBack);
  1474. },
  1475. /**
  1476. * Inits list of current devices and event listener for device change.
  1477. * @private
  1478. */
  1479. _initDeviceList() {
  1480. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1481. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1482. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1483. // Ugly way to synchronize real device IDs with local
  1484. // storage and settings menu. This is a workaround until
  1485. // getConstraints() method will be implemented in browsers.
  1486. if (localAudio) {
  1487. APP.settings.setMicDeviceId(
  1488. localAudio.getDeviceId(), false);
  1489. }
  1490. if (localVideo) {
  1491. APP.settings.setCameraDeviceId(
  1492. localVideo.getDeviceId(), false);
  1493. }
  1494. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1495. APP.UI.onAvailableDevicesChanged(devices);
  1496. });
  1497. JitsiMeetJS.mediaDevices.addEventListener(
  1498. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1499. (devices) =>
  1500. window.setTimeout(
  1501. () => this._onDeviceListChanged(devices), 0));
  1502. }
  1503. },
  1504. /**
  1505. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1506. * handle change of available media devices.
  1507. * @private
  1508. * @param {MediaDeviceInfo[]} devices
  1509. * @returns {Promise}
  1510. */
  1511. _onDeviceListChanged(devices) {
  1512. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1513. // Event handler can be fired before direct
  1514. // enumerateDevices() call, so handle this situation here.
  1515. if (!currentDevices.audioinput &&
  1516. !currentDevices.videoinput &&
  1517. !currentDevices.audiooutput) {
  1518. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1519. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1520. }
  1521. let newDevices =
  1522. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1523. devices, this.isSharingScreen, localVideo, localAudio);
  1524. let promises = [];
  1525. let audioWasMuted = this.audioMuted;
  1526. let videoWasMuted = this.videoMuted;
  1527. let availableAudioInputDevices =
  1528. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1529. let availableVideoInputDevices =
  1530. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1531. if (typeof newDevices.audiooutput !== 'undefined') {
  1532. // Just ignore any errors in catch block.
  1533. promises.push(APP.settings
  1534. .setAudioOutputDeviceId(newDevices.audiooutput)
  1535. .catch());
  1536. }
  1537. promises.push(
  1538. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1539. createLocalTracks,
  1540. newDevices.videoinput,
  1541. newDevices.audioinput)
  1542. .then(tracks =>
  1543. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1544. .then(() => {
  1545. // If audio was muted before, or we unplugged current device
  1546. // and selected new one, then mute new audio track.
  1547. if (audioWasMuted ||
  1548. currentDevices.audioinput.length >
  1549. availableAudioInputDevices.length) {
  1550. muteLocalAudio(true);
  1551. }
  1552. // If video was muted before, or we unplugged current device
  1553. // and selected new one, then mute new video track.
  1554. if (videoWasMuted ||
  1555. currentDevices.videoinput.length >
  1556. availableVideoInputDevices.length) {
  1557. muteLocalVideo(true);
  1558. }
  1559. }));
  1560. return Promise.all(promises)
  1561. .then(() => {
  1562. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1563. APP.UI.onAvailableDevicesChanged(devices);
  1564. });
  1565. },
  1566. /**
  1567. * Toggles the local "raised hand" status, if the current state allows
  1568. * toggling.
  1569. */
  1570. maybeToggleRaisedHand() {
  1571. // If we are the dominant speaker, we don't enable "raise hand".
  1572. if (this.isHandRaised || !this.isDominantSpeaker) {
  1573. this.setRaisedHand(!this.isHandRaised);
  1574. }
  1575. },
  1576. /**
  1577. * Sets the local "raised hand" status to a particular value.
  1578. */
  1579. setRaisedHand(raisedHand) {
  1580. if (raisedHand !== this.isHandRaised)
  1581. {
  1582. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1583. this.isHandRaised = raisedHand;
  1584. // Advertise the updated status
  1585. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1586. // Update the view
  1587. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1588. }
  1589. }
  1590. };