-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
adagioBidAdapter.js
847 lines (727 loc) · 28.3 KB
/
adagioBidAdapter.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js';
import {
canAccessWindowTop,
cleanObj,
deepAccess,
deepClone,
generateUUID,
getDNT,
getWindowSelf,
isArray,
isArrayOfNums,
isFn,
isInteger,
isNumber,
isStr,
logError,
logInfo,
logWarn,
} from '../src/utils.js';
import { getRefererInfo, parseDomain } from '../src/refererDetection.js';
import { OUTSTREAM } from '../src/video.js';
import { Renderer } from '../src/Renderer.js';
import { config } from '../src/config.js';
import { convertOrtbRequestToProprietaryNative } from '../src/native.js';
import { find } from '../src/polyfill.js';
import { getGptSlotInfoForAdUnitCode } from '../libraries/gptUtils/gptUtils.js';
import { _ADAGIO } from '../libraries/adagioUtils/adagioUtils.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { userSync } from '../src/userSync.js';
const BIDDER_CODE = 'adagio';
const LOG_PREFIX = 'Adagio:';
export const ENDPOINT = 'https://mp.4dex.io/prebid';
const SUPPORTED_MEDIA_TYPES = [BANNER, NATIVE, VIDEO];
const GVLID = 617;
const BB_PUBLICATION = 'adagio';
const BB_RENDERER_DEFAULT = 'renderer';
export const BB_RENDERER_URL = `https://${BB_PUBLICATION}.bbvms.com/r/$RENDERER.js`;
const CURRENCY = 'USD';
// This provide a whitelist and a basic validation of OpenRTB 2.5 options used by the Adagio SSP.
// Accept all options but 'protocol', 'companionad', 'companiontype', 'ext'
// https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-API-Specification-Version-2-5-FINAL.pdf
export const ORTB_VIDEO_PARAMS = {
'mimes': (value) => Array.isArray(value) && value.length > 0 && value.every(v => typeof v === 'string'),
'minduration': (value) => isInteger(value),
'maxduration': (value) => isInteger(value),
'protocols': (value) => isArrayOfNums(value),
'w': (value) => isInteger(value),
'h': (value) => isInteger(value),
'startdelay': (value) => isInteger(value),
'placement': (value) => {
logWarn(LOG_PREFIX, 'The OpenRTB video param `placement` is deprecated and should not be used anymore.');
return isInteger(value)
},
'plcmt': (value) => isInteger(value),
'linearity': (value) => isInteger(value),
'skip': (value) => [1, 0].includes(value),
'skipmin': (value) => isInteger(value),
'skipafter': (value) => isInteger(value),
'sequence': (value) => isInteger(value),
'battr': (value) => isArrayOfNums(value),
'maxextended': (value) => isInteger(value),
'minbitrate': (value) => isInteger(value),
'maxbitrate': (value) => isInteger(value),
'boxingallowed': (value) => isInteger(value),
'playbackmethod': (value) => isArrayOfNums(value),
'playbackend': (value) => isInteger(value),
'delivery': (value) => isArrayOfNums(value),
'pos': (value) => isInteger(value),
'api': (value) => isArrayOfNums(value)
};
/**
* Returns the window.ADAGIO global object used to store Adagio data.
* This object is created in window.top if possible, otherwise in window.self.
*/
function getDevice() {
const language = navigator.language ? 'language' : 'userLanguage';
return {
userAgent: navigator.userAgent,
language: navigator[language],
dnt: getDNT() ? 1 : 0,
geo: {},
js: 1
};
};
function getSite(bidderRequest) {
const { refererInfo } = bidderRequest;
return {
domain: parseDomain(refererInfo.topmostLocation) || '',
page: refererInfo.topmostLocation || '',
referrer: refererInfo.ref || getWindowSelf().document.referrer || '',
top: refererInfo.reachedTop
};
};
function autoDetectAdUnitElementIdFromGpt(adUnitCode) {
const autoDetectedAdUnit = getGptSlotInfoForAdUnitCode(adUnitCode);
if (autoDetectedAdUnit.divId) {
return autoDetectedAdUnit.divId;
}
};
function isRendererPreferredFromPublisher(bidRequest) {
// renderer defined at adUnit level
const adUnitRenderer = deepAccess(bidRequest, 'renderer');
const hasValidAdUnitRenderer = !!(adUnitRenderer && adUnitRenderer.url && adUnitRenderer.render);
// renderer defined at adUnit.mediaTypes level
const mediaTypeRenderer = deepAccess(bidRequest, 'mediaTypes.video.renderer');
const hasValidMediaTypeRenderer = !!(mediaTypeRenderer && mediaTypeRenderer.url && mediaTypeRenderer.render);
return !!(
(hasValidAdUnitRenderer && !(adUnitRenderer.backupOnly === true)) ||
(hasValidMediaTypeRenderer && !(mediaTypeRenderer.backupOnly === true))
);
}
/**
* Check if the publisher has defined its own video player and uses it for all ad-units.
* If not or if the `backupOnly` flag is true, this means we use our own player (BlueBillywig) defined in this adapter.
*/
function getPlayerName(bidRequest) {
return _internal.isRendererPreferredFromPublisher(bidRequest) ? 'other' : 'adagio'; ;
}
function hasRtd() {
const rtdConfigs = config.getConfig('realTimeData.dataProviders') || [];
return rtdConfigs.find(provider => provider.name === 'adagio');
};
export const _internal = {
canAccessWindowTop,
getAdagioNs: function() {
return _ADAGIO;
},
getDevice,
getSite,
getRefererInfo,
hasRtd,
isRendererPreferredFromPublisher,
};
function _getGdprConsent(bidderRequest) {
if (!deepAccess(bidderRequest, 'gdprConsent')) {
return false;
}
const {
apiVersion,
gdprApplies,
consentString,
allowAuctionWithoutConsent
} = bidderRequest.gdprConsent;
return cleanObj({
apiVersion,
consentString,
consentRequired: gdprApplies ? 1 : 0,
allowAuctionWithoutConsent: allowAuctionWithoutConsent ? 1 : 0
});
}
function _getCoppa() {
return {
required: config.getConfig('coppa') === true ? 1 : 0
};
}
function _getUspConsent(bidderRequest) {
return (deepAccess(bidderRequest, 'uspConsent')) ? { uspConsent: bidderRequest.uspConsent } : false;
}
function _getGppConsent(bidderRequest) {
let gpp = deepAccess(bidderRequest, 'gppConsent.gppString')
let gppSid = deepAccess(bidderRequest, 'gppConsent.applicableSections')
if (!gpp || !gppSid) {
gpp = deepAccess(bidderRequest, 'ortb2.regs.gpp', '')
gppSid = deepAccess(bidderRequest, 'ortb2.regs.gpp_sid', [])
}
return { gpp, gppSid }
}
function _getSchain(bidRequest) {
return deepAccess(bidRequest, 'schain');
}
function _getEids(bidRequest) {
if (deepAccess(bidRequest, 'userIdAsEids')) {
return bidRequest.userIdAsEids;
}
}
function _buildVideoBidRequest(bidRequest) {
const videoAdUnitParams = deepAccess(bidRequest, 'mediaTypes.video', {});
const videoBidderParams = deepAccess(bidRequest, 'params.video', {});
const computedParams = {};
// Special case for playerSize.
// Eeach props will be overrided if they are defined in config.
if (Array.isArray(videoAdUnitParams.playerSize)) {
const tempSize = (Array.isArray(videoAdUnitParams.playerSize[0])) ? videoAdUnitParams.playerSize[0] : videoAdUnitParams.playerSize;
computedParams.w = tempSize[0];
computedParams.h = tempSize[1];
}
const videoParams = {
...computedParams,
...videoAdUnitParams,
...videoBidderParams
};
if (videoParams.context && videoParams.context === OUTSTREAM) {
bidRequest.mediaTypes.video.playerName = getPlayerName(bidRequest);
}
// Only whitelisted OpenRTB options need to be validated.
// Other options will still remain in the `mediaTypes.video` object
// sent in the ad-request, but will be ignored by the SSP.
Object.keys(ORTB_VIDEO_PARAMS).forEach(paramName => {
if (videoParams.hasOwnProperty(paramName)) {
if (ORTB_VIDEO_PARAMS[paramName](videoParams[paramName])) {
bidRequest.mediaTypes.video[paramName] = videoParams[paramName];
} else {
delete bidRequest.mediaTypes.video[paramName];
logWarn(`${LOG_PREFIX} The OpenRTB video param ${paramName} has been skipped due to misformating. Please refer to OpenRTB 2.5 spec.`);
}
}
});
}
function _parseNativeBidResponse(bid) {
if (!bid.admNative || !Array.isArray(bid.admNative.assets)) {
logError(`${LOG_PREFIX} Invalid native response`);
return;
}
const native = {}
function addAssetDataValue(data) {
const map = {
1: 'sponsoredBy', // sponsored
2: 'body', // desc
3: 'rating',
4: 'likes',
5: 'downloads',
6: 'price',
7: 'salePrice',
8: 'phone',
9: 'address',
10: 'body2', // desc2
11: 'displayUrl',
12: 'cta'
}
if (map.hasOwnProperty(data.type) && typeof data.value === 'string') {
native[map[data.type]] = data.value;
}
}
// assets
bid.admNative.assets.forEach(asset => {
if (asset.title) {
native.title = asset.title.text
} else if (asset.data) {
addAssetDataValue(asset.data)
} else if (asset.img) {
switch (asset.img.type) {
case 1:
native.icon = {
url: asset.img.url,
width: asset.img.w,
height: asset.img.h
};
break;
default:
native.image = {
url: asset.img.url,
width: asset.img.w,
height: asset.img.h
};
break;
}
}
});
if (bid.admNative.link) {
if (bid.admNative.link.url) {
native.clickUrl = bid.admNative.link.url;
}
if (Array.isArray(bid.admNative.link.clicktrackers)) {
native.clickTrackers = bid.admNative.link.clicktrackers
}
}
if (Array.isArray(bid.admNative.eventtrackers)) {
native.impressionTrackers = [];
bid.admNative.eventtrackers.forEach(tracker => {
// Only Impression events are supported. Prebid does not support Viewability events yet.
if (tracker.event !== 1) {
return;
}
// methods:
// 1: image
// 2: js
// note: javascriptTrackers is a string. If there's more than one JS tracker in bid response, the last script will be used.
switch (tracker.method) {
case 1:
native.impressionTrackers.push(tracker.url);
break;
case 2:
const script = `<script async src=\"${tracker.url}\"></script>`;
if (!native.javascriptTrackers) {
native.javascriptTrackers = script;
} else {
native.javascriptTrackers += `\n${script}`;
}
break;
}
});
} else {
native.impressionTrackers = Array.isArray(bid.admNative.imptrackers) ? bid.admNative.imptrackers : [];
if (bid.admNative.jstracker) {
native.javascriptTrackers = bid.admNative.jstracker;
}
}
if (bid.admNative.privacy) {
native.privacyLink = bid.admNative.privacy;
}
if (bid.admNative.ext) {
native.ext = {}
if (bid.admNative.ext.bvw) {
native.ext.adagio_bvw = bid.admNative.ext.bvw;
}
}
bid.native = native
}
// bidRequest param must be the `bidRequest` object with the original `auctionId` value.
function _getFloors(bidRequest) {
if (!isFn(bidRequest.getFloor)) {
return false;
}
const floors = [];
const getAndPush = (mediaType, size) => {
const info = bidRequest.getFloor({
currency: CURRENCY,
mediaType,
size
});
floors.push(cleanObj({
mt: mediaType,
s: isArray(size) ? `${size[0]}x${size[1]}` : undefined,
f: (!isNaN(info.floor) && info.currency === CURRENCY) ? info.floor : undefined
}));
}
Object.keys(bidRequest.mediaTypes).forEach(mediaType => {
if (SUPPORTED_MEDIA_TYPES.indexOf(mediaType) !== -1) {
const sizeProp = mediaType === VIDEO ? 'playerSize' : 'sizes';
if (bidRequest.mediaTypes[mediaType][sizeProp] && bidRequest.mediaTypes[mediaType][sizeProp].length) {
if (isArray(bidRequest.mediaTypes[mediaType][sizeProp][0])) {
bidRequest.mediaTypes[mediaType][sizeProp].forEach(size => {
getAndPush(mediaType, [size[0], size[1]]);
});
} else {
getAndPush(mediaType, [bidRequest.mediaTypes[mediaType][sizeProp][0], bidRequest.mediaTypes[mediaType][sizeProp][1]]);
}
} else {
getAndPush(mediaType, '*');
}
}
});
return floors;
}
/**
* Try to find the value of `paramName` and set it to adUnit.params if
* it has not already been set.
* This function will check through:
* - bidderSettings object
* - ortb2.site.ext.data FPD…
*
* @param {*} bid
* @param {String} paramName
*/
export function setExtraParam(bid, paramName) {
bid.params = bid.params || {};
// eslint-disable-next-line
if (!!(bid.params[paramName])) {
return;
}
const adgGlobalConf = config.getConfig('adagio') || {};
const ortb2Conf = bid.ortb2;
const detected = adgGlobalConf[paramName] || deepAccess(ortb2Conf, `site.ext.data.${paramName}`, null);
if (detected) {
// First Party Data can be an array.
// As we consider that params detected from FPD are fallbacks, we just keep the 1st value.
if (Array.isArray(detected)) {
if (detected.length) {
bid.params[paramName] = detected[0].toString();
}
return;
}
bid.params[paramName] = detected.toString();
}
}
function autoFillParams(bid) {
// adUnitElementId …
const adgGlobalConf = config.getConfig('adagio') || {};
bid.params = bid.params || {};
// adgGlobalConf.siteId is a shortcut to facilitate the integration for publisher.
if (adgGlobalConf.siteId) {
bid.params.organizationId = adgGlobalConf.siteId.split(':')[0];
bid.params.site = adgGlobalConf.siteId.split(':')[1];
}
// `useAdUnitCodeAsPlacement` is an edge case. Useful when a Prebid Manager cannot handle properly params setting.
// In Prebid.js 9, `placement` should be defined in ortb2Imp and the `useAdUnitCodeAsPlacement` param should be removed
bid.params.placement = deepAccess(bid, 'ortb2Imp.ext.data.placement', bid.params.placement);
if (!bid.params.placement && (adgGlobalConf.useAdUnitCodeAsPlacement === true || bid.params.useAdUnitCodeAsPlacement === true)) {
bid.params.placement = bid.adUnitCode;
}
bid.params.adUnitElementId = deepAccess(bid, 'ortb2Imp.ext.data.divId', bid.params.adUnitElementId);
if (!bid.params.adUnitElementId) {
if (adgGlobalConf.useAdUnitCodeAsAdUnitElementId === true || bid.params.useAdUnitCodeAsAdUnitElementId === true) {
bid.params.adUnitElementId = bid.adUnitCode;
} else {
bid.params.adUnitElementId = autoDetectAdUnitElementIdFromGpt(bid.adUnitCode);
}
}
// extra params
setExtraParam(bid, 'pagetype');
setExtraParam(bid, 'category');
}
// See https://support.bluebillywig.com/developers/vast-renderer/
const OUTSTREAM_RENDERER = {
bootstrapPlayer: function(bid) {
const rendererCode = bid.outstreamRendererCode;
const config = {
code: bid.adUnitCode,
};
if (bid.vastXml) {
config.vastXml = bid.vastXml;
} else if (bid.vastUrl) {
config.vastUrl = bid.vastUrl;
}
if (!bid.vastXml && !bid.vastUrl) {
logError(`${LOG_PREFIX} no vastXml or vastUrl on bid`);
return;
}
if (!window.bluebillywig || !window.bluebillywig.renderers || !window.bluebillywig.renderers.length) {
logError(`${LOG_PREFIX} no BlueBillywig renderers found!`);
return;
}
const rendererId = this.getRendererId(BB_PUBLICATION, rendererCode);
const override = {}
if (bid.skipOffset) {
override.skipOffset = bid.skipOffset.toString()
}
const renderer = window.bluebillywig.renderers.find(bbr => bbr._id === rendererId);
if (!renderer) {
logError(`${LOG_PREFIX} couldn't find a renderer with ID ${rendererId}`);
return;
}
const el = document.getElementById(bid.adUnitCode);
renderer.bootstrap(config, el, override);
},
newRenderer: function(adUnitCode, rendererCode) {
const rendererUrl = BB_RENDERER_URL.replace('$RENDERER', rendererCode);
const renderer = Renderer.install({
url: rendererUrl,
loaded: false,
adUnitCode
});
try {
renderer.setRender(this.outstreamRender);
} catch (err) {
logError(`${LOG_PREFIX} error trying to setRender`, err);
}
return renderer;
},
outstreamRender: function(bid) {
bid.renderer.push(() => {
OUTSTREAM_RENDERER.bootstrapPlayer(bid)
});
},
getRendererId: function(publication, renderer) {
// By convention, the RENDERER_ID is always the publication name (adagio) and the ad unit code (eg. renderer)
// joined together by a dash. It's used to identify the correct renderer instance on the page in case there's multiple.
return `${publication}-${renderer}`;
}
};
export const spec = {
code: BIDDER_CODE,
gvlid: GVLID,
supportedMediaTypes: SUPPORTED_MEDIA_TYPES,
isBidRequestValid(bid) {
bid.params = bid.params || {};
autoFillParams(bid);
// Note: `bid.params.placement` is not related to the video param `placement`.
if (!(bid.params.organizationId && bid.params.site && bid.params.placement)) {
logWarn(`${LOG_PREFIX} at least one required param is missing.`);
return false;
}
return true;
},
buildRequests(validBidRequests, bidderRequest) {
// convert Native ORTB definition to old-style prebid native definition
validBidRequests = convertOrtbRequestToProprietaryNative(validBidRequests);
const secure = (location.protocol === 'https:') ? 1 : 0;
const device = _internal.getDevice();
const site = _internal.getSite(bidderRequest);
const pageviewId = _internal.getAdagioNs().pageviewId;
const gdprConsent = _getGdprConsent(bidderRequest) || {};
const uspConsent = _getUspConsent(bidderRequest) || {};
const coppa = _getCoppa();
const gppConsent = _getGppConsent(bidderRequest)
const schain = _getSchain(validBidRequests[0]);
const eids = _getEids(validBidRequests[0]) || [];
const syncEnabled = deepAccess(config.getConfig('userSync'), 'syncEnabled')
const canSyncWithIframe = syncEnabled && userSync.canBidderRegisterSync('iframe', 'adagio')
// We don't validate the dsa object in adapter and let our server do it.
const dsa = deepAccess(bidderRequest, 'ortb2.regs.ext.dsa');
// If no session data is provided, we always generate a new one.
const sessionData = deepAccess(bidderRequest, 'ortb2.site.ext.data.adg_rtd.session', {});
if (!Object.keys(sessionData).length) {
logInfo(LOG_PREFIX, 'No session data provided. A new session is be generated.')
sessionData.new = true;
sessionData.rnd = Math.random()
}
const aucId = deepAccess(bidderRequest, 'ortb2.site.ext.data.adg_rtd.uid') || generateUUID()
const adUnits = validBidRequests.map(rawBidRequest => {
const bidRequest = deepClone(rawBidRequest);
// Fix https://github.com/prebid/Prebid.js/issues/9781
bidRequest.auctionId = aucId
// Force the Split Keyword to be a String
if (bidRequest.params.splitKeyword) {
if (isStr(bidRequest.params.splitKeyword) || isNumber(bidRequest.params.splitKeyword)) {
bidRequest.params.splitKeyword = bidRequest.params.splitKeyword.toString();
} else {
delete bidRequest.params.splitKeyword;
logWarn(LOG_PREFIX, 'The splitKeyword param have been removed because the type is invalid, accepted type: number or string.');
}
}
// Enforce the organizationId param to be a string
bidRequest.params.organizationId = bidRequest.params.organizationId.toString();
// Force the Data Layer key and value to be a String
if (bidRequest.params.dataLayer) {
if (isStr(bidRequest.params.dataLayer) || isNumber(bidRequest.params.dataLayer) || isArray(bidRequest.params.dataLayer) || isFn(bidRequest.params.dataLayer)) {
logWarn(LOG_PREFIX, 'The dataLayer param is invalid, only object is accepted as a type.');
delete bidRequest.params.dataLayer;
} else {
let invalidDlParam = false;
bidRequest.params.dl = bidRequest.params.dataLayer
// Remove the dataLayer from the BidRequest to send the `dl` instead of the `dataLayer`
delete bidRequest.params.dataLayer
Object.keys(bidRequest.params.dl).forEach((key) => {
if (bidRequest.params.dl[key]) {
if (isStr(bidRequest.params.dl[key]) || isNumber(bidRequest.params.dl[key])) {
bidRequest.params.dl[key] = bidRequest.params.dl[key].toString();
} else {
invalidDlParam = true;
delete bidRequest.params.dl[key];
}
}
});
if (invalidDlParam) {
logWarn(LOG_PREFIX, 'Some parameters of the dataLayer property have been removed because the type is invalid, accepted type: number or string.');
}
}
}
// Handle priceFloors module
// We need to use `rawBidRequest` as param because:
// - adagioBidAdapter generates its own auctionId due to transmitTid activity limitation (see https://github.com/prebid/Prebid.js/pull/10079)
// - the priceFloors.getFloor() uses a `_floorDataForAuction` map to store the floors based on the auctionId.
const computedFloors = _getFloors(rawBidRequest);
if (isArray(computedFloors) && computedFloors.length) {
bidRequest.floors = computedFloors
if (deepAccess(bidRequest, 'mediaTypes.banner')) {
const bannerObj = bidRequest.mediaTypes.banner
const computeNewSizeArray = (sizeArr = []) => {
const size = { size: sizeArr, floor: null }
const bannerFloors = bidRequest.floors.filter(floor => floor.mt === BANNER)
const BannerSizeFloor = bannerFloors.find(floor => floor.s === sizeArr.join('x'))
size.floor = (bannerFloors) ? (BannerSizeFloor) ? BannerSizeFloor.f : bannerFloors[0].f : null
return size
}
// `bannerSizes`, internal property name
bidRequest.mediaTypes.banner.bannerSizes = (isArray(bannerObj.sizes[0]))
? bannerObj.sizes.map(sizeArr => {
return computeNewSizeArray(sizeArr)
})
: computeNewSizeArray(bannerObj.sizes)
}
if (deepAccess(bidRequest, 'mediaTypes.video')) {
const videoObj = bidRequest.mediaTypes.video
const videoFloors = bidRequest.floors.filter(floor => floor.mt === VIDEO);
const playerSize = (videoObj.playerSize && isArray(videoObj.playerSize[0])) ? videoObj.playerSize[0] : videoObj.playerSize
const videoSizeFloor = (playerSize) ? videoFloors.find(floor => floor.s === playerSize.join('x')) : undefined
bidRequest.mediaTypes.video.floor = (videoFloors) ? videoSizeFloor ? videoSizeFloor.f : videoFloors[0].f : null
}
if (deepAccess(bidRequest, 'mediaTypes.native')) {
const nativeFloors = bidRequest.floors.filter(floor => floor.mt === NATIVE);
if (nativeFloors.length) {
bidRequest.mediaTypes.native.floor = nativeFloors[0].f
}
}
}
if (deepAccess(bidRequest, 'mediaTypes.video')) {
_buildVideoBidRequest(bidRequest);
}
const gpid = deepAccess(bidRequest, 'ortb2Imp.ext.gpid') || deepAccess(bidRequest, 'ortb2Imp.ext.data.pbadslot');
if (gpid) {
bidRequest.gpid = gpid;
}
// features are added by the adagioRtdProvider.
const rawFeatures = {
...deepAccess(bidRequest, 'ortb2.site.ext.data.adg_rtd.features', {}),
print_number: (bidRequest.bidderRequestsCount || 1).toString(),
adunit_position: deepAccess(bidRequest, 'ortb2Imp.ext.data.adg_rtd.adunit_position', null)
}
// Clean the features object from null or undefined values.
bidRequest.features = Object.entries(rawFeatures).reduce((a, [k, v]) => (v == null ? a : (a[k] = v, a)), {})
// Remove some params that are not needed on the server side.
delete bidRequest.params.siteId;
// whitelist the fields that are allowed to be sent to the server.
const adUnit = {
adUnitCode: bidRequest.adUnitCode,
auctionId: bidRequest.auctionId,
bidder: bidRequest.bidder,
bidId: bidRequest.bidId,
params: bidRequest.params,
features: bidRequest.features,
gpid: bidRequest.gpid,
mediaTypes: bidRequest.mediaTypes,
nativeParams: bidRequest.nativeParams,
score: bidRequest.score,
transactionId: bidRequest.transactionId,
}
return adUnit;
});
// Group ad units by organizationId
const groupedAdUnits = adUnits.reduce((groupedAdUnits, adUnit) => {
const organizationId = adUnit.params.organizationId
groupedAdUnits[organizationId] = groupedAdUnits[organizationId] || [];
groupedAdUnits[organizationId].push(adUnit);
return groupedAdUnits;
}, {});
// Adding more params on the original bid object.
// Those params are not sent to the server.
// They are used for further operations on analytics adapter.
validBidRequests.forEach(rawBidRequest => {
rawBidRequest.params.adagioAuctionId = aucId
rawBidRequest.params.pageviewId = pageviewId
});
// Build one request per organizationId
const requests = Object.keys(groupedAdUnits).map(organizationId => {
return {
method: 'POST',
url: ENDPOINT,
data: {
organizationId: organizationId,
hasRtd: _internal.hasRtd() ? 1 : 0,
secure: secure,
device: device,
site: site,
pageviewId: pageviewId,
adUnits: groupedAdUnits[organizationId],
data: {
session: sessionData
},
regs: {
gdpr: gdprConsent,
coppa: coppa,
ccpa: uspConsent,
gpp: gppConsent.gpp,
gppSid: gppConsent.gppSid,
dsa: dsa // populated if exists
},
schain: schain,
user: {
eids: eids
},
prebidVersion: '$prebid.version$',
usIfr: canSyncWithIframe
},
options: {
contentType: 'text/plain'
}
};
});
return requests;
},
interpretResponse(serverResponse, bidRequest) {
let bidResponses = [];
try {
const response = serverResponse.body;
if (response) {
if (response.data) {
if (_internal.hasRtd()) {
_internal.getAdagioNs().queue.push({
action: 'ssp-data',
ts: Date.now(),
data: response.data
});
}
}
if (response.bids) {
response.bids.forEach(bidObj => {
const bidReq = (find(bidRequest.data.adUnits, bid => bid.bidId === bidObj.requestId));
if (bidReq) {
// bidObj.meta is the `bidResponse.meta` object according to https://docs.prebid.org/dev-docs/bidder-adaptor.html#interpreting-the-response
bidObj.meta = deepAccess(bidObj, 'meta', {});
bidObj.meta.mediaType = bidObj.mediaType;
bidObj.meta.advertiserDomains = (Array.isArray(bidObj.aDomain) && bidObj.aDomain.length) ? bidObj.aDomain : [];
if (bidObj.mediaType === VIDEO) {
const mediaTypeContext = deepAccess(bidReq, 'mediaTypes.video.context');
// Adagio SSP returns a `vastXml` only. No `vastUrl` nor `videoCacheKey`.
if (!bidObj.vastUrl && bidObj.vastXml) {
bidObj.vastUrl = 'data:text/xml;charset=utf-8;base64,' + window.btoa(bidObj.vastXml.replace(/\\"/g, '"'));
}
if (mediaTypeContext === OUTSTREAM) {
bidObj.outstreamRendererCode = deepAccess(bidReq, 'params.rendererCode', BB_RENDERER_DEFAULT)
if (deepAccess(bidReq, 'mediaTypes.video.skip')) {
const skipOffset = deepAccess(bidReq, 'mediaTypes.video.skipafter', 5) // default 5s.
bidObj.skipOffset = skipOffset
}
bidObj.renderer = OUTSTREAM_RENDERER.newRenderer(bidObj.adUnitCode, bidObj.outstreamRendererCode);
}
}
if (bidObj.mediaType === NATIVE) {
_parseNativeBidResponse(bidObj);
}
bidObj.site = bidReq.params.site;
bidObj.placement = bidReq.params.placement;
bidObj.pagetype = bidReq.params.pagetype;
bidObj.category = bidReq.params.category;
}
bidResponses.push(bidObj);
});
}
}
} catch (err) {
logError(err);
}
return bidResponses;
},
getUserSyncs(syncOptions, serverResponses) {
if (!serverResponses.length || serverResponses[0].body === '' || !serverResponses[0].body.userSyncs) {
return false;
}
const syncs = serverResponses[0].body.userSyncs.map(sync => ({
type: sync.t === 'p' ? 'image' : 'iframe',
url: sync.u
}));
return syncs;
},
};
registerBidder(spec);