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 16KB

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