Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiMeetJS.js 18KB

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