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

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