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

JitsiMeetJS.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /* global __filename */
  2. import { createGetUserMediaEvent } from './service/statistics/AnalyticsEvents';
  3. import AuthUtil from './modules/util/AuthUtil';
  4. import * as ConnectionQualityEvents
  5. from './service/connectivity/ConnectionQualityEvents';
  6. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  7. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  8. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  9. import JitsiConnection from './JitsiConnection';
  10. import * as JitsiConnectionErrors from './JitsiConnectionErrors';
  11. import * as JitsiConnectionEvents from './JitsiConnectionEvents';
  12. import JitsiMediaDevices from './JitsiMediaDevices';
  13. import * as JitsiMediaDevicesEvents from './JitsiMediaDevicesEvents';
  14. import JitsiTrackError from './JitsiTrackError';
  15. import * as JitsiTrackErrors from './JitsiTrackErrors';
  16. import * as JitsiTrackEvents from './JitsiTrackEvents';
  17. import * as JitsiTranscriptionStatus from './JitsiTranscriptionStatus';
  18. import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
  19. import Logger from 'jitsi-meet-logger';
  20. import * as MediaType from './service/RTC/MediaType';
  21. import Resolutions from './service/RTC/Resolutions';
  22. import { ParticipantConnectionStatus }
  23. from './modules/connectivity/ParticipantConnectionStatus';
  24. import RTC from './modules/RTC/RTC';
  25. import browser from './modules/browser';
  26. import RTCUIHelper from './modules/RTC/RTCUIHelper';
  27. import ScriptUtil from './modules/util/ScriptUtil';
  28. import recordingConstants from './modules/recording/recordingConstants';
  29. import Statistics from './modules/statistics/statistics';
  30. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  31. const logger = Logger.getLogger(__filename);
  32. /**
  33. * The amount of time to wait until firing
  34. * {@link JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN} event.
  35. */
  36. const USER_MEDIA_PERMISSION_PROMPT_TIMEOUT = 1000;
  37. /**
  38. * Gets the next lowest desirable resolution to try for a camera. If the given
  39. * resolution is already the lowest acceptable resolution, returns {@code null}.
  40. *
  41. * @param resolution the current resolution
  42. * @return the next lowest resolution from the given one, or {@code null} if it
  43. * is already the lowest acceptable resolution.
  44. */
  45. function getLowerResolution(resolution) {
  46. if (!Resolutions[resolution]) {
  47. return null;
  48. }
  49. const order = Resolutions[resolution].order;
  50. let res = null;
  51. let resName = null;
  52. Object.keys(Resolutions).forEach(r => {
  53. const value = Resolutions[r];
  54. if (!res || (res.order < value.order && value.order < order)) {
  55. resName = r;
  56. res = value;
  57. }
  58. });
  59. if (resName === resolution) {
  60. resName = null;
  61. }
  62. return resName;
  63. }
  64. /**
  65. * Extracts from an 'options' objects with a specific format (TODO what IS the
  66. * format?) the attributes which are to be logged in analytics events.
  67. *
  68. * @param options gum options (???)
  69. * @returns {*} the attributes to attach to analytics events.
  70. */
  71. function getAnalyticsAttributesFromOptions(options) {
  72. const attributes = {
  73. 'audio_requested':
  74. options.devices.includes('audio'),
  75. 'video_requested':
  76. options.devices.includes('video'),
  77. 'screen_sharing_requested':
  78. options.devices.includes('desktop')
  79. };
  80. if (attributes.video_requested) {
  81. attributes.resolution = options.resolution;
  82. }
  83. return attributes;
  84. }
  85. /**
  86. * Tries to deal with the following problem: {@code JitsiMeetJS} is not only
  87. * this module, it's also a global (i.e. attached to {@code window}) namespace
  88. * for all globals of the projects in the Jitsi Meet family. If lib-jitsi-meet
  89. * is loaded through an HTML {@code script} tag, {@code JitsiMeetJS} will
  90. * automatically be attached to {@code window} by webpack. Unfortunately,
  91. * webpack's source code does not check whether the global variable has already
  92. * been assigned and overwrites it. Which is OK for the module
  93. * {@code JitsiMeetJS} but is not OK for the namespace {@code JitsiMeetJS}
  94. * because it may already contain the values of other projects in the Jitsi Meet
  95. * family. The solution offered here works around webpack by merging all
  96. * existing values of the namespace {@code JitsiMeetJS} into the module
  97. * {@code JitsiMeetJS}.
  98. *
  99. * @param {Object} module - The module {@code JitsiMeetJS} (which will be
  100. * exported and may be attached to {@code window} by webpack later on).
  101. * @private
  102. * @returns {Object} - A {@code JitsiMeetJS} module which contains all existing
  103. * value of the namespace {@code JitsiMeetJS} (if any).
  104. */
  105. function _mergeNamespaceAndModule(module) {
  106. return (
  107. typeof window.JitsiMeetJS === 'object'
  108. ? Object.assign({}, window.JitsiMeetJS, module)
  109. : module);
  110. }
  111. /**
  112. * The public API of the Jitsi Meet library (a.k.a. {@code JitsiMeetJS}).
  113. */
  114. export default _mergeNamespaceAndModule({
  115. version: '{#COMMIT_HASH#}',
  116. JitsiConnection,
  117. constants: {
  118. participantConnectionStatus: ParticipantConnectionStatus,
  119. recording: recordingConstants,
  120. sipVideoGW: VideoSIPGWConstants,
  121. transcriptionStatus: JitsiTranscriptionStatus
  122. },
  123. events: {
  124. conference: JitsiConferenceEvents,
  125. connection: JitsiConnectionEvents,
  126. track: JitsiTrackEvents,
  127. mediaDevices: JitsiMediaDevicesEvents,
  128. connectionQuality: ConnectionQualityEvents
  129. },
  130. errors: {
  131. conference: JitsiConferenceErrors,
  132. connection: JitsiConnectionErrors,
  133. track: JitsiTrackErrors
  134. },
  135. errorTypes: {
  136. JitsiTrackError
  137. },
  138. logLevels: Logger.levels,
  139. mediaDevices: JitsiMediaDevices,
  140. analytics: Statistics.analytics,
  141. init(options) {
  142. Statistics.init(options);
  143. // Initialize global window.connectionTimes
  144. // FIXME do not use 'window'
  145. if (!window.connectionTimes) {
  146. window.connectionTimes = {};
  147. }
  148. if (options.enableAnalyticsLogging !== true) {
  149. logger.warn('Analytics disabled, disposing.');
  150. this.analytics.dispose();
  151. }
  152. if (options.enableWindowOnErrorHandler) {
  153. GlobalOnErrorHandler.addHandler(
  154. this.getGlobalOnErrorHandler.bind(this));
  155. }
  156. // Log deployment-specific information, if available. Defined outside
  157. // the application by individual deployments
  158. const aprops = options.deploymentInfo;
  159. if (aprops && Object.keys(aprops).length > 0) {
  160. const logObject = {};
  161. for (const attr in aprops) {
  162. if (aprops.hasOwnProperty(attr)) {
  163. logObject[attr] = aprops[attr];
  164. }
  165. }
  166. logObject.id = 'deployment_info';
  167. Statistics.sendLog(JSON.stringify(logObject));
  168. }
  169. if (this.version) {
  170. const logObject = {
  171. id: 'component_version',
  172. component: 'lib-jitsi-meet',
  173. version: this.version
  174. };
  175. Statistics.sendLog(JSON.stringify(logObject));
  176. }
  177. return RTC.init(options || {});
  178. },
  179. /**
  180. * Returns whether the desktop sharing is enabled or not.
  181. *
  182. * @returns {boolean}
  183. */
  184. isDesktopSharingEnabled() {
  185. return RTC.isDesktopSharingEnabled();
  186. },
  187. setLogLevel(level) {
  188. Logger.setLogLevel(level);
  189. },
  190. /**
  191. * Sets the log level to the <tt>Logger</tt> instance with given id.
  192. *
  193. * @param {Logger.levels} level the logging level to be set
  194. * @param {string} id the logger id to which new logging level will be set.
  195. * Usually it's the name of the JavaScript source file including the path
  196. * ex. "modules/xmpp/ChatRoom.js"
  197. */
  198. setLogLevelById(level, id) {
  199. Logger.setLogLevelById(level, id);
  200. },
  201. /**
  202. * Registers new global logger transport to the library logging framework.
  203. *
  204. * @param globalTransport
  205. * @see Logger.addGlobalTransport
  206. */
  207. addGlobalLogTransport(globalTransport) {
  208. Logger.addGlobalTransport(globalTransport);
  209. },
  210. /**
  211. * Removes global logging transport from the library logging framework.
  212. *
  213. * @param globalTransport
  214. * @see Logger.removeGlobalTransport
  215. */
  216. removeGlobalLogTransport(globalTransport) {
  217. Logger.removeGlobalTransport(globalTransport);
  218. },
  219. /**
  220. * Creates the media tracks and returns them trough the callback.
  221. *
  222. * @param options Object with properties / settings specifying the tracks
  223. * which should be created. should be created or some additional
  224. * configurations about resolution for example.
  225. * @param {Array} options.devices the devices that will be requested
  226. * @param {string} options.resolution resolution constraints
  227. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with
  228. * the following structure {stream: the Media Stream, type: "audio" or
  229. * "video", videoType: "camera" or "desktop"} will be returned trough the
  230. * Promise, otherwise JitsiTrack objects will be returned.
  231. * @param {string} options.cameraDeviceId
  232. * @param {string} options.micDeviceId
  233. * @param {object} options.desktopSharingExtensionExternalInstallation -
  234. * enables external installation process for desktop sharing extension if
  235. * the inline installation is not posible. The following properties should
  236. * be provided:
  237. * @param {intiger} interval - the interval (in ms) for
  238. * checking whether the desktop sharing extension is installed or not
  239. * @param {Function} checkAgain - returns boolean. While checkAgain()==true
  240. * createLocalTracks will wait and check on every "interval" ms for the
  241. * extension. If the desktop extension is not install and checkAgain()==true
  242. * createLocalTracks will finish with rejected Promise.
  243. * @param {Function} listener - The listener will be called to notify the
  244. * user of lib-jitsi-meet that createLocalTracks is starting external
  245. * extension installation process.
  246. * NOTE: If the inline installation process is not possible and external
  247. * installation is enabled the listener property will be called to notify
  248. * the start of external installation process. After that createLocalTracks
  249. * will start to check for the extension on every interval ms until the
  250. * plugin is installed or until checkAgain return false. If the extension
  251. * is found createLocalTracks will try to get the desktop sharing track and
  252. * will finish the execution. If checkAgain returns false, createLocalTracks
  253. * will finish the execution with rejected Promise.
  254. *
  255. * @param {boolean} (firePermissionPromptIsShownEvent) - if event
  256. * JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN should be fired
  257. * @param originalOptions - internal use only, to be able to store the
  258. * originally requested options.
  259. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise
  260. * that returns an array of created JitsiTracks if resolved, or a
  261. * JitsiConferenceError if rejected.
  262. */
  263. createLocalTracks(
  264. options = {}, firePermissionPromptIsShownEvent, originalOptions) {
  265. let promiseFulfilled = false;
  266. if (firePermissionPromptIsShownEvent === true) {
  267. window.setTimeout(() => {
  268. if (!promiseFulfilled) {
  269. JitsiMediaDevices.emitEvent(
  270. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  271. browser.getName());
  272. }
  273. }, USER_MEDIA_PERMISSION_PROMPT_TIMEOUT);
  274. }
  275. if (!window.connectionTimes) {
  276. window.connectionTimes = {};
  277. }
  278. window.connectionTimes['obtainPermissions.start']
  279. = window.performance.now();
  280. return RTC.obtainAudioAndVideoPermissions(options)
  281. .then(tracks => {
  282. promiseFulfilled = true;
  283. window.connectionTimes['obtainPermissions.end']
  284. = window.performance.now();
  285. Statistics.sendAnalytics(
  286. createGetUserMediaEvent(
  287. 'success',
  288. getAnalyticsAttributesFromOptions(options)));
  289. if (!RTC.options.disableAudioLevels) {
  290. for (let i = 0; i < tracks.length; i++) {
  291. const track = tracks[i];
  292. const mStream = track.getOriginalStream();
  293. if (track.getType() === MediaType.AUDIO) {
  294. Statistics.startLocalStats(mStream,
  295. track.setAudioLevel.bind(track));
  296. track.addEventListener(
  297. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  298. () => {
  299. Statistics.stopLocalStats(mStream);
  300. });
  301. }
  302. }
  303. }
  304. // set real device ids
  305. const currentlyAvailableMediaDevices
  306. = RTC.getCurrentlyAvailableMediaDevices();
  307. if (currentlyAvailableMediaDevices) {
  308. for (let i = 0; i < tracks.length; i++) {
  309. const track = tracks[i];
  310. track._setRealDeviceIdFromDeviceList(
  311. currentlyAvailableMediaDevices);
  312. }
  313. }
  314. return tracks;
  315. })
  316. .catch(error => {
  317. promiseFulfilled = true;
  318. if (error.name === JitsiTrackErrors.UNSUPPORTED_RESOLUTION
  319. && !browser.usesNewGumFlow()) {
  320. const oldResolution = options.resolution || '720';
  321. const newResolution = getLowerResolution(oldResolution);
  322. if (newResolution !== null) {
  323. options.resolution = newResolution;
  324. logger.debug(
  325. 'Retry createLocalTracks with resolution',
  326. newResolution);
  327. Statistics.sendAnalytics(createGetUserMediaEvent(
  328. 'warning',
  329. {
  330. 'old_resolution': oldResolution,
  331. 'new_resolution': newResolution,
  332. reason: 'unsupported resolution'
  333. }));
  334. return this.createLocalTracks(
  335. options,
  336. undefined,
  337. originalOptions || Object.assign({}, options));
  338. }
  339. // We tried everything. If there is a mandatory device id,
  340. // remove it and let gum find a device to use.
  341. if (originalOptions
  342. && error.gum.constraints
  343. && error.gum.constraints.video
  344. && error.gum.constraints.video.mandatory
  345. && error.gum.constraints.video.mandatory.sourceId) {
  346. originalOptions.cameraDeviceId = undefined;
  347. return this.createLocalTracks(originalOptions);
  348. }
  349. }
  350. if (error.name
  351. === JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  352. // User cancelled action is not really an error, so only
  353. // log it as an event to avoid having conference classified
  354. // as partially failed
  355. const logObject = {
  356. id: 'chrome_extension_user_canceled',
  357. message: error.message
  358. };
  359. Statistics.sendLog(JSON.stringify(logObject));
  360. Statistics.sendAnalytics(
  361. createGetUserMediaEvent(
  362. 'warning',
  363. {
  364. reason: 'extension install user canceled'
  365. }));
  366. } else if (error.name === JitsiTrackErrors.NOT_FOUND) {
  367. // logs not found devices with just application log to cs
  368. const logObject = {
  369. id: 'usermedia_missing_device',
  370. status: error.gum.devices
  371. };
  372. Statistics.sendLog(JSON.stringify(logObject));
  373. const attributes
  374. = getAnalyticsAttributesFromOptions(options);
  375. attributes.reason = 'device not found';
  376. attributes.devices = error.gum.devices.join('.');
  377. Statistics.sendAnalytics(
  378. createGetUserMediaEvent('error', attributes));
  379. } else {
  380. // Report gUM failed to the stats
  381. Statistics.sendGetUserMediaFailed(error);
  382. const attributes
  383. = getAnalyticsAttributesFromOptions(options);
  384. attributes.reason = error.name;
  385. Statistics.sendAnalytics(
  386. createGetUserMediaEvent('error', attributes));
  387. }
  388. window.connectionTimes['obtainPermissions.end']
  389. = window.performance.now();
  390. return Promise.reject(error);
  391. });
  392. },
  393. /**
  394. * Checks if its possible to enumerate available cameras/microphones.
  395. *
  396. * @returns {Promise<boolean>} a Promise which will be resolved only once
  397. * the WebRTC stack is ready, either with true if the device listing is
  398. * available available or with false otherwise.
  399. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceListAvailable instead
  400. */
  401. isDeviceListAvailable() {
  402. logger.warn('This method is deprecated, use '
  403. + 'JitsiMeetJS.mediaDevices.isDeviceListAvailable instead');
  404. return this.mediaDevices.isDeviceListAvailable();
  405. },
  406. /**
  407. * Returns true if changing the input (camera / microphone) or output
  408. * (audio) device is supported and false if not.
  409. *
  410. * @param {string} [deviceType] - type of device to change. Default is
  411. * {@code undefined} or 'input', 'output' - for audio output device change.
  412. * @returns {boolean} {@code true} if available; {@code false}, otherwise.
  413. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead
  414. */
  415. isDeviceChangeAvailable(deviceType) {
  416. logger.warn('This method is deprecated, use '
  417. + 'JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead');
  418. return this.mediaDevices.isDeviceChangeAvailable(deviceType);
  419. },
  420. /**
  421. * Checks if the current environment supports having multiple audio
  422. * input devices in use simultaneously.
  423. *
  424. * @returns {boolean} True if multiple audio input devices can be used.
  425. */
  426. isMultipleAudioInputSupported() {
  427. return this.mediaDevices.isMultipleAudioInputSupported();
  428. },
  429. /**
  430. * Checks if local tracks can collect stats and collection is enabled.
  431. *
  432. * @param {boolean} True if stats are being collected for local tracks.
  433. */
  434. isCollectingLocalStats() {
  435. return Statistics.audioLevelsEnabled
  436. && LocalStatsCollector.isLocalStatsSupported();
  437. },
  438. /**
  439. * Executes callback with list of media devices connected.
  440. *
  441. * @param {function} callback
  442. * @deprecated use JitsiMeetJS.mediaDevices.enumerateDevices instead
  443. */
  444. enumerateDevices(callback) {
  445. logger.warn('This method is deprecated, use '
  446. + 'JitsiMeetJS.mediaDevices.enumerateDevices instead');
  447. this.mediaDevices.enumerateDevices(callback);
  448. },
  449. /* eslint-disable max-params */
  450. /**
  451. * @returns function that can be used to be attached to window.onerror and
  452. * if options.enableWindowOnErrorHandler is enabled returns
  453. * the function used by the lib.
  454. * (function(message, source, lineno, colno, error)).
  455. */
  456. getGlobalOnErrorHandler(message, source, lineno, colno, error) {
  457. logger.error(
  458. `UnhandledError: ${message}`,
  459. `Script: ${source}`,
  460. `Line: ${lineno}`,
  461. `Column: ${colno}`,
  462. 'StackTrace: ', error);
  463. Statistics.reportGlobalError(error);
  464. },
  465. /* eslint-enable max-params */
  466. /**
  467. * Represents a hub/namespace for utility functionality which may be of
  468. * interest to lib-jitsi-meet clients.
  469. */
  470. util: {
  471. AuthUtil,
  472. RTCUIHelper,
  473. ScriptUtil,
  474. browser
  475. }
  476. });