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

JitsiMeetJS.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. var USER_MEDIA_PERMISSION_PROMPT_TIMEOUT = 500;
  29. function getLowerResolution(resolution) {
  30. if(!Resolutions[resolution])
  31. return null;
  32. var order = Resolutions[resolution].order;
  33. var res = null;
  34. var resName = null;
  35. for(const i in Resolutions) {
  36. var tmp = Resolutions[i];
  37. if (!res || (res.order < tmp.order && tmp.order < order)) {
  38. resName = i;
  39. res = tmp;
  40. }
  41. }
  42. return resName;
  43. }
  44. /**
  45. * Checks the available devices in options and concatenate the data to the
  46. * name, which will be used as analytics event name. Adds resolution for the
  47. * devices.
  48. * @param name name of event
  49. * @param options gum options
  50. * @returns {*}
  51. */
  52. function addDeviceTypeToAnalyticsEvent(name, options) {
  53. if (options.devices.indexOf("audio") !== -1) {
  54. name += ".audio";
  55. }
  56. if (options.devices.indexOf("desktop") !== -1) {
  57. name += ".desktop";
  58. }
  59. if (options.devices.indexOf("video") !== -1) {
  60. // we have video add resolution
  61. name += ".video." + options.resolution;
  62. }
  63. return name;
  64. }
  65. /**
  66. * Namespace for the interface of Jitsi Meet Library.
  67. */
  68. var LibJitsiMeet = {
  69. version: '{#COMMIT_HASH#}',
  70. JitsiConnection,
  71. events: {
  72. conference: JitsiConferenceEvents,
  73. connection: JitsiConnectionEvents,
  74. track: JitsiTrackEvents,
  75. mediaDevices: JitsiMediaDevicesEvents,
  76. connectionQuality: ConnectionQualityEvents
  77. },
  78. errors: {
  79. conference: JitsiConferenceErrors,
  80. connection: JitsiConnectionErrors,
  81. recorder: JitsiRecorderErrors,
  82. track: JitsiTrackErrors
  83. },
  84. errorTypes: {
  85. JitsiTrackError
  86. },
  87. logLevels: Logger.levels,
  88. mediaDevices: JitsiMediaDevices,
  89. analytics: null,
  90. init (options) {
  91. let logObject, attr;
  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. logObject = {};
  105. for (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. 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. var 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. window.connectionTimes["obtainPermissions.start"] =
  212. window.performance.now();
  213. return RTC.obtainAudioAndVideoPermissions(options || {})
  214. .then(function(tracks) {
  215. promiseFulfilled = true;
  216. window.connectionTimes["obtainPermissions.end"] =
  217. window.performance.now();
  218. Statistics.analytics.sendEvent(addDeviceTypeToAnalyticsEvent(
  219. "getUserMedia.success", options), {value: options});
  220. if(!RTC.options.disableAudioLevels)
  221. for(let i = 0; i < tracks.length; i++) {
  222. const track = tracks[i];
  223. var mStream = track.getOriginalStream();
  224. if(track.getType() === MediaType.AUDIO){
  225. Statistics.startLocalStats(mStream,
  226. track.setAudioLevel.bind(track));
  227. track.addEventListener(
  228. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  229. function(){
  230. Statistics.stopLocalStats(mStream);
  231. });
  232. }
  233. }
  234. // set real device ids
  235. var currentlyAvailableMediaDevices
  236. = RTC.getCurrentlyAvailableMediaDevices();
  237. if (currentlyAvailableMediaDevices) {
  238. for(let i = 0; i < tracks.length; i++) {
  239. const track = tracks[i];
  240. track._setRealDeviceIdFromDeviceList(
  241. currentlyAvailableMediaDevices);
  242. }
  243. }
  244. return tracks;
  245. }).catch(function (error) {
  246. promiseFulfilled = true;
  247. if(error.name === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  248. var oldResolution = options.resolution || '360',
  249. newResolution = getLowerResolution(oldResolution);
  250. if (newResolution !== null) {
  251. options.resolution = newResolution;
  252. logger.debug("Retry createLocalTracks with resolution",
  253. newResolution);
  254. Statistics.analytics.sendEvent(
  255. "getUserMedia.fail.resolution." + oldResolution);
  256. return LibJitsiMeet.createLocalTracks(options);
  257. }
  258. }
  259. if (JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED ===
  260. error.name) {
  261. // User cancelled action is not really an error, so only
  262. // log it as an event to avoid having conference classified
  263. // as partially failed
  264. const logObject = {
  265. id: "chrome_extension_user_canceled",
  266. message: error.message
  267. };
  268. Statistics.sendLog(JSON.stringify(logObject));
  269. Statistics.analytics.sendEvent(
  270. "getUserMedia.userCancel.extensionInstall");
  271. } else if (JitsiTrackErrors.NOT_FOUND === error.name) {
  272. // logs not found devices with just application log to cs
  273. const logObject = {
  274. id: "usermedia_missing_device",
  275. status: error.gum.devices
  276. };
  277. Statistics.sendLog(JSON.stringify(logObject));
  278. Statistics.analytics.sendEvent(
  279. "getUserMedia.deviceNotFound."
  280. + error.gum.devices.join('.'));
  281. } else {
  282. // Report gUM failed to the stats
  283. Statistics.sendGetUserMediaFailed(error);
  284. Statistics.analytics.sendEvent(
  285. addDeviceTypeToAnalyticsEvent(
  286. "getUserMedia.failed", options) + '.' + error.name,
  287. {value: options});
  288. }
  289. window.connectionTimes["obtainPermissions.end"] =
  290. window.performance.now();
  291. return Promise.reject(error);
  292. }.bind(this));
  293. },
  294. /**
  295. * Checks if its possible to enumerate available cameras/micropones.
  296. * @returns {Promise<boolean>} a Promise which will be resolved only once
  297. * the WebRTC stack is ready, either with true if the device listing is
  298. * available available or with false otherwise.
  299. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceListAvailable instead
  300. */
  301. isDeviceListAvailable () {
  302. logger.warn('This method is deprecated, use ' +
  303. 'JitsiMeetJS.mediaDevices.isDeviceListAvailable instead');
  304. return this.mediaDevices.isDeviceListAvailable();
  305. },
  306. /**
  307. * Returns true if changing the input (camera / microphone) or output
  308. * (audio) device is supported and false if not.
  309. * @params {string} [deviceType] - type of device to change. Default is
  310. * undefined or 'input', 'output' - for audio output device change.
  311. * @returns {boolean} true if available, false otherwise.
  312. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead
  313. */
  314. isDeviceChangeAvailable (deviceType) {
  315. logger.warn('This method is deprecated, use ' +
  316. 'JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead');
  317. return this.mediaDevices.isDeviceChangeAvailable(deviceType);
  318. },
  319. /**
  320. * Executes callback with list of media devices connected.
  321. * @param {function} callback
  322. * @deprecated use JitsiMeetJS.mediaDevices.enumerateDevices instead
  323. */
  324. enumerateDevices (callback) {
  325. logger.warn('This method is deprecated, use ' +
  326. 'JitsiMeetJS.mediaDevices.enumerateDevices instead');
  327. this.mediaDevices.enumerateDevices(callback);
  328. },
  329. /**
  330. * @returns function that can be used to be attached to window.onerror and
  331. * if options.enableWindowOnErrorHandler is enabled returns
  332. * the function used by the lib.
  333. * (function(message, source, lineno, colno, error)).
  334. */
  335. getGlobalOnErrorHandler (message, source, lineno, colno, error) {
  336. logger.error(
  337. 'UnhandledError: ' + message,
  338. 'Script: ' + source,
  339. 'Line: ' + lineno,
  340. 'Column: ' + colno,
  341. 'StackTrace: ', error);
  342. Statistics.reportGlobalError(error);
  343. },
  344. /**
  345. * Returns current machine id saved from the local storage.
  346. * @returns {string} the machine id
  347. */
  348. getMachineId() {
  349. return Settings.getMachineId();
  350. },
  351. /**
  352. * Represents a hub/namespace for utility functionality which may be of
  353. * interest to LibJitsiMeet clients.
  354. */
  355. util: {
  356. ScriptUtil,
  357. RTCUIHelper,
  358. AuthUtil
  359. }
  360. };
  361. module.exports = LibJitsiMeet;