|
| 1 | +const { net } = require('electron'); |
| 2 | +const { v4: uuidv4 } = require('uuid'); |
| 3 | +const { machineIdSync } = require('node-machine-id'); |
| 4 | +const log = require('electron-log'); |
| 5 | + |
| 6 | +class Analytics4 { |
| 7 | + constructor(trackingID, secretKey, clientID = machineIdSync(), sessionID = uuidv4()) { |
| 8 | + this.trackingID = trackingID; |
| 9 | + this.secretKey = secretKey; |
| 10 | + this.clientID = clientID; |
| 11 | + this.sessionID = sessionID; |
| 12 | + this.customParams = {}; |
| 13 | + this.userProperties = null; |
| 14 | + this.baseURL = 'https://google-analytics.com/mp'; |
| 15 | + this.collectURL = '/collect'; |
| 16 | + } |
| 17 | + |
| 18 | + set(key, value) { |
| 19 | + if (value !== null) { |
| 20 | + this.customParams[key] = value; |
| 21 | + } else { |
| 22 | + delete this.customParams[key]; |
| 23 | + } |
| 24 | + return this; |
| 25 | + } |
| 26 | + |
| 27 | + setParams(params) { |
| 28 | + if (typeof params === 'object' && Object.keys(params).length > 0) { |
| 29 | + Object.assign(this.customParams, params); |
| 30 | + } else { |
| 31 | + this.customParams = {}; |
| 32 | + } |
| 33 | + return this; |
| 34 | + } |
| 35 | + |
| 36 | + setUserProperties(upValue) { |
| 37 | + if (typeof upValue === 'object' && Object.keys(upValue).length > 0) { |
| 38 | + this.userProperties = upValue; |
| 39 | + } else { |
| 40 | + this.userProperties = null; |
| 41 | + } |
| 42 | + return this; |
| 43 | + } |
| 44 | + |
| 45 | + event(eventName) { |
| 46 | + const payload = { |
| 47 | + client_id: this.clientID, |
| 48 | + events: [ |
| 49 | + { |
| 50 | + name: eventName, |
| 51 | + params: { |
| 52 | + session_id: this.sessionID, |
| 53 | + ...this.customParams, |
| 54 | + }, |
| 55 | + }, |
| 56 | + ], |
| 57 | + }; |
| 58 | + |
| 59 | + if (this.userProperties) { |
| 60 | + Object.assign(payload, { user_properties: this.userProperties }); |
| 61 | + } |
| 62 | + |
| 63 | + const url = `${this.baseURL}${this.collectURL}?measurement_id=${this.trackingID}&api_secret=${this.secretKey}`; |
| 64 | + const request = net.request({ |
| 65 | + method: 'POST', |
| 66 | + url, |
| 67 | + }); |
| 68 | + |
| 69 | + request.on('response', (response) => { |
| 70 | + let responseData = ''; |
| 71 | + response.on('data', (chunk) => { |
| 72 | + responseData += chunk; |
| 73 | + }); |
| 74 | + |
| 75 | + response.on('end', () => { |
| 76 | + if (response.statusCode >= 200 && response.statusCode < 300) { |
| 77 | + log.info('success', responseData); |
| 78 | + } else { |
| 79 | + log.error('response error', response.statusCode); |
| 80 | + } |
| 81 | + }); |
| 82 | + }); |
| 83 | + |
| 84 | + request.on('error', (error) => { |
| 85 | + log.error('Error posting data:', error); |
| 86 | + }); |
| 87 | + |
| 88 | + request.write(JSON.stringify(payload)); |
| 89 | + |
| 90 | + request.end(); |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +module.exports = Analytics4; |
0 commit comments