Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

AnalyticsAdapter.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import { getLogger } from '@jitsi/logger';
  2. import {
  3. TYPE_OPERATIONAL,
  4. TYPE_PAGE,
  5. TYPE_TRACK,
  6. TYPE_UI
  7. } from '../../service/statistics/AnalyticsEvents';
  8. import browser from '../browser';
  9. const MAX_CACHE_SIZE = 100;
  10. // eslist-disable-line no-undef
  11. const logger = getLogger(__filename);
  12. /**
  13. * This class provides an API to lib-jitsi-meet and its users for sending
  14. * analytics events. It serves as a bridge to different backend implementations
  15. * ("analytics handlers") and a cache for events attempted to be sent before
  16. * the analytics handlers were enabled.
  17. *
  18. * The API is designed to be an easy replacement for the previous version of
  19. * this adapter, and is meant to be extended with more convenience methods.
  20. *
  21. *
  22. * The API calls are translated to objects with the following structure, which
  23. * are then passed to the sendEvent(event) function of the underlying handlers:
  24. *
  25. * {
  26. * type,
  27. *
  28. * action,
  29. * actionSubject,
  30. * actionSubjectId,
  31. * attributes,
  32. * categories,
  33. * containerId,
  34. * containerType,
  35. * name,
  36. * objectId,
  37. * objectType,
  38. * source,
  39. * tags
  40. * }
  41. *
  42. * The 'type' is one of 'operational', 'page', 'track' or 'ui', and some of the
  43. * other properties are considered required according to the type.
  44. *
  45. * For events with type 'page', the required properties are: name.
  46. *
  47. * For events with type 'operational' and 'ui', the required properties are:
  48. * action, actionSubject, source
  49. *
  50. * For events with type 'page', the required properties are:
  51. * action, actionSubject, source, containerType, containerId, objectType,
  52. * objectId
  53. */
  54. class AnalyticsAdapter {
  55. /**
  56. * Creates new AnalyticsAdapter instance.
  57. */
  58. constructor() {
  59. this.reset();
  60. }
  61. /**
  62. * Reset the state to the initial one.
  63. *
  64. * @returns {void}
  65. */
  66. reset() {
  67. /**
  68. * Whether this AnalyticsAdapter has been disposed of or not. Once this
  69. * is set to true, the AnalyticsAdapter is disabled and does not accept
  70. * any more events, and it can not be re-enabled.
  71. * @type {boolean}
  72. */
  73. this.disposed = false;
  74. /**
  75. * The set of handlers to which events will be sent.
  76. * @type {Set<any>}
  77. */
  78. this.analyticsHandlers = new Set();
  79. /**
  80. * The cache of events which are not sent yet. The cache is enabled
  81. * while this field is truthy, and disabled otherwise.
  82. * @type {Array}
  83. */
  84. this.cache = [];
  85. /**
  86. * Map of properties that will be added to every event. Note that the
  87. * keys will be prefixed with "permanent.".
  88. */
  89. this.permanentProperties = {};
  90. /**
  91. * The name of the conference that this AnalyticsAdapter is associated
  92. * with.
  93. * @type {null}
  94. */
  95. this.conferenceName = '';
  96. this.addPermanentProperties({
  97. 'user_agent': navigator.userAgent,
  98. 'browser_name': browser.getName()
  99. });
  100. }
  101. /**
  102. * Dispose analytics. Clears all handlers.
  103. */
  104. dispose() {
  105. logger.warn('Disposing of analytics adapter.');
  106. if (this.analyticsHandlers && this.analyticsHandlers.size > 0) {
  107. this.analyticsHandlers.forEach(handler => {
  108. if (typeof handler.dispose === 'function') {
  109. handler.dispose();
  110. }
  111. });
  112. }
  113. this.setAnalyticsHandlers([]);
  114. this.disposed = true;
  115. }
  116. /**
  117. * Sets the handlers that are going to be used to send analytics. Sends any
  118. * cached events.
  119. * @param {Array} handlers the handlers
  120. */
  121. setAnalyticsHandlers(handlers) {
  122. if (this.disposed) {
  123. return;
  124. }
  125. this.analyticsHandlers = new Set(handlers);
  126. this._setUserProperties();
  127. // Note that we disable the cache even if the set of handlers is empty.
  128. const cache = this.cache;
  129. this.cache = null;
  130. if (cache) {
  131. cache.forEach(event => this._sendEvent(event));
  132. }
  133. }
  134. /**
  135. * Set the user properties to the analytics handlers.
  136. *
  137. * @returns {void}
  138. */
  139. _setUserProperties() {
  140. this.analyticsHandlers.forEach(handler => {
  141. try {
  142. handler.setUserProperties(this.permanentProperties);
  143. } catch (error) {
  144. logger.warn('Error in setUserProperties method of one of the '
  145. + `analytics handlers: ${error}`);
  146. }
  147. });
  148. }
  149. /**
  150. * Adds a set of permanent properties to this this AnalyticsAdapter.
  151. * Permanent properties will be added as "attributes" to events sent to
  152. * the underlying "analytics handlers", and their keys will be prefixed
  153. * by "permanent_", i.e. adding a permanent property {key: "value"} will
  154. * result in {"permanent_key": "value"} object to be added to the
  155. * "attributes" field of events.
  156. *
  157. * @param {Object} properties the properties to add
  158. */
  159. addPermanentProperties(properties) {
  160. this.permanentProperties = {
  161. ...this.permanentProperties,
  162. ...properties
  163. };
  164. this._setUserProperties();
  165. }
  166. /**
  167. * Sets the name of the conference that this AnalyticsAdapter is associated
  168. * with.
  169. * @param name the name to set.
  170. */
  171. setConferenceName(name) {
  172. this.conferenceName = name;
  173. this.addPermanentProperties({ 'conference_name': name });
  174. }
  175. /**
  176. * Sends an event with a given name and given properties. The first
  177. * parameter is either a string or an object. If it is a string, it is used
  178. * as the event name and the second parameter is used at the attributes to
  179. * attach to the event. If it is an object, it represents the whole event,
  180. * including any desired attributes, and the second parameter is ignored.
  181. *
  182. * @param {String|Object} eventName either a string to be used as the name
  183. * of the event, or an event object. If an event object is passed, the
  184. * properties parameters is ignored.
  185. * @param {Object} properties the properties/attributes to attach to the
  186. * event, if eventName is a string.
  187. */
  188. sendEvent(eventName, properties = {}) {
  189. if (this.disposed) {
  190. return;
  191. }
  192. let event = null;
  193. if (typeof eventName === 'string') {
  194. event = {
  195. type: TYPE_OPERATIONAL,
  196. action: eventName,
  197. actionSubject: eventName,
  198. source: eventName,
  199. attributes: properties
  200. };
  201. } else if (typeof eventName === 'object') {
  202. event = eventName;
  203. }
  204. if (!this._verifyRequiredFields(event)) {
  205. logger.error(
  206. `Dropping a mis-formatted event: ${JSON.stringify(event)}`);
  207. return;
  208. }
  209. this._sendEvent(event);
  210. }
  211. /**
  212. * Checks whether an event has all of the required fields set, and tries
  213. * to fill in some of the missing fields with reasonable default values.
  214. * Returns true if after this operation the event has all of the required
  215. * fields set, and false otherwise (if some of the required fields were not
  216. * set and the attempt to fill them in with a default failed).
  217. *
  218. * @param event the event object.
  219. * @return {boolean} true if the event (after the call to this function)
  220. * contains all of the required fields, and false otherwise.
  221. * @private
  222. */
  223. _verifyRequiredFields(event) {
  224. if (!event) {
  225. return false;
  226. }
  227. if (!event.type) {
  228. event.type = TYPE_OPERATIONAL;
  229. }
  230. const type = event.type;
  231. if (type !== TYPE_OPERATIONAL && type !== TYPE_PAGE
  232. && type !== TYPE_UI && type !== TYPE_TRACK) {
  233. logger.error(`Unknown event type: ${type}`);
  234. return false;
  235. }
  236. if (type === TYPE_PAGE) {
  237. return Boolean(event.name);
  238. }
  239. // Try to set some reasonable default values in case some of the
  240. // parameters required by the handler API are missing.
  241. event.action = event.action || event.name || event.actionSubject;
  242. event.actionSubject = event.actionSubject || event.name || event.action;
  243. event.source = event.source || event.name || event.action
  244. || event.actionSubject;
  245. if (!event.action || !event.actionSubject || !event.source) {
  246. logger.error(
  247. 'Required field missing (action, actionSubject or source)');
  248. return false;
  249. }
  250. // Track events have additional required fields.
  251. if (type === TYPE_TRACK) {
  252. event.objectType = event.objectType || 'generic-object-type';
  253. event.containerType = event.containerType || 'conference';
  254. if (event.containerType === 'conference' && !event.containerId) {
  255. event.containerId = this.conferenceName;
  256. }
  257. if (!event.objectType || !event.objectId
  258. || !event.containerType || !event.containerId) {
  259. logger.error(
  260. 'Required field missing (containerId, containerType, '
  261. + 'objectId or objectType)');
  262. return false;
  263. }
  264. }
  265. return true;
  266. }
  267. /**
  268. * Saves an event to the cache, if the cache is enabled.
  269. * @param event the event to save.
  270. * @returns {boolean} true if the event was saved, and false otherwise (i.e.
  271. * if the cache was disabled).
  272. * @private
  273. */
  274. _maybeCacheEvent(event) {
  275. if (this.cache) {
  276. this.cache.push(event);
  277. // We limit the size of the cache, in case the user fails to ever
  278. // set the analytics handlers.
  279. if (this.cache.length > MAX_CACHE_SIZE) {
  280. this.cache.splice(0, 1);
  281. }
  282. return true;
  283. }
  284. return false;
  285. }
  286. /**
  287. *
  288. * @param event
  289. * @private
  290. */
  291. _sendEvent(event) {
  292. if (this._maybeCacheEvent(event)) {
  293. // The event was consumed by the cache.
  294. } else {
  295. this.analyticsHandlers.forEach(handler => {
  296. try {
  297. handler.sendEvent(event);
  298. } catch (e) {
  299. logger.warn(`Error sending analytics event: ${e}`);
  300. }
  301. });
  302. }
  303. }
  304. }
  305. export default new AnalyticsAdapter();