-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
medianetBidAdapter.js
557 lines (493 loc) · 16.4 KB
/
medianetBidAdapter.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import {
buildUrl,
deepAccess,
getWindowTop,
isArray,
isEmpty,
isEmptyStr,
isStr,
logError,
logInfo,
triggerPixel
} from '../src/utils.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {config} from '../src/config.js';
import {BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js';
import {getRefererInfo} from '../src/refererDetection.js';
import {Renderer} from '../src/Renderer.js';
import { convertOrtbRequestToProprietaryNative } from '../src/native.js';
import {getGlobal} from '../src/prebidGlobal.js';
import {getGptSlotInfoForAdUnitCode} from '../libraries/gptUtils/gptUtils.js';
/**
* @typedef {import('../src/adapters/bidderFactory.js').BidRequest} BidRequest
* @typedef {import('../src/adapters/bidderFactory.js').Bid} Bid
* @typedef {import('../src/adapters/bidderFactory.js').TimedOutBid} TimedOutBid
*/
const BIDDER_CODE = 'medianet';
const TRUSTEDSTACK_CODE = 'trustedstack';
const BID_URL = 'https://prebid.media.net/rtb/prebid';
const TRUSTEDSTACK_URL = 'https://prebid.trustedstack.com/rtb/trustedstack';
const PLAYER_URL = 'https://prebid.media.net/video/bundle.js';
const SLOT_VISIBILITY = {
NOT_DETERMINED: 0,
ABOVE_THE_FOLD: 1,
BELOW_THE_FOLD: 2
};
const EVENTS = {
TIMEOUT_EVENT_NAME: 'client_timeout',
BID_WON_EVENT_NAME: 'client_bid_won'
};
const EVENT_PIXEL_URL = 'qsearch-a.akamaihd.net/log';
const OUTSTREAM = 'outstream';
// TODO: this should be picked from bidderRequest
let refererInfo = getRefererInfo();
let mnData = {};
window.mnet = window.mnet || {};
window.mnet.queue = window.mnet.queue || [];
mnData.urlData = {
domain: refererInfo.domain,
page: refererInfo.page,
isTop: refererInfo.reachedTop
};
const aliases = [
{ code: TRUSTEDSTACK_CODE, gvlid: 1288 },
];
getGlobal().medianetGlobals = getGlobal().medianetGlobals || {};
function getTopWindowReferrer() {
try {
return window.top.document.referrer;
} catch (e) {
return document.referrer;
}
}
function siteDetails(site, bidderRequest) {
const urlData = bidderRequest.refererInfo;
site = site || {};
let siteData = {
domain: site.domain || urlData.domain,
page: site.page || urlData.page,
ref: site.ref || getTopWindowReferrer(),
topMostLocation: urlData.topmostLocation,
isTop: site.isTop || urlData.reachedTop
};
return Object.assign(siteData, getPageMeta());
}
function getPageMeta() {
if (mnData.pageMeta) {
return mnData.pageMeta;
}
let canonicalUrl = getUrlFromSelector('link[rel="canonical"]', 'href');
let ogUrl = getUrlFromSelector('meta[property="og:url"]', 'content');
let twitterUrl = getUrlFromSelector('meta[name="twitter:url"]', 'content');
mnData.pageMeta = Object.assign({},
canonicalUrl && { 'canonical_url': canonicalUrl },
ogUrl && { 'og_url': ogUrl },
twitterUrl && { 'twitter_url': twitterUrl }
);
return mnData.pageMeta;
}
function getUrlFromSelector(selector, attribute) {
let attr = getAttributeFromSelector(selector, attribute);
return attr && getAbsoluteUrl(attr);
}
function getAttributeFromSelector(selector, attribute) {
try {
let doc = getWindowTop().document;
let element = doc.querySelector(selector);
if (element !== null && element[attribute]) {
return element[attribute];
}
} catch (e) {}
}
function getAbsoluteUrl(url) {
let aTag = getWindowTop().document.createElement('a');
aTag.href = url;
return aTag.href;
}
function filterUrlsByType(urls, type) {
return urls.filter(url => url.type === type);
}
function transformSizes(sizes) {
if (isArray(sizes) && sizes.length === 2 && !isArray(sizes[0])) {
return [getSize(sizes)];
}
return sizes.map(size => getSize(size))
}
function getSize(size) {
return {
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
}
}
function getWindowSize() {
return {
w: window.screen.width || -1,
h: window.screen.height || -1
}
}
function getCoordinates(adUnitCode) {
let element = document.getElementById(adUnitCode);
if (!element && adUnitCode.indexOf('/') !== -1) {
// now it means that adUnitCode is GAM AdUnitPath
const {divId} = getGptSlotInfoForAdUnitCode(adUnitCode);
if (isStr(divId)) {
element = document.getElementById(divId);
}
}
if (element && element.getBoundingClientRect) {
const rect = element.getBoundingClientRect();
let coordinates = {};
coordinates.top_left = {
y: rect.top,
x: rect.left
};
coordinates.bottom_right = {
y: rect.bottom,
x: rect.right
};
return coordinates
}
return null;
}
function extParams(bidRequest, bidderRequests) {
const params = deepAccess(bidRequest, 'params');
const gdpr = deepAccess(bidderRequests, 'gdprConsent');
const uspConsent = deepAccess(bidderRequests, 'uspConsent');
const userId = deepAccess(bidRequest, 'userId');
const sChain = deepAccess(bidRequest, 'schain') || {};
const windowSize = spec.getWindowSize();
const gdprApplies = !!(gdpr && gdpr.gdprApplies);
const uspApplies = !!(uspConsent);
const coppaApplies = !!(config.getConfig('coppa'));
return Object.assign({},
{ customer_id: params.cid },
{ prebid_version: 'v' + '$prebid.version$' },
{ gdpr_applies: gdprApplies },
(gdprApplies) && { gdpr_consent_string: gdpr.consentString || '' },
{ usp_applies: uspApplies },
uspApplies && { usp_consent_string: uspConsent || '' },
{coppa_applies: coppaApplies},
windowSize.w !== -1 && windowSize.h !== -1 && { screen: windowSize },
userId && { user_id: userId },
getGlobal().medianetGlobals.analyticsEnabled && { analytics: true },
!isEmpty(sChain) && {schain: sChain}
);
}
function slotParams(bidRequest, bidderRequests) {
// check with Media.net Account manager for bid floor and crid parameters
let params = {
id: bidRequest.bidId,
transactionId: bidRequest.ortb2Imp?.ext?.tid,
ext: {
dfp_id: bidRequest.adUnitCode,
display_count: bidRequest.bidRequestsCount
},
all: bidRequest.params
};
if (bidRequest.ortb2Imp) {
params.ortb2Imp = bidRequest.ortb2Imp;
}
let bannerSizes = deepAccess(bidRequest, 'mediaTypes.banner.sizes') || [];
const videoInMediaType = deepAccess(bidRequest, 'mediaTypes.video') || {};
const videoInParams = deepAccess(bidRequest, 'params.video') || {};
const videoCombinedObj = Object.assign({}, videoInParams, videoInMediaType);
if (!isEmpty(videoCombinedObj)) {
params.video = videoCombinedObj;
}
if (bannerSizes.length > 0) {
params.banner = transformSizes(bannerSizes);
}
if (bidRequest.nativeParams) {
try {
params.native = JSON.stringify(bidRequest.nativeParams);
} catch (e) {
logError((`${BIDDER_CODE} : Incorrect JSON : bidRequest.nativeParams`));
}
}
if (bidRequest.params.crid) {
params.tagid = bidRequest.params.crid.toString();
}
let bidFloor = parseFloat(bidRequest.params.bidfloor || bidRequest.params.bidFloor);
if (bidFloor) {
params.bidfloor = bidFloor;
}
const coordinates = getCoordinates(bidRequest.adUnitCode);
if (coordinates && params.banner && params.banner.length !== 0) {
let normCoordinates = normalizeCoordinates(coordinates);
params.ext.coordinates = normCoordinates;
params.ext.viewability = getSlotVisibility(coordinates.top_left, getMinSize(params.banner));
if (getSlotVisibility(normCoordinates.top_left, getMinSize(params.banner)) > 0.5) {
params.ext.visibility = SLOT_VISIBILITY.ABOVE_THE_FOLD;
} else {
params.ext.visibility = SLOT_VISIBILITY.BELOW_THE_FOLD;
}
} else {
params.ext.visibility = SLOT_VISIBILITY.NOT_DETERMINED;
}
const floorInfo = getBidFloorByType(bidRequest);
if (floorInfo && floorInfo.length > 0) {
params.bidfloors = floorInfo;
}
if (bidderRequests.paapi?.enabled) {
params.ext.ae = bidRequest?.ortb2Imp?.ext?.ae;
}
return params;
}
function getBidFloorByType(bidRequest) {
let floorInfo = [];
if (typeof bidRequest.getFloor === 'function') {
[BANNER, VIDEO, NATIVE].forEach(mediaType => {
if (bidRequest.mediaTypes.hasOwnProperty(mediaType)) {
if (mediaType == BANNER) {
bidRequest.mediaTypes.banner.sizes.forEach(
size => {
setFloorInfo(bidRequest, mediaType, size, floorInfo)
}
)
} else {
setFloorInfo(bidRequest, mediaType, '*', floorInfo)
}
}
});
}
return floorInfo;
}
function setFloorInfo(bidRequest, mediaType, size, floorInfo) {
let floor = bidRequest.getFloor({currency: 'USD', mediaType: mediaType, size: size});
if (size.length > 1) floor.size = size;
floor.mediaType = mediaType;
floorInfo.push(floor);
}
function getMinSize(sizes) {
return sizes.reduce((min, size) => size.h * size.w < min.h * min.w ? size : min);
}
function getSlotVisibility(topLeft, size) {
let maxArea = size.w * size.h;
let windowSize = spec.getWindowSize();
let bottomRight = {
x: topLeft.x + size.w,
y: topLeft.y + size.h
};
if (maxArea === 0 || windowSize.w === -1 || windowSize.h === -1) {
return 0;
}
return getOverlapArea(topLeft, bottomRight, {x: 0, y: 0}, {x: windowSize.w, y: windowSize.h}) / maxArea;
}
// find the overlapping area between two rectangles
function getOverlapArea(topLeft1, bottomRight1, topLeft2, bottomRight2) {
// If no overlap, return 0
if ((topLeft1.x > bottomRight2.x || bottomRight1.x < topLeft2.x) || (topLeft1.y > bottomRight2.y || bottomRight1.y < topLeft2.y)) {
return 0;
}
// return overlapping area : [ min of rightmost/bottommost co-ordinates ] - [ max of leftmost/topmost co-ordinates ]
return ((Math.min(bottomRight1.x, bottomRight2.x) - Math.max(topLeft1.x, topLeft2.x)) * (Math.min(bottomRight1.y, bottomRight2.y) - Math.max(topLeft1.y, topLeft2.y)));
}
function normalizeCoordinates(coordinates) {
return {
top_left: {
x: coordinates.top_left.x + window.pageXOffset,
y: coordinates.top_left.y + window.pageYOffset,
},
bottom_right: {
x: coordinates.bottom_right.x + window.pageXOffset,
y: coordinates.bottom_right.y + window.pageYOffset,
}
}
}
function getBidderURL(bidderCode, cid) {
const url = (bidderCode === TRUSTEDSTACK_CODE) ? TRUSTEDSTACK_URL : BID_URL;
return url + '?cid=' + encodeURIComponent(cid);
}
function generatePayload(bidRequests, bidderRequests) {
return {
site: siteDetails(bidRequests[0].params.site, bidderRequests),
ext: extParams(bidRequests[0], bidderRequests),
// TODO: fix auctionId leak: https://github.com/prebid/Prebid.js/issues/9781
id: bidRequests[0].auctionId,
imp: bidRequests.map(request => slotParams(request, bidderRequests)),
ortb2: bidderRequests.ortb2,
tmax: bidderRequests.timeout
}
}
function isValidBid(bid) {
return bid.no_bid === false && parseFloat(bid.cpm) > 0.0;
}
function fetchCookieSyncUrls(response) {
if (!isEmpty(response) && response[0].body &&
response[0].body.ext && isArray(response[0].body.ext.csUrl)) {
return response[0].body.ext.csUrl;
}
return [];
}
function getLoggingData(event, data) {
data = (isArray(data) && data) || [];
let params = {};
params.logid = 'kfk';
params.evtid = 'projectevents';
params.project = 'prebid';
params.acid = deepAccess(data, '0.auctionId') || '';
params.cid = getGlobal().medianetGlobals.cid || '';
params.crid = data.map((adunit) => deepAccess(adunit, 'params.0.crid') || adunit.adUnitCode).join('|');
params.adunit_count = data.length || 0;
params.dn = mnData.urlData.domain || '';
params.requrl = mnData.urlData.page || '';
params.istop = mnData.urlData.isTop || '';
params.event = event.name || '';
params.value = event.value || '';
params.rd = event.related_data || '';
return params;
}
function logEvent (event, data) {
let getParams = {
protocol: 'https',
hostname: EVENT_PIXEL_URL,
search: getLoggingData(event, data)
};
triggerPixel(buildUrl(getParams));
}
function clearMnData() {
mnData = {};
}
function addRenderer(bid) {
const videoContext = deepAccess(bid, 'context') || '';
const vastTimeout = deepAccess(bid, 'vto');
/* Adding renderer only when the context is Outstream
and the provider has responded with a renderer.
*/
if (videoContext == OUTSTREAM && vastTimeout) {
bid.renderer = newVideoRenderer(bid);
}
}
function newVideoRenderer(bid) {
const renderer = Renderer.install({
url: PLAYER_URL,
});
renderer.setRender(function (bid) {
window.mnet.queue.push(function () {
const obj = {
width: bid.width,
height: bid.height,
vastTimeout: bid.vto,
maxAllowedVastTagRedirects: bid.mavtr,
allowVpaid: bid.avp,
autoPlay: bid.ap,
preload: bid.pl,
mute: bid.mt
}
const adUnitCode = bid.dfp_id;
const divId = getGptSlotInfoForAdUnitCode(adUnitCode).divId || adUnitCode;
window.mnet.mediaNetoutstreamPlayer(bid, divId, obj);
});
});
return renderer;
}
export const spec = {
code: BIDDER_CODE,
gvlid: 142,
aliases,
supportedMediaTypes: [BANNER, NATIVE, VIDEO],
/**
* Determines whether or not the given bid request is valid.
*
* @param {object} bid The bid to validate.
* @return boolean True if this is a valid bid (if cid is present), and false otherwise.
*/
isBidRequestValid: function(bid) {
if (!bid.params) {
logError(`${BIDDER_CODE} : Missing bid parameters`);
return false;
}
if (!bid.params.cid || !isStr(bid.params.cid) || isEmptyStr(bid.params.cid)) {
logError(`${BIDDER_CODE} : cid should be a string`);
return false;
}
Object.assign(getGlobal().medianetGlobals, !getGlobal().medianetGlobals.cid && {cid: bid.params.cid});
return true;
},
/**
* Make a server request from the list of BidRequests.
*
* @param {BidRequest[]} bidRequests A non-empty list of bid requests which should be sent to the Server.
* @param {BidderRequests} bidderRequests
* @return ServerRequest Info describing the request to the server.
*/
buildRequests: function(bidRequests, bidderRequests) {
// convert Native ORTB definition to old-style prebid native definition
bidRequests = convertOrtbRequestToProprietaryNative(bidRequests);
let payload = generatePayload(bidRequests, bidderRequests);
return {
method: 'POST',
url: getBidderURL(bidderRequests.bidderCode, payload.ext.customer_id),
data: JSON.stringify(payload)
};
},
/**
* Unpack the response from the server into a list of bids.
*
* @param {*} serverResponse A successful response from the server.
* @returns {{bids: *[], fledgeAuctionConfigs: *[]} | *[]} An object containing bids and fledgeAuctionConfigs if present, otherwise an array of bids.
*/
interpretResponse: function(serverResponse, request) {
let validBids = [];
if (!serverResponse || !serverResponse.body) {
logInfo(`${BIDDER_CODE} : response is empty`);
return validBids;
}
let bids = serverResponse.body.bidList;
if (!isArray(bids) || bids.length === 0) {
logInfo(`${BIDDER_CODE} : no bids`);
} else {
validBids = bids.filter(bid => isValidBid(bid));
validBids.forEach(addRenderer);
}
const fledgeAuctionConfigs = deepAccess(serverResponse, 'body.ext.paApiAuctionConfigs') || [];
const ortbAuctionConfigs = deepAccess(serverResponse, 'body.ext.igi') || [];
if (fledgeAuctionConfigs.length === 0 && ortbAuctionConfigs.length === 0) {
return validBids;
}
if (ortbAuctionConfigs.length > 0) {
fledgeAuctionConfigs.push(...ortbAuctionConfigs.map(({igs}) => igs || []).flat());
}
return {
bids: validBids,
paapi: fledgeAuctionConfigs,
}
},
getUserSyncs: function(syncOptions, serverResponses) {
let cookieSyncUrls = fetchCookieSyncUrls(serverResponses);
if (syncOptions.iframeEnabled) {
return filterUrlsByType(cookieSyncUrls, 'iframe');
}
if (syncOptions.pixelEnabled) {
return filterUrlsByType(cookieSyncUrls, 'image');
}
},
/**
* @param {TimedOutBid} timeoutData
*/
onTimeout: (timeoutData) => {
try {
let eventData = {
name: EVENTS.TIMEOUT_EVENT_NAME,
value: timeoutData.length,
related_data: timeoutData[0].timeout || config.getConfig('bidderTimeout')
};
logEvent(eventData, timeoutData);
} catch (e) {}
},
/**
* @param {TimedOutBid} timeoutData
*/
onBidWon: (bid) => {
try {
let eventData = {
name: EVENTS.BID_WON_EVENT_NAME,
value: bid.cpm
};
logEvent(eventData, [bid]);
} catch (e) {}
},
clearMnData,
getWindowSize,
};
registerBidder(spec);