This repository was archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathHealthDataManager.js
More file actions
374 lines (333 loc) · 15.8 KB
/
HealthDataManager.js
File metadata and controls
374 lines (333 loc) · 15.8 KB
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
/*
* Copyright (c) 2015 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*global define, $, brackets, console, appshell */
define(function (require, exports, module) {
"use strict";
var AppInit = brackets.getModule("utils/AppInit"),
CommandManager = brackets.getModule("command/CommandManager"),
HealthLogger = brackets.getModule("utils/HealthLogger"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
UrlParams = brackets.getModule("utils/UrlParams").UrlParams,
Strings = brackets.getModule("strings"),
HealthDataUtils = require("HealthDataUtils"),
uuid = require("thirdparty/uuid"),
prefs = PreferencesManager.getExtensionPrefs("healthData"),
params = new UrlParams(),
ONE_MINUTE = 60 * 1000,
ONE_DAY = 24 * 60 * ONE_MINUTE,
FIRST_LAUNCH_SEND_DELAY = 30 * ONE_MINUTE,
timeoutVar;
prefs.definePreference("healthDataTracking", "boolean", true, {
description: Strings.DESCRIPTION_HEALTH_DATA_TRACKING
});
params.parse();
/**
* Get the Health Data which will be sent to the server. Initially it is only one time data.
*/
function getHealthData() {
var result = new $.Deferred(),
oneTimeHealthData = {};
oneTimeHealthData.snapshotTime = Date.now();
oneTimeHealthData.os = brackets.platform;
oneTimeHealthData.userAgent = window.navigator.userAgent;
oneTimeHealthData.osLanguage = brackets.app.language;
oneTimeHealthData.bracketsLanguage = brackets.getLocale();
oneTimeHealthData.bracketsVersion = brackets.metadata.version;
$.extend(oneTimeHealthData, HealthLogger.getAggregatedHealthData());
HealthDataUtils.getUserInstalledExtensions()
.done(function (userInstalledExtensions) {
oneTimeHealthData.installedExtensions = userInstalledExtensions;
})
.always(function () {
HealthDataUtils.getUserInstalledTheme()
.done(function (bracketsTheme) {
oneTimeHealthData.bracketsTheme = bracketsTheme;
})
.always(function () {
var userUuid = PreferencesManager.getViewState("UUID");
var olderUuid = PreferencesManager.getViewState("OlderUUID");
if (userUuid && olderUuid) {
oneTimeHealthData.uuid = userUuid;
oneTimeHealthData.olderuuid = olderUuid;
return result.resolve(oneTimeHealthData);
} else {
// So we are going to get the Machine hash in either of the cases.
if (appshell.app.getMachineHash) {
appshell.app.getMachineHash(function (err, macHash) {
var generatedUuid;
if (err) {
generatedUuid = uuid.v4();
} else {
generatedUuid = macHash;
}
if (!userUuid) {
// Could be a new user. In this case
// both will remain the same.
userUuid = olderUuid = generatedUuid;
} else {
// For existing user, we will still cache
// the older uuid, so that we can improve
// our reporting in terms of figuring out
// the new users accurately.
olderUuid = userUuid;
userUuid = generatedUuid;
}
PreferencesManager.setViewState("UUID", userUuid);
PreferencesManager.setViewState("OlderUUID", olderUuid);
oneTimeHealthData.uuid = userUuid;
oneTimeHealthData.olderuuid = olderUuid;
return result.resolve(oneTimeHealthData);
});
} else {
// Probably running on older shell, in which case we will
// assign the same uuid to olderuuid.
if (!userUuid) {
oneTimeHealthData.uuid = oneTimeHealthData.olderuuid = uuid.v4();
} else {
oneTimeHealthData.olderuuid = userUuid;
}
PreferencesManager.setViewState("UUID", oneTimeHealthData.uuid);
PreferencesManager.setViewState("OlderUUID", oneTimeHealthData.olderuuid);
return result.resolve(oneTimeHealthData);
}
}
});
});
return result.promise();
}
/**
*@param{Object} eventParams contails Event Data
* will return complete Analyics Data in Json Format
*/
function getAnalyticsData(eventParams) {
var userUuid = PreferencesManager.getViewState("UUID"),
olderUuid = PreferencesManager.getViewState("OlderUUID");
//Create default Values
var defaultEventParams = {
eventCategory: "pingData",
eventSubCategory: "",
eventType: "",
eventSubType: ""
};
//Override with default values if not present
if (!eventParams) {
eventParams = defaultEventParams;
} else {
var e;
for (e in defaultEventParams) {
if (defaultEventParams.hasOwnProperty(e) && !eventParams[e]) {
eventParams[e] = defaultEventParams[e];
}
}
}
return {
project: brackets.config.serviceKey,
environment: brackets.config.environment,
time: new Date().toISOString(),
ingesttype: "dunamis",
data: {
"event.guid": uuid.v4(),
"event.user_guid": olderUuid || userUuid,
"event.dts_end": new Date().toISOString(),
"event.category": eventParams.eventCategory,
"event.subcategory": eventParams.eventSubCategory,
"event.type": eventParams.eventType,
"event.subtype": eventParams.eventSubType,
"event.user_agent": window.navigator.userAgent || "",
"event.language": brackets.app.language,
"source.name": brackets.metadata.version,
"source.platform": brackets.platform,
"source.version": brackets.metadata.version
}
};
}
/**
* Send data to the server
*/
function sendHealthDataToServer() {
var result = new $.Deferred();
getHealthData().done(function (healthData) {
var url = brackets.config.healthDataServerURL,
data = JSON.stringify(healthData);
$.ajax({
url: url,
type: "POST",
data: data,
dataType: "text",
contentType: "text/plain"
})
.done(function () {
result.resolve();
})
.fail(function (jqXHR, status, errorThrown) {
console.error("Error in sending Health Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown);
result.reject();
});
})
.fail(function () {
result.reject();
});
return result.promise();
}
// Send Analytics data to Server
function sendAnalyticsDataToServer(eventParams) {
var result = new $.Deferred();
var analyticsData = getAnalyticsData(eventParams);
$.ajax({
url: brackets.config.analyticsDataServerURL,
type: "POST",
data: JSON.stringify({events: [analyticsData]}),
headers: {
"Content-Type": "application/json",
"x-api-key": brackets.config.serviceKey
}
})
.done(function () {
result.resolve();
})
.fail(function (jqXHR, status, errorThrown) {
console.error("Error in sending Adobe Analytics Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown);
result.reject();
});
return result.promise();
}
/*
* Check if the Health Data is to be sent to the server. If the user has enabled tracking, Health Data will be sent once every 24 hours.
* Send Health Data to the server if the period is more than 24 hours.
* We are sending the data as soon as the user launches brackets. The data will be sent to the server only after the notification dialog
* for opt-out/in is closed.
@param forceSend Flag for sending analytics data for testing purpose
*/
function checkHealthDataSend(forceSend) {
var result = new $.Deferred(),
isHDTracking = prefs.get("healthDataTracking"),
nextTimeToSend,
currentTime;
HealthLogger.setHealthLogsEnabled(isHDTracking);
window.clearTimeout(timeoutVar);
if (isHDTracking) {
nextTimeToSend = PreferencesManager.getViewState("nextHealthDataSendTime");
currentTime = Date.now();
// Never send data before FIRST_LAUNCH_SEND_DELAY has ellapsed on a fresh install. This gives the user time to read the notification
// popup, learn more, and opt out if desired
if (!nextTimeToSend) {
nextTimeToSend = currentTime + FIRST_LAUNCH_SEND_DELAY;
PreferencesManager.setViewState("nextHealthDataSendTime", nextTimeToSend);
// don't return yet though - still want to set the timeout below
}
if (currentTime >= nextTimeToSend || forceSend) {
// Bump up nextHealthDataSendTime at the begining of chaining to avoid any chance of sending data again before 24 hours, // e.g. if the server request fails or the code below crashes
PreferencesManager.setViewState("nextHealthDataSendTime", currentTime + ONE_DAY);
sendHealthDataToServer().always(function() {
sendAnalyticsDataToServer()
.done(function () {
// We have already sent the health data, so can clear all health data
// Logged till now
HealthLogger.clearHealthData();
result.resolve();
})
.fail(function () {
result.reject();
})
.always(function () {
timeoutVar = setTimeout(checkHealthDataSend, ONE_DAY);
});
});
} else {
timeoutVar = setTimeout(checkHealthDataSend, nextTimeToSend - currentTime);
result.reject();
}
} else {
result.reject();
}
return result.promise();
}
/**
* Check if the Analytic Data is to be sent to the server.
* If the user has enabled tracking, Analytic Data will be sent once per session
* Send Analytic Data to the server if the Data associated with the given Event is not yet sent in this session.
* We are sending the data as soon as the user triggers the event.
* The data will be sent to the server only after the notification dialog
* for opt-out/in is closed.
* @param{Object} event event object
* @param{Object} Eventparams Object Containg Data to be sent to Server
* @param{boolean} forceSend Flag for sending analytics data for testing purpose
**/
function checkAnalyticsDataSend(event, Eventparams, forceSend) {
var result = new $.Deferred(),
isHDTracking = prefs.get("healthDataTracking"),
isEventDataAlreadySent;
if (isHDTracking) {
isEventDataAlreadySent = HealthLogger.analyticsEventMap.get(Eventparams.eventName);
HealthLogger.analyticsEventMap.set(Eventparams.eventName, true);
if (!isEventDataAlreadySent || forceSend) {
sendAnalyticsDataToServer(Eventparams)
.done(function () {
HealthLogger.analyticsEventMap.set(Eventparams.eventName, true);
result.resolve();
}).fail(function () {
HealthLogger.analyticsEventMap.set(Eventparams.eventName, false);
result.reject();
});
} else {
result.reject();
}
} else {
result.reject();
}
return result.promise();
}
/**
* This function is auto called after 24 hours to empty the map
* Map is used to make sure that we send an event only once per 24 hours
**/
function emptyAnalyticsMap() {
HealthLogger.analyticsEventMap.clear();
setTimeout(emptyAnalyticsMap, ONE_DAY);
}
setTimeout(emptyAnalyticsMap, ONE_DAY);
// Expose a command to test data sending capability, but limit it to dev environment only
CommandManager.register("Sends health data and Analytics data for testing purpose", "sendHealthData", function() {
if (brackets.config.environment === "stage") {
return checkHealthDataSend(true);
} else {
return $.Deferred().reject().promise();
}
});
prefs.on("change", "healthDataTracking", function () {
checkHealthDataSend();
});
HealthLogger.on("SendAnalyticsData", checkAnalyticsDataSend);
window.addEventListener("online", function () {
checkHealthDataSend();
});
window.addEventListener("offline", function () {
window.clearTimeout(timeoutVar);
});
AppInit.appReady(function () {
checkHealthDataSend();
});
exports.getHealthData = getHealthData;
exports.getAnalyticsData = getAnalyticsData;
exports.checkHealthDataSend = checkHealthDataSend;
});