Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 69KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. const logger = require("jitsi-meet-logger").getLogger(__filename);
  3. import {openConnection} from './connection';
  4. import Invite from './modules/UI/invite/Invite';
  5. import ContactList from './modules/UI/side_pannels/contactlist/ContactList';
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import Recorder from './modules/recorder/Recorder';
  8. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  9. import { reload, reportError } from './modules/util/helpers';
  10. import UIEvents from './service/UI/UIEvents';
  11. import UIUtil from './modules/UI/util/UIUtil';
  12. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  13. import analytics from './modules/analytics/analytics';
  14. import EventEmitter from "events";
  15. import {
  16. AVATAR_ID_COMMAND,
  17. AVATAR_URL_COMMAND,
  18. conferenceFailed,
  19. conferenceJoined,
  20. conferenceLeft,
  21. EMAIL_COMMAND
  22. } from './react/features/base/conference';
  23. import {
  24. isFatalJitsiConnectionError
  25. } from './react/features/base/lib-jitsi-meet';
  26. import {
  27. changeParticipantAvatarID,
  28. changeParticipantAvatarURL,
  29. changeParticipantEmail,
  30. participantJoined,
  31. participantLeft,
  32. participantRoleChanged
  33. } from './react/features/base/participants';
  34. import {
  35. mediaPermissionPromptVisibilityChanged,
  36. suspendDetected
  37. } from './react/features/overlay';
  38. const ConnectionEvents = JitsiMeetJS.events.connection;
  39. const ConnectionErrors = JitsiMeetJS.errors.connection;
  40. const ConferenceEvents = JitsiMeetJS.events.conference;
  41. const ConferenceErrors = JitsiMeetJS.errors.conference;
  42. const TrackEvents = JitsiMeetJS.events.track;
  43. const TrackErrors = JitsiMeetJS.errors.track;
  44. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  45. const eventEmitter = new EventEmitter();
  46. let room, connection, localAudio, localVideo;
  47. /**
  48. * Indicates whether extension external installation is in progress or not.
  49. */
  50. let DSExternalInstallationInProgress = false;
  51. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  52. /**
  53. * Known custom conference commands.
  54. */
  55. const commands = {
  56. AVATAR_ID: AVATAR_ID_COMMAND,
  57. AVATAR_URL: AVATAR_URL_COMMAND,
  58. CUSTOM_ROLE: "custom-role",
  59. EMAIL: EMAIL_COMMAND,
  60. ETHERPAD: "etherpad",
  61. SHARED_VIDEO: "shared-video"
  62. };
  63. /**
  64. * Max length of the display names. If we receive longer display name the
  65. * additional chars are going to be cut.
  66. */
  67. const MAX_DISPLAY_NAME_LENGTH = 50;
  68. /**
  69. * Open Connection. When authentication failed it shows auth dialog.
  70. * @param roomName the room name to use
  71. * @returns Promise<JitsiConnection>
  72. */
  73. function connect(roomName) {
  74. return openConnection({retry: true, roomName: roomName})
  75. .catch(function (err) {
  76. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  77. APP.UI.notifyTokenAuthFailed();
  78. } else {
  79. APP.UI.notifyConnectionFailed(err);
  80. }
  81. throw err;
  82. });
  83. }
  84. /**
  85. * Creates local media tracks and connects to room. Will show error
  86. * dialogs in case if accessing local microphone and/or camera failed. Will
  87. * show guidance overlay for users on how to give access to camera and/or
  88. * microphone,
  89. * @param {string} roomName
  90. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  91. */
  92. function createInitialLocalTracksAndConnect(roomName) {
  93. let audioAndVideoError,
  94. audioOnlyError;
  95. JitsiMeetJS.mediaDevices.addEventListener(
  96. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  97. browser =>
  98. APP.store.dispatch(
  99. mediaPermissionPromptVisibilityChanged(true, browser))
  100. );
  101. // First try to retrieve both audio and video.
  102. let tryCreateLocalTracks = createLocalTracks(
  103. { devices: ['audio', 'video'] }, true)
  104. .catch(err => {
  105. // If failed then try to retrieve only audio.
  106. audioAndVideoError = err;
  107. return createLocalTracks({ devices: ['audio'] }, true);
  108. })
  109. .catch(err => {
  110. // If audio failed too then just return empty array for tracks.
  111. audioOnlyError = err;
  112. return [];
  113. });
  114. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  115. .then(([tracks, con]) => {
  116. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  117. if (audioAndVideoError) {
  118. if (audioOnlyError) {
  119. // If both requests for 'audio' + 'video' and 'audio' only
  120. // failed, we assume that there is some problems with user's
  121. // microphone and show corresponding dialog.
  122. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  123. } else {
  124. // If request for 'audio' + 'video' failed, but request for
  125. // 'audio' only was OK, we assume that we had problems with
  126. // camera and show corresponding dialog.
  127. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  128. }
  129. }
  130. return [tracks, con];
  131. });
  132. }
  133. /**
  134. * Share data to other users.
  135. * @param command the command
  136. * @param {string} value new value
  137. */
  138. function sendData (command, value) {
  139. room.removeCommand(command);
  140. room.sendCommand(command, {value: value});
  141. }
  142. /**
  143. * Sets up initially the properties of the local participant - email, avatarID,
  144. * avatarURL, displayName, etc.
  145. */
  146. function _setupLocalParticipantProperties() {
  147. const email = APP.settings.getEmail();
  148. email && sendData(commands.EMAIL, email);
  149. const avatarUrl = APP.settings.getAvatarUrl();
  150. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  151. if (!email && !avatarUrl) {
  152. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  153. }
  154. let nick = APP.settings.getDisplayName();
  155. if (config.useNicks && !nick) {
  156. nick = APP.UI.askForNickname();
  157. APP.settings.setDisplayName(nick);
  158. }
  159. nick && room.setDisplayName(nick);
  160. }
  161. /**
  162. * Get user nickname by user id.
  163. * @param {string} id user id
  164. * @returns {string?} user nickname or undefined if user is unknown.
  165. */
  166. function getDisplayName (id) {
  167. if (APP.conference.isLocalId(id)) {
  168. return APP.settings.getDisplayName();
  169. }
  170. let participant = room.getParticipantById(id);
  171. if (participant && participant.getDisplayName()) {
  172. return participant.getDisplayName();
  173. }
  174. }
  175. /**
  176. * Mute or unmute local audio stream if it exists.
  177. * @param {boolean} muted - if audio stream should be muted or unmuted.
  178. * @param {boolean} userInteraction - indicates if this local audio mute was a
  179. * result of user interaction
  180. */
  181. function muteLocalAudio (muted) {
  182. muteLocalMedia(localAudio, muted, 'Audio');
  183. }
  184. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  185. if (!localMedia) {
  186. return;
  187. }
  188. const method = muted ? 'mute' : 'unmute';
  189. localMedia[method]().catch(reason => {
  190. logger.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  191. });
  192. }
  193. /**
  194. * Mute or unmute local video stream if it exists.
  195. * @param {boolean} muted if video stream should be muted or unmuted.
  196. */
  197. function muteLocalVideo (muted) {
  198. muteLocalMedia(localVideo, muted, 'Video');
  199. }
  200. /**
  201. * Check if the welcome page is enabled and redirects to it.
  202. * If requested show a thank you dialog before that.
  203. * If we have a close page enabled, redirect to it without
  204. * showing any other dialog.
  205. *
  206. * @param {object} options used to decide which particular close page to show
  207. * or if close page is disabled, whether we should show the thankyou dialog
  208. * @param {boolean} options.thankYouDialogVisible - whether we should
  209. * show thank you dialog
  210. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  211. */
  212. function maybeRedirectToWelcomePage(options) {
  213. // if close page is enabled redirect to it, without further action
  214. if (config.enableClosePage) {
  215. // save whether current user is guest or not, before navigating
  216. // to close page
  217. window.sessionStorage.setItem('guest', APP.tokenData.isGuest);
  218. assignWindowLocationPathname('static/'
  219. + (options.feedbackSubmitted ? "close.html" : "close2.html"));
  220. return;
  221. }
  222. // else: show thankYou dialog only if there is no feedback
  223. if (options.thankYouDialogVisible)
  224. APP.UI.messageHandler.openMessageDialog(
  225. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  226. // if Welcome page is enabled redirect to welcome page after 3 sec.
  227. if (config.enableWelcomePage) {
  228. setTimeout(() => {
  229. APP.settings.setWelcomePageEnabled(true);
  230. assignWindowLocationPathname('./');
  231. }, 3000);
  232. }
  233. }
  234. /**
  235. * Assigns a specific pathname to window.location.pathname taking into account
  236. * the context root of the Web app.
  237. *
  238. * @param {string} pathname - The pathname to assign to
  239. * window.location.pathname. If the specified pathname is relative, the context
  240. * root of the Web app will be prepended to the specified pathname before
  241. * assigning it to window.location.pathname.
  242. * @return {void}
  243. */
  244. function assignWindowLocationPathname(pathname) {
  245. const windowLocation = window.location;
  246. if (!pathname.startsWith('/')) {
  247. // XXX To support a deployment in a sub-directory, assume that the room
  248. // (name) is the last non-directory component of the path (name).
  249. let contextRoot = windowLocation.pathname;
  250. contextRoot
  251. = contextRoot.substring(0, contextRoot.lastIndexOf('/') + 1);
  252. // A pathname equal to ./ specifies the current directory. It will be
  253. // fine but pointless to include it because contextRoot is the current
  254. // directory.
  255. pathname.startsWith('./') && (pathname = pathname.substring(2));
  256. pathname = contextRoot + pathname;
  257. }
  258. windowLocation.pathname = pathname;
  259. }
  260. /**
  261. * Create local tracks of specified types.
  262. * @param {Object} options
  263. * @param {string[]} options.devices - required track types
  264. * ('audio', 'video' etc.)
  265. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  266. * undefined - one from settings will be used
  267. * @param {string|null} (options.micDeviceId) - microphone device id, if
  268. * undefined - one from settings will be used
  269. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  270. * for gUM permission prompt
  271. * @returns {Promise<JitsiLocalTrack[]>}
  272. */
  273. function createLocalTracks (options, checkForPermissionPrompt) {
  274. options || (options = {});
  275. return JitsiMeetJS
  276. .createLocalTracks({
  277. // copy array to avoid mutations inside library
  278. devices: options.devices.slice(0),
  279. resolution: config.resolution,
  280. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  281. options.cameraDeviceId === null
  282. ? APP.settings.getCameraDeviceId()
  283. : options.cameraDeviceId,
  284. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  285. options.micDeviceId === null
  286. ? APP.settings.getMicDeviceId()
  287. : options.micDeviceId,
  288. // adds any ff fake device settings if any
  289. firefox_fake_device: config.firefox_fake_device,
  290. desktopSharingExtensionExternalInstallation:
  291. options.desktopSharingExtensionExternalInstallation
  292. }, checkForPermissionPrompt).then( (tracks) => {
  293. tracks.forEach((track) => {
  294. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  295. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  296. });
  297. return tracks;
  298. }).catch(function (err) {
  299. logger.error(
  300. 'failed to create local tracks', options.devices, err);
  301. return Promise.reject(err);
  302. });
  303. }
  304. class ConferenceConnector {
  305. constructor(resolve, reject, invite) {
  306. this._resolve = resolve;
  307. this._reject = reject;
  308. this._invite = invite;
  309. this.reconnectTimeout = null;
  310. room.on(ConferenceEvents.CONFERENCE_JOINED,
  311. this._handleConferenceJoined.bind(this));
  312. room.on(ConferenceEvents.CONFERENCE_FAILED,
  313. this._onConferenceFailed.bind(this));
  314. room.on(ConferenceEvents.CONFERENCE_ERROR,
  315. this._onConferenceError.bind(this));
  316. }
  317. _handleConferenceFailed(err) {
  318. this._unsubscribe();
  319. this._reject(err);
  320. }
  321. _onConferenceFailed(err, ...params) {
  322. APP.store.dispatch(conferenceFailed(room, err, ...params));
  323. logger.error('CONFERENCE FAILED:', err, ...params);
  324. APP.UI.hideRingOverLay();
  325. switch (err) {
  326. // room is locked by the password
  327. case ConferenceErrors.PASSWORD_REQUIRED:
  328. APP.UI.emitEvent(UIEvents.PASSWORD_REQUIRED);
  329. break;
  330. case ConferenceErrors.CONNECTION_ERROR:
  331. {
  332. let [msg] = params;
  333. APP.UI.notifyConnectionFailed(msg);
  334. }
  335. break;
  336. case ConferenceErrors.NOT_ALLOWED_ERROR:
  337. {
  338. // let's show some auth not allowed page
  339. assignWindowLocationPathname('static/authError.html');
  340. }
  341. break;
  342. // not enough rights to create conference
  343. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  344. // schedule reconnect to check if someone else created the room
  345. this.reconnectTimeout = setTimeout(function () {
  346. room.join();
  347. }, 5000);
  348. // notify user that auth is required
  349. AuthHandler.requireAuth(
  350. room, this._invite.getRoomLocker().password);
  351. break;
  352. case ConferenceErrors.RESERVATION_ERROR:
  353. {
  354. let [code, msg] = params;
  355. APP.UI.notifyReservationError(code, msg);
  356. }
  357. break;
  358. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  359. APP.UI.notifyGracefulShutdown();
  360. break;
  361. case ConferenceErrors.JINGLE_FATAL_ERROR:
  362. APP.UI.notifyInternalError();
  363. break;
  364. case ConferenceErrors.CONFERENCE_DESTROYED:
  365. {
  366. let [reason] = params;
  367. APP.UI.hideStats();
  368. APP.UI.notifyConferenceDestroyed(reason);
  369. }
  370. break;
  371. // FIXME FOCUS_DISCONNECTED is confusing event name.
  372. // What really happens there is that the library is not ready yet,
  373. // because Jicofo is not available, but it is going to give
  374. // it another try.
  375. case ConferenceErrors.FOCUS_DISCONNECTED:
  376. {
  377. let [focus, retrySec] = params;
  378. APP.UI.notifyFocusDisconnected(focus, retrySec);
  379. }
  380. break;
  381. case ConferenceErrors.FOCUS_LEFT:
  382. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  383. // FIXME the conference should be stopped by the library and not by
  384. // the app. Both the errors above are unrecoverable from the library
  385. // perspective.
  386. room.leave().then(() => connection.disconnect());
  387. break;
  388. case ConferenceErrors.CONFERENCE_MAX_USERS:
  389. connection.disconnect();
  390. APP.UI.notifyMaxUsersLimitReached();
  391. break;
  392. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  393. reload();
  394. break;
  395. default:
  396. this._handleConferenceFailed(err, ...params);
  397. }
  398. }
  399. _onConferenceError(err, ...params) {
  400. logger.error('CONFERENCE Error:', err, params);
  401. switch (err) {
  402. case ConferenceErrors.CHAT_ERROR:
  403. {
  404. let [code, msg] = params;
  405. APP.UI.showChatError(code, msg);
  406. }
  407. break;
  408. default:
  409. logger.error("Unknown error.", err);
  410. }
  411. }
  412. _unsubscribe() {
  413. room.off(
  414. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  415. room.off(
  416. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  417. if (this.reconnectTimeout !== null) {
  418. clearTimeout(this.reconnectTimeout);
  419. }
  420. AuthHandler.closeAuth();
  421. }
  422. _handleConferenceJoined() {
  423. this._unsubscribe();
  424. this._resolve();
  425. }
  426. connect() {
  427. room.join();
  428. }
  429. }
  430. /**
  431. * Disconnects the connection.
  432. * @returns resolved Promise. We need this in order to make the Promise.all
  433. * call in hangup() to resolve when all operations are finished.
  434. */
  435. function disconnect() {
  436. connection.disconnect();
  437. APP.API.notifyConferenceLeft(APP.conference.roomName);
  438. return Promise.resolve();
  439. }
  440. /**
  441. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  442. *
  443. * @param {JitsiMeetJS.connection.error} error - The reported error.
  444. * @returns {void}
  445. * @private
  446. */
  447. function _connectionFailedHandler(error) {
  448. if (isFatalJitsiConnectionError(error)) {
  449. APP.connection.removeEventListener(
  450. ConnectionEvents.CONNECTION_FAILED,
  451. _connectionFailedHandler);
  452. if (room)
  453. room.leave();
  454. }
  455. }
  456. export default {
  457. isModerator: false,
  458. audioMuted: false,
  459. videoMuted: false,
  460. isSharingScreen: false,
  461. isDesktopSharingEnabled: false,
  462. /*
  463. * Whether the local "raisedHand" flag is on.
  464. */
  465. isHandRaised: false,
  466. /*
  467. * Whether the local participant is the dominant speaker in the conference.
  468. */
  469. isDominantSpeaker: false,
  470. /**
  471. * Open new connection and join to the conference.
  472. * @param {object} options
  473. * @param {string} roomName name of the conference
  474. * @returns {Promise}
  475. */
  476. init(options) {
  477. this.roomName = options.roomName;
  478. // attaches global error handler, if there is already one, respect it
  479. if(JitsiMeetJS.getGlobalOnErrorHandler){
  480. var oldOnErrorHandler = window.onerror;
  481. window.onerror = function (message, source, lineno, colno, error) {
  482. JitsiMeetJS.getGlobalOnErrorHandler(
  483. message, source, lineno, colno, error);
  484. if(oldOnErrorHandler)
  485. oldOnErrorHandler(message, source, lineno, colno, error);
  486. };
  487. var oldOnUnhandledRejection = window.onunhandledrejection;
  488. window.onunhandledrejection = function(event) {
  489. JitsiMeetJS.getGlobalOnErrorHandler(
  490. null, null, null, null, event.reason);
  491. if(oldOnUnhandledRejection)
  492. oldOnUnhandledRejection(event);
  493. };
  494. }
  495. return JitsiMeetJS.init(
  496. Object.assign(
  497. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  498. ).then(() => {
  499. analytics.init();
  500. return createInitialLocalTracksAndConnect(options.roomName);
  501. }).then(([tracks, con]) => {
  502. logger.log('initialized with %s local tracks', tracks.length);
  503. con.addEventListener(
  504. ConnectionEvents.CONNECTION_FAILED,
  505. _connectionFailedHandler);
  506. APP.connection = connection = con;
  507. this.isDesktopSharingEnabled =
  508. JitsiMeetJS.isDesktopSharingEnabled();
  509. APP.remoteControl.init();
  510. this._createRoom(tracks);
  511. if (UIUtil.isButtonEnabled('contacts')
  512. && !interfaceConfig.filmStripOnly) {
  513. APP.UI.ContactList = new ContactList(room);
  514. }
  515. // if user didn't give access to mic or camera or doesn't have
  516. // them at all, we disable corresponding toolbar buttons
  517. if (!tracks.find((t) => t.isAudioTrack())) {
  518. APP.UI.setMicrophoneButtonEnabled(false);
  519. }
  520. if (!tracks.find((t) => t.isVideoTrack())) {
  521. APP.UI.setCameraButtonEnabled(false);
  522. }
  523. this._initDeviceList();
  524. if (config.iAmRecorder)
  525. this.recorder = new Recorder();
  526. // XXX The API will take care of disconnecting from the XMPP
  527. // server (and, thus, leaving the room) on unload.
  528. return new Promise((resolve, reject) => {
  529. (new ConferenceConnector(
  530. resolve, reject, this.invite)).connect();
  531. });
  532. });
  533. },
  534. /**
  535. * Check if id is id of the local user.
  536. * @param {string} id id to check
  537. * @returns {boolean}
  538. */
  539. isLocalId (id) {
  540. return this.getMyUserId() === id;
  541. },
  542. /**
  543. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  544. * @param mute true for mute and false for unmute.
  545. */
  546. muteAudio (mute) {
  547. muteLocalAudio(mute);
  548. },
  549. /**
  550. * Returns whether local audio is muted or not.
  551. * @returns {boolean}
  552. */
  553. isLocalAudioMuted() {
  554. return this.audioMuted;
  555. },
  556. /**
  557. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  558. */
  559. toggleAudioMuted () {
  560. this.muteAudio(!this.audioMuted);
  561. },
  562. /**
  563. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  564. * @param mute true for mute and false for unmute.
  565. */
  566. muteVideo (mute) {
  567. muteLocalVideo(mute);
  568. },
  569. /**
  570. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  571. */
  572. toggleVideoMuted () {
  573. this.muteVideo(!this.videoMuted);
  574. },
  575. /**
  576. * Retrieve list of conference participants (without local user).
  577. * @returns {JitsiParticipant[]}
  578. */
  579. listMembers () {
  580. return room.getParticipants();
  581. },
  582. /**
  583. * Retrieve list of ids of conference participants (without local user).
  584. * @returns {string[]}
  585. */
  586. listMembersIds () {
  587. return room.getParticipants().map(p => p.getId());
  588. },
  589. /**
  590. * Checks whether the participant identified by id is a moderator.
  591. * @id id to search for participant
  592. * @return {boolean} whether the participant is moderator
  593. */
  594. isParticipantModerator (id) {
  595. let user = room.getParticipantById(id);
  596. return user && user.isModerator();
  597. },
  598. /**
  599. * Check if SIP is supported.
  600. * @returns {boolean}
  601. */
  602. sipGatewayEnabled () {
  603. return room.isSIPCallingSupported();
  604. },
  605. get membersCount () {
  606. return room.getParticipants().length + 1;
  607. },
  608. /**
  609. * Returns true if the callstats integration is enabled, otherwise returns
  610. * false.
  611. *
  612. * @returns true if the callstats integration is enabled, otherwise returns
  613. * false.
  614. */
  615. isCallstatsEnabled () {
  616. return room && room.isCallstatsEnabled();
  617. },
  618. /**
  619. * Sends the given feedback through CallStats if enabled.
  620. *
  621. * @param overallFeedback an integer between 1 and 5 indicating the
  622. * user feedback
  623. * @param detailedFeedback detailed feedback from the user. Not yet used
  624. */
  625. sendFeedback (overallFeedback, detailedFeedback) {
  626. return room.sendFeedback (overallFeedback, detailedFeedback);
  627. },
  628. /**
  629. * Get speaker stats that track total dominant speaker time.
  630. *
  631. * @returns {object} A hash with keys being user ids and values being the
  632. * library's SpeakerStats model used for calculating time as dominant
  633. * speaker.
  634. */
  635. getSpeakerStats() {
  636. return room.getSpeakerStats();
  637. },
  638. /**
  639. * Returns the connection times stored in the library.
  640. */
  641. getConnectionTimes () {
  642. return this._room.getConnectionTimes();
  643. },
  644. // used by torture currently
  645. isJoined () {
  646. return this._room
  647. && this._room.isJoined();
  648. },
  649. getConnectionState () {
  650. return this._room
  651. && this._room.getConnectionState();
  652. },
  653. /**
  654. * Obtains current P2P ICE connection state.
  655. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  656. * P2P connection
  657. */
  658. getP2PConnectionState () {
  659. return this._room
  660. && this._room.getP2PConnectionState();
  661. },
  662. /**
  663. * Starts P2P (for tests only)
  664. * @private
  665. */
  666. _startP2P () {
  667. try {
  668. this._room && this._room.startP2PSession();
  669. } catch (error) {
  670. logger.error("Start P2P failed", error);
  671. throw error;
  672. }
  673. },
  674. /**
  675. * Stops P2P (for tests only)
  676. * @private
  677. */
  678. _stopP2P () {
  679. try {
  680. this._room && this._room.stopP2PSession();
  681. } catch (error) {
  682. logger.error("Stop P2P failed", error);
  683. throw error;
  684. }
  685. },
  686. /**
  687. * Checks whether or not our connection is currently in interrupted and
  688. * reconnect attempts are in progress.
  689. *
  690. * @returns {boolean} true if the connection is in interrupted state or
  691. * false otherwise.
  692. */
  693. isConnectionInterrupted () {
  694. return this._room.isConnectionInterrupted();
  695. },
  696. /**
  697. * Finds JitsiParticipant for given id.
  698. *
  699. * @param {string} id participant's identifier(MUC nickname).
  700. *
  701. * @returns {JitsiParticipant|null} participant instance for given id or
  702. * null if not found.
  703. */
  704. getParticipantById (id) {
  705. return room ? room.getParticipantById(id) : null;
  706. },
  707. /**
  708. * Checks whether the user identified by given id is currently connected.
  709. *
  710. * @param {string} id participant's identifier(MUC nickname)
  711. *
  712. * @returns {boolean|null} true if participant's connection is ok or false
  713. * if the user is having connectivity issues.
  714. */
  715. isParticipantConnectionActive (id) {
  716. let participant = this.getParticipantById(id);
  717. return participant ? participant.isConnectionActive() : null;
  718. },
  719. /**
  720. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  721. * the given <tt>id</tt>.
  722. *
  723. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  724. *
  725. * @return {string} the participant's display name or the default string if
  726. * absent.
  727. */
  728. getParticipantDisplayName (id) {
  729. let displayName = getDisplayName(id);
  730. if (displayName) {
  731. return displayName;
  732. } else {
  733. if (APP.conference.isLocalId(id)) {
  734. return APP.translation.generateTranslationHTML(
  735. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  736. } else {
  737. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  738. }
  739. }
  740. },
  741. getMyUserId () {
  742. return this._room
  743. && this._room.myUserId();
  744. },
  745. /**
  746. * Indicates if recording is supported in this conference.
  747. */
  748. isRecordingSupported() {
  749. return this._room && this._room.isRecordingSupported();
  750. },
  751. /**
  752. * Returns the recording state or undefined if the room is not defined.
  753. */
  754. getRecordingState() {
  755. return (this._room) ? this._room.getRecordingState() : undefined;
  756. },
  757. /**
  758. * Will be filled with values only when config.debug is enabled.
  759. * Its used by torture to check audio levels.
  760. */
  761. audioLevelsMap: {},
  762. /**
  763. * Returns the stored audio level (stored only if config.debug is enabled)
  764. * @param id the id for the user audio level to return (the id value is
  765. * returned for the participant using getMyUserId() method)
  766. */
  767. getPeerSSRCAudioLevel (id) {
  768. return this.audioLevelsMap[id];
  769. },
  770. /**
  771. * @return {number} the number of participants in the conference with at
  772. * least one track.
  773. */
  774. getNumberOfParticipantsWithTracks() {
  775. return this._room.getParticipants()
  776. .filter((p) => p.getTracks().length > 0)
  777. .length;
  778. },
  779. /**
  780. * Returns the stats.
  781. */
  782. getStats() {
  783. return room.connectionQuality.getStats();
  784. },
  785. // end used by torture
  786. getLogs () {
  787. return room.getLogs();
  788. },
  789. /**
  790. * Download logs, a function that can be called from console while
  791. * debugging.
  792. * @param filename (optional) specify target filename
  793. */
  794. saveLogs (filename = 'meetlog.json') {
  795. // this can be called from console and will not have reference to this
  796. // that's why we reference the global var
  797. let logs = APP.conference.getLogs();
  798. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  799. let elem = document.createElement('a');
  800. elem.download = filename;
  801. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  802. elem.dataset.downloadurl
  803. = ['text/json', elem.download, elem.href].join(':');
  804. elem.dispatchEvent(new MouseEvent('click', {
  805. view: window,
  806. bubbles: true,
  807. cancelable: false
  808. }));
  809. },
  810. /**
  811. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  812. * desire to keep room private to this instance and (2) the need of other
  813. * modules to send and receive commands to and from participants.
  814. * Eventually, this instance remains in control with respect to the
  815. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  816. * JitsiConference) is to be used in the implementation of the Command(s)
  817. * API of this instance.
  818. */
  819. commands: {
  820. /**
  821. * Known custom conference commands.
  822. */
  823. defaults: commands,
  824. /**
  825. * Receives notifications from other participants about commands aka
  826. * custom events (sent by sendCommand or sendCommandOnce methods).
  827. * @param command {String} the name of the command
  828. * @param handler {Function} handler for the command
  829. */
  830. addCommandListener () {
  831. room.addCommandListener.apply(room, arguments);
  832. },
  833. /**
  834. * Removes command.
  835. * @param name {String} the name of the command.
  836. */
  837. removeCommand () {
  838. room.removeCommand.apply(room, arguments);
  839. },
  840. /**
  841. * Sends command.
  842. * @param name {String} the name of the command.
  843. * @param values {Object} with keys and values that will be sent.
  844. */
  845. sendCommand () {
  846. room.sendCommand.apply(room, arguments);
  847. },
  848. /**
  849. * Sends command one time.
  850. * @param name {String} the name of the command.
  851. * @param values {Object} with keys and values that will be sent.
  852. */
  853. sendCommandOnce () {
  854. room.sendCommandOnce.apply(room, arguments);
  855. }
  856. },
  857. _createRoom (localTracks) {
  858. room = connection.initJitsiConference(APP.conference.roomName,
  859. this._getConferenceOptions());
  860. this._setLocalAudioVideoStreams(localTracks);
  861. this.invite = new Invite(room);
  862. this._room = room; // FIXME do not use this
  863. _setupLocalParticipantProperties();
  864. this._setupListeners();
  865. },
  866. /**
  867. * Sets local video and audio streams.
  868. * @param {JitsiLocalTrack[]} tracks=[]
  869. * @returns {Promise[]}
  870. * @private
  871. */
  872. _setLocalAudioVideoStreams(tracks = []) {
  873. return tracks.map(track => {
  874. if (track.isAudioTrack()) {
  875. return this.useAudioStream(track);
  876. } else if (track.isVideoTrack()) {
  877. return this.useVideoStream(track);
  878. } else {
  879. logger.error(
  880. "Ignored not an audio nor a video track: ", track);
  881. return Promise.resolve();
  882. }
  883. });
  884. },
  885. _getConferenceOptions() {
  886. let options = config;
  887. if(config.enableRecording && !config.recordingType) {
  888. options.recordingType = (config.hosts &&
  889. (typeof config.hosts.jirecon != "undefined"))?
  890. "jirecon" : "colibri";
  891. }
  892. return options;
  893. },
  894. /**
  895. * Start using provided video stream.
  896. * Stops previous video stream.
  897. * @param {JitsiLocalTrack} [stream] new stream to use or null
  898. * @returns {Promise}
  899. */
  900. useVideoStream (newStream) {
  901. return room.replaceTrack(localVideo, newStream)
  902. .then(() => {
  903. // We call dispose after doing the replace because
  904. // dispose will try and do a new o/a after the
  905. // track removes itself. Doing it after means
  906. // the JitsiLocalTrack::conference member is already
  907. // cleared, so it won't try and do the o/a
  908. if (localVideo) {
  909. localVideo.dispose();
  910. }
  911. localVideo = newStream;
  912. if (newStream) {
  913. this.videoMuted = newStream.isMuted();
  914. this.isSharingScreen = newStream.videoType === 'desktop';
  915. APP.UI.addLocalStream(newStream);
  916. newStream.videoType === 'camera'
  917. && APP.UI.setCameraButtonEnabled(true);
  918. } else {
  919. this.videoMuted = false;
  920. this.isSharingScreen = false;
  921. }
  922. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  923. APP.UI.updateDesktopSharingButtons();
  924. });
  925. },
  926. /**
  927. * Start using provided audio stream.
  928. * Stops previous audio stream.
  929. * @param {JitsiLocalTrack} [stream] new stream to use or null
  930. * @returns {Promise}
  931. */
  932. useAudioStream (newStream) {
  933. return room.replaceTrack(localAudio, newStream)
  934. .then(() => {
  935. // We call dispose after doing the replace because
  936. // dispose will try and do a new o/a after the
  937. // track removes itself. Doing it after means
  938. // the JitsiLocalTrack::conference member is already
  939. // cleared, so it won't try and do the o/a
  940. if (localAudio) {
  941. localAudio.dispose();
  942. }
  943. localAudio = newStream;
  944. if (newStream) {
  945. this.audioMuted = newStream.isMuted();
  946. APP.UI.addLocalStream(newStream);
  947. } else {
  948. this.audioMuted = false;
  949. }
  950. APP.UI.setMicrophoneButtonEnabled(true);
  951. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  952. });
  953. },
  954. videoSwitchInProgress: false,
  955. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  956. if (this.videoSwitchInProgress) {
  957. logger.warn("Switch in progress.");
  958. return;
  959. }
  960. if (!this.isDesktopSharingEnabled) {
  961. logger.warn("Cannot toggle screen sharing: not supported.");
  962. return;
  963. }
  964. this.videoSwitchInProgress = true;
  965. let externalInstallation = false;
  966. if (shareScreen) {
  967. this.screenSharingPromise = createLocalTracks({
  968. devices: ['desktop'],
  969. desktopSharingExtensionExternalInstallation: {
  970. interval: 500,
  971. checkAgain: () => {
  972. return DSExternalInstallationInProgress;
  973. },
  974. listener: (status, url) => {
  975. switch(status) {
  976. case "waitingForExtension":
  977. DSExternalInstallationInProgress = true;
  978. externalInstallation = true;
  979. APP.UI.showExtensionExternalInstallationDialog(
  980. url);
  981. break;
  982. case "extensionFound":
  983. if(externalInstallation) //close the dialog
  984. $.prompt.close();
  985. break;
  986. default:
  987. //Unknown status
  988. }
  989. }
  990. }
  991. }).then(([stream]) => {
  992. DSExternalInstallationInProgress = false;
  993. // close external installation dialog on success.
  994. if(externalInstallation)
  995. $.prompt.close();
  996. stream.on(
  997. TrackEvents.LOCAL_TRACK_STOPPED,
  998. () => {
  999. // if stream was stopped during screensharing session
  1000. // then we should switch to video
  1001. // otherwise we stopped it because we already switched
  1002. // to video, so nothing to do here
  1003. if (this.isSharingScreen) {
  1004. this.toggleScreenSharing(false);
  1005. }
  1006. }
  1007. );
  1008. return this.useVideoStream(stream);
  1009. }).then(() => {
  1010. this.videoSwitchInProgress = false;
  1011. JitsiMeetJS.analytics.sendEvent(
  1012. 'conference.sharingDesktop.start');
  1013. logger.log('sharing local desktop');
  1014. }).catch((err) => {
  1015. // close external installation dialog to show the error.
  1016. if(externalInstallation)
  1017. $.prompt.close();
  1018. this.videoSwitchInProgress = false;
  1019. this.toggleScreenSharing(false);
  1020. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1021. return;
  1022. }
  1023. logger.error('failed to share local desktop', err);
  1024. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1025. APP.UI.showExtensionRequiredDialog(
  1026. config.desktopSharingFirefoxExtensionURL
  1027. );
  1028. return;
  1029. }
  1030. // Handling:
  1031. // TrackErrors.PERMISSION_DENIED
  1032. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1033. // TrackErrors.GENERAL
  1034. // and any other
  1035. let dialogTxt;
  1036. let dialogTitleKey;
  1037. if (err.name === TrackErrors.PERMISSION_DENIED) {
  1038. dialogTxt = APP.translation.generateTranslationHTML(
  1039. "dialog.screenSharingPermissionDeniedError");
  1040. dialogTitleKey = "dialog.error";
  1041. } else {
  1042. dialogTxt = APP.translation.generateTranslationHTML(
  1043. "dialog.failtoinstall");
  1044. dialogTitleKey = "dialog.permissionDenied";
  1045. }
  1046. APP.UI.messageHandler.openDialog(
  1047. dialogTitleKey, dialogTxt, false);
  1048. });
  1049. } else {
  1050. APP.remoteControl.receiver.stop();
  1051. this.screenSharingPromise = createLocalTracks(
  1052. { devices: ['video'] })
  1053. .then(
  1054. ([stream]) => this.useVideoStream(stream)
  1055. ).then(() => {
  1056. this.videoSwitchInProgress = false;
  1057. JitsiMeetJS.analytics.sendEvent(
  1058. 'conference.sharingDesktop.stop');
  1059. logger.log('sharing local video');
  1060. }).catch((err) => {
  1061. this.useVideoStream(null);
  1062. this.videoSwitchInProgress = false;
  1063. logger.error('failed to share local video', err);
  1064. });
  1065. }
  1066. },
  1067. /**
  1068. * Setup interaction between conference and UI.
  1069. */
  1070. _setupListeners () {
  1071. // add local streams when joined to the conference
  1072. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1073. APP.store.dispatch(conferenceJoined(room));
  1074. APP.UI.mucJoined();
  1075. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1076. APP.UI.markVideoInterrupted(false);
  1077. });
  1078. room.on(
  1079. ConferenceEvents.CONFERENCE_LEFT,
  1080. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1081. room.on(
  1082. ConferenceEvents.AUTH_STATUS_CHANGED,
  1083. function (authEnabled, authLogin) {
  1084. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1085. }
  1086. );
  1087. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1088. user => APP.UI.onUserFeaturesChanged(user));
  1089. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1090. if (user.isHidden())
  1091. return;
  1092. APP.store.dispatch(participantJoined({
  1093. id,
  1094. name: user.getDisplayName(),
  1095. role: user.getRole()
  1096. }));
  1097. logger.log('USER %s connnected', id, user);
  1098. APP.API.notifyUserJoined(id);
  1099. APP.UI.addUser(user);
  1100. // check the roles for the new user and reflect them
  1101. APP.UI.updateUserRole(user);
  1102. });
  1103. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1104. APP.store.dispatch(participantLeft(id, user));
  1105. logger.log('USER %s LEFT', id, user);
  1106. APP.API.notifyUserLeft(id);
  1107. APP.UI.removeUser(id, user.getDisplayName());
  1108. APP.UI.onSharedVideoStop(id);
  1109. });
  1110. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1111. APP.store.dispatch(participantRoleChanged(id, role));
  1112. if (this.isLocalId(id)) {
  1113. logger.info(`My role changed, new role: ${role}`);
  1114. if (this.isModerator !== room.isModerator()) {
  1115. this.isModerator = room.isModerator();
  1116. APP.UI.updateLocalRole(room.isModerator());
  1117. }
  1118. } else {
  1119. let user = room.getParticipantById(id);
  1120. if (user) {
  1121. APP.UI.updateUserRole(user);
  1122. }
  1123. }
  1124. });
  1125. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1126. if(!track || track.isLocal())
  1127. return;
  1128. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1129. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1130. });
  1131. APP.UI.addRemoteStream(track);
  1132. });
  1133. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1134. if(!track || track.isLocal())
  1135. return;
  1136. APP.UI.removeRemoteStream(track);
  1137. });
  1138. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1139. if(!track)
  1140. return;
  1141. const handler = (track.getType() === "audio")?
  1142. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1143. let id;
  1144. const mute = track.isMuted();
  1145. if(track.isLocal()){
  1146. id = APP.conference.getMyUserId();
  1147. if(track.getType() === "audio") {
  1148. this.audioMuted = mute;
  1149. } else {
  1150. this.videoMuted = mute;
  1151. }
  1152. } else {
  1153. id = track.getParticipantId();
  1154. }
  1155. handler(id , mute);
  1156. });
  1157. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1158. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1159. lvl = 0;
  1160. }
  1161. if(config.debug)
  1162. {
  1163. this.audioLevelsMap[id] = lvl;
  1164. if(config.debugAudioLevels)
  1165. logger.log("AudioLevel:" + id + "/" + lvl);
  1166. }
  1167. APP.UI.setAudioLevel(id, lvl);
  1168. });
  1169. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1170. APP.UI.showToolbar(6000);
  1171. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  1172. });
  1173. room.on(
  1174. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1175. (leavingIds, enteringIds) => {
  1176. APP.UI.handleLastNEndpoints(leavingIds, enteringIds);
  1177. });
  1178. room.on(
  1179. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1180. (id, isActive) => {
  1181. APP.UI.participantConnectionStatusChanged(id, isActive);
  1182. });
  1183. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1184. if (this.isLocalId(id)) {
  1185. this.isDominantSpeaker = true;
  1186. this.setRaisedHand(false);
  1187. } else {
  1188. this.isDominantSpeaker = false;
  1189. var participant = room.getParticipantById(id);
  1190. if (participant) {
  1191. APP.UI.setRaisedHandStatus(participant, false);
  1192. }
  1193. }
  1194. APP.UI.markDominantSpeaker(id);
  1195. });
  1196. if (!interfaceConfig.filmStripOnly) {
  1197. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1198. APP.UI.markVideoInterrupted(true);
  1199. });
  1200. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1201. APP.UI.markVideoInterrupted(false);
  1202. });
  1203. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1204. let nick = getDisplayName(id);
  1205. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1206. APP.UI.addMessage(id, nick, text, ts);
  1207. });
  1208. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1209. APP.API.notifySendingChatMessage(message);
  1210. room.sendTextMessage(message);
  1211. });
  1212. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1213. try {
  1214. // do not try to select participant if there is none (we
  1215. // are alone in the room), otherwise an error will be
  1216. // thrown cause reporting mechanism is not available
  1217. // (datachannels currently)
  1218. if (room.getParticipants().length === 0)
  1219. return;
  1220. room.selectParticipant(id);
  1221. } catch (e) {
  1222. JitsiMeetJS.analytics.sendEvent(
  1223. 'selectParticipant.failed');
  1224. reportError(e);
  1225. }
  1226. });
  1227. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1228. (smallVideo, isPinned) => {
  1229. let smallVideoId = smallVideo.getId();
  1230. let isLocal = APP.conference.isLocalId(smallVideoId);
  1231. let eventName
  1232. = (isPinned ? "pinned" : "unpinned") + "." +
  1233. (isLocal ? "local" : "remote");
  1234. let participantCount = room.getParticipantCount();
  1235. JitsiMeetJS.analytics.sendEvent(
  1236. eventName,
  1237. { value: participantCount });
  1238. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1239. // the participant is on the large video ?
  1240. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1241. && !isLocal) {
  1242. // When the library starts supporting multiple pins we
  1243. // would pass the isPinned parameter together with the
  1244. // identifier, but currently we send null to indicate that
  1245. // we unpin the last pinned.
  1246. try {
  1247. room.pinParticipant(isPinned ? smallVideoId : null);
  1248. } catch (e) {
  1249. reportError(e);
  1250. }
  1251. }
  1252. });
  1253. }
  1254. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1255. APP.UI.showLocalConnectionInterrupted(true);
  1256. });
  1257. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1258. APP.UI.showLocalConnectionInterrupted(false);
  1259. });
  1260. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1261. const formattedDisplayName
  1262. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1263. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1264. APP.UI.changeDisplayName(id, formattedDisplayName);
  1265. });
  1266. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1267. (participant, name, oldValue, newValue) => {
  1268. if (name === "raisedHand") {
  1269. APP.UI.setRaisedHandStatus(participant, newValue);
  1270. }
  1271. });
  1272. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1273. logger.log("Received recorder status change: ", status, error);
  1274. APP.UI.updateRecordingState(status);
  1275. });
  1276. room.on(ConferenceEvents.KICKED, () => {
  1277. APP.UI.hideStats();
  1278. APP.UI.notifyKicked();
  1279. // FIXME close
  1280. });
  1281. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1282. APP.store.dispatch(suspendDetected());
  1283. // After wake up, we will be in a state where conference is left
  1284. // there will be dialog shown to user.
  1285. // We do not want video/audio as we show an overlay and after it
  1286. // user need to rejoin or close, while waking up we can detect
  1287. // camera wakeup as a problem with device.
  1288. // We also do not care about device change, which happens
  1289. // on resume after suspending PC.
  1290. if (this.deviceChangeListener)
  1291. JitsiMeetJS.mediaDevices.removeEventListener(
  1292. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1293. this.deviceChangeListener);
  1294. // stop local video
  1295. if (localVideo) {
  1296. localVideo.dispose();
  1297. }
  1298. // stop local audio
  1299. if (localAudio) {
  1300. localAudio.dispose();
  1301. }
  1302. });
  1303. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1304. APP.UI.updateDTMFSupport(isDTMFSupported);
  1305. });
  1306. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1307. // Wait a little bit more just to be sure that we won't miss the
  1308. // extension installation
  1309. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1310. });
  1311. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1312. window.open(
  1313. url, "extension_store_window",
  1314. "resizable,scrollbars=yes,status=1");
  1315. });
  1316. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1317. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1318. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1319. (stats) => {
  1320. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1321. });
  1322. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1323. (id, stats) => {
  1324. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1325. });
  1326. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1327. APP.UI.initEtherpad(value);
  1328. });
  1329. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1330. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1331. APP.store.dispatch(changeParticipantEmail(from, data.value));
  1332. APP.UI.setUserEmail(from, data.value);
  1333. });
  1334. room.addCommandListener(
  1335. this.commands.defaults.AVATAR_URL,
  1336. (data, from) => {
  1337. APP.store.dispatch(
  1338. changeParticipantAvatarURL(from, data.value));
  1339. APP.UI.setUserAvatarUrl(from, data.value);
  1340. });
  1341. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1342. (data, from) => {
  1343. APP.store.dispatch(
  1344. changeParticipantAvatarID(from, data.value));
  1345. APP.UI.setUserAvatarID(from, data.value);
  1346. });
  1347. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1348. this.changeLocalDisplayName.bind(this));
  1349. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1350. (startAudioMuted, startVideoMuted) => {
  1351. room.setStartMutedPolicy({
  1352. audio: startAudioMuted,
  1353. video: startVideoMuted
  1354. });
  1355. }
  1356. );
  1357. room.on(
  1358. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1359. ({ audio, video }) => {
  1360. APP.UI.onStartMutedChanged(audio, video);
  1361. }
  1362. );
  1363. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1364. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1365. && APP.UI.notifyInitiallyMuted();
  1366. });
  1367. room.on(
  1368. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1369. APP.UI.updateDevicesAvailability(id, devices);
  1370. }
  1371. );
  1372. // call hangup
  1373. APP.UI.addListener(UIEvents.HANGUP, () => {
  1374. this.hangup(true);
  1375. });
  1376. // logout
  1377. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1378. AuthHandler.logout(room).then(url => {
  1379. if (url) {
  1380. UIUtil.redirect(url);
  1381. } else {
  1382. this.hangup(true);
  1383. }
  1384. });
  1385. });
  1386. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1387. room.dial(sipNumber);
  1388. });
  1389. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1390. (id, oldResolution, newResolution, delay) => {
  1391. var logObject = {
  1392. id: "resolution_change",
  1393. participant: id,
  1394. oldValue: oldResolution,
  1395. newValue: newResolution,
  1396. delay: delay
  1397. };
  1398. room.sendApplicationLog(JSON.stringify(logObject));
  1399. // We only care about the delay between simulcast streams.
  1400. // Longer delays will be caused by something else and will just
  1401. // poison the data.
  1402. if (delay < 2000) {
  1403. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1404. {value: delay});
  1405. }
  1406. });
  1407. // Starts or stops the recording for the conference.
  1408. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1409. room.toggleRecording(options);
  1410. });
  1411. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1412. room.setSubject(topic);
  1413. });
  1414. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1415. APP.UI.setSubject(subject);
  1416. });
  1417. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1418. room.kickParticipant(id);
  1419. });
  1420. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1421. room.muteParticipant(id);
  1422. });
  1423. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1424. AuthHandler.authenticate(room);
  1425. });
  1426. APP.UI.addListener(
  1427. UIEvents.VIDEO_DEVICE_CHANGED,
  1428. (cameraDeviceId) => {
  1429. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1430. createLocalTracks({
  1431. devices: ['video'],
  1432. cameraDeviceId: cameraDeviceId,
  1433. micDeviceId: null
  1434. })
  1435. .then(([stream]) => {
  1436. this.useVideoStream(stream);
  1437. logger.log('switched local video device');
  1438. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1439. })
  1440. .catch((err) => {
  1441. APP.UI.showDeviceErrorDialog(null, err);
  1442. APP.UI.setSelectedCameraFromSettings();
  1443. });
  1444. }
  1445. );
  1446. APP.UI.addListener(
  1447. UIEvents.AUDIO_DEVICE_CHANGED,
  1448. (micDeviceId) => {
  1449. JitsiMeetJS.analytics.sendEvent(
  1450. 'settings.changeDevice.audioIn');
  1451. createLocalTracks({
  1452. devices: ['audio'],
  1453. cameraDeviceId: null,
  1454. micDeviceId: micDeviceId
  1455. })
  1456. .then(([stream]) => {
  1457. this.useAudioStream(stream);
  1458. logger.log('switched local audio device');
  1459. APP.settings.setMicDeviceId(micDeviceId, true);
  1460. })
  1461. .catch((err) => {
  1462. APP.UI.showDeviceErrorDialog(err, null);
  1463. APP.UI.setSelectedMicFromSettings();
  1464. });
  1465. }
  1466. );
  1467. APP.UI.addListener(
  1468. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1469. (audioOutputDeviceId) => {
  1470. JitsiMeetJS.analytics.sendEvent(
  1471. 'settings.changeDevice.audioOut');
  1472. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1473. .then(() => logger.log('changed audio output device'))
  1474. .catch((err) => {
  1475. logger.warn('Failed to change audio output device. ' +
  1476. 'Default or previously set audio output device ' +
  1477. 'will be used instead.', err);
  1478. APP.UI.setSelectedAudioOutputFromSettings();
  1479. });
  1480. }
  1481. );
  1482. APP.UI.addListener(
  1483. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1484. );
  1485. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1486. (url, state, time, isMuted, volume) => {
  1487. // send start and stop commands once, and remove any updates
  1488. // that had left
  1489. if (state === 'stop' || state === 'start' || state === 'playing') {
  1490. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1491. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1492. value: url,
  1493. attributes: {
  1494. state: state,
  1495. time: time,
  1496. muted: isMuted,
  1497. volume: volume
  1498. }
  1499. });
  1500. }
  1501. else {
  1502. // in case of paused, in order to allow late users to join
  1503. // paused
  1504. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1505. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1506. value: url,
  1507. attributes: {
  1508. state: state,
  1509. time: time,
  1510. muted: isMuted,
  1511. volume: volume
  1512. }
  1513. });
  1514. }
  1515. });
  1516. room.addCommandListener(
  1517. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1518. if (attributes.state === 'stop') {
  1519. APP.UI.onSharedVideoStop(id, attributes);
  1520. }
  1521. else if (attributes.state === 'start') {
  1522. APP.UI.onSharedVideoStart(id, value, attributes);
  1523. }
  1524. else if (attributes.state === 'playing'
  1525. || attributes.state === 'pause') {
  1526. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1527. }
  1528. });
  1529. },
  1530. /**
  1531. * Adds any room listener.
  1532. * @param {string} eventName one of the ConferenceEvents
  1533. * @param {Function} listener the function to be called when the event
  1534. * occurs
  1535. */
  1536. addConferenceListener(eventName, listener) {
  1537. room.on(eventName, listener);
  1538. },
  1539. /**
  1540. * Removes any room listener.
  1541. * @param {string} eventName one of the ConferenceEvents
  1542. * @param {Function} listener the listener to be removed.
  1543. */
  1544. removeConferenceListener(eventName, listener) {
  1545. room.off(eventName, listener);
  1546. },
  1547. /**
  1548. * Inits list of current devices and event listener for device change.
  1549. * @private
  1550. */
  1551. _initDeviceList() {
  1552. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1553. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1554. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1555. // Ugly way to synchronize real device IDs with local
  1556. // storage and settings menu. This is a workaround until
  1557. // getConstraints() method will be implemented in browsers.
  1558. if (localAudio) {
  1559. APP.settings.setMicDeviceId(
  1560. localAudio.getDeviceId(), false);
  1561. }
  1562. if (localVideo) {
  1563. APP.settings.setCameraDeviceId(
  1564. localVideo.getDeviceId(), false);
  1565. }
  1566. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1567. APP.UI.onAvailableDevicesChanged(devices);
  1568. });
  1569. this.deviceChangeListener = (devices) =>
  1570. window.setTimeout(
  1571. () => this._onDeviceListChanged(devices), 0);
  1572. JitsiMeetJS.mediaDevices.addEventListener(
  1573. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1574. this.deviceChangeListener);
  1575. }
  1576. },
  1577. /**
  1578. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1579. * handle change of available media devices.
  1580. * @private
  1581. * @param {MediaDeviceInfo[]} devices
  1582. * @returns {Promise}
  1583. */
  1584. _onDeviceListChanged(devices) {
  1585. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1586. // Event handler can be fired before direct
  1587. // enumerateDevices() call, so handle this situation here.
  1588. if (!currentDevices.audioinput &&
  1589. !currentDevices.videoinput &&
  1590. !currentDevices.audiooutput) {
  1591. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1592. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1593. }
  1594. let newDevices =
  1595. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1596. devices, this.isSharingScreen, localVideo, localAudio);
  1597. let promises = [];
  1598. let audioWasMuted = this.audioMuted;
  1599. let videoWasMuted = this.videoMuted;
  1600. let availableAudioInputDevices =
  1601. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1602. let availableVideoInputDevices =
  1603. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1604. if (typeof newDevices.audiooutput !== 'undefined') {
  1605. // Just ignore any errors in catch block.
  1606. promises.push(APP.settings
  1607. .setAudioOutputDeviceId(newDevices.audiooutput)
  1608. .catch());
  1609. }
  1610. promises.push(
  1611. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1612. createLocalTracks,
  1613. newDevices.videoinput,
  1614. newDevices.audioinput)
  1615. .then(tracks =>
  1616. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1617. .then(() => {
  1618. // If audio was muted before, or we unplugged current device
  1619. // and selected new one, then mute new audio track.
  1620. if (audioWasMuted ||
  1621. currentDevices.audioinput.length >
  1622. availableAudioInputDevices.length) {
  1623. muteLocalAudio(true);
  1624. }
  1625. // If video was muted before, or we unplugged current device
  1626. // and selected new one, then mute new video track.
  1627. if (videoWasMuted ||
  1628. currentDevices.videoinput.length >
  1629. availableVideoInputDevices.length) {
  1630. muteLocalVideo(true);
  1631. }
  1632. }));
  1633. return Promise.all(promises)
  1634. .then(() => {
  1635. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1636. APP.UI.onAvailableDevicesChanged(devices);
  1637. });
  1638. },
  1639. /**
  1640. * Toggles the local "raised hand" status.
  1641. */
  1642. maybeToggleRaisedHand() {
  1643. this.setRaisedHand(!this.isHandRaised);
  1644. },
  1645. /**
  1646. * Sets the local "raised hand" status to a particular value.
  1647. */
  1648. setRaisedHand(raisedHand) {
  1649. if (raisedHand !== this.isHandRaised)
  1650. {
  1651. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1652. this.isHandRaised = raisedHand;
  1653. // Advertise the updated status
  1654. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1655. // Update the view
  1656. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1657. }
  1658. },
  1659. /**
  1660. * Log event to callstats and analytics.
  1661. * @param {string} name the event name
  1662. * @param {int} value the value (it's int because google analytics supports
  1663. * only int).
  1664. * @param {string} label short text which provides more info about the event
  1665. * which allows to distinguish between few event cases of the same name
  1666. * NOTE: Should be used after conference.init
  1667. */
  1668. logEvent(name, value, label) {
  1669. if(JitsiMeetJS.analytics) {
  1670. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  1671. }
  1672. if(room) {
  1673. room.sendApplicationLog(JSON.stringify({name, value, label}));
  1674. }
  1675. },
  1676. /**
  1677. * Methods logs an application event given in the JSON format.
  1678. * @param {string} logJSON an event to be logged in JSON format
  1679. */
  1680. logJSON(logJSON) {
  1681. if (room) {
  1682. room.sendApplicationLog(logJSON);
  1683. }
  1684. },
  1685. /**
  1686. * Disconnect from the conference and optionally request user feedback.
  1687. * @param {boolean} [requestFeedback=false] if user feedback should be
  1688. * requested
  1689. */
  1690. hangup (requestFeedback = false) {
  1691. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  1692. APP.UI.hideRingOverLay();
  1693. let requestFeedbackPromise = requestFeedback
  1694. ? APP.UI.requestFeedbackOnHangup()
  1695. // false - because the thank you dialog shouldn't be displayed
  1696. .catch(() => Promise.resolve(false))
  1697. : Promise.resolve(true);// true - because the thank you dialog
  1698. //should be displayed
  1699. // All promises are returning Promise.resolve to make Promise.all to
  1700. // be resolved when both Promises are finished. Otherwise Promise.all
  1701. // will reject on first rejected Promise and we can redirect the page
  1702. // before all operations are done.
  1703. Promise.all([
  1704. requestFeedbackPromise,
  1705. room.leave().then(disconnect, disconnect)
  1706. ]).then(values => {
  1707. APP.API.notifyReadyToClose();
  1708. maybeRedirectToWelcomePage(values[0]);
  1709. });
  1710. },
  1711. /**
  1712. * Changes the email for the local user
  1713. * @param email {string} the new email
  1714. */
  1715. changeLocalEmail(email = '') {
  1716. email = email.trim();
  1717. if (email === APP.settings.getEmail()) {
  1718. return;
  1719. }
  1720. APP.store.dispatch(changeParticipantEmail(room.myUserId(), email));
  1721. APP.settings.setEmail(email);
  1722. APP.UI.setUserEmail(room.myUserId(), email);
  1723. sendData(commands.EMAIL, email);
  1724. },
  1725. /**
  1726. * Changes the avatar url for the local user
  1727. * @param url {string} the new url
  1728. */
  1729. changeLocalAvatarUrl(url = '') {
  1730. url = url.trim();
  1731. if (url === APP.settings.getAvatarUrl()) {
  1732. return;
  1733. }
  1734. APP.store.dispatch(changeParticipantAvatarURL(room.myUserId(), url));
  1735. APP.settings.setAvatarUrl(url);
  1736. APP.UI.setUserAvatarUrl(room.myUserId(), url);
  1737. sendData(commands.AVATAR_URL, url);
  1738. },
  1739. /**
  1740. * Sends a message via the data channel.
  1741. * @param {string} to the id of the endpoint that should receive the
  1742. * message. If "" - the message will be sent to all participants.
  1743. * @param {object} payload the payload of the message.
  1744. * @throws NetworkError or InvalidStateError or Error if the operation
  1745. * fails.
  1746. */
  1747. sendEndpointMessage (to, payload) {
  1748. room.sendEndpointMessage(to, payload);
  1749. },
  1750. /**
  1751. * Adds new listener.
  1752. * @param {String} eventName the name of the event
  1753. * @param {Function} listener the listener.
  1754. */
  1755. addListener (eventName, listener) {
  1756. eventEmitter.addListener(eventName, listener);
  1757. },
  1758. /**
  1759. * Removes listener.
  1760. * @param {String} eventName the name of the event that triggers the
  1761. * listener
  1762. * @param {Function} listener the listener.
  1763. */
  1764. removeListener (eventName, listener) {
  1765. eventEmitter.removeListener(eventName, listener);
  1766. },
  1767. /**
  1768. * Checks if the participant given by participantId is currently in the
  1769. * last N set if there's one supported.
  1770. *
  1771. * @param participantId the identifier of the participant
  1772. * @returns {boolean} {true} if the participant given by the participantId
  1773. * is currently in the last N set or if there's no last N set at this point
  1774. * and {false} otherwise
  1775. */
  1776. isInLastN (participantId) {
  1777. return room.isInLastN(participantId);
  1778. },
  1779. /**
  1780. * Changes the display name for the local user
  1781. * @param nickname {string} the new display name
  1782. */
  1783. changeLocalDisplayName(nickname = '') {
  1784. const formattedNickname
  1785. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  1786. if (formattedNickname === APP.settings.getDisplayName()) {
  1787. return;
  1788. }
  1789. APP.settings.setDisplayName(formattedNickname);
  1790. room.setDisplayName(formattedNickname);
  1791. APP.UI.changeDisplayName(this.getMyUserId(),
  1792. formattedNickname);
  1793. }
  1794. };