-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathbidManager.js
811 lines (722 loc) · 31 KB
/
bidManager.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
var CONFIG = require("./config.js");
var CONSTANTS = require("./constants.js");
var util = require("./util.js");
// var GDPR = require("./gdpr.js");
var bmEntry = require("./bmEntry.js");
var refThis = this;
function createBidEntry(divID){ // TDD, i/o : done
/* istanbul ignore else */
if(! util.isOwnProperty(window.PWT.bidMap, divID) ){
window.PWT.bidMap[divID] = bmEntry.createBMEntry(divID);
}
}
/* start-test-block */
exports.createBidEntry = createBidEntry;
/* end-test-block */
exports.setSizes = function(divID, slotSizes){ // TDD, i/o : done
refThis.createBidEntry(divID);
window.PWT.bidMap[divID].setSizes(slotSizes);
};
exports.setCallInitTime = function(divID, adapterID){ // TDD, i/o : done
refThis.createBidEntry(divID);
window.PWT.bidMap[divID].setAdapterEntry(adapterID);
};
exports.setAllPossibleBidsReceived = function(divID){
window.PWT.bidMap[divID].setAllPossibleBidsReceived();
};
exports.setBidFromBidder = function(divID, bidDetails){ // TDD done
var bidderID = bidDetails.getAdapterID();
var bidID = bidDetails.getBidID();
var bidMapEntry = window.PWT.bidMap[divID];
/* istanbul ignore else */
if(!util.isOwnProperty(window.PWT.bidMap, divID)){
util.logWarning("BidManager is not expecting bid for "+ divID +", from " + bidderID);
return;
}
var isPostTimeout = (bidMapEntry.getCreationTime()+CONFIG.getTimeout()) < bidDetails.getReceivedTime() ? true : false,
latency = bidDetails.getReceivedTime() - bidMapEntry.getCreationTime();
refThis.createBidEntry(divID);
util.log("BdManagerSetBid: divID: "+divID+", bidderID: "+bidderID+", ecpm: "+bidDetails.getGrossEcpm() + ", size: " + bidDetails.getWidth()+"x"+bidDetails.getHeight() + ", postTimeout: "+isPostTimeout + ", defaultBid: " + bidDetails.getDefaultBidStatus());
/* istanbul ignore else */
if(isPostTimeout === true /*&& !bidDetails.isServerSide*/){
bidDetails.setPostTimeoutStatus();
}
var lastBidID = bidMapEntry.getLastBidIDForAdapter(bidderID);
if(lastBidID != ""){
var lastBid = bidMapEntry.getBid(bidderID, lastBidID), //todo: what if the lastBid is null
lastBidWasDefaultBid = lastBid.getDefaultBidStatus() === 1,
lastBidWasErrorBid = lastBid.getDefaultBidStatus() === -1
;
if( lastBidWasDefaultBid || !isPostTimeout || lastBidWasErrorBid){
/* istanbul ignore else */
if(lastBidWasDefaultBid){
util.log(CONSTANTS.MESSAGES.M23 + bidderID);
}
if( lastBidWasDefaultBid || lastBid.getNetEcpm() < bidDetails.getNetEcpm() || lastBidWasErrorBid){
util.log(CONSTANTS.MESSAGES.M12+lastBid.getNetEcpm()+CONSTANTS.MESSAGES.M13+bidDetails.getNetEcpm()+CONSTANTS.MESSAGES.M14 + bidderID);
refThis.storeBidInBidMap(divID, bidderID, bidDetails, latency);
}else{
util.log(CONSTANTS.MESSAGES.M12+lastBid.getNetEcpm()+CONSTANTS.MESSAGES.M15+bidDetails.getNetEcpm()+CONSTANTS.MESSAGES.M16 + bidderID);
}
}else{
util.log(CONSTANTS.MESSAGES.M17);
}
}else{
util.log(CONSTANTS.MESSAGES.M18 + bidderID);
refThis.storeBidInBidMap(divID, bidderID, bidDetails, latency);
}
if (isPostTimeout) {
//explicitly trigger user syncs since its a post timeout bid
setTimeout(window[CONSTANTS.COMMON.PREBID_NAMESPACE].triggerUserSyncs, 10);
}
};
function storeBidInBidMap(slotID, adapterID, theBid, latency){ // TDD, i/o : done
// Adding a hook for publishers to modify the bid we have to store
// we should not call the hook for defaultbids and post-timeout bids
// Here slotID, adapterID, and latency are read-only and theBid can be modified
// if(theBid.getDefaultBidStatus() === 0 && theBid.getPostTimeoutStatus() === false){
// util.handleHook(CONSTANTS.HOOKS.BID_RECEIVED, [slotID, adapterID, theBid, latency]);
// }
window.PWT.bidMap[slotID].setNewBid(adapterID, theBid);
window.PWT.bidIdMap[theBid.getBidID()] = {
s: slotID,
a: adapterID
};
/* istanbul ignore else */
if(theBid.getDefaultBidStatus() === 0 && theBid.adapterID !== "pubmaticServer"){
util.vLogInfo(slotID, {
type: "bid",
bidder: adapterID + (CONFIG.getBidPassThroughStatus(adapterID) !== 0 ? '(Passthrough)' : ''),
bidDetails: theBid,
latency: latency,
s2s: CONFIG.isServerSideAdapter(adapterID),
adServerCurrency: util.getCurrencyToDisplay()
});
}
}
/* start-test-block */
exports.storeBidInBidMap = storeBidInBidMap;
/* end-test-block */
function resetBid(divID, impressionID){ // TDD, i/o : done
util.vLogInfo(divID, {type: "hr"});
delete window.PWT.bidMap[divID];
refThis.createBidEntry(divID);
window.PWT.bidMap[divID].setImpressionID(impressionID);
}
/* start-test-block */
exports.resetBid = resetBid;
/* end-test-block */
// removeIf(removeLegacyAnalyticsRelatedCode)
function createMetaDataKey(pattern, bmEntry, keyValuePairs){
var output = "",
validBidCount = 0,
partnerCount = 0,
macros = CONSTANTS.METADATA_MACROS,
macroRegexFlag = "g";
util.forEachOnObject(bmEntry.adapters, function(adapterID, adapterEntry) {
if (adapterEntry.getLastBidID() != "") {
// If pubmaticServerBidAdapter then don't increase partnerCount
(adapterID !== "pubmaticServer") && partnerCount++;
util.forEachOnObject(adapterEntry.bids, function(bidID, theBid) {
// Description-> adapterID == "pubmatic" && theBid.netEcpm == 0 this check is put because from pubmaticBidAdapter in prebid we are
// passing zero bid when there are no bid under timout for latency reports and this caused issue to have zero bids in pwtm key
// so put this check which will not log zero bids for pubmatic. Note : From prebid 1.x onwards we do not get zero bids in case of no bids.
if(theBid.getDefaultBidStatus() == 1 || theBid.getPostTimeoutStatus() == 1 || theBid.getGrossEcpm() == 0){
return;
}
validBidCount++;
output += replaceMetaDataMacros(pattern, theBid);
});
}
});
if(output.length == 0){
output = pattern;
}
output = output.replace(new RegExp(macros.BID_COUNT, macroRegexFlag), validBidCount);
output = output.replace(new RegExp(macros.PARTNER_COUNT, macroRegexFlag), partnerCount);
keyValuePairs[CONSTANTS.WRAPPER_TARGETING_KEYS.META_DATA] = encodeURIComponent(output);
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
/* start-test-block */
exports.createMetaDataKey = createMetaDataKey;
/* end-test-block */
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
function replaceMetaDataMacros(pattern, theBid){
var macros = CONSTANTS.METADATA_MACROS,
macroRegexFlag = "g"
;
return pattern
.replace(new RegExp(macros.PARTNER, macroRegexFlag), theBid.getAdapterID())
.replace(new RegExp(macros.WIDTH, macroRegexFlag), theBid.getWidth())
.replace(new RegExp(macros.HEIGHT, macroRegexFlag), theBid.getHeight())
.replace(new RegExp(macros.GROSS_ECPM, macroRegexFlag), theBid.getGrossEcpm())
.replace(new RegExp(macros.NET_ECPM, macroRegexFlag), theBid.getNetEcpm());
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
/* start-test-block */
exports.replaceMetaDataMacros = replaceMetaDataMacros;
/* end-test-block */
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
function auctionBids(bmEntry) { // TDD, i/o : done
var winningBid = null,
keyValuePairs = {};
util.forEachOnObject(bmEntry.adapters, function(adapterID, adapterEntry) {
var obj = refThis.auctionBidsCallBack(adapterID, adapterEntry, keyValuePairs, winningBid);
winningBid = obj.winningBid;
keyValuePairs = obj.keyValuePairs;
});
// removeIf(removeLegacyAnalyticsRelatedCode)
if(CONFIG.getMataDataPattern() !== null){
createMetaDataKey(CONFIG.getMataDataPattern(), bmEntry, keyValuePairs);
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
return {
wb: winningBid,
kvp: keyValuePairs
};
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
/* start-test-block */
exports.auctionBids = auctionBids;
/* end-test-block */
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeNativeRelatedCode)
function updateNativeTargtingKeys(keyValuePairs) {
for(var key in keyValuePairs) {
if (key.indexOf("native") >= 0 && key.split("_").length === 3) {
delete keyValuePairs[key];
}
}
}
// endRemoveIf(removeNativeRelatedCode)
// removeIf(removeNativeRelatedCode)
/* start-test-block */
exports.updateNativeTargtingKeys = updateNativeTargtingKeys;
/* end-test-block */
// endRemoveIf(removeNativeRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
function auctionBidsCallBack(adapterID, adapterEntry, keyValuePairs, winningBid) { // TDD, i/o : done
var refThis = this;
if (adapterEntry.getLastBidID() != "") {
util.forEachOnObject(adapterEntry.bids, function(bidID, theBid) {
// do not consider post-timeout bids
/* istanbul ignore else */
if (theBid.getPostTimeoutStatus() === true) {
return { winningBid: winningBid , keyValuePairs: keyValuePairs };
}
/* istanbul ignore else */
if(theBid.getDefaultBidStatus() !== 1 && CONFIG.getSendAllBidsStatus() == 1){
theBid.setSendAllBidsKeys();
}
if (winningBid !== null ) {
if (winningBid.getNetEcpm() < theBid.getNetEcpm()) {
// i.e. the current bid is the winning bid, so remove the native keys from keyValuePairs
// removeIf(removeNativeRelatedCode)
refThis.updateNativeTargtingKeys(keyValuePairs);
// endRemoveIf(removeNativeRelatedCode)
} else {
// i.e. the current bid is not the winning bid, so remove the native keys from theBid.keyValuePairs
var bidKeyValuePairs = theBid.getKeyValuePairs();
// removeIf(removeNativeRelatedCode)
refThis.updateNativeTargtingKeys(bidKeyValuePairs);
// endRemoveIf(removeNativeRelatedCode)
theBid.keyValuePairs = bidKeyValuePairs;
}
}
util.copyKeyValueObject(keyValuePairs, theBid.getKeyValuePairs());
/* istanbul ignore else */
if (CONFIG.getBidPassThroughStatus(adapterID) !== 0) {
return { winningBid: winningBid , keyValuePairs: keyValuePairs };
}
if (winningBid == null) {
winningBid = theBid;
} else if (winningBid.getNetEcpm() < theBid.getNetEcpm()) {
winningBid = theBid;
}
});
return { winningBid: winningBid , keyValuePairs: keyValuePairs };
} else {
return { winningBid: winningBid , keyValuePairs: keyValuePairs };
}
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
/* start-test-block */
exports.auctionBidsCallBack = auctionBidsCallBack;
/* end-test-block */
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.getBid = function(divID){ // TDD, i/o : done
var winningBid = null;
var keyValuePairs = null;
/* istanbul ignore else */
if( util.isOwnProperty(window.PWT.bidMap, divID) ){
var data = refThis.auctionBids(window.PWT.bidMap[divID]);
winningBid = data.wb;
keyValuePairs = data.kvp;
window.PWT.bidMap[divID].setAnalyticEnabled();//Analytics Enabled
if(winningBid && winningBid.getNetEcpm() > 0){
winningBid.setStatus(1);
winningBid.setWinningBidStatus();
util.vLogInfo(divID, {
type: "win-bid",
bidDetails: winningBid,
adServerCurrency: util.getCurrencyToDisplay()
});
}else{
util.vLogInfo(divID, {
type: "win-bid-fail",
});
}
}
return {wb: winningBid, kvp: keyValuePairs};
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.getBidById = function(bidID) { // TDD, i/o : done
/* istanbul ignore else */
if (!util.isOwnProperty(window.PWT.bidIdMap, bidID)) {
util.log(CONSTANTS.MESSAGES.M25 + bidID);
return null;
}
var divID = window.PWT.bidIdMap[bidID].s;
var adapterID = window.PWT.bidIdMap[bidID].a;
/* istanbul ignore else */
if (util.isOwnProperty(window.PWT.bidMap, divID)) {
util.log("BidID: " + bidID + ", DivID: " + divID + CONSTANTS.MESSAGES.M19 + adapterID);
var theBid = window.PWT.bidMap[divID].getBid(adapterID, bidID);
/* istanbul ignore else */
if (theBid == null) {
return null;
}
return {
bid: theBid,
slotid: divID
};
}
util.log(CONSTANTS.MESSAGES.M25 + bidID);
return null;
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.displayCreative = function(theDocument, bidID){ // TDD, i/o : done
var bidDetails = refThis.getBidById(bidID);
/* istanbul ignore else */
if(bidDetails){
var theBid = bidDetails.bid,
divID = bidDetails.slotid
;
util.displayCreative(theDocument, theBid);
util.vLogInfo(divID, {type: 'disp', adapter: theBid.getAdapterID()});
refThis.executeMonetizationPixel(divID, theBid);
}
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.executeAnalyticsPixel = function(){ // TDD, i/o : done
var outputObj = {
s: []
},
pubId = CONFIG.getPublisherId(),
// gdprData = GDPR.getUserConsentDataFromLS(),
// consentString = "",
pixelURL = CONFIG.getAnalyticsPixelURL(),
impressionIDMap = {} // impID => slots[]
;
/* istanbul ignore else */
if(!pixelURL){
return;
}
pixelURL = CONSTANTS.COMMON.PROTOCOL + pixelURL + "pubid=" + pubId;
outputObj[CONSTANTS.CONFIG.PUBLISHER_ID] = CONFIG.getPublisherId();
outputObj[CONSTANTS.LOGGER_PIXEL_PARAMS.TIMEOUT] = ""+CONFIG.getTimeout();
outputObj[CONSTANTS.LOGGER_PIXEL_PARAMS.PAGE_URL] = window.decodeURIComponent(util.metaInfo.pageURL);
outputObj[CONSTANTS.LOGGER_PIXEL_PARAMS.PAGE_DOMAIN] = util.metaInfo.pageDomain;
outputObj[CONSTANTS.LOGGER_PIXEL_PARAMS.TIMESTAMP] = util.getCurrentTimestamp();
outputObj[CONSTANTS.CONFIG.PROFILE_ID] = CONFIG.getProfileID();
outputObj[CONSTANTS.CONFIG.PROFILE_VERSION_ID] = CONFIG.getProfileDisplayVersionID();
outputObj["tgid"] = (function() {
var testGroupId = parseInt(PWT.testGroupId || 0);
if (testGroupId <= 15 && testGroupId >= 0) {
return testGroupId;
}
return 0;
})();
// As discussed we won't be seding gdpr data to logger
// if (CONFIG.getGdpr()) {
// consentString = gdprData && gdprData.c ? encodeURIComponent(gdprData.c) : "";
// outputObj[CONSTANTS.CONFIG.GDPR_CONSENT] = gdprData && gdprData.g;
// outputObj[CONSTANTS.CONFIG.CONSENT_STRING] = consentString;
// pixelURL += "&gdEn=" + (CONFIG.getGdpr() ? 1 : 0);
// }
util.forEachOnObject(window.PWT.bidMap, function (slotID, bmEntry) {
refThis.analyticalPixelCallback(slotID, bmEntry, impressionIDMap);
});
util.forEachOnObject(impressionIDMap, function(impressionID, slots){ /* istanbul ignore next */
/* istanbul ignore else */
if(slots.length > 0){
outputObj.s = slots;
outputObj[CONSTANTS.COMMON.IMPRESSION_ID] = window.encodeURIComponent(impressionID);
if(CONFIG.isFloorPriceModuleEnabled()){
var _floorData = window.PWT.floorData[outputObj[CONSTANTS.COMMON.IMPRESSION_ID]];
outputObj["fmv"] = _floorData.floorRequestData ? _floorData.floorRequestData.modelVersion || undefined : undefined,
outputObj["ft"] = _floorData.floorResponseData ? (_floorData.floorResponseData.enforcements.enforceJS == false ? 0 : 1) : undefined;
}
outputObj.psl = slots.psl;
outputObj.dvc = { "plt": util.getDevicePlatform()}
// (new window.Image()).src = pixelURL + "&json=" + window.encodeURIComponent(JSON.stringify(outputObj));
util.ajaxRequest(pixelURL, function(){}, "json=" + window.encodeURIComponent(JSON.stringify(outputObj)), {
contentType : "application/x-www-form-urlencoded", // as per https://inside.pubmatic.com:8443/confluence/pages/viewpage.action?spaceKey=Products&title=POST+support+for+logger+in+Wrapper-tracker
withCredentials : true
});
}
});
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.executeMonetizationPixel = function(slotID, theBid){ // TDD, i/o : done
var pixelURL = util.generateMonetizationPixel(slotID,theBid);
if(!pixelURL){
return;
}
refThis.setImageSrcToPixelURL(pixelURL);
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
function getAdUnitSizes(bmEntry){
var _adapter = Object.keys(bmEntry.adapters).filter(function(adapter){
if( Object.keys(bmEntry.adapters[adapter].bids).filter(function(bid){
if(!!bmEntry.adapters[adapter].bids[bid].isWinningBid && bmEntry.adapters[adapter].bids[bid].adFormat === "native")
return bmEntry.adapters[adapter].bids[bid];
}).length == 1)
return adapter;
})
if(!!_adapter.length){
return ["1x1"];
}
return bmEntry.getSizes();
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
/* start-test-block */
exports.getAdUnitSizes = getAdUnitSizes;
/* end-test-block */
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
function getAdUnitInfo(slotId){
return window.PWT.adUnits[slotId]|| slotId;
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
/* start-test-block */
exports.getAdUnitInfo = getAdUnitInfo;
/* end-test-block */
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
function getAdUnitAdFormats(mediaTypes){
var af = !!mediaTypes ? Object.keys(mediaTypes).map( function(mediatype){
return CONSTANTS.MEDIATYPE[mediatype.toUpperCase()];
}).filter(function(mtype){
return mtype != null
}) : [];
return af || [];
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
/* start-test-block */
exports.getAdUnitAdFormats = getAdUnitAdFormats;
/* end-test-block */
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
function getAdDomain(bidResponse) {
if (bidResponse.meta && bidResponse.meta.advertiserDomains && bidResponse.meta.advertiserDomains.length > 0) {
var adomain = bidResponse.meta.advertiserDomains[0];
if (adomain) {
try {
var hostname = new URL(adomain);
return hostname.hostname.replace('www.', '');
} catch (e) {
util.log("Adomain URL (Not a proper URL):"+ adomain);
return adomain.split('/')[0].replace('www.', '');
}
}
}
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
function analyticalPixelCallback(slotID, bmEntry, impressionIDMap) { // TDD, i/o : done
var usePBSAdapter = CONFIG.usePBSAdapter();
var startTime = bmEntry.getCreationTime() || 0;
var pslTime = (usePBSAdapter && window.pbsLatency) ? 0 : undefined;
var impressionID = bmEntry.getImpressionID();
var adUnitInfo = refThis.getAdUnitInfo(slotID);
var latencyValue = {};
const isAnalytics = true; // this flag is required to get grossCpm and netCpm in dollars instead of adserver currency
/* istanbul ignore else */
if (bmEntry.getAnalyticEnabledStatus() && !bmEntry.getExpiredStatus()) {
var slotObject = {
"sn": slotID,
"sz": refThis.getAdUnitSizes(bmEntry),
"au": adUnitInfo.adUnitId || slotID,
"fskp" : window.PWT.floorData ? (window.PWT.floorData[impressionID] ? (window.PWT.floorData[impressionID].floorRequestData ? (window.PWT.floorData[impressionID].floorRequestData.skipped == false ? 0 : 1) : undefined) : undefined) : undefined,
"mt": refThis.getAdUnitAdFormats(adUnitInfo.mediaTypes),
"ps": []
};
bmEntry.setExpired();
impressionIDMap[impressionID] = impressionIDMap[impressionID] || [];
util.forEachOnObject(bmEntry.adapters, function(adapterID, adapterEntry) {
/* istanbul ignore else */
if (CONFIG.getBidPassThroughStatus(adapterID) == 1) {
return;
}
util.forEachOnObject(adapterEntry.bids, function(bidID, theBid) {
if(usePBSAdapter) {
// In PrebidServerBidAdapater we are capturing start and end time of request
// fetching these values here to calculate psl time for logger call
latencyValue = window.pbsLatency && window.pbsLatency[impressionID];
if(latencyValue && latencyValue['endTime'] && latencyValue['startTime']) {
pslTime = latencyValue['endTime'] - latencyValue['startTime'];
}
// When we use PrebidServerBidAdapter we do not get seatbid for zero bid / no bid partners
// as we need to log PubMatic partner in logger will be changing db = 0.
if((adapterID === "pubmatic" || adapterID === "pubmatic2") && (util.isOwnProperty(window.partnersWithoutErrorAndBids, impressionID) && window.partnersWithoutErrorAndBids[impressionID].includes(adapterID))) {
theBid.defaultBid = 0;
} else if(util.isOwnProperty(window.partnersWithoutErrorAndBids, impressionID) &&
window.partnersWithoutErrorAndBids[impressionID].includes(adapterID) &&
CONFIG.getAdapterNameForAlias(adapterID).includes('pubmatic')) {
theBid.defaultBid = 0;
}
}
var endTime = theBid.getReceivedTime();
if (adapterID === "pubmaticServer") {
if ((util.isOwnProperty(window.PWT.owLatency, impressionID)) &&
(util.isOwnProperty(window.PWT.owLatency[impressionID], "startTime")) &&
(util.isOwnProperty(window.PWT.owLatency[impressionID], "endTime"))) {
pslTime = (window.PWT.owLatency[impressionID].endTime - window.PWT.owLatency[impressionID].startTime);
} else {
pslTime = 0;
util.log("Logging pubmaticServer latency as 0 for impressionID: " + impressionID);
}
util.log("PSL logging: time logged for id " +impressionID+ " is " + pslTime);
return;
}
if(CONFIG.getAdapterMaskBidsStatus(adapterID) == 1){
if(theBid.getWinningBidStatus() === false){
return;
}
}
/* if serverside adapter and
db == 0 and
getServerSideResponseTime returns -1, it means that server responded with error code 1/2/6
hence do not add entry in logger.
keeping the check for responseTime on -1 since there could be a case where:
ss status = 1, db status = 0, and responseTime is 0, but error code is 4, i,e. no bid. And for error code 4,
we want to log the data not skip it.
*/
if (theBid.getServerSideStatus()) {
if (theBid.getDefaultBidStatus() === -1 &&
theBid.getServerSideResponseTime() === -1) {
return;
}
}
// Logic : if adapter is pubmatic and bid falls under two condition :
/**
* 1.timeout zero bids
* 2.no response from translator
* Then we don't log it for pubmatic
* Reason : Logging timeout zero bids causing reports to show more zero in comparision to other bidders
* Originally we started logging this for latency purposes.
* Future Scope : Remove below check to log with appt. value(s)
*/
/*istanbul ignore else*/
if( (adapterID === "pubmatic" || adapterID === "pubmatic2") && (theBid.getDefaultBidStatus() || (theBid.getPostTimeoutStatus() && theBid.getGrossEcpm(isAnalytics) == 0))){
return;
}
var pbbid = theBid.getPbBid();
//todo: take all these key names from constants
slotObject["ps"].push({
"pn": CONFIG.getAdapterNameForAlias(adapterID),
"bc": adapterID,
"bidid": bidID,
"db": theBid.getDefaultBidStatus(),
"kgpv": theBid.getKGPV(),
"kgpsv": theBid.getKGPV(true),
"psz": theBid.getWidth() + "x" + theBid.getHeight(),
"eg": theBid.getGrossEcpm(isAnalytics),
"en": theBid.getNetEcpm(isAnalytics),
"di": theBid.getDealID(),
"dc": theBid.getDealChannel(),
"l1": theBid.getServerSideStatus() ? theBid.getServerSideResponseTime() : (endTime - startTime),
"l2": 0,
"adv": pbbid ? getAdDomain(pbbid) || undefined : undefined,
"ss": theBid.getServerSideStatus(),
"t": theBid.getPostTimeoutStatus() === false ? 0 : 1,
"wb": theBid.getWinningBidStatus() === true ? 1 : 0,
"mi": theBid.getServerSideStatus() ? theBid.getMi(adapterID) : undefined,
"af": theBid.getAdFormat(),
"ocpm": CONFIG.getAdServerCurrency() ? theBid.getOriginalCpm() : theBid.getGrossEcpm(),
"ocry": CONFIG.getAdServerCurrency() ? theBid.getOriginalCurrency() : CONSTANTS.COMMON.ANALYTICS_CURRENCY,
"piid": theBid.getsspID(),
"frv": theBid.getServerSideStatus() ? undefined : (pbbid ? ( pbbid.floorData ? pbbid.floorData.floorRuleValue : undefined ) : undefined),
});
})
});
impressionIDMap[impressionID].push(slotObject);
// special handling when all media types are disabled for adunit and
// if we are using PrebidServerBidAdapter with
if(usePBSAdapter && CONFIG.getServerEnabledAdaptars().length && pslTime == undefined && !window.pbsLatency) {
pslTime = 0;
}
if (pslTime !== undefined) {
impressionIDMap[impressionID].psl = pslTime;
}
}
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
/* start-test-block */
exports.analyticalPixelCallback = analyticalPixelCallback;
/* end-test-block */
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
// removeIf(removeLegacyAnalyticsRelatedCode)
// todo: using removeLegacyAnalyticsRelatedCode will make this function unavailable with PBJS analytics,
// i assume we will not be using this function for Native when PBJS analytics is enabled
/**
* function which takes url and creates an image and executes them
* used to execute trackers
* @param {*} pixelURL
* @param {*} useProtocol
* @returns
*/
exports.setImageSrcToPixelURL = function (pixelURL, useProtocol) { // TDD, i/o : done
var img = new window.Image();
if(useProtocol != undefined && !useProtocol){
img.src = pixelURL;
return;
}
if(String(pixelURL).trim().substring(0,8) != CONSTANTS.COMMON.PROTOCOL){
pixelURL = CONSTANTS.COMMON.PROTOCOL + pixelURL;
}
img.src = pixelURL;
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)
exports.getAllPartnersBidStatuses = function (bidMaps, divIds) {
var status = true;
util.forEachOnArray(divIds, function (key, divId) {
// OLD APPROACH: check if we have got bids per bidder for each slot
// bidMaps[divId] && util.forEachOnObject(bidMaps[divId].adapters, function (adapterID, adapter) {
// util.forEachOnObject(adapter.bids, function (bidId, theBid) {
// status = status && (theBid.getDefaultBidStatus() === 0);
// });
// });
// NEW APPROACH: check allPossibleBidsReceived flag which is set when pbjs.requestBids->bidsBackHandler is executed
if(bidMaps[divId]){
status = status && (bidMaps[divId].hasAllPossibleBidsReceived() === true);
}
});
return status;
};
// removeIf(removeNativeRelatedCode)
/**
* This function is used to execute trackers on event
* in case of native. On click of native create element
* @param {*} event
*/
exports.loadTrackers = function(event){
var bidId = util.getBidFromEvent(event);
window.parent.postMessage(
JSON.stringify({
pwt_type: "3",
pwt_bidID: bidId,
pwt_origin: CONSTANTS.COMMON.PROTOCOL + window.location.hostname,
pwt_action:"click"
}),
"*"
);
};
// endRemoveIf(removeNativeRelatedCode)
// removeIf(removeNativeRelatedCode)
/**
* function takes bidID and post a message to parent pwt.js to execute monetization pixels.
* @param {*} bidID
*/
exports.executeTracker = function(bidID){
window.parent.postMessage(
JSON.stringify({
pwt_type: "3",
pwt_bidID: bidID,
pwt_origin: CONSTANTS.COMMON.PROTOCOL + window.location.hostname,
pwt_action:"imptrackers"
}),
"*"
);
};
// endRemoveIf(removeNativeRelatedCode)
// removeIf(removeNativeRelatedCode)
/**
* based on action it executes either the clickTrackers or
* impressionTrackers and javascriptTrackers.
* Javascript trackers is a valid html, urls already wrapped in script tagsand its guidelines can be found at
* iab spec document.
* @param {*} bidDetails
* @param {*} action
*/
exports.fireTracker = function(bidDetails, action) {
var trackers;
if (action === "click") {
trackers = bidDetails["native"] && bidDetails["native"].clickTrackers;
} else if(action === "imptrackers") {
trackers = bidDetails["native"] && bidDetails["native"].impressionTrackers;
if (bidDetails['native'] && bidDetails['native'].javascriptTrackers) {
var iframe = util.createInvisibleIframe();
/* istanbul ignore else */
if(!iframe){
throw {message: 'Failed to create invisible frame for native javascript trackers'};
}
/* istanbul ignore else */
if(!iframe.contentWindow){
throw {message: 'Unable to access frame window for native javascript trackers'};
}
window.document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(bidDetails['native'].javascriptTrackers);
iframe.contentWindow.document.close();
}
}
(trackers || []).forEach(function(url){refThis.setImageSrcToPixelURL(url,false);});
};
// endRemoveIf(removeNativeRelatedCode)
// this function generates all satndard key-value pairs for a given bid and setup, set these key-value pairs in an object
// todo: write unit test cases
// removeIf(removeLegacyAnalyticsRelatedCode)
exports.setStandardKeys = function(winningBid, keyValuePairs){
if (winningBid) {
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.BID_ID ] = winningBid.getBidID();
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.BID_STATUS ] = winningBid.getStatus();
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.BID_ECPM ] = winningBid.getNetEcpm().toFixed(CONSTANTS.COMMON.BID_PRECISION);
var dealID = winningBid.getDealID();
if(dealID){
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.BID_DEAL_ID ] = dealID;
}
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.BID_ADAPTER_ID ] = winningBid.getAdapterID();
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.PUBLISHER_ID ] = CONFIG.getPublisherId();
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.PROFILE_ID ] = CONFIG.getProfileID();
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.PROFILE_VERSION_ID ] = CONFIG.getProfileDisplayVersionID();
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.BID_SIZE ] = winningBid.width + 'x' + winningBid.height;
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.PLATFORM_KEY ] = (winningBid.getAdFormat() == CONSTANTS.FORMAT_VALUES.VIDEO && winningBid.getcacheUUID()) ? CONSTANTS.PLATFORM_VALUES.VIDEO : (winningBid.getNative() ? CONSTANTS.PLATFORM_VALUES.NATIVE : CONSTANTS.PLATFORM_VALUES.DISPLAY);
if(winningBid.getAdFormat() == CONSTANTS.FORMAT_VALUES.VIDEO && winningBid.getcacheUUID()){
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.CACHE_PATH ] = CONSTANTS.CONFIG.CACHE_PATH;
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.CACHE_URL ] = CONSTANTS.CONFIG.CACHE_URL;
keyValuePairs[ CONSTANTS.WRAPPER_TARGETING_KEYS.CACHE_ID ] = winningBid.getcacheUUID();
}
} else {
util.logWarning('Not generating key-value pairs as invalid winningBid object passed. WinningBid: ');
util.logWarning(winningBid);
}
}
// endRemoveIf(removeLegacyAnalyticsRelatedCode)