-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
ttdBidAdapter.js
519 lines (463 loc) · 15 KB
/
ttdBidAdapter.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
import * as utils from '../src/utils.js';
import { config } from '../src/config.js';
import { createEidsArray } from './userId/eids.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { BANNER, VIDEO } from '../src/mediaTypes.js';
const BIDADAPTERVERSION = 'TTD-PREBID-2022.02.18';
const BIDDER_CODE = 'ttd';
const BIDDER_CODE_LONG = 'thetradedesk';
const BIDDER_ENDPOINT = 'https://direct.adsrvr.org/bid/bidder/';
const USER_SYNC_ENDPOINT = 'https://match.adsrvr.org';
const MEDIA_TYPE = {
BANNER: 1,
VIDEO: 2
};
function getExt(firstPartyData) {
const ext = {
ver: BIDADAPTERVERSION,
pbjs: '$prebid.version$',
keywords: firstPartyData.site?.keywords ? firstPartyData.site.keywords.split(',').map(k => k.trim()) : []
}
return {
ttdprebid: ext
};
}
function getRegs(bidderRequest) {
let regs = {};
if (bidderRequest.gdprConsent && typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') {
utils.deepSetValue(regs, 'ext.gdpr', bidderRequest.gdprConsent.gdprApplies ? 1 : 0);
}
if (bidderRequest.uspConsent) {
utils.deepSetValue(regs, 'ext.us_privacy', bidderRequest.uspConsent);
}
if (config.getConfig('coppa') === true) {
regs.coppa = 1;
}
return regs;
}
function getBidFloor(bid) {
if (!utils.isFn(bid.getFloor)) {
return null;
}
let floor = bid.getFloor({
currency: 'USD',
mediaType: '*',
size: '*'
});
if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') {
return floor.floor;
}
return null;
}
function getSource(validBidRequests) {
let source = {};
if (validBidRequests[0].schain) {
utils.deepSetValue(source, 'ext.schain', validBidRequests[0].schain);
}
return source;
}
function getDevice() {
const language = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
let device = {
ua: navigator.userAgent,
dnt: utils.getDNT() ? 1 : 0,
language: language,
connectiontype: getConnectionType()
};
return device;
};
function getConnectionType() {
const connection = navigator.connection || navigator.webkitConnection;
if (!connection) {
return 0;
}
switch (connection.type) {
case 'ethernet':
return 1;
case 'wifi':
return 2;
case 'cellular':
switch (connection.effectiveType) {
case 'slow-2g':
case '2g':
return 4;
case '3g':
return 5;
case '4g':
return 6;
default:
return 3;
}
default:
return 0;
}
}
function getUser(bidderRequest) {
let user = {};
if (bidderRequest.gdprConsent) {
utils.deepSetValue(user, 'ext.consent', bidderRequest.gdprConsent.consentString);
}
if (utils.isStr(utils.deepAccess(bidderRequest, 'bids.0.userId.tdid'))) {
user.buyeruid = bidderRequest.bids[0].userId.tdid;
}
var eids = createEidsArray(utils.deepAccess(bidderRequest, 'bids.0.userId'))
if (eids.length) {
utils.deepSetValue(user, 'ext.eids', eids);
}
return user;
}
function getSite(bidderRequest, firstPartyData) {
var site = {
id: utils.deepAccess(bidderRequest, 'bids.0.params.siteId'),
page: utils.deepAccess(bidderRequest, 'refererInfo.page'),
publisher: {
id: utils.deepAccess(bidderRequest, 'bids.0.params.publisherId'),
},
...firstPartyData.site
};
var publisherDomain = bidderRequest.refererInfo.domain;
if (publisherDomain) {
utils.deepSetValue(site, 'publisher.domain', publisherDomain);
}
return site;
}
function getImpression(bidRequest) {
let impression = {
id: bidRequest.bidId,
tagid: bidRequest.params.placementId
};
let gpid = utils.deepAccess(bidRequest, 'ortb2Imp.ext.gpid');
if (gpid) {
impression.ext = {
gpid: gpid
}
}
const mediaTypesVideo = utils.deepAccess(bidRequest, 'mediaTypes.video');
const mediaTypesBanner = utils.deepAccess(bidRequest, 'mediaTypes.banner');
let mediaTypes = {};
if (mediaTypesBanner) {
mediaTypes[BANNER] = banner(bidRequest);
}
if (mediaTypesVideo) {
mediaTypes[VIDEO] = video(bidRequest);
}
Object.assign(impression, mediaTypes);
let bidfloor = getBidFloor(bidRequest);
if (bidfloor) {
impression.bidfloor = parseFloat(bidfloor);
impression.bidfloorcur = 'USD';
}
return impression;
}
function getSizes(sizes) {
const sizeStructs = utils.parseSizesInput(sizes)
.filter(x => x) // sizes that don't conform are returned as null, which we want to ignore
.map(x => x.split('x'))
.map(size => {
return {
width: parseInt(size[0]),
height: parseInt(size[1]),
}
});
return sizeStructs;
}
function banner(bid) {
const sizes = getSizes(bid.mediaTypes.banner.sizes).map(x => {
return {
w: x.width,
h: x.height,
}
});
const pos = parseInt(utils.deepAccess(bid, 'mediaTypes.banner.pos'));
const expdir = utils.deepAccess(bid, 'params.banner.expdir');
let optionalParams = {};
if (pos) {
optionalParams.pos = pos;
}
if (expdir && Array.isArray(expdir)) {
optionalParams.expdir = expdir;
}
const banner = Object.assign(
{
w: sizes[0].w,
h: sizes[0].h,
format: sizes,
},
optionalParams);
return banner;
}
function video(bid) {
let minduration = utils.deepAccess(bid, 'mediaTypes.video.minduration');
const maxduration = utils.deepAccess(bid, 'mediaTypes.video.maxduration');
const playerSize = utils.deepAccess(bid, 'mediaTypes.video.playerSize');
const api = utils.deepAccess(bid, 'mediaTypes.video.api');
const mimes = utils.deepAccess(bid, 'mediaTypes.video.mimes');
const placement = utils.deepAccess(bid, 'mediaTypes.video.placement');
const protocols = utils.deepAccess(bid, 'mediaTypes.video.protocols');
const playbackmethod = utils.deepAccess(bid, 'mediaTypes.video.playbackmethod');
const pos = utils.deepAccess(bid, 'mediaTypes.video.pos');
const startdelay = utils.deepAccess(bid, 'mediaTypes.video.startdelay');
const skip = utils.deepAccess(bid, 'mediaTypes.video.skip');
const skipmin = utils.deepAccess(bid, 'mediaTypes.video.skipmin');
const skipafter = utils.deepAccess(bid, 'mediaTypes.video.skipafter');
const minbitrate = utils.deepAccess(bid, 'mediaTypes.video.minbitrate');
const maxbitrate = utils.deepAccess(bid, 'mediaTypes.video.maxbitrate');
if (!minduration || !utils.isInteger(minduration)) {
minduration = 0
}
let video = {
minduration: minduration,
maxduration: maxduration,
api: api,
mimes: mimes,
placement: placement,
protocols: protocols
};
if (typeof playerSize !== 'undefined') {
if (utils.isArray(playerSize[0])) {
video.w = parseInt(playerSize[0][0]);
video.h = parseInt(playerSize[0][1]);
} else if (utils.isNumber(playerSize[0])) {
video.w = parseInt(playerSize[0]);
video.h = parseInt(playerSize[1]);
}
}
if (playbackmethod) {
video.playbackmethod = playbackmethod;
}
if (pos) {
video.pos = pos;
}
if (startdelay && utils.isInteger(startdelay)) {
video.startdelay = startdelay;
}
if (skip && (skip === 0 || skip === 1)) {
video.skip = skip;
}
if (skipmin && utils.isInteger(skipmin)) {
video.skipmin = skipmin;
}
if (skipafter && utils.isInteger(skipafter)) {
video.skipafter = skipafter;
}
if (minbitrate && utils.isInteger(minbitrate)) {
video.minbitrate = minbitrate;
}
if (maxbitrate && utils.isInteger(maxbitrate)) {
video.maxbitrate = maxbitrate;
}
return video;
}
export const spec = {
code: BIDDER_CODE,
gvlid: 21,
aliases: [BIDDER_CODE_LONG],
supportedMediaTypes: [BANNER, VIDEO],
/**
* Determines whether or not the given bid request is valid.
*
* @param {BidRequest} bid The bid params to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: function (bid) {
const alphaRegex = /^[\w+]+$/;
// required parameters
if (!bid || !bid.params) {
utils.logWarn(BIDDER_CODE + ': Missing bid parameters');
return false;
}
if (!bid.params.supplySourceId) {
utils.logWarn(BIDDER_CODE + ': Missing required parameter params.supplySourceId');
return false;
}
if (!alphaRegex.test(bid.params.supplySourceId)) {
utils.logWarn(BIDDER_CODE + ': supplySourceId must only contain alphabetic characters');
return false;
}
if (!bid.params.publisherId) {
utils.logWarn(BIDDER_CODE + ': Missing required parameter params.publisherId');
return false;
}
if (bid.params.publisherId.length > 32) {
utils.logWarn(BIDDER_CODE + ': params.publisherId must be 32 characters or less');
return false;
}
if (!bid.params.siteId) {
utils.logWarn(BIDDER_CODE + ': Missing required parameter params.siteId');
return false;
}
if (bid.params.siteId.length > 50) {
utils.logWarn(BIDDER_CODE + ': params.siteId must be 50 characters or less');
return false;
}
if (!bid.params.placementId) {
utils.logWarn(BIDDER_CODE + ': Missing required parameter params.placementId');
return false;
}
if (bid.params.placementId.length > 128) {
utils.logWarn(BIDDER_CODE + ': params.placementId must be 128 characters or less');
return false;
}
const mediaTypesBanner = utils.deepAccess(bid, 'mediaTypes.banner');
const mediaTypesVideo = utils.deepAccess(bid, 'mediaTypes.video');
if (!mediaTypesBanner && !mediaTypesVideo) {
utils.logWarn(BIDDER_CODE + ': one of mediaTypes.banner or mediaTypes.video must be passed');
return false;
}
if (mediaTypesVideo) {
if (!mediaTypesVideo.maxduration || !utils.isInteger(mediaTypesVideo.maxduration)) {
utils.logWarn(BIDDER_CODE + ': mediaTypes.video.maxduration must be set to the maximum video ad duration in seconds');
return false;
}
if (!mediaTypesVideo.api || mediaTypesVideo.api.length === 0) {
utils.logWarn(BIDDER_CODE + ': mediaTypes.video.api should be an array of supported api frameworks. See the Open RTB v2.5 spec for valid values');
return false;
}
if (!mediaTypesVideo.mimes || mediaTypesVideo.mimes.length === 0) {
utils.logWarn(BIDDER_CODE + ': mediaTypes.video.mimes should be an array of supported mime types');
return false;
}
if (!mediaTypesVideo.protocols) {
utils.logWarn(BIDDER_CODE + ': mediaTypes.video.protocols should be an array of supported protocols. See the Open RTB v2.5 spec for valid values')
return false;
}
}
return true;
},
/**
* Make a server request from the list of BidRequests.
*
* @param {BidRequest[]} an array of validBidRequests
* @param {*} bidderRequest
* @return {ServerRequest} Info describing the request to the server.
*/
buildRequests: function (validBidRequests, bidderRequest) {
const firstPartyData = bidderRequest.ortb2 || {};
let topLevel = {
id: bidderRequest.auctionId,
imp: validBidRequests.map(bidRequest => getImpression(bidRequest)),
site: getSite(bidderRequest, firstPartyData),
device: getDevice(),
user: getUser(bidderRequest),
at: 1,
cur: ['USD'],
regs: getRegs(bidderRequest),
source: getSource(validBidRequests),
ext: getExt(firstPartyData)
}
let url = BIDDER_ENDPOINT + bidderRequest.bids[0].params.supplySourceId;
let serverRequest = {
method: 'POST',
url: url,
data: topLevel,
options: {
withCredentials: true
}
};
return serverRequest;
},
/**
* Format responses as Prebid bid responses
*
* Each bid can have the following elements:
* - requestId (required)
* - cpm (required)
* - width (required)
* - height (required)
* - ad (required)
* - ttl (required)
* - creativeId (required)
* - netRevenue (required)
* - currency (required)
* - vastUrl
* - vastImpUrl
* - vastXml
* - dealId
*
* @param {ttdResponseObj} bidResponse A successful response from ttd.
* @param {ServerRequest} serverRequest The result of buildRequests() that lead to this response.
* @return {Bid[]} An array of formatted bids.
*/
interpretResponse: function (response, serverRequest) {
let seatBidsInResponse = utils.deepAccess(response, 'body.seatbid');
const currency = utils.deepAccess(response, 'body.cur');
if (!seatBidsInResponse || seatBidsInResponse.length === 0) {
return [];
}
let bidResponses = [];
let requestedImpressions = utils.deepAccess(serverRequest, 'data.imp');
seatBidsInResponse.forEach(seatBid => {
seatBid.bid.forEach(bid => {
let matchingRequestedImpression = requestedImpressions.find(imp => imp.id === bid.impid);
const cpm = bid.price || 0;
let bidResponse = {
requestId: bid.impid,
cpm: cpm,
creativeId: bid.crid,
dealId: bid.dealid || null,
currency: currency || 'USD',
netRevenue: true,
ttl: bid.ttl || 360,
meta: {},
};
if (bid.adomain && bid.adomain.length > 0) {
bidResponse.meta.advertiserDomains = bid.adomain;
}
if (bid.ext.mediatype === MEDIA_TYPE.BANNER) {
Object.assign(
bidResponse,
{
width: bid.w,
height: bid.h,
ad: utils.replaceAuctionPrice(bid.adm, cpm),
mediaType: BANNER
}
);
} else if (bid.ext.mediatype === MEDIA_TYPE.VIDEO) {
Object.assign(
bidResponse,
{
width: matchingRequestedImpression.video.w,
height: matchingRequestedImpression.video.h,
mediaType: VIDEO
}
);
if (bid.nurl) {
bidResponse.vastUrl = utils.replaceAuctionPrice(bid.nurl, cpm);
} else {
bidResponse.vastXml = utils.replaceAuctionPrice(bid.adm, cpm);
}
}
bidResponses.push(bidResponse);
});
});
return bidResponses;
},
/**
* Register the user sync pixels which should be dropped after the auction.
*
* @param {SyncOptions} syncOptions Which user syncs are allowed?
* @param {ServerResponse[]} serverResponses List of server's responses.
* @param {gdprConsent} gdprConsent GDPR consent object
* @param {uspConsent} uspConsent USP consent object
* @return {UserSync[]} The user syncs which should be dropped.
*/
getUserSyncs: function(syncOptions, serverResponses, gdprConsent = {}, uspConsent = '') {
const syncs = [];
let gdprParams = `&gdpr=${gdprConsent.gdprApplies ? 1 : 0}&gdpr_consent=${encodeURIComponent(gdprConsent.consentString)}`;
let url = `${USER_SYNC_ENDPOINT}/track/usersync?us_privacy=${encodeURIComponent(uspConsent)}${gdprParams}`;
if (syncOptions.pixelEnabled) {
syncs.push({
type: 'image',
url: url + '&ust=image'
});
} else if (syncOptions.iframeEnabled) {
syncs.push({
type: 'iframe',
url: url + '&ust=iframe'
});
}
return syncs;
},
};
registerBidder(spec)