Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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