-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
appnexusBidAdapter.js
1250 lines (1110 loc) · 39.4 KB
/
appnexusBidAdapter.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 {
chunk,
convertCamelToUnderscore,
convertTypes,
createTrackPixelHtml,
deepAccess,
deepClone,
fill,
getBidRequest,
getMaxValueFromArray,
getMinValueFromArray,
getParameterByName,
isArray,
isArrayOfNums,
isEmpty,
isFn,
isNumber,
isPlainObject,
isStr,
logError,
logInfo,
logMessage,
logWarn,
transformBidderParamKeywords,
getWindowFromDocument
} from '../src/utils.js';
import {Renderer} from '../src/Renderer.js';
import {config} from '../src/config.js';
import {getIabSubCategory, registerBidder} from '../src/adapters/bidderFactory.js';
import {ADPOD, BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js';
import {auctionManager} from '../src/auctionManager.js';
import {find, includes} from '../src/polyfill.js';
import {INSTREAM, OUTSTREAM} from '../src/video.js';
import {getStorageManager} from '../src/storageManager.js';
import {bidderSettings} from '../src/bidderSettings.js';
import {hasPurpose1Consent} from '../src/utils/gpdr.js';
import { convertOrtbRequestToProprietaryNative } from '../src/native.js';
const BIDDER_CODE = 'appnexus';
const URL = 'https://ib.adnxs.com/ut/v3/prebid';
const URL_SIMPLE = 'https://ib.adnxs-simple.com/ut/v3/prebid';
const VIDEO_TARGETING = ['id', 'minduration', 'maxduration',
'skippable', 'playback_method', 'frameworks', 'context', 'skipoffset'];
const VIDEO_RTB_TARGETING = ['minduration', 'maxduration', 'skip', 'skipafter', 'playbackmethod', 'api'];
const USER_PARAMS = ['age', 'externalUid', 'segments', 'gender', 'dnt', 'language'];
const APP_DEVICE_PARAMS = ['geo', 'device_id']; // appid is collected separately
const DEBUG_PARAMS = ['enabled', 'dongle', 'member_id', 'debug_timeout'];
const VIDEO_MAPPING = {
playback_method: {
'unknown': 0,
'auto_play_sound_on': 1,
'auto_play_sound_off': 2,
'click_to_play': 3,
'mouse_over': 4,
'auto_play_sound_unknown': 5
},
context: {
'unknown': 0,
'pre_roll': 1,
'mid_roll': 2,
'post_roll': 3,
'outstream': 4,
'in-banner': 5
}
};
const NATIVE_MAPPING = {
body: 'description',
body2: 'desc2',
cta: 'ctatext',
image: {
serverName: 'main_image',
requiredParams: { required: true }
},
icon: {
serverName: 'icon',
requiredParams: { required: true }
},
sponsoredBy: 'sponsored_by',
privacyLink: 'privacy_link',
salePrice: 'saleprice',
displayUrl: 'displayurl'
};
const SOURCE = 'pbjs';
const MAX_IMPS_PER_REQUEST = 15;
const mappingFileUrl = 'https://acdn.adnxs-simple.com/prebid/appnexus-mapping/mappings.json';
const SCRIPT_TAG_START = '<script';
const VIEWABILITY_URL_START = /\/\/cdn\.adnxs\.com\/v|\/\/cdn\.adnxs\-simple\.com\/v/;
const VIEWABILITY_FILE_NAME = 'trk.js';
const GVLID = 32;
const storage = getStorageManager({gvlid: GVLID, bidderCode: BIDDER_CODE});
export const spec = {
code: BIDDER_CODE,
gvlid: GVLID,
aliases: [
{ code: 'appnexusAst', gvlid: 32 },
{ code: 'emxdigital', gvlid: 183 },
{ code: 'pagescience' },
{ code: 'defymedia' },
{ code: 'gourmetads' },
{ code: 'matomy' },
{ code: 'featureforward' },
{ code: 'oftmedia' },
{ code: 'adasta' },
{ code: 'beintoo', gvlid: 618 },
],
supportedMediaTypes: [BANNER, VIDEO, NATIVE],
/**
* Determines whether or not the given bid request is valid.
*
* @param {object} bid The bid to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: function (bid) {
return !!(bid.params.placementId || (bid.params.member && bid.params.invCode));
},
/**
* Make a server request from the list of BidRequests.
*
* @param {BidRequest[]} bidRequests A non-empty list of bid requests which should be sent to the Server.
* @return ServerRequest Info describing the request to the server.
*/
buildRequests: function (bidRequests, bidderRequest) {
// convert Native ORTB definition to old-style prebid native definition
bidRequests = convertOrtbRequestToProprietaryNative(bidRequests);
const tags = bidRequests.map(bidToTag);
const userObjBid = find(bidRequests, hasUserInfo);
let userObj = {};
if (config.getConfig('coppa') === true) {
userObj = { 'coppa': true };
}
if (userObjBid) {
Object.keys(userObjBid.params.user)
.filter(param => includes(USER_PARAMS, param))
.forEach((param) => {
let uparam = convertCamelToUnderscore(param);
if (param === 'segments' && isArray(userObjBid.params.user[param])) {
let segs = [];
userObjBid.params.user[param].forEach(val => {
if (isNumber(val)) {
segs.push({'id': val});
} else if (isPlainObject(val)) {
segs.push(val);
}
});
userObj[uparam] = segs;
} else if (param !== 'segments') {
userObj[uparam] = userObjBid.params.user[param];
}
});
}
const appDeviceObjBid = find(bidRequests, hasAppDeviceInfo);
let appDeviceObj;
if (appDeviceObjBid && appDeviceObjBid.params && appDeviceObjBid.params.app) {
appDeviceObj = {};
Object.keys(appDeviceObjBid.params.app)
.filter(param => includes(APP_DEVICE_PARAMS, param))
.forEach(param => appDeviceObj[param] = appDeviceObjBid.params.app[param]);
}
const appIdObjBid = find(bidRequests, hasAppId);
let appIdObj;
if (appIdObjBid && appIdObjBid.params && appDeviceObjBid.params.app && appDeviceObjBid.params.app.id) {
appIdObj = {
appid: appIdObjBid.params.app.id
};
}
let debugObj = {};
let debugObjParams = {};
const debugCookieName = 'apn_prebid_debug';
const debugCookie = storage.getCookie(debugCookieName) || null;
if (debugCookie) {
try {
debugObj = JSON.parse(debugCookie);
} catch (e) {
logError('AppNexus Debug Auction Cookie Error:\n\n' + e);
}
} else {
const debugBidRequest = find(bidRequests, hasDebug);
if (debugBidRequest && debugBidRequest.debug) {
debugObj = debugBidRequest.debug;
}
}
if (debugObj && debugObj.enabled) {
Object.keys(debugObj)
.filter(param => includes(DEBUG_PARAMS, param))
.forEach(param => {
debugObjParams[param] = debugObj[param];
});
}
const memberIdBid = find(bidRequests, hasMemberId);
const member = memberIdBid ? parseInt(memberIdBid.params.member, 10) : 0;
const schain = bidRequests[0].schain;
const omidSupport = find(bidRequests, hasOmidSupport);
const payload = {
tags: [...tags],
user: userObj,
sdk: {
source: SOURCE,
version: '$prebid.version$'
},
schain: schain
};
if (omidSupport) {
payload['iab_support'] = {
omidpn: 'Appnexus',
omidpv: '$prebid.version$'
}
}
if (member > 0) {
payload.member_id = member;
}
if (appDeviceObjBid) {
payload.device = appDeviceObj
}
if (appIdObjBid) {
payload.app = appIdObj;
}
let auctionKeywords = config.getConfig('appnexusAuctionKeywords');
if (isPlainObject(auctionKeywords)) {
let aucKeywords = transformBidderParamKeywords(auctionKeywords);
if (aucKeywords.length > 0) {
aucKeywords.forEach(deleteValues);
}
payload.keywords = aucKeywords;
}
if (config.getConfig('adpod.brandCategoryExclusion')) {
payload.brand_category_uniqueness = true;
}
if (debugObjParams.enabled) {
payload.debug = debugObjParams;
logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4));
}
if (bidderRequest && bidderRequest.gdprConsent) {
// note - objects for impbus use underscore instead of camelCase
payload.gdpr_consent = {
consent_string: bidderRequest.gdprConsent.consentString,
consent_required: bidderRequest.gdprConsent.gdprApplies
};
if (bidderRequest.gdprConsent.addtlConsent && bidderRequest.gdprConsent.addtlConsent.indexOf('~') !== -1) {
let ac = bidderRequest.gdprConsent.addtlConsent;
// pull only the ids from the string (after the ~) and convert them to an array of ints
let acStr = ac.substring(ac.indexOf('~') + 1);
payload.gdpr_consent.addtl_consent = acStr.split('.').map(id => parseInt(id, 10));
}
}
if (bidderRequest && bidderRequest.uspConsent) {
payload.us_privacy = bidderRequest.uspConsent
}
if (bidderRequest && bidderRequest.refererInfo) {
let refererinfo = {
// TODO: are these the correct referer values?
rd_ref: encodeURIComponent(bidderRequest.refererInfo.topmostLocation),
rd_top: bidderRequest.refererInfo.reachedTop,
rd_ifs: bidderRequest.refererInfo.numIframes,
rd_stk: bidderRequest.refererInfo.stack.map((url) => encodeURIComponent(url)).join(',')
}
let pubPageUrl = bidderRequest.refererInfo.canonicalUrl;
if (isStr(pubPageUrl) && pubPageUrl !== '') {
refererinfo.rd_can = pubPageUrl;
}
payload.referrer_detection = refererinfo;
}
const hasAdPodBid = find(bidRequests, hasAdPod);
if (hasAdPodBid) {
bidRequests.filter(hasAdPod).forEach(adPodBid => {
const adPodTags = createAdPodRequest(tags, adPodBid);
// don't need the original adpod placement because it's in adPodTags
const nonPodTags = payload.tags.filter(tag => tag.uuid !== adPodBid.bidId);
payload.tags = [...nonPodTags, ...adPodTags];
});
}
if (bidRequests[0].userId) {
let eids = [];
addUserId(eids, deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null);
addUserId(eids, deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null);
addUserId(eids, deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null);
addUserId(eids, deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID');
addUserId(eids, deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2');
if (bidRequests[0].userId.pubProvidedId) {
bidRequests[0].userId.pubProvidedId.forEach(ppId => {
ppId.uids.forEach(uid => {
eids.push({ source: ppId.source, id: uid.id });
});
});
}
if (eids.length) {
payload.eids = eids;
}
}
if (tags[0].publisher_id) {
payload.publisher_id = tags[0].publisher_id;
}
const request = formatRequest(payload, bidderRequest);
return request;
},
/**
* Unpack the response from the server into a list of bids.
*
* @param {*} serverResponse A successful response from the server.
* @return {Bid[]} An array of bids which were nested inside the server.
*/
interpretResponse: function (serverResponse, { bidderRequest }) {
serverResponse = serverResponse.body;
const bids = [];
if (!serverResponse || serverResponse.error) {
let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`;
if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; }
logError(errorMessage);
return bids;
}
if (serverResponse.tags) {
serverResponse.tags.forEach(serverBid => {
const rtbBid = getRtbBid(serverBid);
if (rtbBid) {
const cpmCheck = (bidderSettings.get(bidderRequest.bidderCode, 'allowZeroCpmBids') === true) ? rtbBid.cpm >= 0 : rtbBid.cpm > 0;
if (cpmCheck && includes(this.supportedMediaTypes, rtbBid.ad_type)) {
const bid = newBid(serverBid, rtbBid, bidderRequest);
bid.mediaType = parseMediaType(rtbBid);
bids.push(bid);
}
}
});
}
if (serverResponse.debug && serverResponse.debug.debug_info) {
let debugHeader = 'AppNexus Debug Auction for Prebid\n\n'
let debugText = debugHeader + serverResponse.debug.debug_info
debugText = debugText
.replace(/(<td>|<th>)/gm, '\t') // Tables
.replace(/(<\/td>|<\/th>)/gm, '\n') // Tables
.replace(/^<br>/gm, '') // Remove leading <br>
.replace(/(<br>\n|<br>)/gm, '\n') // <br>
.replace(/<h1>(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1
.replace(/<h[2-6]>(.*)<\/h[2-6]>/gm, '\n\n*** $1 ***\n\n') // Headers
.replace(/(<([^>]+)>)/igm, ''); // Remove any other tags
logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction');
logMessage(debugText);
}
return bids;
},
/**
* @typedef {Object} mappingFileInfo
* @property {string} url mapping file json url
* @property {number} refreshInDays prebid stores mapping data in localstorage so you can return in how many days you want to update value stored in localstorage.
* @property {string} localStorageKey unique key to store your mapping json in localstorage
*/
/**
* Returns mapping file info. This info will be used by bidderFactory to preload mapping file and store data in local storage
* @returns {mappingFileInfo}
*/
getMappingFileInfo: function () {
return {
url: mappingFileUrl,
refreshInDays: 2
}
},
getUserSyncs: function (syncOptions, responses, gdprConsent) {
if (syncOptions.iframeEnabled && hasPurpose1Consent(gdprConsent)) {
return [{
type: 'iframe',
url: 'https://acdn.adnxs.com/dmp/async_usersync.html'
}];
}
},
transformBidParams: function (params, isOpenRtb, adUnit, bidRequests) {
let conversionFn = transformBidderParamKeywords;
if (isOpenRtb === true) {
let s2sEndpointUrl = null;
let s2sConfig = config.getConfig('s2sConfig');
if (isPlainObject(s2sConfig)) {
s2sEndpointUrl = deepAccess(s2sConfig, 'endpoint.p1Consent');
} else if (isArray(s2sConfig)) {
s2sConfig.forEach(s2sCfg => {
if (includes(s2sCfg.bidders, adUnit.bids[0].bidder)) {
s2sEndpointUrl = deepAccess(s2sCfg, 'endpoint.p1Consent');
}
})
}
if (s2sEndpointUrl && s2sEndpointUrl.match('/openrtb2/prebid')) {
conversionFn = convertKeywordsToString;
}
}
params = convertTypes({
'member': 'string',
'invCode': 'string',
'placementId': 'number',
'keywords': conversionFn,
'publisherId': 'number'
}, params);
if (isOpenRtb) {
params.use_pmt_rule = (typeof params.usePaymentRule === 'boolean') ? params.usePaymentRule : false;
if (params.usePaymentRule) { delete params.usePaymentRule; }
if (isPopulatedArray(params.keywords)) {
params.keywords.forEach(deleteValues);
}
Object.keys(params).forEach(paramKey => {
let convertedKey = convertCamelToUnderscore(paramKey);
if (convertedKey !== paramKey) {
params[convertedKey] = params[paramKey];
delete params[paramKey];
}
});
}
return params;
},
/**
* Add element selector to javascript tracker to improve native viewability
* @param {Bid} bid
*/
onBidWon: function (bid) {
if (FEATURES.NATIVE && bid.native) {
reloadViewabilityScriptWithCorrectParameters(bid);
}
}
}
function isPopulatedArray(arr) {
return !!(isArray(arr) && arr.length > 0);
}
function deleteValues(keyPairObj) {
if (isPopulatedArray(keyPairObj.value) && keyPairObj.value[0] === '') {
delete keyPairObj.value;
}
}
function reloadViewabilityScriptWithCorrectParameters(bid) {
let viewJsPayload = getAppnexusViewabilityScriptFromJsTrackers(bid.native.javascriptTrackers);
if (viewJsPayload) {
let prebidParams = 'pbjs_adid=' + bid.adId + ';pbjs_auc=' + bid.adUnitCode;
let jsTrackerSrc = getViewabilityScriptUrlFromPayload(viewJsPayload)
let newJsTrackerSrc = jsTrackerSrc.replace('dom_id=%native_dom_id%', prebidParams);
// find iframe containing script tag
let frameArray = document.getElementsByTagName('iframe');
// boolean var to modify only one script. That way if there are muliple scripts,
// they won't all point to the same creative.
let modifiedAScript = false;
// first, loop on all ifames
for (let i = 0; i < frameArray.length && !modifiedAScript; i++) {
let currentFrame = frameArray[i];
try {
// IE-compatible, see https://stackoverflow.com/a/3999191/2112089
let nestedDoc = currentFrame.contentDocument || currentFrame.contentWindow.document;
if (nestedDoc) {
// if the doc is present, we look for our jstracker
let scriptArray = nestedDoc.getElementsByTagName('script');
for (let j = 0; j < scriptArray.length && !modifiedAScript; j++) {
let currentScript = scriptArray[j];
if (currentScript.getAttribute('data-src') == jsTrackerSrc) {
currentScript.setAttribute('src', newJsTrackerSrc);
currentScript.setAttribute('data-src', '');
if (currentScript.removeAttribute) {
currentScript.removeAttribute('data-src');
}
modifiedAScript = true;
}
}
}
} catch (exception) {
// trying to access a cross-domain iframe raises a SecurityError
// this is expected and ignored
if (!(exception instanceof DOMException && exception.name === 'SecurityError')) {
// all other cases are raised again to be treated by the calling function
throw exception;
}
}
}
}
}
function strIsAppnexusViewabilityScript(str) {
let regexMatchUrlStart = str.match(VIEWABILITY_URL_START);
let viewUrlStartInStr = regexMatchUrlStart != null && regexMatchUrlStart.length >= 1;
let regexMatchFileName = str.match(VIEWABILITY_FILE_NAME);
let fileNameInStr = regexMatchFileName != null && regexMatchFileName.length >= 1;
return str.startsWith(SCRIPT_TAG_START) && fileNameInStr && viewUrlStartInStr;
}
function getAppnexusViewabilityScriptFromJsTrackers(jsTrackerArray) {
let viewJsPayload;
if (isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) {
viewJsPayload = jsTrackerArray;
} else if (isArray(jsTrackerArray)) {
for (let i = 0; i < jsTrackerArray.length; i++) {
let currentJsTracker = jsTrackerArray[i];
if (strIsAppnexusViewabilityScript(currentJsTracker)) {
viewJsPayload = currentJsTracker;
}
}
}
return viewJsPayload;
}
function getViewabilityScriptUrlFromPayload(viewJsPayload) {
// extracting the content of the src attribute
// -> substring between src=" and "
let indexOfFirstQuote = viewJsPayload.indexOf('src="') + 5; // offset of 5: the length of 'src=' + 1
let indexOfSecondQuote = viewJsPayload.indexOf('"', indexOfFirstQuote);
let jsTrackerSrc = viewJsPayload.substring(indexOfFirstQuote, indexOfSecondQuote);
return jsTrackerSrc;
}
function formatRequest(payload, bidderRequest) {
let request = [];
let options = {
withCredentials: true
};
let endpointUrl = URL;
if (!hasPurpose1Consent(bidderRequest?.gdprConsent)) {
endpointUrl = URL_SIMPLE;
}
if (getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) {
options.customHeaders = {
'X-Is-Test': 1
}
}
if (payload.tags.length > MAX_IMPS_PER_REQUEST) {
const clonedPayload = deepClone(payload);
chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => {
clonedPayload.tags = tags;
const payloadString = JSON.stringify(clonedPayload);
request.push({
method: 'POST',
url: endpointUrl,
data: payloadString,
bidderRequest,
options
});
});
} else {
const payloadString = JSON.stringify(payload);
request = {
method: 'POST',
url: endpointUrl,
data: payloadString,
bidderRequest,
options
};
}
return request;
}
function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) {
const renderer = Renderer.install({
id: rtbBid.renderer_id,
url: rtbBid.renderer_url,
config: rendererOptions,
loaded: false,
adUnitCode
});
try {
renderer.setRender(outstreamRender);
} catch (err) {
logWarn('Prebid Error calling setRender on renderer', err);
}
renderer.setEventHandlers({
impression: () => logMessage('AppNexus outstream video impression event'),
loaded: () => logMessage('AppNexus outstream video loaded event'),
ended: () => {
logMessage('AppNexus outstream renderer video event');
document.querySelector(`#${adUnitCode}`).style.display = 'none';
}
});
return renderer;
}
/**
* Unpack the Server's Bid into a Prebid-compatible one.
* @param serverBid
* @param rtbBid
* @param bidderRequest
* @return Bid
*/
function newBid(serverBid, rtbBid, bidderRequest) {
const bidRequest = getBidRequest(serverBid.uuid, [bidderRequest]);
const bid = {
requestId: serverBid.uuid,
cpm: rtbBid.cpm,
creativeId: rtbBid.creative_id,
dealId: rtbBid.deal_id,
currency: 'USD',
netRevenue: true,
ttl: 300,
adUnitCode: bidRequest.adUnitCode,
appnexus: {
buyerMemberId: rtbBid.buyer_member_id,
dealPriority: rtbBid.deal_priority,
dealCode: rtbBid.deal_code
}
};
// WE DON'T FULLY SUPPORT THIS ATM - future spot for adomain code; creating a stub for 5.0 compliance
if (rtbBid.adomain) {
bid.meta = Object.assign({}, bid.meta, { advertiserDomains: [] });
}
if (rtbBid.advertiser_id) {
bid.meta = Object.assign({}, bid.meta, { advertiserId: rtbBid.advertiser_id });
}
// temporary function; may remove at later date if/when adserver fully supports dchain
function setupDChain(rtbBid) {
let dchain = {
ver: '1.0',
complete: 0,
nodes: [{
bsid: rtbBid.buyer_member_id.toString()
}],
};
return dchain;
}
if (rtbBid.buyer_member_id) {
bid.meta = Object.assign({}, bid.meta, {dchain: setupDChain(rtbBid)});
}
if (rtbBid.brand_id) {
bid.meta = Object.assign({}, bid.meta, { brandId: rtbBid.brand_id });
}
if (rtbBid.rtb.video) {
// shared video properties used for all 3 contexts
Object.assign(bid, {
width: rtbBid.rtb.video.player_width,
height: rtbBid.rtb.video.player_height,
vastImpUrl: rtbBid.notify_url,
ttl: 3600
});
const videoContext = deepAccess(bidRequest, 'mediaTypes.video.context');
switch (videoContext) {
case ADPOD:
const primaryCatId = getIabSubCategory(bidRequest.bidder, rtbBid.brand_category_id);
bid.meta = Object.assign({}, bid.meta, { primaryCatId });
const dealTier = rtbBid.deal_priority;
bid.video = {
context: ADPOD,
durationSeconds: Math.floor(rtbBid.rtb.video.duration_ms / 1000),
dealTier
};
bid.vastUrl = rtbBid.rtb.video.asset_url;
break;
case OUTSTREAM:
bid.adResponse = serverBid;
bid.adResponse.ad = bid.adResponse.ads[0];
bid.adResponse.ad.video = bid.adResponse.ad.rtb.video;
bid.vastXml = rtbBid.rtb.video.content;
if (rtbBid.renderer_url) {
const videoBid = find(bidderRequest.bids, bid => bid.bidId === serverBid.uuid);
let rendererOptions = deepAccess(videoBid, 'mediaTypes.video.renderer.options'); // mediaType definition has preference (shouldn't options be .config?)
if (!rendererOptions) {
rendererOptions = deepAccess(videoBid, 'renderer.options'); // second the adUnit definition has preference (shouldn't options be .config?)
}
bid.renderer = newRenderer(bid.adUnitCode, rtbBid, rendererOptions);
}
break;
case INSTREAM:
bid.vastUrl = rtbBid.notify_url + '&redir=' + encodeURIComponent(rtbBid.rtb.video.asset_url);
break;
}
} else if (FEATURES.NATIVE && rtbBid.rtb[NATIVE]) {
const nativeAd = rtbBid.rtb[NATIVE];
// setting up the jsTracker:
// we put it as a data-src attribute so that the tracker isn't called
// until we have the adId (see onBidWon)
let jsTrackerDisarmed = rtbBid.viewability.config.replace('src=', 'data-src=');
let jsTrackers = nativeAd.javascript_trackers;
if (jsTrackers == undefined) {
jsTrackers = jsTrackerDisarmed;
} else if (isStr(jsTrackers)) {
jsTrackers = [jsTrackers, jsTrackerDisarmed];
} else {
jsTrackers.push(jsTrackerDisarmed);
}
bid[NATIVE] = {
title: nativeAd.title,
body: nativeAd.desc,
body2: nativeAd.desc2,
cta: nativeAd.ctatext,
rating: nativeAd.rating,
sponsoredBy: nativeAd.sponsored,
privacyLink: nativeAd.privacy_link,
address: nativeAd.address,
downloads: nativeAd.downloads,
likes: nativeAd.likes,
phone: nativeAd.phone,
price: nativeAd.price,
salePrice: nativeAd.saleprice,
clickUrl: nativeAd.link.url,
displayUrl: nativeAd.displayurl,
clickTrackers: nativeAd.link.click_trackers,
impressionTrackers: nativeAd.impression_trackers,
javascriptTrackers: jsTrackers
};
if (nativeAd.main_img) {
bid['native'].image = {
url: nativeAd.main_img.url,
height: nativeAd.main_img.height,
width: nativeAd.main_img.width,
};
}
if (nativeAd.icon) {
bid['native'].icon = {
url: nativeAd.icon.url,
height: nativeAd.icon.height,
width: nativeAd.icon.width,
};
}
} else {
Object.assign(bid, {
width: rtbBid.rtb.banner.width,
height: rtbBid.rtb.banner.height,
ad: rtbBid.rtb.banner.content
});
try {
if (rtbBid.rtb.trackers) {
for (let i = 0; i < rtbBid.rtb.trackers[0].impression_urls.length; i++) {
const url = rtbBid.rtb.trackers[0].impression_urls[i];
const tracker = createTrackPixelHtml(url);
bid.ad += tracker;
}
}
} catch (error) {
logError('Error appending tracking pixel', error);
}
}
return bid;
}
function bidToTag(bid) {
const tag = {};
tag.sizes = transformSizes(bid.sizes);
tag.primary_size = tag.sizes[0];
tag.ad_types = [];
tag.uuid = bid.bidId;
if (bid.params.placementId) {
tag.id = parseInt(bid.params.placementId, 10);
} else {
tag.code = bid.params.invCode;
}
tag.allow_smaller_sizes = bid.params.allowSmallerSizes || false;
tag.use_pmt_rule = bid.params.usePaymentRule || false
tag.prebid = true;
tag.disable_psa = true;
let bidFloor = getBidFloor(bid);
if (bidFloor) {
tag.reserve = bidFloor;
}
if (bid.params.position) {
tag.position = { 'above': 1, 'below': 2 }[bid.params.position] || 0;
} else {
let mediaTypePos = deepAccess(bid, `mediaTypes.banner.pos`) || deepAccess(bid, `mediaTypes.video.pos`);
// only support unknown, atf, and btf values for position at this time
if (mediaTypePos === 0 || mediaTypePos === 1 || mediaTypePos === 3) {
// ortb spec treats btf === 3, but our system interprets btf === 2; so converting the ortb value here for consistency
tag.position = (mediaTypePos === 3) ? 2 : mediaTypePos;
}
}
if (bid.params.trafficSourceCode) {
tag.traffic_source_code = bid.params.trafficSourceCode;
}
if (bid.params.privateSizes) {
tag.private_sizes = transformSizes(bid.params.privateSizes);
}
if (bid.params.supplyType) {
tag.supply_type = bid.params.supplyType;
}
if (bid.params.pubClick) {
tag.pubclick = bid.params.pubClick;
}
if (bid.params.extInvCode) {
tag.ext_inv_code = bid.params.extInvCode;
}
if (bid.params.publisherId) {
tag.publisher_id = parseInt(bid.params.publisherId, 10);
}
if (bid.params.externalImpId) {
tag.external_imp_id = bid.params.externalImpId;
}
if (!isEmpty(bid.params.keywords)) {
let keywords = transformBidderParamKeywords(bid.params.keywords);
if (keywords.length > 0) {
keywords.forEach(deleteValues);
}
tag.keywords = keywords;
}
let gpid = deepAccess(bid, 'ortb2Imp.ext.data.pbadslot');
if (gpid) {
tag.gpid = gpid;
}
if (FEATURES.NATIVE && (bid.mediaType === NATIVE || deepAccess(bid, `mediaTypes.${NATIVE}`))) {
tag.ad_types.push(NATIVE);
if (tag.sizes.length === 0) {
tag.sizes = transformSizes([1, 1]);
}
if (bid.nativeParams) {
const nativeRequest = buildNativeRequest(bid.nativeParams);
tag[NATIVE] = { layouts: [nativeRequest] };
}
}
const videoMediaType = deepAccess(bid, `mediaTypes.${VIDEO}`);
const context = deepAccess(bid, 'mediaTypes.video.context');
if (videoMediaType && context === 'adpod') {
tag.hb_source = 7;
} else {
tag.hb_source = 1;
}
if (bid.mediaType === VIDEO || videoMediaType) {
tag.ad_types.push(VIDEO);
}
// instream gets vastUrl, outstream gets vastXml
if (bid.mediaType === VIDEO || (videoMediaType && context !== 'outstream')) {
tag.require_asset_url = true;
}
if (bid.params.video) {
tag.video = {};
// place any valid video params on the tag
Object.keys(bid.params.video)
.filter(param => includes(VIDEO_TARGETING, param))
.forEach(param => {
switch (param) {
case 'context':
case 'playback_method':
let type = bid.params.video[param];
type = (isArray(type)) ? type[0] : type;
tag.video[param] = VIDEO_MAPPING[param][type];
break;
// Deprecating tags[].video.frameworks in favor of tags[].video_frameworks
case 'frameworks':
break;
default:
tag.video[param] = bid.params.video[param];
}
});
if (bid.params.video.frameworks && isArray(bid.params.video.frameworks)) {
tag['video_frameworks'] = bid.params.video.frameworks;
}
}
// use IAB ORTB values if the corresponding values weren't already set by bid.params.video
if (videoMediaType) {
tag.video = tag.video || {};
Object.keys(videoMediaType)
.filter(param => includes(VIDEO_RTB_TARGETING, param))
.forEach(param => {
switch (param) {
case 'minduration':
case 'maxduration':
if (typeof tag.video[param] !== 'number') tag.video[param] = videoMediaType[param];
break;
case 'skip':
if (typeof tag.video['skippable'] !== 'boolean') tag.video['skippable'] = (videoMediaType[param] === 1);
break;
case 'skipafter':
if (typeof tag.video['skipoffset'] !== 'number') tag.video['skippoffset'] = videoMediaType[param];
break;
case 'playbackmethod':
if (typeof tag.video['playback_method'] !== 'number') {
let type = videoMediaType[param];
type = (isArray(type)) ? type[0] : type;
// we only support iab's options 1-4 at this time.
if (type >= 1 && type <= 4) {
tag.video['playback_method'] = type;
}
}
break;
case 'api':
if (!tag['video_frameworks'] && isArray(videoMediaType[param])) {
// need to read thru array; remove 6 (we don't support it), swap 4 <> 5 if found (to match our adserver mapping for these specific values)
let apiTmp = videoMediaType[param].map(val => {
let v = (val === 4) ? 5 : (val === 5) ? 4 : val;
if (v >= 1 && v <= 5) {
return v;
}
}).filter(v => v);
tag['video_frameworks'] = apiTmp;
}
break;
}
});
}
if (bid.renderer) {
tag.video = Object.assign({}, tag.video, { custom_renderer_present: true });
}
if (bid.params.frameworks && isArray(bid.params.frameworks)) {
tag['banner_frameworks'] = bid.params.frameworks;
}
let adUnit = find(auctionManager.getAdUnits(), au => bid.transactionId === au.transactionId);
if (adUnit && adUnit.mediaTypes && adUnit.mediaTypes.banner) {
tag.ad_types.push(BANNER);
}
if (tag.ad_types.length === 0) {
delete tag.ad_types;
}
return tag;
}
/* Turn bid request sizes into ut-compatible format */
function transformSizes(requestSizes) {
let sizes = [];
let sizeObj = {};
if (isArray(requestSizes) && requestSizes.length === 2 &&
!isArray(requestSizes[0])) {
sizeObj.width = parseInt(requestSizes[0], 10);
sizeObj.height = parseInt(requestSizes[1], 10);
sizes.push(sizeObj);
} else if (typeof requestSizes === 'object') {
for (let i = 0; i < requestSizes.length; i++) {
let size = requestSizes[i];
sizeObj = {};
sizeObj.width = parseInt(size[0], 10);
sizeObj.height = parseInt(size[1], 10);
sizes.push(sizeObj);
}
}
return sizes;