Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JitsiMeetJS.js 17KB

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