Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 72KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121
  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. participantJoined,
  33. participantLeft,
  34. participantRoleChanged,
  35. participantUpdated
  36. } from './react/features/base/participants';
  37. import {
  38. replaceLocalTrack,
  39. trackAdded,
  40. trackRemoved
  41. } from './react/features/base/tracks';
  42. import {
  43. showDesktopPicker
  44. } from './react/features/desktop-picker';
  45. import {
  46. mediaPermissionPromptVisibilityChanged,
  47. suspendDetected
  48. } from './react/features/overlay';
  49. import { showDesktopSharingButton } from './react/features/toolbox';
  50. const ConnectionEvents = JitsiMeetJS.events.connection;
  51. const ConnectionErrors = JitsiMeetJS.errors.connection;
  52. const ConferenceEvents = JitsiMeetJS.events.conference;
  53. const ConferenceErrors = JitsiMeetJS.errors.conference;
  54. const TrackEvents = JitsiMeetJS.events.track;
  55. const TrackErrors = JitsiMeetJS.errors.track;
  56. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  57. const eventEmitter = new EventEmitter();
  58. let room;
  59. let connection;
  60. let localAudio, localVideo;
  61. let initialAudioMutedState = false, initialVideoMutedState = false;
  62. /**
  63. * Indicates whether extension external installation is in progress or not.
  64. */
  65. let DSExternalInstallationInProgress = false;
  66. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  67. /*
  68. * Logic to open a desktop picker put on the window global for
  69. * lib-jitsi-meet to detect and invoke
  70. */
  71. window.JitsiMeetScreenObtainer = {
  72. openDesktopPicker(onSourceChoose) {
  73. APP.store.dispatch(showDesktopPicker(onSourceChoose));
  74. }
  75. };
  76. /**
  77. * Known custom conference commands.
  78. */
  79. const commands = {
  80. AVATAR_ID: AVATAR_ID_COMMAND,
  81. AVATAR_URL: AVATAR_URL_COMMAND,
  82. CUSTOM_ROLE: "custom-role",
  83. EMAIL: EMAIL_COMMAND,
  84. ETHERPAD: "etherpad",
  85. SHARED_VIDEO: "shared-video"
  86. };
  87. /**
  88. * Max length of the display names. If we receive longer display name the
  89. * additional chars are going to be cut.
  90. */
  91. const MAX_DISPLAY_NAME_LENGTH = 50;
  92. /**
  93. * Open Connection. When authentication failed it shows auth dialog.
  94. * @param roomName the room name to use
  95. * @returns Promise<JitsiConnection>
  96. */
  97. function connect(roomName) {
  98. return openConnection({retry: true, roomName: roomName})
  99. .catch(function (err) {
  100. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  101. APP.UI.notifyTokenAuthFailed();
  102. } else {
  103. APP.UI.notifyConnectionFailed(err);
  104. }
  105. throw err;
  106. });
  107. }
  108. /**
  109. * Creates local media tracks and connects to room. Will show error
  110. * dialogs in case if accessing local microphone and/or camera failed. Will
  111. * show guidance overlay for users on how to give access to camera and/or
  112. * microphone,
  113. * @param {string} roomName
  114. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  115. */
  116. function createInitialLocalTracksAndConnect(roomName) {
  117. let audioAndVideoError,
  118. audioOnlyError;
  119. JitsiMeetJS.mediaDevices.addEventListener(
  120. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  121. browser =>
  122. APP.store.dispatch(
  123. mediaPermissionPromptVisibilityChanged(true, browser))
  124. );
  125. // First try to retrieve both audio and video.
  126. let tryCreateLocalTracks = createLocalTracks(
  127. { devices: ['audio', 'video'] }, true)
  128. .catch(err => {
  129. // If failed then try to retrieve only audio.
  130. audioAndVideoError = err;
  131. return createLocalTracks({ devices: ['audio'] }, true);
  132. })
  133. .catch(err => {
  134. // If audio failed too then just return empty array for tracks.
  135. audioOnlyError = err;
  136. return [];
  137. });
  138. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  139. .then(([tracks, con]) => {
  140. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  141. if (audioAndVideoError) {
  142. if (audioOnlyError) {
  143. // If both requests for 'audio' + 'video' and 'audio' only
  144. // failed, we assume that there is some problems with user's
  145. // microphone and show corresponding dialog.
  146. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  147. } else {
  148. // If request for 'audio' + 'video' failed, but request for
  149. // 'audio' only was OK, we assume that we had problems with
  150. // camera and show corresponding dialog.
  151. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  152. }
  153. }
  154. return [tracks, con];
  155. });
  156. }
  157. /**
  158. * Share data to other users.
  159. * @param command the command
  160. * @param {string} value new value
  161. */
  162. function sendData(command, value) {
  163. if(!room) {
  164. return;
  165. }
  166. room.removeCommand(command);
  167. room.sendCommand(command, {value: value});
  168. }
  169. /**
  170. * Sets up initially the properties of the local participant - email, avatarID,
  171. * avatarURL, displayName, etc.
  172. */
  173. function _setupLocalParticipantProperties() {
  174. const email = APP.settings.getEmail();
  175. email && sendData(commands.EMAIL, email);
  176. const avatarUrl = APP.settings.getAvatarUrl();
  177. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  178. if (!email && !avatarUrl) {
  179. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  180. }
  181. let nick = APP.settings.getDisplayName();
  182. if (config.useNicks && !nick) {
  183. nick = APP.UI.askForNickname();
  184. APP.settings.setDisplayName(nick);
  185. }
  186. nick && room.setDisplayName(nick);
  187. }
  188. /**
  189. * Get user nickname by user id.
  190. * @param {string} id user id
  191. * @returns {string?} user nickname or undefined if user is unknown.
  192. */
  193. function getDisplayName(id) {
  194. if (APP.conference.isLocalId(id)) {
  195. return APP.settings.getDisplayName();
  196. }
  197. let participant = room.getParticipantById(id);
  198. if (participant && participant.getDisplayName()) {
  199. return participant.getDisplayName();
  200. }
  201. }
  202. /**
  203. * Mute or unmute local audio stream if it exists.
  204. * @param {boolean} muted - if audio stream should be muted or unmuted.
  205. * @param {boolean} userInteraction - indicates if this local audio mute was a
  206. * result of user interaction
  207. */
  208. function muteLocalAudio(muted) {
  209. muteLocalMedia(localAudio, muted, 'Audio');
  210. }
  211. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  212. if (!localMedia) {
  213. return;
  214. }
  215. const method = muted ? 'mute' : 'unmute';
  216. localMedia[method]().catch(reason => {
  217. logger.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  218. });
  219. }
  220. /**
  221. * Mute or unmute local video stream if it exists.
  222. * @param {boolean} muted if video stream should be muted or unmuted.
  223. */
  224. function muteLocalVideo(muted) {
  225. muteLocalMedia(localVideo, muted, 'Video');
  226. }
  227. /**
  228. * Check if the welcome page is enabled and redirects to it.
  229. * If requested show a thank you dialog before that.
  230. * If we have a close page enabled, redirect to it without
  231. * showing any other dialog.
  232. *
  233. * @param {object} options used to decide which particular close page to show
  234. * or if close page is disabled, whether we should show the thankyou dialog
  235. * @param {boolean} options.thankYouDialogVisible - whether we should
  236. * show thank you dialog
  237. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  238. */
  239. function maybeRedirectToWelcomePage(options) {
  240. // if close page is enabled redirect to it, without further action
  241. if (config.enableClosePage) {
  242. const { isGuest } = APP.store.getState()['features/jwt'];
  243. // save whether current user is guest or not, before navigating
  244. // to close page
  245. window.sessionStorage.setItem('guest', isGuest);
  246. assignWindowLocationPathname('static/'
  247. + (options.feedbackSubmitted ? "close.html" : "close2.html"));
  248. return;
  249. }
  250. // else: show thankYou dialog only if there is no feedback
  251. if (options.thankYouDialogVisible)
  252. APP.UI.messageHandler.openMessageDialog(
  253. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  254. // if Welcome page is enabled redirect to welcome page after 3 sec.
  255. if (config.enableWelcomePage) {
  256. setTimeout(() => {
  257. APP.settings.setWelcomePageEnabled(true);
  258. assignWindowLocationPathname('./');
  259. }, 3000);
  260. }
  261. }
  262. /**
  263. * Assigns a specific pathname to window.location.pathname taking into account
  264. * the context root of the Web app.
  265. *
  266. * @param {string} pathname - The pathname to assign to
  267. * window.location.pathname. If the specified pathname is relative, the context
  268. * root of the Web app will be prepended to the specified pathname before
  269. * assigning it to window.location.pathname.
  270. * @return {void}
  271. */
  272. function assignWindowLocationPathname(pathname) {
  273. const windowLocation = window.location;
  274. if (!pathname.startsWith('/')) {
  275. // A pathname equal to ./ specifies the current directory. It will be
  276. // fine but pointless to include it because contextRoot is the current
  277. // directory.
  278. pathname.startsWith('./') && (pathname = pathname.substring(2));
  279. pathname = getLocationContextRoot(windowLocation) + pathname;
  280. }
  281. windowLocation.pathname = pathname;
  282. }
  283. /**
  284. * Create local tracks of specified types.
  285. * @param {Object} options
  286. * @param {string[]} options.devices - required track types
  287. * ('audio', 'video' etc.)
  288. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  289. * undefined - one from settings will be used
  290. * @param {string|null} (options.micDeviceId) - microphone device id, if
  291. * undefined - one from settings will be used
  292. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  293. * for gUM permission prompt
  294. * @returns {Promise<JitsiLocalTrack[]>}
  295. */
  296. function createLocalTracks(options, checkForPermissionPrompt) {
  297. options || (options = {});
  298. return JitsiMeetJS
  299. .createLocalTracks({
  300. // copy array to avoid mutations inside library
  301. devices: options.devices.slice(0),
  302. resolution: config.resolution,
  303. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  304. options.cameraDeviceId === null
  305. ? APP.settings.getCameraDeviceId()
  306. : options.cameraDeviceId,
  307. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  308. options.micDeviceId === null
  309. ? APP.settings.getMicDeviceId()
  310. : options.micDeviceId,
  311. // adds any ff fake device settings if any
  312. firefox_fake_device: config.firefox_fake_device,
  313. desktopSharingExtensionExternalInstallation:
  314. options.desktopSharingExtensionExternalInstallation
  315. }, checkForPermissionPrompt).then( (tracks) => {
  316. tracks.forEach((track) => {
  317. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  318. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  319. });
  320. return tracks;
  321. }).catch(function (err) {
  322. logger.error(
  323. 'failed to create local tracks', options.devices, err);
  324. return Promise.reject(err);
  325. });
  326. }
  327. class ConferenceConnector {
  328. constructor(resolve, reject) {
  329. this._resolve = resolve;
  330. this._reject = reject;
  331. this.reconnectTimeout = null;
  332. room.on(ConferenceEvents.CONFERENCE_JOINED,
  333. this._handleConferenceJoined.bind(this));
  334. room.on(ConferenceEvents.CONFERENCE_FAILED,
  335. this._onConferenceFailed.bind(this));
  336. room.on(ConferenceEvents.CONFERENCE_ERROR,
  337. this._onConferenceError.bind(this));
  338. }
  339. _handleConferenceFailed(err) {
  340. this._unsubscribe();
  341. this._reject(err);
  342. }
  343. _onConferenceFailed(err, ...params) {
  344. APP.store.dispatch(conferenceFailed(room, err, ...params));
  345. logger.error('CONFERENCE FAILED:', err, ...params);
  346. switch (err) {
  347. case ConferenceErrors.CONNECTION_ERROR:
  348. {
  349. let [msg] = params;
  350. APP.UI.notifyConnectionFailed(msg);
  351. }
  352. break;
  353. case ConferenceErrors.NOT_ALLOWED_ERROR:
  354. {
  355. // let's show some auth not allowed page
  356. assignWindowLocationPathname('static/authError.html');
  357. }
  358. break;
  359. // not enough rights to create conference
  360. case ConferenceErrors.AUTHENTICATION_REQUIRED: {
  361. // Schedule reconnect to check if someone else created the room.
  362. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  363. const { password }
  364. = APP.store.getState()['features/base/conference'];
  365. AuthHandler.requireAuth(room, password);
  366. }
  367. break;
  368. case ConferenceErrors.RESERVATION_ERROR:
  369. {
  370. let [code, msg] = params;
  371. APP.UI.notifyReservationError(code, msg);
  372. }
  373. break;
  374. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  375. APP.UI.notifyGracefulShutdown();
  376. break;
  377. case ConferenceErrors.JINGLE_FATAL_ERROR:
  378. APP.UI.notifyInternalError();
  379. break;
  380. case ConferenceErrors.CONFERENCE_DESTROYED:
  381. {
  382. let [reason] = params;
  383. APP.UI.hideStats();
  384. APP.UI.notifyConferenceDestroyed(reason);
  385. }
  386. break;
  387. // FIXME FOCUS_DISCONNECTED is confusing event name.
  388. // What really happens there is that the library is not ready yet,
  389. // because Jicofo is not available, but it is going to give
  390. // it another try.
  391. case ConferenceErrors.FOCUS_DISCONNECTED:
  392. {
  393. let [focus, retrySec] = params;
  394. APP.UI.notifyFocusDisconnected(focus, retrySec);
  395. }
  396. break;
  397. case ConferenceErrors.FOCUS_LEFT:
  398. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  399. // FIXME the conference should be stopped by the library and not by
  400. // the app. Both the errors above are unrecoverable from the library
  401. // perspective.
  402. room.leave().then(() => connection.disconnect());
  403. break;
  404. case ConferenceErrors.CONFERENCE_MAX_USERS:
  405. connection.disconnect();
  406. APP.UI.notifyMaxUsersLimitReached();
  407. break;
  408. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  409. reload();
  410. break;
  411. default:
  412. this._handleConferenceFailed(err, ...params);
  413. }
  414. }
  415. _onConferenceError(err, ...params) {
  416. logger.error('CONFERENCE Error:', err, params);
  417. switch (err) {
  418. case ConferenceErrors.CHAT_ERROR:
  419. {
  420. let [code, msg] = params;
  421. APP.UI.showChatError(code, msg);
  422. }
  423. break;
  424. default:
  425. logger.error("Unknown error.", err);
  426. }
  427. }
  428. _unsubscribe() {
  429. room.off(
  430. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  431. room.off(
  432. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  433. if (this.reconnectTimeout !== null) {
  434. clearTimeout(this.reconnectTimeout);
  435. }
  436. AuthHandler.closeAuth();
  437. }
  438. _handleConferenceJoined() {
  439. this._unsubscribe();
  440. this._resolve();
  441. }
  442. connect() {
  443. room.join();
  444. }
  445. }
  446. /**
  447. * Disconnects the connection.
  448. * @returns resolved Promise. We need this in order to make the Promise.all
  449. * call in hangup() to resolve when all operations are finished.
  450. */
  451. function disconnect() {
  452. connection.disconnect();
  453. APP.API.notifyConferenceLeft(APP.conference.roomName);
  454. return Promise.resolve();
  455. }
  456. /**
  457. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  458. *
  459. * @param {JitsiMeetJS.connection.error} error - The reported error.
  460. * @returns {void}
  461. * @private
  462. */
  463. function _connectionFailedHandler(error) {
  464. if (isFatalJitsiConnectionError(error)) {
  465. APP.connection.removeEventListener(
  466. ConnectionEvents.CONNECTION_FAILED,
  467. _connectionFailedHandler);
  468. if (room)
  469. room.leave();
  470. }
  471. }
  472. export default {
  473. isModerator: false,
  474. audioMuted: false,
  475. videoMuted: false,
  476. isSharingScreen: false,
  477. isDesktopSharingEnabled: false,
  478. /*
  479. * Whether the local "raisedHand" flag is on.
  480. */
  481. isHandRaised: false,
  482. /*
  483. * Whether the local participant is the dominant speaker in the conference.
  484. */
  485. isDominantSpeaker: false,
  486. /**
  487. * Open new connection and join to the conference.
  488. * @param {object} options
  489. * @param {string} roomName name of the conference
  490. * @returns {Promise}
  491. */
  492. init(options) {
  493. this.roomName = options.roomName;
  494. // attaches global error handler, if there is already one, respect it
  495. if(JitsiMeetJS.getGlobalOnErrorHandler){
  496. var oldOnErrorHandler = window.onerror;
  497. window.onerror = function (message, source, lineno, colno, error) {
  498. JitsiMeetJS.getGlobalOnErrorHandler(
  499. message, source, lineno, colno, error);
  500. if(oldOnErrorHandler)
  501. oldOnErrorHandler(message, source, lineno, colno, error);
  502. };
  503. var oldOnUnhandledRejection = window.onunhandledrejection;
  504. window.onunhandledrejection = function(event) {
  505. JitsiMeetJS.getGlobalOnErrorHandler(
  506. null, null, null, null, event.reason);
  507. if(oldOnUnhandledRejection)
  508. oldOnUnhandledRejection(event);
  509. };
  510. }
  511. return JitsiMeetJS.init(
  512. Object.assign(
  513. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  514. ).then(() => {
  515. analytics.init();
  516. return createInitialLocalTracksAndConnect(options.roomName);
  517. }).then(([tracks, con]) => {
  518. tracks.forEach(track => {
  519. if((track.isAudioTrack() && initialAudioMutedState)
  520. || (track.isVideoTrack() && initialVideoMutedState)) {
  521. track.mute();
  522. }
  523. });
  524. logger.log('initialized with %s local tracks', tracks.length);
  525. con.addEventListener(
  526. ConnectionEvents.CONNECTION_FAILED,
  527. _connectionFailedHandler);
  528. APP.connection = connection = con;
  529. this.isDesktopSharingEnabled =
  530. JitsiMeetJS.isDesktopSharingEnabled();
  531. eventEmitter.emit(
  532. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  533. this.isDesktopSharingEnabled);
  534. APP.store.dispatch(showDesktopSharingButton());
  535. this._createRoom(tracks);
  536. APP.remoteControl.init();
  537. if (UIUtil.isButtonEnabled('contacts')
  538. && !interfaceConfig.filmStripOnly) {
  539. APP.UI.ContactList = new ContactList(room);
  540. }
  541. // if user didn't give access to mic or camera or doesn't have
  542. // them at all, we disable corresponding toolbar buttons
  543. if (!tracks.find((t) => t.isAudioTrack())) {
  544. APP.UI.setMicrophoneButtonEnabled(false);
  545. }
  546. if (!tracks.find((t) => t.isVideoTrack())) {
  547. APP.UI.setCameraButtonEnabled(false);
  548. }
  549. this._initDeviceList();
  550. if (config.iAmRecorder)
  551. this.recorder = new Recorder();
  552. // XXX The API will take care of disconnecting from the XMPP
  553. // server (and, thus, leaving the room) on unload.
  554. return new Promise((resolve, reject) => {
  555. (new ConferenceConnector(resolve, reject)).connect();
  556. });
  557. });
  558. },
  559. /**
  560. * Check if id is id of the local user.
  561. * @param {string} id id to check
  562. * @returns {boolean}
  563. */
  564. isLocalId(id) {
  565. return this.getMyUserId() === id;
  566. },
  567. /**
  568. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  569. * @param mute true for mute and false for unmute.
  570. */
  571. muteAudio(mute) {
  572. muteLocalAudio(mute);
  573. },
  574. /**
  575. * Returns whether local audio is muted or not.
  576. * @returns {boolean}
  577. */
  578. isLocalAudioMuted() {
  579. return this.audioMuted;
  580. },
  581. /**
  582. * Simulates toolbar button click for audio mute. Used by shortcuts
  583. * and API.
  584. * @param {boolean} force - If the track is not created, the operation
  585. * will be executed after the track is created. Otherwise the operation
  586. * will be ignored.
  587. */
  588. toggleAudioMuted(force = false) {
  589. if(!localAudio && force) {
  590. initialAudioMutedState = !initialAudioMutedState;
  591. return;
  592. }
  593. this.muteAudio(!this.audioMuted);
  594. },
  595. /**
  596. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  597. * @param mute true for mute and false for unmute.
  598. */
  599. muteVideo(mute) {
  600. muteLocalVideo(mute);
  601. },
  602. /**
  603. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  604. * @param {boolean} force - If the track is not created, the operation
  605. * will be executed after the track is created. Otherwise the operation
  606. * will be ignored.
  607. */
  608. toggleVideoMuted(force = false) {
  609. if(!localVideo && force) {
  610. initialVideoMutedState = !initialVideoMutedState;
  611. return;
  612. }
  613. this.muteVideo(!this.videoMuted);
  614. },
  615. /**
  616. * Retrieve list of conference participants (without local user).
  617. * @returns {JitsiParticipant[]}
  618. */
  619. listMembers() {
  620. return room.getParticipants();
  621. },
  622. /**
  623. * Retrieve list of ids of conference participants (without local user).
  624. * @returns {string[]}
  625. */
  626. listMembersIds() {
  627. return room.getParticipants().map(p => p.getId());
  628. },
  629. /**
  630. * Checks whether the participant identified by id is a moderator.
  631. * @id id to search for participant
  632. * @return {boolean} whether the participant is moderator
  633. */
  634. isParticipantModerator(id) {
  635. let user = room.getParticipantById(id);
  636. return user && user.isModerator();
  637. },
  638. /**
  639. * Check if SIP is supported.
  640. * @returns {boolean}
  641. */
  642. sipGatewayEnabled() {
  643. return room.isSIPCallingSupported();
  644. },
  645. get membersCount() {
  646. return room.getParticipants().length + 1;
  647. },
  648. /**
  649. * Returns true if the callstats integration is enabled, otherwise returns
  650. * false.
  651. *
  652. * @returns true if the callstats integration is enabled, otherwise returns
  653. * false.
  654. */
  655. isCallstatsEnabled() {
  656. return room && room.isCallstatsEnabled();
  657. },
  658. /**
  659. * Sends the given feedback through CallStats if enabled.
  660. *
  661. * @param overallFeedback an integer between 1 and 5 indicating the
  662. * user feedback
  663. * @param detailedFeedback detailed feedback from the user. Not yet used
  664. */
  665. sendFeedback(overallFeedback, detailedFeedback) {
  666. return room.sendFeedback (overallFeedback, detailedFeedback);
  667. },
  668. /**
  669. * Get speaker stats that track total dominant speaker time.
  670. *
  671. * @returns {object} A hash with keys being user ids and values being the
  672. * library's SpeakerStats model used for calculating time as dominant
  673. * speaker.
  674. */
  675. getSpeakerStats() {
  676. return room.getSpeakerStats();
  677. },
  678. /**
  679. * Returns the connection times stored in the library.
  680. */
  681. getConnectionTimes() {
  682. return this._room.getConnectionTimes();
  683. },
  684. // used by torture currently
  685. isJoined() {
  686. return this._room
  687. && this._room.isJoined();
  688. },
  689. getConnectionState() {
  690. return this._room
  691. && this._room.getConnectionState();
  692. },
  693. /**
  694. * Obtains current P2P ICE connection state.
  695. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  696. * P2P connection
  697. */
  698. getP2PConnectionState() {
  699. return this._room
  700. && this._room.getP2PConnectionState();
  701. },
  702. /**
  703. * Starts P2P (for tests only)
  704. * @private
  705. */
  706. _startP2P() {
  707. try {
  708. this._room && this._room.startP2PSession();
  709. } catch (error) {
  710. logger.error("Start P2P failed", error);
  711. throw error;
  712. }
  713. },
  714. /**
  715. * Stops P2P (for tests only)
  716. * @private
  717. */
  718. _stopP2P() {
  719. try {
  720. this._room && this._room.stopP2PSession();
  721. } catch (error) {
  722. logger.error("Stop P2P failed", error);
  723. throw error;
  724. }
  725. },
  726. /**
  727. * Checks whether or not our connection is currently in interrupted and
  728. * reconnect attempts are in progress.
  729. *
  730. * @returns {boolean} true if the connection is in interrupted state or
  731. * false otherwise.
  732. */
  733. isConnectionInterrupted() {
  734. return this._room.isConnectionInterrupted();
  735. },
  736. /**
  737. * Finds JitsiParticipant for given id.
  738. *
  739. * @param {string} id participant's identifier(MUC nickname).
  740. *
  741. * @returns {JitsiParticipant|null} participant instance for given id or
  742. * null if not found.
  743. */
  744. getParticipantById(id) {
  745. return room ? room.getParticipantById(id) : null;
  746. },
  747. /**
  748. * Get participant connection status for the participant.
  749. *
  750. * @param {string} id participant's identifier(MUC nickname)
  751. *
  752. * @returns {ParticipantConnectionStatus|null} the status of the participant
  753. * or null if no such participant is found or participant is the local user.
  754. */
  755. getParticipantConnectionStatus(id) {
  756. let participant = this.getParticipantById(id);
  757. return participant ? participant.getConnectionStatus() : null;
  758. },
  759. /**
  760. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  761. * the given <tt>id</tt>.
  762. *
  763. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  764. *
  765. * @return {string} the participant's display name or the default string if
  766. * absent.
  767. */
  768. getParticipantDisplayName(id) {
  769. let displayName = getDisplayName(id);
  770. if (displayName) {
  771. return displayName;
  772. } else {
  773. if (APP.conference.isLocalId(id)) {
  774. return APP.translation.generateTranslationHTML(
  775. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  776. } else {
  777. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  778. }
  779. }
  780. },
  781. getMyUserId() {
  782. return this._room
  783. && this._room.myUserId();
  784. },
  785. /**
  786. * Indicates if recording is supported in this conference.
  787. */
  788. isRecordingSupported() {
  789. return this._room && this._room.isRecordingSupported();
  790. },
  791. /**
  792. * Returns the recording state or undefined if the room is not defined.
  793. */
  794. getRecordingState() {
  795. return (this._room) ? this._room.getRecordingState() : undefined;
  796. },
  797. /**
  798. * Will be filled with values only when config.debug is enabled.
  799. * Its used by torture to check audio levels.
  800. */
  801. audioLevelsMap: {},
  802. /**
  803. * Returns the stored audio level (stored only if config.debug is enabled)
  804. * @param id the id for the user audio level to return (the id value is
  805. * returned for the participant using getMyUserId() method)
  806. */
  807. getPeerSSRCAudioLevel(id) {
  808. return this.audioLevelsMap[id];
  809. },
  810. /**
  811. * @return {number} the number of participants in the conference with at
  812. * least one track.
  813. */
  814. getNumberOfParticipantsWithTracks() {
  815. return this._room.getParticipants()
  816. .filter((p) => p.getTracks().length > 0)
  817. .length;
  818. },
  819. /**
  820. * Returns the stats.
  821. */
  822. getStats() {
  823. return room.connectionQuality.getStats();
  824. },
  825. // end used by torture
  826. getLogs() {
  827. return room.getLogs();
  828. },
  829. /**
  830. * Download logs, a function that can be called from console while
  831. * debugging.
  832. * @param filename (optional) specify target filename
  833. */
  834. saveLogs(filename = 'meetlog.json') {
  835. // this can be called from console and will not have reference to this
  836. // that's why we reference the global var
  837. let logs = APP.conference.getLogs();
  838. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  839. let elem = document.createElement('a');
  840. elem.download = filename;
  841. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  842. elem.dataset.downloadurl
  843. = ['text/json', elem.download, elem.href].join(':');
  844. elem.dispatchEvent(new MouseEvent('click', {
  845. view: window,
  846. bubbles: true,
  847. cancelable: false
  848. }));
  849. },
  850. /**
  851. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  852. * desire to keep room private to this instance and (2) the need of other
  853. * modules to send and receive commands to and from participants.
  854. * Eventually, this instance remains in control with respect to the
  855. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  856. * JitsiConference) is to be used in the implementation of the Command(s)
  857. * API of this instance.
  858. */
  859. commands: {
  860. /**
  861. * Known custom conference commands.
  862. */
  863. defaults: commands,
  864. /**
  865. * Receives notifications from other participants about commands aka
  866. * custom events (sent by sendCommand or sendCommandOnce methods).
  867. * @param command {String} the name of the command
  868. * @param handler {Function} handler for the command
  869. */
  870. addCommandListener () {
  871. room.addCommandListener.apply(room, arguments);
  872. },
  873. /**
  874. * Removes command.
  875. * @param name {String} the name of the command.
  876. */
  877. removeCommand () {
  878. room.removeCommand.apply(room, arguments);
  879. },
  880. /**
  881. * Sends command.
  882. * @param name {String} the name of the command.
  883. * @param values {Object} with keys and values that will be sent.
  884. */
  885. sendCommand () {
  886. room.sendCommand.apply(room, arguments);
  887. },
  888. /**
  889. * Sends command one time.
  890. * @param name {String} the name of the command.
  891. * @param values {Object} with keys and values that will be sent.
  892. */
  893. sendCommandOnce () {
  894. room.sendCommandOnce.apply(room, arguments);
  895. }
  896. },
  897. _createRoom (localTracks) {
  898. room = connection.initJitsiConference(APP.conference.roomName,
  899. this._getConferenceOptions());
  900. this._setLocalAudioVideoStreams(localTracks);
  901. this._room = room; // FIXME do not use this
  902. _setupLocalParticipantProperties();
  903. this._setupListeners();
  904. },
  905. /**
  906. * Sets local video and audio streams.
  907. * @param {JitsiLocalTrack[]} tracks=[]
  908. * @returns {Promise[]}
  909. * @private
  910. */
  911. _setLocalAudioVideoStreams(tracks = []) {
  912. return tracks.map(track => {
  913. if (track.isAudioTrack()) {
  914. return this.useAudioStream(track);
  915. } else if (track.isVideoTrack()) {
  916. return this.useVideoStream(track);
  917. } else {
  918. logger.error(
  919. "Ignored not an audio nor a video track: ", track);
  920. return Promise.resolve();
  921. }
  922. });
  923. },
  924. _getConferenceOptions() {
  925. let options = config;
  926. if(config.enableRecording && !config.recordingType) {
  927. options.recordingType = (config.hosts &&
  928. (typeof config.hosts.jirecon != "undefined"))?
  929. "jirecon" : "colibri";
  930. }
  931. return options;
  932. },
  933. /**
  934. * Start using provided video stream.
  935. * Stops previous video stream.
  936. * @param {JitsiLocalTrack} [stream] new stream to use or null
  937. * @returns {Promise}
  938. */
  939. useVideoStream(newStream) {
  940. return APP.store.dispatch(
  941. replaceLocalTrack(localVideo, newStream, room))
  942. .then(() => {
  943. localVideo = newStream;
  944. if (newStream) {
  945. this.videoMuted = newStream.isMuted();
  946. this.isSharingScreen = newStream.videoType === 'desktop';
  947. APP.UI.addLocalStream(newStream);
  948. newStream.videoType === 'camera'
  949. && APP.UI.setCameraButtonEnabled(true);
  950. } else {
  951. this.videoMuted = false;
  952. this.isSharingScreen = false;
  953. }
  954. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  955. APP.UI.updateDesktopSharingButtons();
  956. });
  957. },
  958. /**
  959. * Start using provided audio stream.
  960. * Stops previous audio stream.
  961. * @param {JitsiLocalTrack} [stream] new stream to use or null
  962. * @returns {Promise}
  963. */
  964. useAudioStream(newStream) {
  965. return APP.store.dispatch(
  966. replaceLocalTrack(localAudio, newStream, room))
  967. .then(() => {
  968. localAudio = newStream;
  969. if (newStream) {
  970. this.audioMuted = newStream.isMuted();
  971. APP.UI.addLocalStream(newStream);
  972. } else {
  973. this.audioMuted = false;
  974. }
  975. APP.UI.setMicrophoneButtonEnabled(true);
  976. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  977. });
  978. },
  979. /**
  980. * Triggers a tooltip to display when a feature was attempted to be used
  981. * while in audio only mode.
  982. *
  983. * @param {string} featureName - The name of the feature that attempted to
  984. * toggle.
  985. * @private
  986. * @returns {void}
  987. */
  988. _displayAudioOnlyTooltip(featureName) {
  989. let tooltipElementId = null;
  990. switch (featureName) {
  991. case 'screenShare':
  992. tooltipElementId = '#screenshareWhileAudioOnly';
  993. break;
  994. case 'videoMute':
  995. tooltipElementId = '#unmuteWhileAudioOnly';
  996. break;
  997. }
  998. if (tooltipElementId) {
  999. APP.UI.showToolbar(6000);
  1000. APP.UI.showCustomToolbarPopup(
  1001. tooltipElementId, true, 5000);
  1002. }
  1003. },
  1004. /**
  1005. * Returns whether or not the conference is currently in audio only mode.
  1006. *
  1007. * @returns {boolean}
  1008. */
  1009. isAudioOnly() {
  1010. return Boolean(
  1011. APP.store.getState()['features/base/conference'].audioOnly);
  1012. },
  1013. videoSwitchInProgress: false,
  1014. toggleScreenSharing(shareScreen = !this.isSharingScreen) {
  1015. if (this.videoSwitchInProgress) {
  1016. logger.warn("Switch in progress.");
  1017. return;
  1018. }
  1019. if (!this.isDesktopSharingEnabled) {
  1020. logger.warn("Cannot toggle screen sharing: not supported.");
  1021. return;
  1022. }
  1023. if (this.isAudioOnly()) {
  1024. this._displayAudioOnlyTooltip('screenShare');
  1025. return;
  1026. }
  1027. this.videoSwitchInProgress = true;
  1028. let externalInstallation = false;
  1029. if (shareScreen) {
  1030. this.screenSharingPromise = 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. this.screenSharingPromise = 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. };