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

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