forked from OtterMind/Chat2DB
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathga4.js
More file actions
94 lines (81 loc) · 2.26 KB
/
Copy pathga4.js
File metadata and controls
94 lines (81 loc) · 2.26 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
const { net } = require('electron');
const { v4: uuidv4 } = require('uuid');
const { machineIdSync } = require('node-machine-id');
const log = require('electron-log');
class Analytics4 {
constructor(trackingID, secretKey, clientID = machineIdSync(), sessionID = uuidv4()) {
this.trackingID = trackingID;
this.secretKey = secretKey;
this.clientID = clientID;
this.sessionID = sessionID;
this.customParams = {};
this.userProperties = null;
this.baseURL = 'https://google-analytics.com/mp';
this.collectURL = '/collect';
}
set(key, value) {
if (value !== null) {
this.customParams[key] = value;
} else {
delete this.customParams[key];
}
return this;
}
setParams(params) {
if (typeof params === 'object' && Object.keys(params).length > 0) {
Object.assign(this.customParams, params);
} else {
this.customParams = {};
}
return this;
}
setUserProperties(upValue) {
if (typeof upValue === 'object' && Object.keys(upValue).length > 0) {
this.userProperties = upValue;
} else {
this.userProperties = null;
}
return this;
}
event(eventName) {
const payload = {
client_id: this.clientID,
events: [
{
name: eventName,
params: {
session_id: this.sessionID,
...this.customParams,
},
},
],
};
if (this.userProperties) {
Object.assign(payload, { user_properties: this.userProperties });
}
const url = `${this.baseURL}${this.collectURL}?measurement_id=${this.trackingID}&api_secret=${this.secretKey}`;
const request = net.request({
method: 'POST',
url,
});
request.on('response', (response) => {
let responseData = '';
response.on('data', (chunk) => {
responseData += chunk;
});
response.on('end', () => {
if (response.statusCode >= 200 && response.statusCode < 300) {
log.info('success', responseData);
} else {
log.error('response error', response.statusCode);
}
});
});
request.on('error', (error) => {
log.error('Error posting data:', error);
});
request.write(JSON.stringify(payload));
request.end();
}
}
module.exports = Analytics4;