spee.ch/helpers/googleAnalytics.js

58 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-02-15 20:00:51 +01:00
const logger = require('winston');
const ua = require('universal-analytics');
const { analytics : { googleId }, site: { name: siteName } } = require('../config/speechConfig.js');
2018-02-15 20:00:51 +01:00
function createServeEventParams (headers, ip, originalUrl) {
return {
2018-02-15 22:18:22 +01:00
eventCategory : 'client requests',
eventAction : 'serve request',
eventLabel : originalUrl,
ipOverride : ip,
userAgentOverride: headers['user-agent'],
2018-02-15 20:00:51 +01:00
};
};
function createPublishTimingEventParams (category, variable, label, startTime, endTime) {
2018-03-07 01:23:21 +01:00
const duration = endTime - startTime;
2018-02-15 20:00:51 +01:00
return {
userTimingCategory : category,
userTimingVariableName: variable,
2018-03-07 01:23:21 +01:00
userTimingTime : duration,
2018-02-15 20:00:51 +01:00
userTimingLabel : label,
};
};
function sendGoogleAnalyticsEvent (ip, params) {
const visitorId = ip.replace(/\./g, '-');
const visitor = ua(googleId, visitorId, { strictCidFormat: false, https: true });
2018-02-15 20:00:51 +01:00
visitor.event(params, (err) => {
if (err) {
logger.error('Google Analytics Event Error >>', err);
}
});
};
function sendGoogleAnalyticsTiming (visitorId, params) {
const visitor = ua(googleId, visitorId, { strictCidFormat: false, https: true });
2018-02-15 20:00:51 +01:00
visitor.timing(params, (err) => {
if (err) {
logger.error('Google Analytics Event Error >>', err);
}
logger.debug(`Timing event successfully sent to google analytics`);
});
};
module.exports = {
sendGAServeEvent (headers, ip, originalUrl) {
const params = createServeEventParams(headers, ip, originalUrl);
sendGoogleAnalyticsEvent(ip, params);
},
sendGATimingEvent (category, variable, label, startTime, endTime) {
const params = createPublishTimingEventParams(category, variable, label, startTime, endTime);
sendGoogleAnalyticsTiming(siteName, params);
2018-02-15 20:00:51 +01:00
},
2018-03-07 01:23:21 +01:00
chooseGaLbrynetPublishLabel ({ channel_name: channelName, channel_id: channelId }) {
return (channelName || channelId ? 'PUBLISH_IN_CHANNEL_CLAIM' : 'PUBLISH_ANONYMOUS_CLAIM');
2018-02-15 20:00:51 +01:00
},
};