您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 66KB

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