forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubmaticBidAdapter.js
1521 lines (1380 loc) · 53.8 KB
/
pubmaticBidAdapter.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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { getBidRequest, logWarn, isBoolean, isStr, isArray, inIframe, mergeDeep, deepAccess, isNumber, deepSetValue, logInfo, logError, deepClone, uniques, isPlainObject, isInteger, generateUUID } from '../src/utils.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { BANNER, VIDEO, NATIVE, ADPOD } from '../src/mediaTypes.js';
import { config } from '../src/config.js';
import { Renderer } from '../src/Renderer.js';
import { bidderSettings } from '../src/bidderSettings.js';
import { NATIVE_IMAGE_TYPES, NATIVE_KEYS_THAT_ARE_NOT_ASSETS, NATIVE_KEYS, NATIVE_ASSET_TYPES } from '../src/constants.js';
/**
* @typedef {import('../src/adapters/bidderFactory.js').BidRequest} BidRequest
* @typedef {import('../src/adapters/bidderFactory.js').Bid} Bid
* @typedef {import('../src/adapters/bidderFactory.js').validBidRequests} validBidRequests
*/
const BIDDER_CODE = 'pubmatic';
const LOG_WARN_PREFIX = 'PubMatic: ';
const ENDPOINT = 'https://hbopenbid.pubmatic.com/translator?source=prebid-client';
const USER_SYNC_URL_IFRAME = 'https://ads.pubmatic.com/AdServer/js/user_sync.html?kdntuid=1&p=';
const USER_SYNC_URL_IMAGE = 'https://image8.pubmatic.com/AdServer/ImgSync?p=';
const DEFAULT_CURRENCY = 'USD';
const AUCTION_TYPE = 1;
const UNDEFINED = undefined;
const DEFAULT_WIDTH = 0;
const DEFAULT_HEIGHT = 0;
const DEFAULT_TTL = 360;
const PREBID_NATIVE_HELP_LINK = 'http://prebid.org/dev-docs/show-native-ads.html';
const PUBLICATION = 'pubmatic'; // Your publication on Blue Billywig, potentially with environment (e.g. publication.bbvms.com or publication.test.bbvms.com)
const RENDERER_URL = 'https://pubmatic.bbvms.com/r/'.concat('$RENDERER', '.js'); // URL of the renderer application
const MSG_VIDEO_PLCMT_MISSING = 'Video.plcmt param missing';
const CUSTOM_PARAMS = {
'kadpageurl': '', // Custom page url
'gender': '', // User gender
'yob': '', // User year of birth
'lat': '', // User location - Latitude
'lon': '', // User Location - Longitude
'wiid': '', // OpenWrap Wrapper Impression ID
'profId': '', // OpenWrap Legacy: Profile ID
'verId': '' // OpenWrap Legacy: version ID
};
const DATA_TYPES = {
'NUMBER': 'number',
'STRING': 'string',
'BOOLEAN': 'boolean',
'ARRAY': 'array',
'OBJECT': 'object'
};
const VIDEO_CUSTOM_PARAMS = {
'mimes': DATA_TYPES.ARRAY,
'minduration': DATA_TYPES.NUMBER,
'maxduration': DATA_TYPES.NUMBER,
'startdelay': DATA_TYPES.NUMBER,
'playbackmethod': DATA_TYPES.ARRAY,
'api': DATA_TYPES.ARRAY,
'protocols': DATA_TYPES.ARRAY,
'w': DATA_TYPES.NUMBER,
'h': DATA_TYPES.NUMBER,
'battr': DATA_TYPES.ARRAY,
'linearity': DATA_TYPES.NUMBER,
'placement': DATA_TYPES.NUMBER,
'plcmt': DATA_TYPES.NUMBER,
'minbitrate': DATA_TYPES.NUMBER,
'maxbitrate': DATA_TYPES.NUMBER,
'skip': DATA_TYPES.NUMBER
}
const NATIVE_ASSET_IMAGE_TYPE = {
'ICON': 1,
'IMAGE': 3
}
const BANNER_CUSTOM_PARAMS = {
'battr': DATA_TYPES.ARRAY
}
const NET_REVENUE = true;
const dealChannelValues = {
1: 'PMP',
5: 'PREF',
6: 'PMPG'
};
// BB stands for Blue BillyWig
const BB_RENDERER = {
bootstrapPlayer: function(bid) {
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) {
logWarn(`${LOG_WARN_PREFIX}: No vastXml or vastUrl on bid, bailing...`);
return;
}
const rendererId = BB_RENDERER.getRendererId(PUBLICATION, bid.rendererCode);
const ele = document.getElementById(bid.adUnitCode); // NB convention
let renderer;
for (let rendererIndex = 0; rendererIndex < window.bluebillywig.renderers.length; rendererIndex++) {
if (window.bluebillywig.renderers[rendererIndex]._id === rendererId) {
renderer = window.bluebillywig.renderers[rendererIndex];
break;
}
}
if (renderer) renderer.bootstrap(config, ele);
else logWarn(`${LOG_WARN_PREFIX}: Couldn't find a renderer with ${rendererId}`);
},
newRenderer: function(rendererCode, adUnitCode) {
var rendererUrl = RENDERER_URL.replace('$RENDERER', rendererCode);
const renderer = Renderer.install({
url: rendererUrl,
loaded: false,
adUnitCode
});
try {
renderer.setRender(BB_RENDERER.outstreamRender);
} catch (err) {
logWarn(`${LOG_WARN_PREFIX}: Error tying to setRender on renderer`, err);
}
return renderer;
},
outstreamRender: function(bid) {
bid.renderer.push(function() { BB_RENDERER.bootstrapPlayer(bid) });
},
getRendererId: function(pub, renderer) {
return `${pub}-${renderer}`; // NB convention!
}
};
const MEDIATYPE = [
BANNER,
VIDEO,
NATIVE
]
const MEDIATYPE_TTL = {
'banner': 360,
'video': 1800,
'native': 1800
};
let publisherId = 0;
let isInvalidNativeRequest = false;
let biddersList = ['pubmatic'];
const allBiddersList = ['all'];
export function _getDomainFromURL(url) {
let anchor = document.createElement('a');
anchor.href = url;
return anchor.hostname;
}
function _parseSlotParam(paramName, paramValue) {
if (!isStr(paramValue)) {
paramValue && logWarn(LOG_WARN_PREFIX + 'Ignoring param key: ' + paramName + ', expects string-value, found ' + typeof paramValue);
return UNDEFINED;
}
switch (paramName) {
case 'pmzoneid':
return paramValue.split(',').slice(0, 50).map(id => id.trim()).join();
case 'kadfloor':
return parseFloat(paramValue) || UNDEFINED;
case 'lat':
return parseFloat(paramValue) || UNDEFINED;
case 'lon':
return parseFloat(paramValue) || UNDEFINED;
case 'yob':
return parseInt(paramValue) || UNDEFINED;
default:
return paramValue;
}
}
function _cleanSlot(slotName) {
if (isStr(slotName)) {
return slotName.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
if (slotName) {
logWarn(BIDDER_CODE + ': adSlot must be a string. Ignoring adSlot');
}
return '';
}
function _parseAdSlot(bid) {
bid.params.adUnit = '';
bid.params.adUnitIndex = '0';
bid.params.width = 0;
bid.params.height = 0;
bid.params.adSlot = _cleanSlot(bid.params.adSlot);
var slot = bid.params.adSlot;
var splits = slot.split(':');
slot = splits[0];
if (splits.length == 2) {
bid.params.adUnitIndex = splits[1];
}
// check if size is mentioned in sizes array. in that case do not check for @ in adslot
splits = slot.split('@');
bid.params.adUnit = splits[0];
if (splits.length > 1) {
// i.e size is specified in adslot, so consider that and ignore sizes array
splits = splits[1].split('x');
if (splits.length != 2) {
logWarn(LOG_WARN_PREFIX + 'AdSlot Error: adSlot not in required format');
return;
}
bid.params.width = parseInt(splits[0], 10);
bid.params.height = parseInt(splits[1], 10);
} else if (bid.hasOwnProperty('mediaTypes') &&
bid.mediaTypes.hasOwnProperty(BANNER) &&
bid.mediaTypes.banner.hasOwnProperty('sizes')) {
var i = 0;
var sizeArray = [];
for (;i < bid.mediaTypes.banner.sizes.length; i++) {
if (bid.mediaTypes.banner.sizes[i].length === 2) { // sizes[i].length will not be 2 in case where size is set as fluid, we want to skip that entry
sizeArray.push(bid.mediaTypes.banner.sizes[i]);
}
}
bid.mediaTypes.banner.sizes = sizeArray;
if (bid.mediaTypes.banner.sizes.length >= 1) {
// set the first size in sizes array in bid.params.width and bid.params.height. These will be sent as primary size.
// The rest of the sizes will be sent in format array.
bid.params.width = bid.mediaTypes.banner.sizes[0][0];
bid.params.height = bid.mediaTypes.banner.sizes[0][1];
bid.mediaTypes.banner.sizes = bid.mediaTypes.banner.sizes.splice(1, bid.mediaTypes.banner.sizes.length - 1);
}
}
}
function _initConf(refererInfo) {
return {
// TODO: do the fallbacks make sense here?
pageURL: refererInfo?.page || window.location.href,
refURL: refererInfo?.ref || window.document.referrer
};
}
function _handleCustomParams(params, conf) {
if (!conf.kadpageurl) {
conf.kadpageurl = conf.pageURL;
}
var key, value, entry;
for (key in CUSTOM_PARAMS) {
if (CUSTOM_PARAMS.hasOwnProperty(key)) {
value = params[key];
if (value) {
entry = CUSTOM_PARAMS[key];
if (typeof entry === 'object') {
// will be used in future when we want to process a custom param before using
// 'keyname': {f: function() {}}
value = entry.f(value, conf);
}
if (isStr(value)) {
conf[key] = value;
} else {
logWarn(LOG_WARN_PREFIX + 'Ignoring param : ' + key + ' with value : ' + CUSTOM_PARAMS[key] + ', expects string-value, found ' + typeof value);
}
}
}
}
return conf;
}
export function getDeviceConnectionType() {
let connection = window.navigator && (window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection);
switch (connection?.effectiveType) {
case 'ethernet':
return 1;
case 'wifi':
return 2;
case 'slow-2g':
case '2g':
return 4;
case '3g':
return 5;
case '4g':
return 6;
default:
return 0;
}
}
function _createOrtbTemplate(conf) {
return {
id: '' + new Date().getTime(),
at: AUCTION_TYPE,
cur: [DEFAULT_CURRENCY],
imp: [],
site: {
page: conf.pageURL,
ref: conf.refURL,
publisher: {}
},
device: {
ua: navigator.userAgent,
js: 1,
dnt: (navigator.doNotTrack == 'yes' || navigator.doNotTrack == '1' || navigator.msDoNotTrack == '1') ? 1 : 0,
h: screen.height,
w: screen.width,
language: navigator.language,
connectiontype: getDeviceConnectionType()
},
user: {},
ext: {}
};
}
function _checkParamDataType(key, value, datatype) {
var errMsg = 'Ignoring param key: ' + key + ', expects ' + datatype + ', found ' + typeof value;
var functionToExecute;
switch (datatype) {
case DATA_TYPES.BOOLEAN:
functionToExecute = isBoolean;
break;
case DATA_TYPES.NUMBER:
functionToExecute = isNumber;
break;
case DATA_TYPES.STRING:
functionToExecute = isStr;
break;
case DATA_TYPES.ARRAY:
functionToExecute = isArray;
break;
}
if (functionToExecute(value)) {
return value;
}
logWarn(LOG_WARN_PREFIX + errMsg);
return UNDEFINED;
}
// TODO delete this code when removing native 1.1 support
const PREBID_NATIVE_DATA_KEYS_TO_ORTB = {
'desc': 'desc',
'desc2': 'desc2',
'body': 'desc',
'body2': 'desc2',
'sponsoredBy': 'sponsored',
'cta': 'ctatext',
'rating': 'rating',
'address': 'address',
'downloads': 'downloads',
'likes': 'likes',
'phone': 'phone',
'price': 'price',
'salePrice': 'saleprice',
'displayUrl': 'displayurl',
'saleprice': 'saleprice',
'displayurl': 'displayurl'
};
const PREBID_NATIVE_DATA_KEY_VALUES = Object.values(PREBID_NATIVE_DATA_KEYS_TO_ORTB);
// TODO remove this function when the support for 1.1 is removed
/**
* Copy of the function toOrtbNativeRequest from core native.js to handle the title len/length
* and ext and mimes parameters from legacy assets.
* @param {object} legacyNativeAssets
* @returns an OpenRTB format of the same bid request
*/
export function toOrtbNativeRequest(legacyNativeAssets) {
if (!legacyNativeAssets && !isPlainObject(legacyNativeAssets)) {
logWarn(`${LOG_WARN_PREFIX}: Native assets object is empty or not an object: ${legacyNativeAssets}`);
isInvalidNativeRequest = true;
return;
}
const ortb = {
ver: '1.2',
assets: []
};
for (let key in legacyNativeAssets) {
// skip conversion for non-asset keys
if (NATIVE_KEYS_THAT_ARE_NOT_ASSETS.includes(key)) continue;
if (!NATIVE_KEYS.hasOwnProperty(key) && !PREBID_NATIVE_DATA_KEY_VALUES.includes(key)) {
logWarn(`${LOG_WARN_PREFIX}: Unrecognized native asset code: ${key}. Asset will be ignored.`);
continue;
}
const asset = legacyNativeAssets[key];
let required = 0;
if (asset.required && isBoolean(asset.required)) {
required = Number(asset.required);
}
const ortbAsset = {
id: ortb.assets.length,
required
};
// data cases
if (key in PREBID_NATIVE_DATA_KEYS_TO_ORTB) {
ortbAsset.data = {
type: NATIVE_ASSET_TYPES[PREBID_NATIVE_DATA_KEYS_TO_ORTB[key]]
}
if (asset.len || asset.length) {
ortbAsset.data.len = asset.len || asset.length;
}
if (asset.ext) {
ortbAsset.data.ext = asset.ext;
}
// icon or image case
} else if (key === 'icon' || key === 'image') {
ortbAsset.img = {
type: key === 'icon' ? NATIVE_IMAGE_TYPES.ICON : NATIVE_IMAGE_TYPES.MAIN,
}
// if min_width and min_height are defined in aspect_ratio, they are preferred
if (asset.aspect_ratios) {
if (!isArray(asset.aspect_ratios)) {
logWarn(`${LOG_WARN_PREFIX}: image.aspect_ratios was passed, but it's not a an array: ${asset.aspect_ratios}`);
} else if (!asset.aspect_ratios.length) {
logWarn(`${LOG_WARN_PREFIX}: image.aspect_ratios was passed, but it's empty: ${asset.aspect_ratios}`);
} else {
const { min_width: minWidth, min_height: minHeight } = asset.aspect_ratios[0];
if (!isInteger(minWidth) || !isInteger(minHeight)) {
logWarn(`${LOG_WARN_PREFIX}: image.aspect_ratios min_width or min_height are invalid: ${minWidth}, ${minHeight}`);
} else {
ortbAsset.img.wmin = minWidth;
ortbAsset.img.hmin = minHeight;
}
const aspectRatios = asset.aspect_ratios
.filter((ar) => ar.ratio_width && ar.ratio_height)
.map(ratio => `${ratio.ratio_width}:${ratio.ratio_height}`);
if (aspectRatios.length > 0) {
ortbAsset.img.ext = {
aspectratios: aspectRatios
}
}
}
}
ortbAsset.img.w = asset.w || asset.width;
ortbAsset.img.h = asset.h || asset.height;
ortbAsset.img.wmin = asset.wmin || asset.minimumWidth || (asset.minsizes ? asset.minsizes[0] : UNDEFINED);
ortbAsset.img.hmin = asset.hmin || asset.minimumHeight || (asset.minsizes ? asset.minsizes[1] : UNDEFINED);
// if asset.sizes exist, by OpenRTB spec we should remove wmin and hmin
if (asset.sizes) {
if (asset.sizes.length !== 2 || !isInteger(asset.sizes[0]) || !isInteger(asset.sizes[1])) {
logWarn(`${LOG_WARN_PREFIX}: image.sizes was passed, but its value is not an array of integers: ${asset.sizes}`);
} else {
logInfo(`${LOG_WARN_PREFIX}: if asset.sizes exist, by OpenRTB spec we should remove wmin and hmin`);
ortbAsset.img.w = asset.sizes[0];
ortbAsset.img.h = asset.sizes[1];
delete ortbAsset.img.hmin;
delete ortbAsset.img.wmin;
}
}
asset.ext && (ortbAsset.img.ext = asset.ext);
asset.mimes && (ortbAsset.img.mimes = asset.mimes);
// title case
} else if (key === 'title') {
ortbAsset.title = {
// in openRTB, len is required for titles, while in legacy prebid was not.
// for this reason, if len is missing in legacy prebid, we're adding a default value of 140.
len: asset.len || asset.length || 140
}
asset.ext && (ortbAsset.title.ext = asset.ext);
// all extensions to the native bid request are passed as is
} else if (key === 'ext') {
ortbAsset.ext = asset;
// in `ext` case, required field is not needed
delete ortbAsset.required;
}
ortb.assets.push(ortbAsset);
}
if (ortb.assets.length < 1) {
logWarn(`${LOG_WARN_PREFIX}: Could not find any valid asset`);
isInvalidNativeRequest = true;
return;
}
return ortb;
}
// TODO delete this code when removing native 1.1 support
function _createNativeRequest(params) {
var nativeRequestObject;
// TODO delete this code when removing native 1.1 support
if (!params.ortb) { // legacy assets definition found
nativeRequestObject = toOrtbNativeRequest(params);
} else { // ortb assets definition found
params = params.ortb;
// TODO delete this code when removing native 1.1 support
nativeRequestObject = { ver: '1.2', ...params, assets: [] };
const { assets } = params;
const isValidAsset = (asset) => asset.title || asset.img || asset.data || asset.video;
if (assets.length < 1 || !assets.some(asset => isValidAsset(asset))) {
logWarn(`${LOG_WARN_PREFIX}: Native assets object is empty or contains some invalid object`);
isInvalidNativeRequest = true;
return nativeRequestObject;
}
assets.forEach(asset => {
var assetObj = asset;
if (assetObj.img) {
if (assetObj.img.type == NATIVE_ASSET_IMAGE_TYPE.IMAGE) {
assetObj.w = assetObj.w || assetObj.width || (assetObj.sizes ? assetObj.sizes[0] : UNDEFINED);
assetObj.h = assetObj.h || assetObj.height || (assetObj.sizes ? assetObj.sizes[1] : UNDEFINED);
assetObj.wmin = assetObj.wmin || assetObj.minimumWidth || (assetObj.minsizes ? assetObj.minsizes[0] : UNDEFINED);
assetObj.hmin = assetObj.hmin || assetObj.minimumHeight || (assetObj.minsizes ? assetObj.minsizes[1] : UNDEFINED);
} else if (assetObj.img.type == NATIVE_ASSET_IMAGE_TYPE.ICON) {
assetObj.w = assetObj.w || assetObj.width || (assetObj.sizes ? assetObj.sizes[0] : UNDEFINED);
assetObj.h = assetObj.h || assetObj.height || (assetObj.sizes ? assetObj.sizes[1] : UNDEFINED);
}
}
if (assetObj && assetObj.id !== undefined && isValidAsset(assetObj)) {
nativeRequestObject.assets.push(assetObj);
}
}
);
}
return nativeRequestObject;
}
function _createBannerRequest(bid) {
var sizes = bid.mediaTypes.banner.sizes;
var format = [];
var bannerObj;
if (sizes !== UNDEFINED && isArray(sizes)) {
bannerObj = {};
if (!bid.params.width && !bid.params.height) {
if (sizes.length === 0) {
// i.e. since bid.params does not have width or height, and length of sizes is 0, need to ignore this banner imp
bannerObj = UNDEFINED;
logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.');
return bannerObj;
} else {
bannerObj.w = parseInt(sizes[0][0], 10);
bannerObj.h = parseInt(sizes[0][1], 10);
sizes = sizes.splice(1, sizes.length - 1);
}
} else {
bannerObj.w = bid.params.width;
bannerObj.h = bid.params.height;
}
if (sizes.length > 0) {
format = [];
sizes.forEach(function (size) {
if (size.length > 1) {
format.push({ w: size[0], h: size[1] });
}
});
if (format.length > 0) {
bannerObj.format = format;
}
}
bannerObj.pos = 0;
bannerObj.topframe = inIframe() ? 0 : 1;
// Adding Banner custom params
const bannerCustomParams = {...deepAccess(bid, 'ortb2Imp.banner')};
for (let key in BANNER_CUSTOM_PARAMS) {
if (bannerCustomParams.hasOwnProperty(key)) {
bannerObj[key] = _checkParamDataType(key, bannerCustomParams[key], BANNER_CUSTOM_PARAMS[key]);
}
}
} else {
logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.');
bannerObj = UNDEFINED;
}
return bannerObj;
}
export function checkVideoPlacement(videoData, adUnitCode) {
// Check for video.placement property. If property is missing display log message.
if (FEATURES.VIDEO && !deepAccess(videoData, 'plcmt')) {
logWarn(MSG_VIDEO_PLCMT_MISSING + ' for ' + adUnitCode);
};
}
function _createVideoRequest(bid) {
var videoData = mergeDeep(deepAccess(bid.mediaTypes, 'video'), bid.params.video);
var videoObj;
if (FEATURES.VIDEO && videoData !== UNDEFINED) {
videoObj = {};
checkVideoPlacement(videoData, bid.adUnitCode);
for (var key in VIDEO_CUSTOM_PARAMS) {
if (videoData.hasOwnProperty(key)) {
videoObj[key] = _checkParamDataType(key, videoData[key], VIDEO_CUSTOM_PARAMS[key]);
}
}
// read playersize and assign to h and w.
if (isArray(bid.mediaTypes.video.playerSize[0])) {
videoObj.w = parseInt(bid.mediaTypes.video.playerSize[0][0], 10);
videoObj.h = parseInt(bid.mediaTypes.video.playerSize[0][1], 10);
} else if (isNumber(bid.mediaTypes.video.playerSize[0])) {
videoObj.w = parseInt(bid.mediaTypes.video.playerSize[0], 10);
videoObj.h = parseInt(bid.mediaTypes.video.playerSize[1], 10);
}
} else {
videoObj = UNDEFINED;
logWarn(LOG_WARN_PREFIX + 'Error: Video config params missing for adunit: ' + bid.params.adUnit + ' with mediaType set as video. Ignoring video impression in the adunit.');
}
return videoObj;
}
// support for PMP deals
function _addPMPDealsInImpression(impObj, bid) {
if (bid.params.deals) {
if (isArray(bid.params.deals)) {
bid.params.deals.forEach(function(dealId) {
if (isStr(dealId) && dealId.length > 3) {
if (!impObj.pmp) {
impObj.pmp = { private_auction: 0, deals: [] };
}
impObj.pmp.deals.push({ id: dealId });
} else {
logWarn(LOG_WARN_PREFIX + 'Error: deal-id present in array bid.params.deals should be a strings with more than 3 charaters length, deal-id ignored: ' + dealId);
}
});
} else {
logWarn(LOG_WARN_PREFIX + 'Error: bid.params.deals should be an array of strings.');
}
}
}
function _addDealCustomTargetings(imp, bid) {
var dctr = '';
var dctrLen;
if (bid.params.dctr) {
dctr = bid.params.dctr;
if (isStr(dctr) && dctr.length > 0) {
var arr = dctr.split('|');
dctr = '';
arr.forEach(val => {
dctr += (val.length > 0) ? (val.trim() + '|') : '';
});
dctrLen = dctr.length;
if (dctr.substring(dctrLen, dctrLen - 1) === '|') {
dctr = dctr.substring(0, dctrLen - 1);
}
imp.ext['key_val'] = dctr.trim();
} else {
logWarn(LOG_WARN_PREFIX + 'Ignoring param : dctr with value : ' + dctr + ', expects string-value, found empty or non-string value');
}
}
}
function _addJWPlayerSegmentData(imp, bid) {
var jwSegData = (bid.rtd && bid.rtd.jwplayer && bid.rtd.jwplayer.targeting) || undefined;
var jwPlayerData = '';
const jwMark = 'jw-';
if (jwSegData === undefined || jwSegData === '' || !jwSegData.hasOwnProperty('segments')) return;
var maxLength = jwSegData.segments.length;
jwPlayerData += jwMark + 'id=' + jwSegData.content.id; // add the content id first
for (var i = 0; i < maxLength; i++) {
jwPlayerData += '|' + jwMark + jwSegData.segments[i] + '=1';
}
var ext;
ext = imp.ext;
ext && ext.key_val === undefined ? ext.key_val = jwPlayerData : ext.key_val += '|' + jwPlayerData;
}
function _createImpressionObject(bid, bidderRequest) {
var impObj = {};
var bannerObj;
var videoObj;
var nativeObj = {};
var sizes = bid.hasOwnProperty('sizes') ? bid.sizes : [];
var mediaTypes = '';
var format = [];
var isFledgeEnabled = bidderRequest?.paapi?.enabled;
impObj = {
id: bid.bidId,
tagid: bid.params.adUnit || undefined,
bidfloor: _parseSlotParam('kadfloor', bid.params.kadfloor),
secure: 1,
ext: {
pmZoneId: _parseSlotParam('pmzoneid', bid.params.pmzoneid)
},
bidfloorcur: bid.params.currency ? _parseSlotParam('currency', bid.params.currency) : DEFAULT_CURRENCY,
displaymanager: 'Prebid.js',
displaymanagerver: '$prebid.version$', // prebid version
pmp: bid.ortb2Imp?.pmp || undefined
};
_addPMPDealsInImpression(impObj, bid);
_addDealCustomTargetings(impObj, bid);
_addJWPlayerSegmentData(impObj, bid);
if (bid.hasOwnProperty('mediaTypes')) {
for (mediaTypes in bid.mediaTypes) {
switch (mediaTypes) {
case BANNER:
bannerObj = _createBannerRequest(bid);
if (bannerObj !== UNDEFINED) {
impObj.banner = bannerObj;
}
break;
case NATIVE:
// TODO uncomment below line when removing native 1.1 support
// nativeObj['request'] = JSON.stringify(_createNativeRequest(bid.nativeOrtbRequest));
// TODO delete below line when removing native 1.1 support
nativeObj['request'] = JSON.stringify(_createNativeRequest(bid.nativeParams));
if (!isInvalidNativeRequest) {
impObj.native = nativeObj;
} else {
logWarn(LOG_WARN_PREFIX + 'Error: Error in Native adunit ' + bid.params.adUnit + '. Ignoring the adunit. Refer to ' + PREBID_NATIVE_HELP_LINK + ' for more details.');
isInvalidNativeRequest = false;
}
break;
case FEATURES.VIDEO && VIDEO:
videoObj = _createVideoRequest(bid);
if (videoObj !== UNDEFINED) {
impObj.video = videoObj;
}
break;
}
}
} else {
// mediaTypes is not present, so this is a banner only impression
// this part of code is required for older testcases with no 'mediaTypes' to run succesfully.
bannerObj = {
pos: 0,
w: bid.params.width,
h: bid.params.height,
topframe: inIframe() ? 0 : 1
};
if (isArray(sizes) && sizes.length > 1) {
sizes = sizes.splice(1, sizes.length - 1);
sizes.forEach(size => {
format.push({
w: size[0],
h: size[1]
});
});
bannerObj.format = format;
}
impObj.banner = bannerObj;
}
_addImpressionFPD(impObj, bid);
_addFloorFromFloorModule(impObj, bid);
_addFledgeflag(impObj, bid, isFledgeEnabled)
return impObj.hasOwnProperty(BANNER) ||
impObj.hasOwnProperty(NATIVE) ||
(FEATURES.VIDEO && impObj.hasOwnProperty(VIDEO)) ? impObj : UNDEFINED;
}
function _addFledgeflag(impObj, bid, isFledgeEnabled) {
if (isFledgeEnabled) {
impObj.ext = impObj.ext || {};
if (bid?.ortb2Imp?.ext?.ae !== undefined) {
impObj.ext.ae = bid.ortb2Imp.ext.ae;
}
} else {
if (impObj.ext?.ae) {
delete impObj.ext.ae;
}
}
}
function _addImpressionFPD(imp, bid) {
const ortb2 = {...deepAccess(bid, 'ortb2Imp.ext.data')};
Object.keys(ortb2).forEach(prop => {
/**
* Prebid AdSlot
* @type {(string|undefined)}
*/
if (prop === 'pbadslot') {
if (typeof ortb2[prop] === 'string' && ortb2[prop]) deepSetValue(imp, 'ext.data.pbadslot', ortb2[prop]);
} else if (prop === 'adserver') {
/**
* Copy GAM AdUnit and Name to imp
*/
['name', 'adslot'].forEach(name => {
/** @type {(string|undefined)} */
const value = deepAccess(ortb2, `adserver.${name}`);
if (typeof value === 'string' && value) {
deepSetValue(imp, `ext.data.adserver.${name.toLowerCase()}`, value);
// copy GAM ad unit id as imp[].ext.dfp_ad_unit_code
if (name === 'adslot') {
deepSetValue(imp, `ext.dfp_ad_unit_code`, value);
}
}
});
} else {
deepSetValue(imp, `ext.data.${prop}`, ortb2[prop]);
}
});
const gpid = deepAccess(bid, 'ortb2Imp.ext.gpid');
gpid && deepSetValue(imp, `ext.gpid`, gpid);
}
function _addFloorFromFloorModule(impObj, bid) {
let bidFloor = -1;
// get lowest floor from floorModule
if (typeof bid.getFloor === 'function' && !config.getConfig('pubmatic.disableFloors')) {
[BANNER, VIDEO, NATIVE].forEach(mediaType => {
if (impObj.hasOwnProperty(mediaType)) {
let sizesArray = [];
if (mediaType === 'banner') {
if (impObj[mediaType].w && impObj[mediaType].h) {
sizesArray.push([impObj[mediaType].w, impObj[mediaType].h]);
}
if (isArray(impObj[mediaType].format)) {
impObj[mediaType].format.forEach(size => sizesArray.push([size.w, size.h]));
}
}
if (sizesArray.length === 0) {
sizesArray.push('*')
}
sizesArray.forEach(size => {
let floorInfo = bid.getFloor({ currency: impObj.bidfloorcur, mediaType: mediaType, size: size });
logInfo(LOG_WARN_PREFIX, 'floor from floor module returned for mediatype:', mediaType, ' and size:', size, ' is: currency', floorInfo.currency, 'floor', floorInfo.floor);
if (isPlainObject(floorInfo) && floorInfo.currency === impObj.bidfloorcur && !isNaN(parseInt(floorInfo.floor))) {
let mediaTypeFloor = parseFloat(floorInfo.floor);
logInfo(LOG_WARN_PREFIX, 'floor from floor module:', mediaTypeFloor, 'previous floor value', bidFloor, 'Min:', Math.min(mediaTypeFloor, bidFloor));
if (bidFloor === -1) {
bidFloor = mediaTypeFloor;
} else {
bidFloor = Math.min(mediaTypeFloor, bidFloor)
}
logInfo(LOG_WARN_PREFIX, 'new floor value:', bidFloor);
}
});
}
});
}
// get highest from impObj.bidfllor and floor from floor module
// as we are using Math.max, it is ok if we have not got any floor from floorModule, then value of bidFloor will be -1
if (impObj.bidfloor) {
logInfo(LOG_WARN_PREFIX, 'floor from floor module:', bidFloor, 'impObj.bidfloor', impObj.bidfloor, 'Max:', Math.max(bidFloor, impObj.bidfloor));
bidFloor = Math.max(bidFloor, impObj.bidfloor)
}
// assign value only if bidFloor is > 0
impObj.bidfloor = ((!isNaN(bidFloor) && bidFloor > 0) ? bidFloor : UNDEFINED);
logInfo(LOG_WARN_PREFIX, 'new impObj.bidfloor value:', impObj.bidfloor);
}
function _handleEids(payload, validBidRequests) {
let bidUserIdAsEids = deepAccess(validBidRequests, '0.userIdAsEids');
if (isArray(bidUserIdAsEids) && bidUserIdAsEids.length > 0) {
deepSetValue(payload, 'user.eids', bidUserIdAsEids);
}
}
export function setTTL(bid, newBid) {
let ttl = MEDIATYPE_TTL[newBid?.mediaType] || DEFAULT_TTL;
newBid.ttl = bid.exp || ttl;
}
// Setting IBV & meta.mediaType field into the bid response
export function setIBVField(bid, newBid) {
if (bid?.ext?.ibv) {
newBid.ext = newBid.ext || {};
newBid.ext['ibv'] = bid.ext.ibv;
// Overriding the mediaType field in meta with the `video` value if bid.ext.ibv is present
newBid.meta = newBid.meta || {};
newBid.meta.mediaType = VIDEO;
}
}
function _checkMediaType(bid, newBid) {
// Create a regex here to check the strings
if (bid.ext && bid.ext['bidtype'] != undefined) {
newBid.mediaType = MEDIATYPE[bid.ext.bidtype];
} else {
logInfo(LOG_WARN_PREFIX + 'bid.ext.bidtype does not exist, checking alternatively for mediaType');
var adm = bid.adm;
var admStr = '';
var videoRegex = new RegExp(/VAST\s+version/);
if (adm.indexOf('span class="PubAPIAd"') >= 0) {
newBid.mediaType = BANNER;
} else if (FEATURES.VIDEO && videoRegex.test(adm)) {
newBid.mediaType = VIDEO;
} else {
try {
admStr = JSON.parse(adm.replace(/\\/g, ''));
if (admStr && admStr.native) {
newBid.mediaType = NATIVE;
}
} catch (e) {
logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + adm);
}
}
}
}
function _parseNativeResponse(bid, newBid) {
if (bid.hasOwnProperty('adm')) {
var adm = '';
try {
adm = JSON.parse(bid.adm.replace(/\\/g, ''));
} catch (ex) {
logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + newBid.adm);
return;
}
newBid.native = {
ortb: { ...adm.native }
};
newBid.mediaType = NATIVE;
if (!newBid.width) {
newBid.width = DEFAULT_WIDTH;
}
if (!newBid.height) {
newBid.height = DEFAULT_HEIGHT;
}
}
}
function _blockedIabCategoriesValidation(payload, blockedIabCategories) {
blockedIabCategories = blockedIabCategories
.filter(function(category) {
if (typeof category === 'string') { // only strings
return true;
} else {
logWarn(LOG_WARN_PREFIX + 'bcat: Each category should be a string, ignoring category: ' + category);
return false;
}
})
.map(category => category.trim()) // trim all
.filter(function(category, index, arr) { // more than 3 charaters length
if (category.length > 3) {
return arr.indexOf(category) === index; // unique value only
} else {
logWarn(LOG_WARN_PREFIX + 'bcat: Each category should have a value of a length of more than 3 characters, ignoring category: ' + category)
}
});
if (blockedIabCategories.length > 0) {
logWarn(LOG_WARN_PREFIX + 'bcat: Selected: ', blockedIabCategories);
payload.bcat = blockedIabCategories;
}
}
function _allowedIabCategoriesValidation(payload, allowedIabCategories) {
allowedIabCategories = allowedIabCategories
.filter(function(category) {
if (typeof category === 'string') { // returns only strings
return true;
} else {
logWarn(LOG_WARN_PREFIX + 'acat: Each category should be a string, ignoring category: ' + category);
return false;
}
})
.map(category => category.trim()) // trim all categories
.filter((category, index, arr) => arr.indexOf(category) === index); // return unique values only
if (allowedIabCategories.length > 0) {
logWarn(LOG_WARN_PREFIX + 'acat: Selected: ', allowedIabCategories);
payload.ext.acat = allowedIabCategories;
}
}
function _assignRenderer(newBid, request) {
let bidParams, context, adUnitCode;
if (request.bidderRequest && request.bidderRequest.bids) {
for (let bidderRequestBidsIndex = 0; bidderRequestBidsIndex < request.bidderRequest.bids.length; bidderRequestBidsIndex++) {
if (request.bidderRequest.bids[bidderRequestBidsIndex].bidId === newBid.requestId) {
bidParams = request.bidderRequest.bids[bidderRequestBidsIndex].params;
if (FEATURES.VIDEO) {
context = request.bidderRequest.bids[bidderRequestBidsIndex].mediaTypes[VIDEO].context;
}
adUnitCode = request.bidderRequest.bids[bidderRequestBidsIndex].adUnitCode;
}
}
if (context && context === 'outstream' && bidParams && bidParams.outstreamAU && adUnitCode) {
newBid.rendererCode = bidParams.outstreamAU;
newBid.renderer = BB_RENDERER.newRenderer(newBid.rendererCode, adUnitCode);
}
}
}
/**
* In case of adpod video context, assign prebiddealpriority to the dealtier property of adpod-video bid,
* so that adpod module can set the hb_pb_cat_dur targetting key.
* @param {*} newBid