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

conference.js 72KB

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