-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathcountly-common.js
More file actions
331 lines (322 loc) · 13.2 KB
/
countly-common.js
File metadata and controls
331 lines (322 loc) · 13.2 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
/**
* main common functionalities will go in here
*/
var crypto = require("crypto");
var cc = {
// debug value from Countly
debug: false,
debugBulk: false,
debugBulkUser: false,
/**
* log level Enums:
* Error - this is a issues that needs attention right now.
* Warning - this is something that is potentially a issue. Maybe a deprecated usage of something, maybe consent is enabled but consent is not given.
* Info - All publicly exposed functions should log a call at this level to indicate that they were called. These calls should include the function name.
* Debug - this should contain logs from the internal workings of the SDK and it's important calls. This should include things like the SDK configuration options, success or fail of the current network request, "request queue is full" and the oldest request get's dropped, etc.
* Verbose - this should give a even deeper look into the SDK's inner working and should contain things that are more noisy and happen often.
*/
logLevelEnums: {
ERROR: '[ERROR] ',
WARNING: '[WARNING] ',
INFO: '[INFO] ',
DEBUG: '[DEBUG] ',
VERBOSE: '[VERBOSE] ',
},
/**
* device ID type:
* 0 - device ID was set by the developer during init
* 1 - device ID was auto generated by Countly
*/
deviceIdTypeEnums: {
DEVELOPER_SUPPLIED: 0,
SDK_GENERATED: 1,
},
/**
* At the current moment there are following internal events and their respective required consent:
* [CLY]_nps - "feedback" consent
* [CLY]_survey - "feedback" consent
* [CLY]_star_rating - "star_rating" consent
* [CLY]_view - "view" consent
* [CLY]_orientation - "users" consent
* [CLY]_push_action - "push" consent
* [CLY]_action - "clicks" or "scroll" consent
*/
internalEventKeyEnums: {
NPS: '[CLY]_nps',
SURVEY: '[CLY]_survey',
STAR_RATING: '[CLY]_star_rating',
VIEW: '[CLY]_view',
ORIENTATION: '[CLY]_orientation',
PUSH_ACTION: '[CLY]_push_action',
ACTION: '[CLY]_action',
},
storageTypeEnums: {
FILE: "file",
MEMORY: "memory",
},
/**
* Get current timestamp
* @returns {number} unix timestamp in seconds
*/
getTimestamp: function getTimestamp() {
return Math.floor(new Date().getTime() / 1000);
},
/*
* Truncates an object's key/value pairs to a certain length
* @param {Object} obj - original object to be truncated
* @param {Number} keyLimit - limit for key length
* @param {Number} valueLimit - limit for value length
* @param {Number} segmentLimit - limit for segments pairs
* @param {string} errorLog - prefix for error log
* @returns {Object} - the new truncated object
*/
truncateObject: function truncateObject(obj, keyLimit, valueLimit, segmentLimit, errorLog) {
var ob = {};
if (obj) {
if (Object.keys(obj).length > segmentLimit) {
var resizedSeg = {};
var i = 0;
for (var e in obj) {
if (i < segmentLimit) {
resizedSeg[e] = obj[e];
i++;
}
}
obj = resizedSeg;
}
for (var key in obj) {
var newKey = this.truncateSingleValue(key, keyLimit, errorLog);
var newValue = this.truncateSingleValue(obj[key], valueLimit, errorLog);
ob[newKey] = newValue;
}
}
return ob;
},
/**
* Truncates a single value to a certain length
* @param {string|number} str - original value to be truncated
* @param {Number} limit - limit length
* @param {string} errorLog - prefix for error log
* @returns {string|number} - the new truncated value
*/
truncateSingleValue: function truncateSingleValue(str, limit, errorLog) {
var newStr = str;
if (typeof str === 'number') {
str = str.toString();
}
if (typeof str === 'string') {
if (str.length > limit) {
newStr = str.substring(0, limit);
if ((this.debug || this.debugBulk || this.debugBulkUser) && typeof console !== "undefined") {
// eslint-disable-next-line no-console
console.log(`${errorLog}, Key: [${str}] is longer than accepted length. It will be truncated.`);
}
}
}
return newStr;
},
/**
* Retrieve only specific properties from object
* @param {Object} orig - object from which to get properties
* @param {Array} props - list of properties to get
* @returns {Object} Object with requested properties
*/
getProperties: function getProperties(orig, props) {
var ob = {};
var prop;
for (var i = 0; i < props.length; i++) {
prop = props[i];
if (typeof orig[prop] !== "undefined") {
ob[prop] = orig[prop];
}
}
return ob;
},
/**
* Convert params object to URL encoded query parameter string
* @param {Object} params - object with query parameters
* @returns {String} URL encoded query string
*/
serializeParams: function serializeParams(params) {
var str = [];
var keys = Object.keys(params || {});
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
str.push(`${key}=${encodeURIComponent(params[key])}`);
}
return str.join("&");
},
/**
* Calculate the SHA-256 checksum for provided request data and salt
* @param {String} data - serialized request data
* @param {String} salt - developer provided shared secret
* @param {Boolean} decodeBeforeHash - if true decodes serialized data before hashing
* @param {Boolean} uppercase - if true returns uppercase hex
* @returns {String} checksum in hex format
*/
calculateChecksum: function calculateChecksum(data, salt, decodeBeforeHash, uppercase) {
var checksumData = data || "";
if (decodeBeforeHash) {
try {
checksumData = decodeURIComponent(checksumData);
}
catch (e) {
this.log(this.logLevelEnums.WARNING, `calculateChecksum, Failed to decode request data before hashing: [${e}]`);
}
}
var hash = crypto.createHash("sha256");
hash.update(`${checksumData}${salt}`);
var checksum = hash.digest("hex");
if (uppercase) {
return checksum.toUpperCase();
}
return checksum;
},
/**
* Append checksum256 to serialized request data when salt is configured
* @param {String} data - serialized request data
* @param {String} salt - developer provided shared secret
* @param {Boolean} decodeBeforeHash - if true decodes serialized data before hashing
* @param {Boolean} uppercase - if true appends uppercase hex
* @returns {String} serialized request data with checksum when configured
*/
addChecksum: function addChecksum(data, salt, decodeBeforeHash, uppercase) {
if (!salt) {
return data;
}
var checksum = this.calculateChecksum(data, salt, decodeBeforeHash, uppercase);
if (!data) {
return `checksum256=${checksum}`;
}
return `${data}&checksum256=${checksum}`;
},
/**
* Removing trailing slashes
* @memberof Countly._internals
* @param {String} str - string from which to remove traling slash
* @returns {String} modified string
*/
stripTrailingSlash: function stripTrailingSlash(str) {
if (str.substring(str.length - 1) === "/") {
return str.substring(0, str.length - 1);
}
return str;
},
/**
* Generate random UUID value
* @returns {String} random UUID value
*/
generateUUID: function generateUUID() {
var d = new Date().getTime();
var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
},
/**
* Check if value is in UUID format
* @param {string} providedId - Id to check
* @returns {Boolean} true if it is in UUID format
*/
isUUID: function isUUID(providedId) {
return /[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-4[0-9a-fA-F]{3}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}/.test(providedId);
},
/**
* Log data if debug mode is enabled
* @param {string} level - log level (error, warning, info, debug, verbose)
* @param {string} message - any string message
*/
log: function log(level, message, ...args) {
if ((this.debug || this.debugBulk || this.debugBulkUser) && typeof console !== "undefined") {
if (args[0] && typeof args[0] === "object") {
args[0] = JSON.stringify(args[0]);
}
if (level === this.logLevelEnums.ERROR) {
// eslint-disable-next-line no-console
console.error(level + message, Array.prototype.slice.call(args).join("\n"));
}
else if (level === this.logLevelEnums.WARNING) {
// eslint-disable-next-line no-console
console.warn(level + message, Array.prototype.slice.call(args).join("\n"));
}
else if (level === this.logLevelEnums.VERBOSE) {
// eslint-disable-next-line no-console
console.log(level + message, Array.prototype.slice.call(args).join("\n"));
}
else if (level === this.logLevelEnums.INFO) {
// eslint-disable-next-line no-console
console.info(level + message, Array.prototype.slice.call(args).join("\n"));
}
else {
// default log level is DEBUG
level = this.logLevelEnums.DEBUG;
// eslint-disable-next-line no-console
console.debug(level + message, Array.prototype.slice.call(args).join("\n"));
}
}
},
/**
* Check if the http response fits the bill of:
* 1. The HTTP response code was successful (which is any 2xx code or code between 200 <= x < 300)
* 2. The returned request is a JSON object
* 3. That JSON object contains the field "result" (there can be other fields)
* @param {Number} statusCode - http incoming statusCode
* @param {String} str - response from server, ideally must be: {"result":"Success"} or should contain at least result field
* @returns {Boolean} - returns true if response passes the tests
*/
isResponseValid: function isResponseValid(statusCode, str) {
// status code and response format check
if (!(statusCode >= 200 && statusCode < 300)) {
this.log(this.logLevelEnums.ERROR, `isResponseValid, The server status code is not within the expected range: [${statusCode}]`);
return false;
}
// Try to parse JSON
try {
var response = JSON.parse(str);
if (response.result) {
// if the 'result' field exists, we return 'true'
return true;
}
// result field was not there
this.log(this.logLevelEnums.ERROR, `isResponseValid, The server response has no 'result' field`);
return false;
}
catch (e) {
this.log(this.logLevelEnums.ERROR, `isResponseValid, Http response is in the wrong format: [${e}]`);
return false;
}
},
/**
* Check if the http response fits the bill of:
* 1. The HTTP response code was successful (which is any 2xx code or code between 200 <= x < 300)
* 2. The returned request is a JSON object OR JSON array
* @param {Number} statusCode - http incoming statusCode
* @param {String} str - response from server, ideally must be: {"result":"Success"} or should contain at least result field
* @returns {Boolean} - returns true if response passes the tests
*/
isResponseValidBroad: function isResponseValidBroad(statusCode, str) {
// status code and response format check
if (!(statusCode >= 200 && statusCode < 300)) {
this.log(this.logLevelEnums.ERROR, `isResponseValidBroad, The server status code is not within the expected range: [${statusCode}] with: [${str}]`);
return false;
}
// Try to parse JSON
try {
var response = JSON.parse(str);
// check if parsed response is a JSON object or JSON array, if not it is not valid
if ((Object.prototype.toString.call(response) !== "[object Object]") && (!Array.isArray(response))) {
this.log(this.logLevelEnums.ERROR, `isResponseValidBroad, Http response is not JSON Object nor JSON Array.`);
return false;
}
// request should be accepted even if does not have result field
return true;
}
catch (e) {
this.log(this.logLevelEnums.ERROR, `isResponseValidBroad, Http response is in the wrong format. Error: `, e);
return false;
}
},
};
module.exports = cc;