forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatsAnalyticsAdapter.js
408 lines (381 loc) · 10.3 KB
/
atsAnalyticsAdapter.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
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
import { logError, logInfo } from '../src/utils.js';
import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js';
import { EVENTS } from '../src/constants.js';
import adaptermanager from '../src/adapterManager.js';
import {ajax} from '../src/ajax.js';
import {getStorageManager} from '../src/storageManager.js';
import {getGlobal} from '../src/prebidGlobal.js';
import {MODULE_TYPE_ANALYTICS} from '../src/activities/modules.js';
const MODULE_CODE = 'atsAnalytics';
export const storage = getStorageManager({moduleType: MODULE_TYPE_ANALYTICS, moduleName: MODULE_CODE});
/**
* Analytics adapter for - https://liveramp.com
* Maintainer - [email protected]
*/
const analyticsType = 'endpoint';
const preflightUrl = 'https://check.analytics.rlcdn.com/check/';
export const analyticsUrl = 'https://analytics.rlcdn.com';
let handlerRequest = [];
let handlerResponse = [];
let atsAnalyticsAdapterVersion = 3;
let browsersList = [
/* Googlebot */
{
test: /googlebot/i,
name: 'Googlebot'
},
/* Opera < 13.0 */
{
test: /opera/i,
name: 'Opera',
},
/* Opera > 13.0 */
{
test: /opr\/|opios/i,
name: 'Opera'
},
{
test: /SamsungBrowser/i,
name: 'Samsung Internet for Android',
},
{
test: /Whale/i,
name: 'NAVER Whale Browser',
},
{
test: /MZBrowser/i,
name: 'MZ Browser'
},
{
test: /focus/i,
name: 'Focus',
},
{
test: /swing/i,
name: 'Swing',
},
{
test: /coast/i,
name: 'Opera Coast',
},
{
test: /opt\/\d+(?:.?_?\d+)+/i,
name: 'Opera Touch',
},
{
test: /yabrowser/i,
name: 'Yandex Browser',
},
{
test: /ucbrowser/i,
name: 'UC Browser',
},
{
test: /Maxthon|mxios/i,
name: 'Maxthon',
},
{
test: /epiphany/i,
name: 'Epiphany',
},
{
test: /puffin/i,
name: 'Puffin',
},
{
test: /sleipnir/i,
name: 'Sleipnir',
},
{
test: /k-meleon/i,
name: 'K-Meleon',
},
{
test: /micromessenger/i,
name: 'WeChat',
},
{
test: /qqbrowser/i,
name: (/qqbrowserlite/i).test(window.navigator.userAgent) ? 'QQ Browser Lite' : 'QQ Browser',
},
{
test: /msie|trident/i,
name: 'Internet Explorer',
},
{
test: /\sedg\//i,
name: 'Microsoft Edge',
},
{
test: /edg([ea]|ios)/i,
name: 'Microsoft Edge',
},
{
test: /vivaldi/i,
name: 'Vivaldi',
},
{
test: /seamonkey/i,
name: 'SeaMonkey',
},
{
test: /sailfish/i,
name: 'Sailfish',
},
{
test: /silk/i,
name: 'Amazon Silk',
},
{
test: /phantom/i,
name: 'PhantomJS',
},
{
test: /slimerjs/i,
name: 'SlimerJS',
},
{
test: /blackberry|\bbb\d+/i,
name: 'BlackBerry',
},
{
test: /(web|hpw)[o0]s/i,
name: 'WebOS Browser',
},
{
test: /bada/i,
name: 'Bada',
},
{
test: /tizen/i,
name: 'Tizen',
},
{
test: /qupzilla/i,
name: 'QupZilla',
},
{
test: /firefox|iceweasel|fxios/i,
name: 'Firefox',
},
{
test: /electron/i,
name: 'Electron',
},
{
test: /MiuiBrowser/i,
name: 'Miui',
},
{
test: /chromium/i,
name: 'Chromium',
},
{
test: /chrome|crios|crmo/i,
name: 'Chrome',
},
{
test: /GSA/i,
name: 'Google Search',
},
/* Android Browser */
{
test: /android/i,
name: 'Android Browser',
},
/* PlayStation 4 */
{
test: /playstation 4/i,
name: 'PlayStation 4',
},
/* Safari */
{
test: /safari|applewebkit/i,
name: 'Safari',
},
];
let listOfSupportedBrowsers = ['Safari', 'Chrome', 'Firefox', 'Microsoft Edge'];
function bidRequestedHandler(args) {
let envelopeSourceCookieValue = storage.getCookie('_lr_env_src_ats');
let envelopeSource = envelopeSourceCookieValue === 'true';
let requests;
requests = args.bids.map(function(bid) {
return {
envelope_source: envelopeSource,
has_envelope: bid.userId ? !!bid.userId.idl_env : false,
bidder: bid.bidder,
bid_id: bid.bidId,
auction_id: args.auctionId,
user_browser: parseBrowser(),
user_platform: navigator.platform,
auction_start: new Date(args.auctionStart).toJSON(),
domain: window.location.hostname,
pid: atsAnalyticsAdapter.context.pid,
adapter_version: atsAnalyticsAdapterVersion,
bid_won: false
};
});
return requests;
}
function bidResponseHandler(args) {
return {
bid_id: args.requestId,
response_time_stamp: new Date(args.responseTimestamp).toJSON(),
currency: args.currency,
cpm: args.cpm,
net_revenue: args.netRevenue
};
}
export function parseBrowser() {
let ua = atsAnalyticsAdapter.getUserAgent();
try {
let result = browsersList.filter(function(obj) {
return obj.test.test(ua);
});
let browserName = result && result.length ? result[0].name : '';
return (listOfSupportedBrowsers.indexOf(browserName) >= 0) ? browserName : 'Unknown';
} catch (err) {
logError('ATS Analytics - Error while checking user browser!', err);
}
}
function sendDataToAnalytic (events) {
// send data to ats analytic endpoint
try {
let dataToSend = {'Data': events};
let strJSON = JSON.stringify(dataToSend);
logInfo('ATS Analytics - tried to send analytics data!');
ajax(analyticsUrl, function () {
logInfo('ATS Analytics - events sent successfully!');
}, strJSON, {method: 'POST', contentType: 'application/json'});
} catch (err) {
logError('ATS Analytics - request encounter an error: ', err);
}
}
// preflight request, to check did publisher have permission to send data to analytics endpoint
function preflightRequest (events) {
logInfo('ATS Analytics - preflight request!');
ajax(preflightUrl + atsAnalyticsAdapter.context.pid,
{
success: function (data) {
let samplingRateObject = JSON.parse(data);
logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject);
let samplingRate = samplingRateObject.samplingRate;
atsAnalyticsAdapter.setSamplingCookie(samplingRate);
let samplingRateNumber = Number(samplingRate);
if (data && samplingRate && atsAnalyticsAdapter.shouldFireRequest(samplingRateNumber)) {
logInfo('ATS Analytics - events to send: ', events);
sendDataToAnalytic(events);
}
},
error: function () {
atsAnalyticsAdapter.setSamplingCookie(0);
logInfo('ATS Analytics - Sampling Rate Request Error!');
}
}, undefined, {method: 'GET', crossOrigin: true});
}
let atsAnalyticsAdapter = Object.assign(adapter(
{
analyticsType
}),
{
track({eventType, args}) {
if (typeof args !== 'undefined') {
atsAnalyticsAdapter.callHandler(eventType, args);
}
}
});
// save the base class function
atsAnalyticsAdapter.originEnableAnalytics = atsAnalyticsAdapter.enableAnalytics;
// add check to not fire request every time, but instead to send 1/100
atsAnalyticsAdapter.shouldFireRequest = function (samplingRate) {
if (samplingRate !== 0) {
let shouldFireRequestValue = (Math.floor((Math.random() * 100 + 1)) === 100);
logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue);
return shouldFireRequestValue;
} else {
logInfo('ATS Analytics - Should Fire Request: ', false);
return false;
}
};
atsAnalyticsAdapter.getUserAgent = function () {
return window.navigator.userAgent;
};
atsAnalyticsAdapter.setSamplingCookie = function (samplRate) {
const now = new Date();
now.setTime(now.getTime() + 604800000);
storage.setCookie('_lr_sampling_rate', samplRate, now.toUTCString());
}
// override enableAnalytics so we can get access to the config passed in from the page
atsAnalyticsAdapter.enableAnalytics = function (config) {
if (!config.options.pid) {
logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work');
return;
}
atsAnalyticsAdapter.context = {
events: [],
pid: config.options.pid,
bidWonTimeout: config.options.bidWonTimeout
};
let initOptions = config.options;
logInfo('ATS Analytics - adapter enabled! ');
atsAnalyticsAdapter.originEnableAnalytics(initOptions); // call the base class function
};
atsAnalyticsAdapter.callHandler = function (evtype, args) {
if (evtype === EVENTS.BID_REQUESTED) {
handlerRequest = handlerRequest.concat(bidRequestedHandler(args));
} else if (evtype === EVENTS.BID_RESPONSE) {
handlerResponse.push(bidResponseHandler(args));
}
if (evtype === EVENTS.AUCTION_END) {
let bidWonTimeout = atsAnalyticsAdapter.context.bidWonTimeout ? atsAnalyticsAdapter.context.bidWonTimeout : 2000;
let events = [];
setTimeout(() => {
let winningBids = getGlobal().getAllWinningBids();
logInfo('ATS Analytics - winning bids: ', winningBids)
// prepare format data for sending to analytics endpoint
if (handlerRequest.length) {
let wonEvent = {};
if (handlerResponse.length) {
events = handlerRequest.filter(request => handlerResponse.filter(function (response) {
if (request.bid_id === response.bid_id) {
Object.assign(request, response);
}
}));
if (winningBids.length) {
events = events.filter(event => winningBids.filter(function (won) {
wonEvent.bid_id = won.requestId;
wonEvent.bid_won = true;
if (event.bid_id === wonEvent.bid_id) {
Object.assign(event, wonEvent);
}
}))
}
} else {
events = handlerRequest;
}
// check should we send data to analytics or not, check first cookie value _lr_sampling_rate
try {
let samplingRateCookie = storage.getCookie('_lr_sampling_rate');
if (!samplingRateCookie) {
preflightRequest(events);
} else {
if (atsAnalyticsAdapter.shouldFireRequest(parseInt(samplingRateCookie))) {
logInfo('ATS Analytics - events to send: ', events);
sendDataToAnalytic(events);
}
}
// empty events array to not send duplicate events
events = [];
} catch (err) {
logError('ATS Analytics - preflight request encounter an error: ', err);
}
}
}, bidWonTimeout);
}
}
adaptermanager.registerAnalyticsAdapter({
adapter: atsAnalyticsAdapter,
code: MODULE_CODE,
gvlid: 97
});
export default atsAnalyticsAdapter;