-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstringer.js
289 lines (248 loc) · 7.67 KB
/
stringer.js
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
"use strict";
(function (window, console, oldStringer, undefined) {
var self = {},
rng = initRandom(window),
device = captureDevice(),
browser = captureBrowser(),
visitor = fetchVisitor(),
sourceSite = "default",
environments = {production: "https://t.mayvenn.com/",
acceptance: "https://t.diva-acceptance.com/",
development: "http://localhost:3013"},
debug = false,
serverURI;
function init(config) {
setCookie("stringer.distinct_id", browser.distinct_id, { domain: rootDomain() });
serverURI = environments[config.environment];
sourceSite = config.sourceSite || sourceSite;
debug = config.debug || debug;
if (!serverURI) {
log("Invalid Environment", config.environment);
}
};
function track (eventName, args, cb) {
var blockRe = /(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i;
if (eventName && !blockRe.test(window.navigator.userAgent)) {
send({
id: uuid(rng),
name: eventName,
source: sourceSite,
resource:{
device: device,
browser: browser,
page: {
url: window.location.href,
title: window.document.title,
referrer: window.document.referrer
},
visitor: visitor,
client: {
ts: Date.now()
}
},
data: args
}, cb);
}
};
function identify (userEmail, userId) {
visitor = {
user_email: userEmail,
user_id: userId
};
setCookie("stringer.user_email", userEmail);
setCookie("stringer.user_id", userId);
};
function clear () {
visitor = {};
removeCookie("stringer.user_email");
removeCookie("stringer.user_id");
};
function isNull(value) {
return (value === null || "undefined" == typeof value);
}
function processQueue(queue) {
log("processing queue", queue);
queue.forEach(function(args) {
var cmdName = args.shift(1),
cmd = self[cmdName];
if (cmd) {
log("invoke", cmdName, args);
cmd.apply(null, args);
} else {
log("invalid command", cmdName);
}
});
queue.length = 0;
}
function captureDevice() {
return {
height: window.screen.height,
width: window.screen.width,
pixel_ratio: window.devicePixelRatio
};
}
function captureBrowser() {
return {
distinct_id: readCookie("stringer.distinct_id") || makeid(24),
height: document.documentElement.clientHeight,
width: document.documentElement.clientWidth,
vendor: window.navigator.vendor
};
}
function fetchVisitor() {
var visitor = {};
var userEmail = readCookie("stringer.user_email");
var userId = readCookie("stringer.user_id");
if (!!userEmail) {
visitor.user_email = userEmail;
}
if (!!userId) {
visitor.user_id = userId;
}
return visitor;
}
function readCookie(key) {
var cookies = document.cookie.split(";");
var cookieRe = RegExp("^\\s*"+key+"=\\s*(.*?)\\s*$");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var found = cookie.match(cookieRe);
if (found) {
return decodeURIComponent(found[1]);
}
}
return null;
}
function rootDomain() {
var domainParts = window.location.hostname.split('.');
var rootDomainParts = domainParts.slice(Math.max(domainParts.length - 2, 0));
return rootDomainParts.join('.');
}
function setCookie(key, value, options) {
options = options || {};
options.domain = options.domain || window.location.hostname;
var expiresAt = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365 * 10);
if (isNull(value)) {
expiresAt = new Date(1970, 1 /*Feb*/, 1);
}
var cookieStr = key + "=" + encodeURIComponent(value) + "; domain=" + options.domain + "; path=/; expires=" + expiresAt.toUTCString();
if (window.location.protocol === "https:") {
cookieStr = cookieStr + ";secure";
}
window.document.cookie = cookieStr;
}
function removeCookie(key, domain) {
setCookie(key, null, {domain : domain});
}
function log() {
try {
if (debug && 'undefined' !== typeof console && console.log) {
console.log.apply(console, Array.prototype.concat.apply(["stringer"], arguments));
}
} catch (e) {}
}
function jsonString(value) {
return JSON.stringify(value)
.replace(/[\u007F-\uFFFF]/g, function(chr) {
return "\\u" + ("0000" + chr.charCodeAt(0).toString(16)).substr(-4);
});
}
function send(payload, cb) {
log("send", serverURI, payload);
// this is referenced like a lock to only fire the callback once
var state = {cbTriggered: false};
var triggerCallback = function(){
if (!state.cbTriggered && cb) cb();
state.cbTriggered = true;
};
window.setTimeout(triggerCallback, 500);
var xhr = new XMLHttpRequest();
xhr.open("POST", serverURI);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) triggerCallback();
};
xhr.send(jsonString(payload));
}
// from https://github.com/broofa/node-uuid
function initRandom(window) {
var _rng;
var _crypto = window.crypto || window.msCrypto;
if (!_rng && _crypto && _crypto.getRandomValues) {
try {
var _rnds8 = new Uint8Array(16);
_rng = function () {
_crypto.getRandomValues(_rnds8);
return _rnds8;
};
_rng();
} catch(e) {}
}
if (!_rng) {
var _rnds = new Array(16);
_rng = function() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }
_rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return _rnds;
};
}
return _rng;
}
function uuid(rng) {
var rnds = rng();
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
var i = 0,
bth = [];
for (var j = 0; j < 256; j++) {
bth[j] = (j + 0x100).toString(16).substr(1);
}
return bth[rnds[i++]] + bth[rnds[i++]] +
bth[rnds[i++]] + bth[rnds[i++]] + '-' +
bth[rnds[i++]] + bth[rnds[i++]] + '-' +
bth[rnds[i++]] + bth[rnds[i++]] + '-' +
bth[rnds[i++]] + bth[rnds[i++]] + '-' +
bth[rnds[i++]] + bth[rnds[i++]] +
bth[rnds[i++]] + bth[rnds[i++]] +
bth[rnds[i++]] + bth[rnds[i++]];
}
/* Gives strings with 62 ^ n bits of entropy
NOTE: this is not a particularly FAST generator. It should only be called
infrequently, unlike the UUID generation code which can more efficiently
generate randomness. */
function makeid(n) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i=0; i < n; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function addPublicFn(name, f) {
self[name] = function() {
try {
f.apply(self, arguments);
} catch (e) {
log("error in " + name, e);
}
return self;
};
}
function getBrowserId(callback) {
return callback(browser.distinct_id);
}
// These should be the only public functions/vars that are exposed through self,
// otherwise leave them in the closure!
self.loaded = true;
addPublicFn("init", init);
addPublicFn("track", track);
addPublicFn("identify", identify);
addPublicFn("clear", clear);
addPublicFn("getBrowserId", getBrowserId);
window.stringer = self;
if (Array.isArray(oldStringer)) {
processQueue(oldStringer);
}
})(window, console, window.stringer);