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

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