forked from ionic-team/ionic-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats.js
More file actions
635 lines (517 loc) · 19.3 KB
/
stats.js
File metadata and controls
635 lines (517 loc) · 19.3 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
var MixpanelAPI, crypto, Buffer, http, querystring, util, path, fs, os, IonicConfig;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__slice = Array.prototype.slice;
var path = require('path'),
http = require('http'),
querystring = require('querystring'),
crypto = require('crypto'),
Buffer = require('buffer').Buffer,
util = require('util'),
es = require('event-stream'),
fs = require('fs'),
os = require('os'),
IonicConfig = require('./config');
/*
Heavily inspired by the original js library copyright Mixpanel, Inc.
(http://mixpanel.com/)
Copyright (c) 2012 Carl Sverre
Released under the MIT license.
*/
var create_client = function(token, config) {
var metrics = {};
if(!token) {
throw new Error("The Mixpanel Client needs a Mixpanel token: `init(token)`");
}
metrics.config = {
test: false,
debug: false,
verbose: false
};
metrics.token = token;
/**
send_request(data)
---
this function sends an async GET request to mixpanel
data:object the data to send in the request
callback:function(err:Error) callback is called when the request is
finished or an error occurs
*/
metrics.send_request = function(endpoint, data, callback) {
callback = callback || function() {};
var event_data = new Buffer(JSON.stringify(data));
var request_data = {
'data': event_data.toString('base64'),
'ip': 0,
'verbose': metrics.config.verbose ? 1 : 0
};
if (endpoint === '/import') {
var key = metrics.config.key;
if (!key) {
throw new Error("The Mixpanel Client needs a Mixpanel api key when importing old events: `init(token, { key: ... })`");
}
request_data.api_key = key;
}
var request_options = {
host: 'api.mixpanel.com',
port: 80,
headers: {}
};
if (metrics.config.test) { request_data.test = 1; }
var query = querystring.stringify(request_data);
request_options.path = [endpoint,"?",query].join("");
http.get(request_options, function(res) {
var data = "";
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
var e;
if(metrics.config.verbose) {
try {
var result = JSON.parse(data);
if(result.status != 1) {
e = new Error("Mixpanel Server Error: " + result.error);
}
}
catch(ex) {
e = new Error("Could not parse response from Mixpanel");
}
}
else {
e = (data !== '1') ? new Error("Mixpanel Server Error: " + data) : undefined;
}
callback(e);
});
}).on('error', function(e) {
if(metrics.config.debug) {
console.log("Got Error: " + e.message);
}
callback(e);
});
};
/**
track(event, properties, callback)
---
this function sends an event to mixpanel.
event:string the event name
properties:object additional event properties to send
callback:function(err:Error) callback is called when the request is
finished or an error occurs
*/
metrics.track = function(event, properties, callback) {
if (typeof(properties) === 'function' || !properties) {
callback = properties;
properties = {};
}
// if properties.time exists, use import endpoint
var endpoint = (typeof(properties.time) === 'number') ? '/import' : '/track';
properties.token = metrics.token;
properties.mp_lib = "node";
var data = {
'event' : event,
'properties' : properties
};
if (metrics.config.debug) {
console.log("Sending the following event to Mixpanel:");
console.log(data);
}
metrics.send_request(endpoint, data, callback);
};
/**
import(event, properties, callback)
---
This function sends an event to mixpanel using the import
endpoint. The time argument should be either a Date or Number,
and should signify the time the event occurred.
It is highly recommended that you specify the distinct_id
property for each event you import, otherwise the events will be
tied to the IP address of the sending machine.
For more information look at:
https://mixpanel.com/docs/api-documentation/importing-events-older-than-31-days
event:string the event name
time:date|number the time of the event
properties:object additional event properties to send
callback:function(err:Error) callback is called when the request is
finished or an error occurs
*/
metrics.import = function(event, time, properties, callback) {
if (typeof(properties) === 'function' || !properties) {
callback = properties;
properties = {};
}
if (time === void 0) {
throw new Error("The import method requires you to specify the time of the event");
} else if (Object.prototype.toString.call(time) === '[object Date]') {
time = Math.floor(time.getTime() / 1000);
}
properties.time = time;
metrics.track(event, properties, callback);
};
/**
alias(distinct_id, alias)
---
This function creates an alias for distinct_id
For more information look at:
https://mixpanel.com/docs/integration-libraries/using-mixpanel-alias
distinct_id:string the current identifier
alias:string the future alias
*/
metrics.alias = function(distinct_id, alias, callback) {
var properties = {
distinct_id: distinct_id,
alias: alias
};
metrics.track('$create_alias', properties, callback);
};
metrics.people = {
/** people.set_once(distinct_id, prop, to, callback)
---
The same as people.set but in the words of mixpanel:
mixpanel.people.set_once
" This method allows you to set a user attribute, only if
it is not currently set. It can be called multiple times
safely, so is perfect for storing things like the first date
you saw a user, or the referrer that brought them to your
website for the first time. "
*/
set_once: function(distinct_id, prop, to, callback) {
var $set = {}, data = {};
if (typeof(prop) === 'object') {
callback = to;
$set = prop;
} else {
$set[prop] = to;
}
this._set(distinct_id, $set, callback, { set_once: true });
},
/**
people.set(distinct_id, prop, to, callback)
---
set properties on an user record in engage
usage:
mixpanel.people.set('bob', 'gender', 'm');
mixpanel.people.set('joe', {
'company': 'acme',
'plan': 'premium'
});
*/
set: function(distinct_id, prop, to, callback) {
var $set = {}, data = {};
if (typeof(prop) === 'object') {
callback = to;
$set = prop;
} else {
$set[prop] = to;
}
this._set(distinct_id, $set, callback);
},
// used internally by set and set_once
_set: function(distinct_id, $set, callback, options) {
var set_key = (options && options.set_once) ? "$set_once" : "$set";
var data = {
'$token': metrics.token,
'$distinct_id': distinct_id
};
data[set_key] = $set;
if ('ip' in $set) {
data.$ip = $set.ip;
delete $set.ip;
}
if ($set.$ignore_time) {
data.$ignore_time = $set.$ignore_time;
delete $set.$ignore_time;
}
if(metrics.config.debug) {
console.log("Sending the following data to Mixpanel (Engage):");
console.log(data);
}
metrics.send_request('/engage', data, callback);
},
/**
people.increment(distinct_id, prop, to, callback)
---
increment/decrement properties on an user record in engage
usage:
mixpanel.people.increment('bob', 'page_views', 1);
// or, for convenience, if you're just incrementing a counter by 1, you can
// simply do
mixpanel.people.increment('bob', 'page_views');
// to decrement a counter, pass a negative number
mixpanel.people.increment('bob', 'credits_left', -1);
// like mixpanel.people.set(), you can increment multiple properties at once:
mixpanel.people.increment('bob', {
counter1: 1,
counter2: 3,
counter3: -2
});
*/
increment: function(distinct_id, prop, by, callback) {
var $add = {};
if (typeof(prop) === 'object') {
callback = by;
Object.keys(prop).forEach(function(key) {
var val = prop[key];
if (isNaN(parseFloat(val))) {
if (metrics.config.debug) {
console.error("Invalid increment value passed to mixpanel.people.increment - must be a number");
console.error("Passed " + key + ":" + val);
}
return;
} else {
$add[key] = val;
}
});
} else {
if (!by) { by = 1; }
$add[prop] = by;
}
var data = {
'$add': $add,
'$token': metrics.token,
'$distinct_id': distinct_id
};
if(metrics.config.debug) {
console.log("Sending the following data to Mixpanel (Engage):");
console.log(data);
}
metrics.send_request('/engage', data, callback);
},
/**
people.track_charge(distinct_id, amount, properties, callback)
---
Record that you have charged the current user a certain
amount of money.
usage:
// charge a user $29.99
mixpanel.people.track_charge('bob', 29.99);
// charge a user $19 on the 1st of february
mixpanel.people.track_charge('bob', 19, { '$time': new Date('feb 1 2012') });
*/
track_charge: function(distinct_id, amount, properties, callback) {
var $append = {};
if (!properties) { properties = {}; }
if (typeof(amount) !== 'number') {
amount = parseFloat(amount);
if (isNaN(amount)) {
console.error("Invalid value passed to mixpanel.people.track_charge - must be a number");
return;
}
}
properties.$amount = amount;
if (properties.hasOwnProperty('$time')) {
var time = properties.$time;
if (Object.prototype.toString.call(time) === '[object Date]') {
properties.$time = time.toISOString();
}
}
var data = {
'$append': { '$transactions': properties },
'$token': metrics.token,
'$distinct_id': distinct_id
};
if(metrics.config.debug) {
console.log("Sending the following data to Mixpanel (Engage):");
console.log(data);
}
metrics.send_request('/engage', data, callback);
},
/**
people.clear_charges(distinct_id, callback)
---
Clear all the current user's transactions.
usage:
mixpanel.people.clear_charges('bob');
*/
clear_charges: function(distinct_id, callback) {
var data = {
'$set': { '$transactions': [] },
'$token': metrics.token,
'$distinct_id': distinct_id
};
if(metrics.config.debug) {
console.log("Clearing this user's charges:", distinct_id);
}
metrics.send_request('/engage', data, callback);
},
/**
people.delete_user(distinct_id, callback)
---
delete an user record in engage
usage:
mixpanel.people.delete_user('bob');
*/
delete_user: function(distinct_id, callback) {
var data = {
'$delete': distinct_id,
'$token': metrics.token,
'$distinct_id': distinct_id
};
if(metrics.config.debug) {
console.log("Deleting the user from engage:", distinct_id);
}
metrics.send_request('/engage', data, callback);
},
/**
people.unset(distinct_id, prop, callback)
---
delete a property on an user record in engage
usage:
mixpanel.people.unset('bob', 'page_views');
mixpanel.people.unset('bob', ['page_views', 'last_login']);
*/
unset: function(distinct_id, prop, callback) {
var $unset = [];
if (util.isArray(prop)) {
$unset = prop;
} else if (typeof(prop) === 'string') {
$unset = [prop];
} else {
if (metrics.config.debug) {
console.error("Invalid argument passed to mixpanel.people.unset - must be a string or array");
console.error("Passed: " + prop);
}
return;
}
var data = {
'$unset': $unset,
'$token': metrics.token,
'$distinct_id': distinct_id
};
if(metrics.config.debug) {
console.log("Sending the following data to Mixpanel (Engage):");
console.log(data);
}
metrics.send_request('/engage', data, callback);
}
};
/**
set_config(config)
---
Modifies the mixpanel config
config:object an object with properties to override in the
mixpanel client config
*/
metrics.set_config = function(config) {
for (var c in config) {
if (config.hasOwnProperty(c)) {
metrics.config[c] = config[c];
}
}
};
if (config) {
metrics.set_config(config);
}
return metrics;
};
// module exporting
/*
module.exports = {
Client: function(token) {
console.warn("The function `Client(token)` is deprecated. It is now called `init(token)`.");
return create_client(token);
},
init: create_client
};
*/
var mixpanel = create_client('69f7271aa8f3d43f2e1b6baf698159b7');
var ionicConfig = IonicConfig.load();
exports.IonicStats = {
t: function(additionalData) {
try {
if(process.argv.length < 3) return;
if( ionicConfig.get('statsOptOut') === true ) {
return;
}
var cmdName = process.argv[2].toLowerCase();
var cmdArgs = (process.argv.length > 3 ? process.argv.slice(3) : []); // skip the cmdName
var statsData = additionalData || {};
var platforms = [];
var x, y, cmd;
// update any aliases with the full cmd so there's a common property
var aliasMap = {
'rm': 'remove',
'ls': 'list',
'up': 'update',
'-w': '--no-cordova',
'-b': '--nobrowser',
'-r': '--nolivereload',
'-x': '--noproxy',
'-l': '--livereload',
'-c': '--consolelogs',
'-s': '--serverlogs',
'-n': '--no-email',
'-s': '--sass'
};
for(x=0; x<cmdArgs.length; x++) {
for(y in aliasMap) {
if(cmdArgs[x].toLowerCase() == y) {
cmdArgs[x] = aliasMap[y];
}
}
}
var platformWhitelist = 'android ios firefoxos wp7 wp8 amazon-fireos blackberry10 tizen'.split(' ');
var argsWhitelist = 'add remove list update check debug release search --livereload --consolelogs --serverlogs --no-cordova --nobrowser --nolivereload --noproxy --no-email --debug --release --device --emulator --sass --splash --icon'.split(' ');
// collect only certain args, skip over everything else
for(x=0; x<cmdArgs.length; x++) {
cmd = cmdArgs[x].toLowerCase();
// gather what platforms this is targeting
for(y=0; y<platformWhitelist.length; y++) {
if(cmd == platformWhitelist[y]) {
platforms.push(cmd); // group them together
statsData[cmd] = true; // also give them their own property
break;
}
}
// gather only args that are in our list of valid stat args
for(y=0; y<argsWhitelist.length; y++) {
if(cmd == argsWhitelist[y]) {
statsData[cmd] = true;
break;
}
}
}
// create a platform property only when there is 1 or more
if(platforms.length) {
statsData.platform = platforms.sort().join(',');
}
// add which ionic lib version they're using
try {
statsData.ionic_version = require( path.resolve('www/lib/ionic/version.json') ).version;
} catch(e2) {}
// add which cli version is being used
try {
statsData.cli_version = require('../../package.json').version;
if(statsData.cli_version.indexOf('beta') > -1) return;
} catch(e2) {}
try {
statsData.email = ionicConfig.get('email');
} catch (e2) {}
try {
statsData.account_id = ionicConfig.get('id');
} catch (e2) {}
this.mp(cmdName, statsData);
//console.log(cmdName, statsData);
} catch(e) {
console.log( ('Error stats: ' + e) );
}
},
mp: function(e, d) {
var unique_id = ionicConfig.get('ank');
if(!unique_id) {
this.createId();
unique_id = ionicConfig.get('ank');
}
d.distinct_id = unique_id;
mixpanel.track(e, d, function(err, data) {
});
},
createId: function() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
ionicConfig.set('ank', uuid);
}
};