forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadxpremiumAnalyticsAdapter.js
271 lines (240 loc) · 8.31 KB
/
adxpremiumAnalyticsAdapter.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
import {deepClone, logError, logInfo} from '../src/utils.js';
import {ajax} from '../src/ajax.js';
import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js';
import adapterManager from '../src/adapterManager.js';
import { EVENTS } from '../src/constants.js';
import {includes} from '../src/polyfill.js';
const analyticsType = 'endpoint';
const defaultUrl = 'https://adxpremium.services/graphql';
let reqCountry = window.reqCountry || null;
// Events needed
const {
AUCTION_INIT,
BID_REQUESTED,
BID_TIMEOUT,
BID_RESPONSE,
BID_WON,
AUCTION_END
} = EVENTS;
let timeoutBased = false;
let requestSent = false;
let requestDelivered = false;
let elementIds = [];
// Memory objects
let completeObject = {
publisher_id: null,
auction_id: null,
referer: null,
screen_resolution: window.screen.width + 'x' + window.screen.height,
device_type: null,
geo: reqCountry,
events: []
};
// Upgraded object
let upgradedObject = null;
let adxpremiumAnalyticsAdapter = Object.assign(adapter({ defaultUrl, analyticsType }), {
track({ eventType, args }) {
switch (eventType) {
case AUCTION_INIT:
auctionInit(args);
break;
case BID_REQUESTED:
bidRequested(args);
break;
case BID_RESPONSE:
bidResponse(args);
break;
case BID_WON:
bidWon(args);
break;
case BID_TIMEOUT:
bidTimeout(args);
break;
case AUCTION_END:
auctionEnd(args);
break;
default:
break;
}
}
});
// DFP support
let googletag = window.googletag || {};
googletag.cmd = googletag.cmd || [];
googletag.cmd.push(function() {
googletag.pubads().addEventListener('slotRenderEnded', args => {
clearSlot(args.slot.getSlotElementId());
});
});
// Event handlers
let bidResponsesMapper = {};
let bidRequestsMapper = {};
let bidMapper = {};
function auctionInit(args) {
// Clear events
completeObject.events = [];
// Allow new requests
requestSent = false;
requestDelivered = false;
// Reset mappers
bidResponsesMapper = {};
bidRequestsMapper = {};
bidMapper = {};
completeObject.auction_id = args.auctionId;
completeObject.publisher_id = adxpremiumAnalyticsAdapter.initOptions.pubId;
// TODO: is 'page' the right value here?
try { completeObject.referer = encodeURI(args.bidderRequests[0].refererInfo.page.split('?')[0]); } catch (e) { logError('AdxPremium Analytics - ' + e.message); }
if (args.adUnitCodes && args.adUnitCodes.length > 0) {
elementIds = args.adUnitCodes;
}
completeObject.device_type = deviceType();
}
function bidRequested(args) {
let tmpObject = {
type: 'REQUEST',
bidder_code: args.bidderCode,
event_timestamp: args.start,
bid_gpt_codes: {}
};
args.bids.forEach(bid => {
tmpObject.bid_gpt_codes[bid.adUnitCode] = bid.sizes;
bidMapper[bid.bidId] = bid.bidderRequestId;
});
bidRequestsMapper[args.bidderRequestId] = completeObject.events.push(tmpObject) - 1;
}
function bidResponse(args) {
let tmpObject = {
type: 'RESPONSE',
bidder_code: args.bidderCode,
event_timestamp: args.responseTimestamp,
size: args.size,
gpt_code: args.adUnitCode,
currency: args.currency,
creative_id: args.creativeId,
time_to_respond: args.timeToRespond,
cpm: args.cpm,
is_winning: false
};
bidResponsesMapper[args.requestId] = completeObject.events.push(tmpObject) - 1;
}
function bidWon(args) {
let eventIndex = bidResponsesMapper[args.requestId];
if (eventIndex !== undefined) {
if (requestDelivered) {
if (completeObject.events[eventIndex]) {
// do the upgrade
logInfo('AdxPremium Analytics - Upgrading request');
completeObject.events[eventIndex].is_winning = true;
completeObject.events[eventIndex].is_upgrade = true;
upgradedObject = deepClone(completeObject);
upgradedObject.events = [completeObject.events[eventIndex]];
sendEvent(upgradedObject); // send upgrade
} else {
logInfo('AdxPremium Analytics - CANNOT FIND INDEX FOR REQUEST ' + args.requestId);
}
} else {
completeObject.events[eventIndex].is_winning = true;
}
} else {
logInfo('AdxPremium Analytics - Response not found, creating new one.');
let tmpObject = {
type: 'RESPONSE',
bidder_code: args.bidderCode,
event_timestamp: args.responseTimestamp,
size: args.size,
gpt_code: args.adUnitCode,
currency: args.currency,
creative_id: args.creativeId,
time_to_respond: args.timeToRespond,
cpm: args.cpm,
is_winning: true,
is_lost: true
};
let lostObject = deepClone(completeObject);
lostObject.events = [tmpObject];
sendEvent(lostObject); // send lost object
}
}
function bidTimeout(args) {
let timeoutObject = deepClone(completeObject);
timeoutObject.events = [];
let usedRequestIds = [];
args.forEach(bid => {
let pulledRequestId = bidMapper[bid.bidId];
let eventIndex = bidRequestsMapper[pulledRequestId];
if (eventIndex !== undefined && completeObject.events[eventIndex] && usedRequestIds.indexOf(pulledRequestId) == -1) {
// mark as timeouted
let tempEventIndex = timeoutObject.events.push(completeObject.events[eventIndex]) - 1;
timeoutObject.events[tempEventIndex]['type'] = 'TIMEOUT';
usedRequestIds.push(pulledRequestId); // mark as used
}
});
if (timeoutObject.events.length > 0) {
sendEvent(timeoutObject); // send timeouted
logInfo('AdxPremium Analytics - Sending timeouted requests');
}
}
function auctionEnd(args) {
logInfo('AdxPremium Analytics - Auction Ended at ' + Date.now());
if (timeoutBased) { setTimeout(function () { requestSent = true; sendEvent(completeObject); }, 3500); } else { sendEventFallback(); }
}
// Methods
function deviceType() {
if ((/ipad|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(navigator.userAgent.toLowerCase()))) {
return 'tablet';
}
if ((/iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/i.test(navigator.userAgent.toLowerCase()))) {
return 'mobile';
}
return 'desktop';
}
function clearSlot(elementId) {
if (includes(elementIds, elementId)) { elementIds.splice(elementIds.indexOf(elementId), 1); logInfo('AdxPremium Analytics - Done with: ' + elementId); }
if (elementIds.length == 0 && !requestSent && !timeoutBased) {
requestSent = true;
sendEvent(completeObject);
logInfo('AdxPremium Analytics - Everything ready');
}
}
export function testSend() {
sendEvent(completeObject);
logInfo('AdxPremium Analytics - Sending without any conditions, used for testing');
}
function sendEventFallback() {
setTimeout(function () {
if (!requestSent) { requestSent = true; sendEvent(completeObject); logInfo('AdxPremium Analytics - Sending event using fallback method.'); }
}, 2000);
}
function sendEvent(completeObject) {
if (!adxpremiumAnalyticsAdapter.enabled) return;
requestDelivered = true;
try {
let responseEvents = btoa(JSON.stringify(completeObject));
let mutation = `mutation {createEvent(input: {event: {eventData: "${responseEvents}"}}) {event {createTime } } }`;
let dataToSend = JSON.stringify({ query: mutation });
let ajaxEndpoint = defaultUrl;
if (adxpremiumAnalyticsAdapter.initOptions.sid) {
ajaxEndpoint = 'https://' + adxpremiumAnalyticsAdapter.initOptions.sid + '.adxpremium.services/graphql'
}
ajax(ajaxEndpoint, function () { logInfo('AdxPremium Analytics - Sending complete events at ' + Date.now()) }, dataToSend, {
contentType: 'application/json',
method: 'POST'
});
} catch (err) { logError('AdxPremium Analytics - Sending event error: ' + err); }
}
// save the base class function
adxpremiumAnalyticsAdapter.originEnableAnalytics = adxpremiumAnalyticsAdapter.enableAnalytics;
// override enableAnalytics so we can get access to the config passed in from the page
adxpremiumAnalyticsAdapter.enableAnalytics = function (config) {
adxpremiumAnalyticsAdapter.initOptions = config.options;
if (!config.options.pubId) {
logError('AdxPremium Analytics - Publisher ID (pubId) option is not defined. Analytics won\'t work');
return;
}
adxpremiumAnalyticsAdapter.originEnableAnalytics(config); // call the base class function
};
adapterManager.registerAnalyticsAdapter({
adapter: adxpremiumAnalyticsAdapter,
code: 'adxpremium'
});
export default adxpremiumAnalyticsAdapter;