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

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