You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiMeetJS.js 17KB

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