-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathanalytics-service.ts
378 lines (308 loc) · 13 KB
/
analytics-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import { ChildProcess } from "child_process";
import * as path from "path";
import { cache } from "../../common/decorators";
import { isInteractive, toBoolean } from '../../common/helpers';
import { DeviceTypes, AnalyticsClients } from "../../common/constants";
import { TrackActionNames } from "../../constants";
export class AnalyticsService implements IAnalyticsService, IDisposable {
private static ANALYTICS_BROKER_START_TIMEOUT = 10 * 1000;
private brokerProcess: ChildProcess;
private shouldDisposeInstance: boolean = true;
private analyticsStatuses: IDictionary<AnalyticsStatus> = {};
constructor(private $logger: ILogger,
private $options: IOptions,
private $staticConfig: Config.IStaticConfig,
private $prompter: IPrompter,
private $userSettingsService: UserSettings.IUserSettingsService,
private $analyticsSettingsService: IAnalyticsSettingsService,
private $childProcess: IChildProcess,
private $projectDataService: IProjectDataService,
private $mobileHelper: Mobile.IMobileHelper,
private $projectHelper: IProjectHelper) {
}
public setShouldDispose(shouldDispose: boolean): void {
this.shouldDisposeInstance = shouldDispose;
}
public async checkConsent(): Promise<void> {
if (await this.$analyticsSettingsService.canDoRequest()) {
const initialTrackFeatureUsageStatus = await this.getStatus(this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME);
let trackFeatureUsage = initialTrackFeatureUsageStatus === AnalyticsStatus.enabled;
if (await this.isNotConfirmed(this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME) && isInteractive()) {
this.$logger.info("Do you want to help us improve "
+ this.$analyticsSettingsService.getClientName()
+ " by automatically sending anonymous usage statistics? We will not use this information to identify or contact you."
+ " You can read our official Privacy Policy at");
const message = this.$analyticsSettingsService.getPrivacyPolicyLink();
trackFeatureUsage = await this.$prompter.confirm(message, () => true);
await this.setStatus(this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME, trackFeatureUsage);
await this.trackAcceptFeatureUsage({ acceptTrackFeatureUsage: trackFeatureUsage });
}
const isErrorReportingUnset = await this.isNotConfirmed(this.$staticConfig.ERROR_REPORT_SETTING_NAME);
const isUsageReportingConfirmed = !await this.isNotConfirmed(this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME);
if (isErrorReportingUnset && isUsageReportingConfirmed) {
await this.setStatus(this.$staticConfig.ERROR_REPORT_SETTING_NAME, trackFeatureUsage);
}
}
}
public async setStatus(settingName: string, enabled: boolean): Promise<void> {
this.analyticsStatuses[settingName] = enabled ? AnalyticsStatus.enabled : AnalyticsStatus.disabled;
await this.$userSettingsService.saveSetting(settingName, enabled.toString());
}
public async isEnabled(settingName: string): Promise<boolean> {
const analyticsStatus = await this.getStatus(settingName);
return analyticsStatus === AnalyticsStatus.enabled;
}
public getStatusMessage(settingName: string, jsonFormat: boolean, readableSettingName: string): Promise<string> {
if (jsonFormat) {
return this.getJsonStatusMessage(settingName);
}
return this.getHumanReadableStatusMessage(settingName, readableSettingName);
}
public async trackAcceptFeatureUsage(settings: { acceptTrackFeatureUsage: boolean }): Promise<void> {
const acceptTracking = !!(settings && settings.acceptTrackFeatureUsage);
const googleAnalyticsEventData: IGoogleAnalyticsEventData = {
googleAnalyticsDataType: GoogleAnalyticsDataType.Event,
action: TrackActionNames.AcceptTracking,
label: acceptTracking.toString()
};
await this.forcefullyTrackInGoogleAnalytics(googleAnalyticsEventData);
}
public async trackInGoogleAnalytics(gaSettings: IGoogleAnalyticsData): Promise<void> {
await this.initAnalyticsStatuses();
if (!this.$staticConfig.disableAnalytics && this.analyticsStatuses[this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME] === AnalyticsStatus.enabled) {
return this.forcefullyTrackInGoogleAnalytics(gaSettings);
}
}
public async trackEventActionInGoogleAnalytics(data: IEventActionData): Promise<void> {
const device = data.device;
const platform = device ? device.deviceInfo.platform : data.platform;
const normalizedPlatform = platform ? this.$mobileHelper.normalizePlatformName(platform) : platform;
const isForDevice = device ? !device.isEmulator : data.isForDevice;
let label: string = "";
label = this.addDataToLabel(label, normalizedPlatform);
// In some cases (like in case action is Build and platform is Android), we do not know if the deviceType is emulator or device.
// Just exclude the device_type in this case.
if (isForDevice !== null && isForDevice !== undefined) {
const deviceType = isForDevice ? DeviceTypes.Device : (this.$mobileHelper.isAndroidPlatform(platform) ? DeviceTypes.Emulator : DeviceTypes.Simulator);
label = this.addDataToLabel(label, deviceType);
}
if (device) {
label = this.addDataToLabel(label, device.deviceInfo.version);
}
if (data.additionalData) {
label = this.addDataToLabel(label, data.additionalData);
}
const customDimensions: IStringDictionary = {};
this.setProjectRelatedCustomDimensions(customDimensions, data.projectDir);
const googleAnalyticsEventData: IGoogleAnalyticsEventData = {
googleAnalyticsDataType: GoogleAnalyticsDataType.Event,
action: data.action,
label,
customDimensions,
value: data.value
};
await this.trackInGoogleAnalytics(googleAnalyticsEventData);
}
public async trackPreviewAppData(platform: string, projectDir: string): Promise<void> {
const customDimensions: IStringDictionary = {};
this.setProjectRelatedCustomDimensions(customDimensions, projectDir);
let label: string = "";
label = this.addDataToLabel(label, this.$mobileHelper.normalizePlatformName(platform));
const eventActionData = {
googleAnalyticsDataType: GoogleAnalyticsDataType.Event,
action: TrackActionNames.PreviewAppData,
platform,
label,
customDimensions,
type: TrackingTypes.PreviewAppData
};
await this.trackInGoogleAnalytics(eventActionData);
}
public async finishTracking(): Promise<void> {
return new Promise((resolve, reject) => {
if (this.brokerProcess && this.brokerProcess.connected) {
let timer: NodeJS.Timer;
const handler = (data: string) => {
if (data === DetachedProcessMessages.ProcessFinishedTasks) {
this.brokerProcess.removeListener("message", handler);
clearTimeout(timer);
resolve();
}
};
timer = setTimeout(() => {
this.brokerProcess.removeListener("message", handler);
resolve();
}, 3000);
this.brokerProcess.on("message", handler);
const msg = { type: TrackingTypes.FinishTracking };
this.brokerProcess.send(msg, (err: Error) => this.$logger.trace(`Error while sending ${JSON.stringify(msg)}`));
} else {
resolve();
}
});
}
private forcefullyTrackInGoogleAnalytics(gaSettings: IGoogleAnalyticsData): Promise<void> {
gaSettings.customDimensions = gaSettings.customDimensions || {};
gaSettings.customDimensions[GoogleAnalyticsCustomDimensions.client] = this.$options.analyticsClient || (isInteractive() ? AnalyticsClients.Cli : AnalyticsClients.Unknown);
this.setProjectRelatedCustomDimensions(gaSettings.customDimensions);
const googleAnalyticsData: IGoogleAnalyticsTrackingInformation = _.merge({ type: TrackingTypes.GoogleAnalyticsData, category: AnalyticsClients.Cli }, gaSettings);
this.$logger.trace("Will send the following information to Google Analytics:", googleAnalyticsData);
return this.sendMessageToBroker(googleAnalyticsData);
}
private setProjectRelatedCustomDimensions(customDimensions: IStringDictionary, projectDir?: string): IStringDictionary {
if (!projectDir) {
try {
projectDir = this.$projectHelper.projectDir;
} catch (err) {
// In case there's no project dir here, the above getter will fail.
this.$logger.trace("Unable to get the projectDir from projectHelper", err);
}
}
if (projectDir) {
const projectData = this.$projectDataService.getProjectData(projectDir);
customDimensions[GoogleAnalyticsCustomDimensions.projectType] = projectData.projectType;
customDimensions[GoogleAnalyticsCustomDimensions.isShared] = projectData.isShared.toString();
}
return customDimensions;
}
public dispose(): void {
if (this.brokerProcess && this.shouldDisposeInstance) {
this.brokerProcess.disconnect();
}
}
private addDataToLabel(label: string, newData: string): string {
if (newData && label) {
return `${label}_${newData}`;
}
return label || newData || "";
}
@cache()
private getAnalyticsBroker(): Promise<ChildProcess> {
return new Promise<ChildProcess>((resolve, reject) => {
const brokerProcessArgs = this.getBrokerProcessArgs();
const broker = this.$childProcess.spawn(process.execPath,
brokerProcessArgs,
{
stdio: ["ignore", "ignore", "ignore", "ipc"],
detached: true
}
);
broker.unref();
let isSettled = false;
const timeoutId = setTimeout(() => {
if (!isSettled) {
reject(new Error("Unable to start Analytics Broker process."));
}
}, AnalyticsService.ANALYTICS_BROKER_START_TIMEOUT);
broker.on("error", (err: Error) => {
clearTimeout(timeoutId);
if (!isSettled) {
isSettled = true;
reject(err);
}
});
broker.on("message", (data: any) => {
if (data === DetachedProcessMessages.ProcessReadyToReceive) {
clearTimeout(timeoutId);
if (!isSettled) {
isSettled = true;
this.brokerProcess = broker;
resolve(broker);
}
}
});
});
}
private getBrokerProcessArgs(): string[] {
const brokerProcessArgs = [
path.join(__dirname, "analytics-broker-process.js"),
this.$staticConfig.PATH_TO_BOOTSTRAP,
];
if (this.$options.analyticsLogFile) {
brokerProcessArgs.push(this.$options.analyticsLogFile);
}
return brokerProcessArgs;
}
private async sendInfoForTracking(trackingInfo: ITrackingInformation, settingName: string): Promise<void> {
await this.initAnalyticsStatuses();
if (!this.$staticConfig.disableAnalytics && this.analyticsStatuses[settingName] === AnalyticsStatus.enabled) {
return this.sendMessageToBroker(trackingInfo);
}
}
private async sendMessageToBroker(message: ITrackingInformation): Promise<void> {
let broker: ChildProcess;
try {
broker = await this.getAnalyticsBroker();
} catch (err) {
this.$logger.trace("Unable to get broker instance due to error: ", err);
return;
}
return new Promise<void>((resolve, reject) => {
if (broker && broker.connected) {
try {
broker.send(message, (error: Error) => resolve());
} catch (err) {
this.$logger.trace("Error while trying to send message to broker:", err);
resolve();
}
} else {
this.$logger.trace("Broker not found or not connected.");
resolve();
}
});
}
@cache()
private async initAnalyticsStatuses(): Promise<void> {
if (await this.$analyticsSettingsService.canDoRequest()) {
this.$logger.trace("Initializing analytics statuses.");
const settingsNames = [this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME, this.$staticConfig.ERROR_REPORT_SETTING_NAME];
for (const settingName of settingsNames) {
await this.getStatus(settingName);
}
this.$logger.trace("Analytics statuses: ", this.analyticsStatuses);
}
}
private async getStatus(settingName: string): Promise<AnalyticsStatus> {
if (!_.has(this.analyticsStatuses, settingName)) {
const settingValue = await this.$userSettingsService.getSettingValue<string>(settingName);
if (settingValue) {
const isEnabled = toBoolean(settingValue);
if (isEnabled) {
this.analyticsStatuses[settingName] = AnalyticsStatus.enabled;
} else {
this.analyticsStatuses[settingName] = AnalyticsStatus.disabled;
}
} else {
this.analyticsStatuses[settingName] = AnalyticsStatus.notConfirmed;
}
}
return this.analyticsStatuses[settingName];
}
private async isNotConfirmed(settingName: string): Promise<boolean> {
const analyticsStatus = await this.getStatus(settingName);
return analyticsStatus === AnalyticsStatus.notConfirmed;
}
private async getHumanReadableStatusMessage(settingName: string, readableSettingName: string): Promise<string> {
let status: string = null;
if (await this.isNotConfirmed(settingName)) {
status = "disabled until confirmed";
} else {
status = await this.getStatus(settingName);
}
return `${readableSettingName} is ${status}.`;
}
private async getJsonStatusMessage(settingName: string): Promise<string> {
const status = await this.getStatus(settingName);
const enabled = status === AnalyticsStatus.notConfirmed ? null : status === AnalyticsStatus.enabled;
return JSON.stringify({ enabled });
}
public trackException(exception: any, message: string): Promise<void> {
const data: IExceptionsTrackingInformation = {
type: TrackingTypes.Exception,
exception,
message
};
return this.sendInfoForTracking(data, this.$staticConfig.ERROR_REPORT_SETTING_NAME);
}
}
$injector.register("analyticsService", AnalyticsService);