forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonetagBidAdapter.js
448 lines (420 loc) · 14.2 KB
/
onetagBidAdapter.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
'use strict';
import { BANNER, VIDEO } from '../src/mediaTypes.js';
import { INSTREAM, OUTSTREAM } from '../src/video.js';
import { Renderer } from '../src/Renderer.js';
import { find } from '../src/polyfill.js';
import { getStorageManager } from '../src/storageManager.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { deepClone, logError, deepAccess } from '../src/utils.js';
/**
* @typedef {import('../src/adapters/bidderFactory.js').BidRequest} BidRequest
* @typedef {import('../src/adapters/bidderFactory.js').validBidRequests} validBidRequests
*/
const ENDPOINT = 'https://onetag-sys.com/prebid-request';
const USER_SYNC_ENDPOINT = 'https://onetag-sys.com/usync/';
const BIDDER_CODE = 'onetag';
const GVLID = 241;
const storage = getStorageManager({ bidderCode: BIDDER_CODE });
/**
* Determines whether or not the given bid request is valid.
*
* @param {BidRequest} bid The bid params to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
function isBidRequestValid(bid) {
if (typeof bid === 'undefined' || typeof bid.params === 'undefined' || typeof bid.params.pubId !== 'string') {
return false;
}
return isValid(BANNER, bid) || isValid(VIDEO, bid);
}
export function hasTypeVideo(bid) {
return typeof bid.mediaTypes !== 'undefined' && typeof bid.mediaTypes.video !== 'undefined';
}
export function isValid(type, bid) {
if (type === BANNER) {
return parseSizes(bid).length > 0;
} else if (type === VIDEO && hasTypeVideo(bid)) {
const context = bid.mediaTypes.video.context;
if (context === 'outstream' || context === 'instream') {
return parseVideoSize(bid).length > 0;
}
}
return false;
}
/**
* Make a server request from the list of BidRequests.
*
* @param {validBidRequests[]} - an array of bids
* @return ServerRequest Info describing the request to the server.
*/
function buildRequests(validBidRequests, bidderRequest) {
const payload = {
bids: requestsToBids(validBidRequests),
...getPageInfo(bidderRequest)
};
if (bidderRequest && bidderRequest.gdprConsent) {
payload.gdprConsent = {
consentString: bidderRequest.gdprConsent.consentString,
consentRequired: bidderRequest.gdprConsent.gdprApplies,
addtlConsent: bidderRequest.gdprConsent.addtlConsent
};
}
if (bidderRequest && bidderRequest.gppConsent) {
payload.gppConsent = {
consentString: bidderRequest.gppConsent.gppString,
applicableSections: bidderRequest.gppConsent.applicableSections
}
}
if (bidderRequest && bidderRequest.uspConsent) {
payload.usPrivacy = bidderRequest.uspConsent;
}
if (bidderRequest && bidderRequest.ortb2) {
payload.ortb2 = bidderRequest.ortb2;
}
if (validBidRequests && validBidRequests.length !== 0 && validBidRequests[0].userIdAsEids) {
payload.userId = validBidRequests[0].userIdAsEids;
}
if (validBidRequests && validBidRequests.length !== 0 && validBidRequests[0].schain && isSchainValid(validBidRequests[0].schain)) {
payload.schain = validBidRequests[0].schain;
}
try {
if (storage.hasLocalStorage()) {
payload.onetagSid = storage.getDataFromLocalStorage('onetag_sid');
}
} catch (e) { }
const connection = navigator.connection || navigator.webkitConnection;
payload.networkConnectionType = (connection && connection.type) ? connection.type : null;
payload.networkEffectiveConnectionType = (connection && connection.effectiveType) ? connection.effectiveType : null;
payload.fledgeEnabled = Boolean(bidderRequest?.paapi?.enabled)
return {
method: 'POST',
url: ENDPOINT,
data: JSON.stringify(payload)
}
}
function interpretResponse(serverResponse, bidderRequest) {
const body = serverResponse.body;
const bids = [];
const requestData = JSON.parse(bidderRequest.data);
if (!body || (body.nobid && body.nobid === true)) {
return bids;
}
if (!body.fledgeAuctionConfigs && (!body.bids || !Array.isArray(body.bids) || body.bids.length === 0)) {
return bids;
}
Array.isArray(body.bids) && body.bids.forEach(bid => {
const responseBid = {
requestId: bid.requestId,
cpm: bid.cpm,
width: bid.width,
height: bid.height,
creativeId: bid.creativeId,
dealId: bid.dealId == null ? bid.dealId : '',
currency: bid.currency,
netRevenue: bid.netRevenue || false,
mediaType: bid.mediaType,
meta: {
mediaType: bid.mediaType,
advertiserDomains: bid.adomain
},
ttl: bid.ttl || 300
};
if (bid.dsa) {
responseBid.meta.dsa = bid.dsa;
}
if (bid.mediaType === BANNER) {
responseBid.ad = bid.ad;
} else if (bid.mediaType === VIDEO) {
const { context, adUnitCode } = find(requestData.bids, (item) =>
item.bidId === bid.requestId &&
item.type === VIDEO
);
if (context === INSTREAM) {
responseBid.vastUrl = bid.vastUrl;
responseBid.videoCacheKey = bid.videoCacheKey;
} else if (context === OUTSTREAM) {
responseBid.vastXml = bid.ad;
responseBid.vastUrl = bid.vastUrl;
if (bid.rendererUrl) {
responseBid.renderer = createRenderer({ ...bid, adUnitCode });
}
}
}
bids.push(responseBid);
});
if (body.fledgeAuctionConfigs && Array.isArray(body.fledgeAuctionConfigs)) {
const fledgeAuctionConfigs = body.fledgeAuctionConfigs
return {
bids,
paapi: fledgeAuctionConfigs,
}
} else {
return bids;
}
}
function createRenderer(bid, rendererOptions = {}) {
const renderer = Renderer.install({
id: bid.requestId,
url: bid.rendererUrl,
config: rendererOptions,
adUnitCode: bid.adUnitCode,
loaded: false
});
try {
renderer.setRender(({ renderer, width, height, vastXml, adUnitCode }) => {
renderer.push(() => {
window.onetag.Player.init({
...bid,
width,
height,
vastXml,
nodeId: adUnitCode,
config: renderer.getConfig()
});
});
});
} catch (e) {
}
return renderer;
}
function getFrameNesting() {
let topmostFrame = window;
let parent = window.parent;
try {
while (topmostFrame !== topmostFrame.parent) {
parent = topmostFrame.parent;
// eslint-disable-next-line no-unused-expressions
parent.location.href;
topmostFrame = topmostFrame.parent;
}
} catch (e) { }
return topmostFrame;
}
function getDocumentVisibility(window) {
try {
if (typeof window.document.hidden !== 'undefined') {
return window.document.hidden;
} else if (typeof window.document['msHidden'] !== 'undefined') {
return window.document['msHidden'];
} else if (typeof window.document['webkitHidden'] !== 'undefined') {
return window.document['webkitHidden'];
} else {
return null;
}
} catch (e) {
return null;
}
}
/**
* Returns information about the page needed by the server in an object to be converted in JSON
* @returns {{location: *, referrer: (*|string), stack: (*|Array.<String>), numIframes: (*|Number), wWidth: (*|Number), wHeight: (*|Number), sWidth, sHeight, date: string, timeOffset: number}}
*/
function getPageInfo(bidderRequest) {
const topmostFrame = getFrameNesting();
return {
location: deepAccess(bidderRequest, 'refererInfo.page', null),
referrer: deepAccess(bidderRequest, 'refererInfo.ref', null),
stack: deepAccess(bidderRequest, 'refererInfo.stack', []),
numIframes: deepAccess(bidderRequest, 'refererInfo.numIframes', 0),
wWidth: topmostFrame.innerWidth,
wHeight: topmostFrame.innerHeight,
oWidth: topmostFrame.outerWidth,
oHeight: topmostFrame.outerHeight,
sWidth: topmostFrame.screen.width,
sHeight: topmostFrame.screen.height,
aWidth: topmostFrame.screen.availWidth,
aHeight: topmostFrame.screen.availHeight,
sLeft: 'screenLeft' in topmostFrame ? topmostFrame.screenLeft : topmostFrame.screenX,
sTop: 'screenTop' in topmostFrame ? topmostFrame.screenTop : topmostFrame.screenY,
xOffset: topmostFrame.pageXOffset,
yOffset: topmostFrame.pageYOffset,
docHidden: getDocumentVisibility(topmostFrame),
docHeight: topmostFrame.document.body ? topmostFrame.document.body.scrollHeight : null,
hLength: history.length,
timing: getTiming(),
version: {
prebid: '$prebid.version$',
adapter: '1.1.1'
}
};
}
function requestsToBids(bidRequests) {
const videoBidRequests = bidRequests.filter(bidRequest => hasTypeVideo(bidRequest)).map(bidRequest => {
const videoObj = {};
setGeneralInfo.call(videoObj, bidRequest);
// Pass parameters
// Context: instream - outstream - adpod
videoObj['context'] = bidRequest.mediaTypes.video.context;
// Sizes
videoObj['playerSize'] = parseVideoSize(bidRequest);
// Other params
videoObj['mediaTypeInfo'] = deepClone(bidRequest.mediaTypes.video);
videoObj['type'] = VIDEO;
videoObj['priceFloors'] = getBidFloor(bidRequest, VIDEO, videoObj['playerSize']);
return videoObj;
});
const bannerBidRequests = bidRequests.filter(bidRequest => isValid(BANNER, bidRequest)).map(bidRequest => {
const bannerObj = {};
setGeneralInfo.call(bannerObj, bidRequest);
bannerObj['sizes'] = parseSizes(bidRequest);
bannerObj['type'] = BANNER;
bannerObj['mediaTypeInfo'] = deepClone(bidRequest.mediaTypes.banner);
bannerObj['priceFloors'] = getBidFloor(bidRequest, BANNER, bannerObj['sizes']);
return bannerObj;
});
return videoBidRequests.concat(bannerBidRequests);
}
function setGeneralInfo(bidRequest) {
const params = bidRequest.params;
this['adUnitCode'] = bidRequest.adUnitCode;
this['bidId'] = bidRequest.bidId;
this['bidderRequestId'] = bidRequest.bidderRequestId;
this['auctionId'] = deepAccess(bidRequest, 'ortb2.source.tid');
this['transactionId'] = deepAccess(bidRequest, 'ortb2Imp.ext.tid');
this['gpid'] = deepAccess(bidRequest, 'ortb2Imp.ext.gpid') || deepAccess(bidRequest, 'ortb2Imp.ext.data.pbadslot');
this['pubId'] = params.pubId;
this['ext'] = params.ext;
this['ortb2Imp'] = deepAccess(bidRequest, 'ortb2Imp');
if (params.pubClick) {
this['click'] = params.pubClick;
}
if (params.dealId) {
this['dealId'] = params.dealId;
}
const coords = getSpaceCoords(bidRequest.adUnitCode);
if (coords) {
this['coords'] = coords;
}
}
function getSpaceCoords(id) {
const space = document.getElementById(id);
try {
const { top, left, width, height } = space.getBoundingClientRect();
let window = space.ownerDocument.defaultView;
const coords = { top: top + window.pageYOffset, left: left + window.pageXOffset, width, height };
let frame = window.frameElement;
while (frame != null) {
const { top, left } = frame.getBoundingClientRect();
coords.top += top + window.pageYOffset;
coords.left += left + window.pageXOffset;
window = window.parent;
frame = window.frameElement;
}
return coords;
} catch (e) {
return null;
}
}
function getTiming() {
try {
if (window.performance != null && window.performance.timing != null) {
const timing = {};
const perf = window.performance.timing;
timing.pageLoadTime = perf.loadEventEnd - perf.navigationStart;
timing.connectTime = perf.responseEnd - perf.requestStart;
timing.renderTime = perf.domComplete - perf.domLoading;
return timing;
}
} catch (e) {
return null;
}
return null;
}
function parseVideoSize(bid) {
const playerSize = bid.mediaTypes.video.playerSize;
if (typeof playerSize !== 'undefined' && Array.isArray(playerSize) && playerSize.length > 0) {
return getSizes(playerSize)
}
return [];
}
function parseSizes(bid) {
let ret = [];
if (typeof bid.mediaTypes !== 'undefined' && typeof bid.mediaTypes.banner !== 'undefined' && typeof bid.mediaTypes.banner.sizes !== 'undefined' && Array.isArray(bid.mediaTypes.banner.sizes) && bid.mediaTypes.banner.sizes.length > 0) {
return getSizes(bid.mediaTypes.banner.sizes)
}
const isVideoBidRequest = hasTypeVideo(bid);
if (!isVideoBidRequest && bid.sizes && Array.isArray(bid.sizes)) {
return getSizes(bid.sizes);
}
return ret;
}
function getSizes(sizes) {
const ret = [];
for (let i = 0; i < sizes.length; i++) {
const size = sizes[i];
ret.push({ width: size[0], height: size[1] })
}
return ret;
}
function getUserSyncs(syncOptions, serverResponses, gdprConsent, uspConsent, gppConsent) {
let syncs = [];
let params = '';
if (gdprConsent) {
if (typeof gdprConsent.gdprApplies === 'boolean') {
params += '&gdpr=' + (gdprConsent.gdprApplies ? 1 : 0);
}
if (typeof gdprConsent.consentString === 'string') {
params += '&gdpr_consent=' + gdprConsent.consentString;
}
}
if (gppConsent) {
if (typeof gppConsent.gppString === 'string') {
params += '&gpp_consent=' + gppConsent.gppString;
}
}
if (uspConsent && typeof uspConsent === 'string') {
params += '&us_privacy=' + uspConsent;
}
if (syncOptions.iframeEnabled) {
syncs.push({
type: 'iframe',
url: USER_SYNC_ENDPOINT + '?cb=' + new Date().getTime() + params
});
}
if (syncOptions.pixelEnabled) {
syncs.push({
type: 'image',
url: USER_SYNC_ENDPOINT + '?tag=img' + params
});
}
return syncs;
}
function getBidFloor(bidRequest, mediaType, sizes) {
const priceFloors = [];
if (typeof bidRequest.getFloor === 'function') {
sizes.forEach(size => {
const floor = bidRequest.getFloor({
currency: 'EUR',
mediaType: mediaType || '*',
size: [size.width, size.height]
}) || {};
floor.size = deepClone(size);
if (!floor.floor) { floor.floor = null; }
priceFloors.push(floor);
});
}
return priceFloors;
}
export function isSchainValid(schain) {
let isValid = false;
const requiredFields = ['asi', 'sid', 'hp'];
if (!schain || !schain.nodes) return isValid;
isValid = schain.nodes.reduce((status, node) => {
if (!status) return status;
return requiredFields.every(field => node.hasOwnProperty(field));
}, true);
if (!isValid) {
logError('OneTag: required schain params missing');
}
return isValid;
}
export const spec = {
code: BIDDER_CODE,
gvlid: GVLID,
supportedMediaTypes: [BANNER, VIDEO],
isBidRequestValid: isBidRequestValid,
buildRequests: buildRequests,
interpretResponse: interpretResponse,
getUserSyncs: getUserSyncs
};
registerBidder(spec);