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

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