2
0
mirror of https://github.com/frappe/books.git synced 2024-11-10 07:40:55 +00:00
books/src/telemetry/telemetry.ts

67 lines
1.8 KiB
TypeScript
Raw Normal View History

import config, { ConfigKeys } from '@/config';
2022-03-09 11:20:48 +00:00
import frappe from 'frappe';
import { cloneDeep } from 'lodash';
import { getCounts, getDeviceId, getInstanceId, getLocale } from './helpers';
import { Noun, Telemetry, Verb } from './types';
class TelemetryManager {
#started = false;
#telemetryObject: Partial<Telemetry> = {};
start() {
this.#telemetryObject.locale ||= getLocale();
this.#telemetryObject.deviceId ||= getDeviceId();
this.#telemetryObject.instanceId ||= getInstanceId();
this.#telemetryObject.openTime ||= new Date().valueOf();
this.#telemetryObject.timeline ??= [];
2022-03-09 11:20:48 +00:00
this.#telemetryObject.errors ??= {};
this.#started = true;
}
getCanLog() {
return !!config.get(ConfigKeys.AnonymizedTelemetry);
}
log(verb: Verb, noun: Noun, more?: Record<string, unknown>) {
if (!this.#started) {
this.start();
}
if (!this.getCanLog) {
return;
}
const time = new Date().valueOf();
if (this.#telemetryObject.timeline === undefined) {
this.#telemetryObject.timeline = [];
}
this.#telemetryObject.timeline.push({ time, verb, noun, more });
}
2022-03-09 11:20:48 +00:00
error(name: string) {
if (this.#telemetryObject.errors === undefined) {
this.#telemetryObject.errors = {};
}
this.#telemetryObject.errors[name] ??= 0;
this.#telemetryObject.errors[name] += 1;
}
async stop() {
// Will set ids if not set.
this.start();
2022-03-09 11:20:48 +00:00
//@ts-ignore
this.#telemetryObject.version = frappe.store.appVersion ?? '';
this.#telemetryObject.counts = this.getCanLog() ? await getCounts() : {};
this.#telemetryObject.closeTime = new Date().valueOf();
}
get telemetryObject(): Readonly<Partial<Telemetry>> {
return cloneDeep(this.#telemetryObject);
}
}
export default new TelemetryManager();