Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiMeetJS.js 16KB

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