-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
adyoulikeBidAdapter.js
559 lines (486 loc) · 15.6 KB
/
adyoulikeBidAdapter.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
import {buildUrl, deepAccess, parseSizesInput} from '../src/utils.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import { config } from '../src/config.js';
import {find} from '../src/polyfill.js';
import {BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js';
import { convertOrtbRequestToProprietaryNative } from '../src/native.js';
/**
* @typedef {import('../src/adapters/bidderFactory.js').BidRequest} BidRequest
* @typedef {import('../src/adapters/bidderFactory.js').Bid} Bid
* @typedef {import('../src/adapters/bidderFactory.js').BidderRequest} BidderRequest
*/
const VERSION = '1.0';
const BIDDER_CODE = 'adyoulike';
const DEFAULT_DC = 'hb-api';
const CURRENCY = 'USD';
const GVLID = 259;
const NATIVE_IMAGE = {
image: {
required: true
},
title: {
required: true
},
sponsoredBy: {
required: true
},
clickUrl: {
required: true
},
body: {
required: false
},
icon: {
required: false
},
cta: {
required: false
}
};
export const spec = {
code: BIDDER_CODE,
gvlid: GVLID,
supportedMediaTypes: [BANNER, NATIVE, VIDEO],
aliases: ['ayl'], // short code
/**
* 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 sizes = getSize(getSizeArray(bid));
const sizeValid = sizes.width > 0 && sizes.height > 0;
// allows no size for native only
return (bid.params && bid.params.placement &&
(sizeValid || (bid.mediaTypes && bid.mediaTypes.native)));
},
/**
* Make a server request from the list of BidRequests.
*
* @param {BidRequest} bidRequests is an array of AdUnits and bids
* @param {BidderRequest} bidderRequest
* @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);
let hasVideo = false;
let eids;
const payload = {
Version: VERSION,
Bids: bidRequests.reduce((accumulator, bidReq) => {
let mediatype = getMediatype(bidReq);
let sizesArray = getSizeArray(bidReq);
let size = getSize(sizesArray);
accumulator[bidReq.bidId] = {};
accumulator[bidReq.bidId].PlacementID = bidReq.params.placement;
accumulator[bidReq.bidId].TransactionID = bidReq.ortb2Imp?.ext?.tid;
accumulator[bidReq.bidId].Width = size.width;
accumulator[bidReq.bidId].Height = size.height;
accumulator[bidReq.bidId].AvailableSizes = sizesArray.join(',');
if (typeof bidReq.getFloor === 'function') {
accumulator[bidReq.bidId].Pricing = getFloor(bidReq, size, mediatype);
}
if (bidReq.schain) {
accumulator[bidReq.bidId].SChain = bidReq.schain;
}
if (!eids && bidReq.userIdAsEids && bidReq.userIdAsEids.length) {
eids = bidReq.userIdAsEids;
}
if (mediatype === NATIVE) {
let nativeReq = bidReq.mediaTypes.native;
if (nativeReq.type === 'image') {
nativeReq = Object.assign({}, NATIVE_IMAGE, nativeReq);
}
// click url is always mandatory even if not specified by publisher
nativeReq.clickUrl = {
required: true
};
accumulator[bidReq.bidId].Native = nativeReq;
}
if (mediatype === VIDEO) {
hasVideo = true;
accumulator[bidReq.bidId].Video = bidReq.mediaTypes.video;
const size = bidReq.mediaTypes.video.playerSize;
if (Array.isArray(size) && !Array.isArray(size[0])) {
accumulator[bidReq.bidId].Video.playerSize = [size];
}
}
return accumulator;
}, {}),
PageRefreshed: getPageRefreshed()
};
if (bidderRequest.gdprConsent) {
payload.gdprConsent = {
consentString: bidderRequest.gdprConsent.consentString,
consentRequired: (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') ? bidderRequest.gdprConsent.gdprApplies : null
};
}
if (bidderRequest.uspConsent) {
payload.uspConsent = bidderRequest.uspConsent;
}
if (bidderRequest.ortb2) {
payload.ortb2 = bidderRequest.ortb2;
}
if (eids) {
payload.eids = eids;
}
payload.pbjs_version = '$prebid.version$';
const data = JSON.stringify(payload);
const options = {
withCredentials: true
};
return {
method: 'POST',
url: createEndpoint(bidRequests, bidderRequest, hasVideo),
data,
options
};
},
/**
* 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, request) {
const bidResponses = [];
var bidRequests = {};
if (!serverResponse || !serverResponse.body) {
return bidResponses;
}
try {
bidRequests = JSON.parse(request.data).Bids;
} catch (err) {
// json error initial request can't be read
}
// For this adapter, serverResponse is a list
serverResponse.body.forEach(response => {
const bid = createBid(response, bidRequests);
if (bid) {
bidResponses.push(bid);
}
});
return bidResponses;
},
/**
* List user sync endpoints.
* Legal information have to be added to the request.
* Only iframe syncs are supported.
*
* @param {*} syncOptions Publisher prebid configuration.
* @param {*} serverResponses A successful response from the server.
* @return {syncs[]} An array of syncs that should be executed.
*/
getUserSyncs: function (syncOptions, serverResponses, gdprConsent, uspConsent, gppConsent) {
if (!syncOptions.iframeEnabled) {
return [];
}
let params = '';
// GDPR
if (gdprConsent) {
params += '&gdpr=' + (gdprConsent.gdprApplies ? 1 : 0);
params += '&gdpr_consent=' + encodeURIComponent(gdprConsent.consentString || '');
}
// coppa compliance
if (config.getConfig('coppa') === true) {
params += '&coppa=1';
}
// CCPA
if (uspConsent) {
params += '&us_privacy=' + encodeURIComponent(uspConsent);
}
// GPP
if (gppConsent?.gppString && gppConsent?.applicableSections?.length) {
params += '&gpp=' + encodeURIComponent(gppConsent.gppString);
params += '&gpp_sid=' + encodeURIComponent(gppConsent?.applicableSections?.join(','));
}
return [{
type: 'iframe',
url: `https://visitor.omnitagjs.com/visitor/isync?uid=19340f4f097d16f41f34fc0274981ca4${params}`
}];
}
}
/* Get hostname from bids */
function getHostname(bidderRequest) {
let dcHostname = find(bidderRequest, bid => bid.params.DC);
if (dcHostname) {
return ('-' + dcHostname.params.DC);
}
return '';
}
/* Get mediatype from bidRequest */
function getMediatype(bidRequest) {
if (deepAccess(bidRequest, 'mediaTypes.banner')) {
return BANNER;
}
if (deepAccess(bidRequest, 'mediaTypes.video')) {
return VIDEO;
}
if (deepAccess(bidRequest, 'mediaTypes.native')) {
return NATIVE;
}
}
/* Get Floor price information */
function getFloor(bidRequest, size, mediaType) {
const bidFloors = bidRequest.getFloor({
currency: CURRENCY,
mediaType,
size: [ size.width, size.height ]
});
if (!isNaN(bidFloors?.floor) && (bidFloors?.currency === CURRENCY)) {
return bidFloors.floor;
}
}
/* Get information on page refresh */
function getPageRefreshed() {
try {
if (performance && performance.navigation) {
return performance.navigation.type === performance.navigation.TYPE_RELOAD;
}
} catch (e) { }
return false;
}
/* Create endpoint url */
function createEndpoint(bidRequests, bidderRequest, hasVideo) {
let host = getHostname(bidRequests);
const endpoint = hasVideo ? '/hb-api/prebid-video/v1' : '/hb-api/prebid/v1';
return buildUrl({
protocol: 'https',
host: `${DEFAULT_DC}${host}.omnitagjs.com`,
pathname: endpoint,
search: createEndpointQS(bidderRequest)
});
}
/* Create endpoint query string */
function createEndpointQS(bidderRequest) {
const qs = {};
if (bidderRequest) {
const ref = bidderRequest.refererInfo;
if (ref) {
if (ref.location) {
// RefererUrl will be removed in a future version.
qs.RefererUrl = encodeURIComponent(ref.location);
if (!ref.reachedTop) {
qs.SafeFrame = true;
}
}
qs.PageUrl = encodeURIComponent(ref.topmostLocation);
qs.PageReferrer = encodeURIComponent(ref.location);
}
// retreive info from ortb2 object if present (prebid7)
const siteInfo = bidderRequest.ortb2?.site;
if (siteInfo) {
qs.PageUrl = encodeURIComponent(siteInfo.page || ref?.topmostLocation);
qs.PageReferrer = encodeURIComponent(siteInfo.ref || ref?.location);
}
}
const can = bidderRequest?.refererInfo?.canonicalUrl;
if (can) {
qs.CanonicalUrl = encodeURIComponent(can);
}
return qs;
}
function getSizeArray(bid) {
let inputSize = bid.sizes || [];
if (bid.mediaTypes && bid.mediaTypes.banner) {
inputSize = bid.mediaTypes.banner.sizes || [];
}
// handle size in bid.params in formats: [w, h] and [[w,h]].
if (bid.params && Array.isArray(bid.params.size)) {
inputSize = bid.params.size;
if (!Array.isArray(inputSize[0])) {
inputSize = [inputSize]
}
}
return parseSizesInput(inputSize);
}
/* Get parsed size from request size */
function getSize(sizesArray) {
const parsed = {};
// the main requested size is the first one
const size = sizesArray[0];
if (typeof size !== 'string') {
return parsed;
}
const parsedSize = size.toUpperCase().split('X');
const width = parseInt(parsedSize[0], 10);
if (width) {
parsed.width = width;
}
const height = parseInt(parsedSize[1], 10);
if (height) {
parsed.height = height;
}
return parsed;
}
function getInternalImgUrl(uid) {
if (!uid) return '';
return 'https://blobs.omnitagjs.com/blobs/' + uid.substr(16, 2) + '/' + uid.substr(16) + '/' + uid;
}
function getImageUrl(config, resource, width, height) {
let url = '';
if (resource && resource.Kind) {
switch (resource.Kind) {
case 'INTERNAL':
url = getInternalImgUrl(resource.Data.Internal.BlobReference.Uid);
break;
case 'EXTERNAL':
const dynPrefix = config.DynamicPrefix;
let extUrl = resource.Data.External.Url;
extUrl = extUrl.replace(/\[height\]/i, '' + height);
extUrl = extUrl.replace(/\[width\]/i, '' + width);
if (extUrl.indexOf(dynPrefix) >= 0) {
const urlmatch = (/.*url=([^&]*)/gm).exec(extUrl);
url = urlmatch ? urlmatch[1] : '';
if (!url) {
url = getInternalImgUrl((/.*key=([^&]*)/gm).exec(extUrl)[1]);
}
} else {
url = extUrl;
}
break;
}
}
return url;
}
function getTrackers(eventsArray, jsTrackers) {
const result = [];
if (!eventsArray) return result;
eventsArray.map((item, index) => {
if ((jsTrackers && item.Kind === 'JAVASCRIPT_URL') ||
(!jsTrackers && item.Kind === 'PIXEL_URL')) {
result.push(item.Url);
}
});
return result;
}
function getNativeAssets(response, nativeConfig) {
if (typeof response.Native === 'object') {
return response.Native;
}
const native = {};
var adJson = {};
var textsJson = {};
if (typeof response.Ad === 'string') {
adJson = JSON.parse(response.Ad.match(/\/\*PREBID\*\/(.*)\/\*PREBID\*\//)[1]);
textsJson = adJson.Content.Preview.Text;
var impressionUrl = adJson.TrackingPrefix +
'/pixel?event_kind=IMPRESSION&attempt=' + adJson.Attempt;
var insertionUrl = adJson.TrackingPrefix +
'/pixel?event_kind=INSERTION&attempt=' + adJson.Attempt;
if (adJson.Campaign) {
impressionUrl += '&campaign=' + adJson.Campaign;
insertionUrl += '&campaign=' + adJson.Campaign;
}
native.clickUrl = adJson.TrackingPrefix + '/ar?event_kind=CLICK&attempt=' + adJson.Attempt +
'&campaign=' + adJson.Campaign + '&url=' + encodeURIComponent(adJson.Content.Landing.Url);
if (adJson.OnEvents) {
native.clickTrackers = getTrackers(adJson.OnEvents['CLICK']);
native.impressionTrackers = getTrackers(adJson.OnEvents['IMPRESSION']);
native.javascriptTrackers = getTrackers(adJson.OnEvents['IMPRESSION'], true);
} else {
native.impressionTrackers = [];
}
native.impressionTrackers.push(impressionUrl, insertionUrl);
}
Object.keys(nativeConfig).map(function(key, index) {
switch (key) {
case 'title':
native[key] = textsJson.TITLE;
break;
case 'body':
native[key] = textsJson.DESCRIPTION;
break;
case 'cta':
native[key] = textsJson.CALLTOACTION;
break;
case 'sponsoredBy':
native[key] = adJson.Content.Preview.Sponsor.Name;
break;
case 'image':
// main image requested size
const imgSize = nativeConfig.image.sizes || [];
if (!imgSize.length) {
imgSize[0] = response.Width || 300;
imgSize[1] = response.Height || 250;
}
const url = getImageUrl(adJson, deepAccess(adJson, 'Content.Preview.Thumbnail.Image'), imgSize[0], imgSize[1]);
if (url) {
native[key] = {
url,
width: imgSize[0],
height: imgSize[1]
};
}
break;
case 'icon':
// icon requested size
const iconSize = nativeConfig.icon.sizes || [];
if (!iconSize.length) {
iconSize[0] = 50;
iconSize[1] = 50;
}
const icurl = getImageUrl(adJson, deepAccess(adJson, 'Content.Preview.Sponsor.Logo.Resource'), iconSize[0], iconSize[1]);
if (icurl) {
native[key] = {
url: icurl,
width: iconSize[0],
height: iconSize[1]
};
}
break;
case 'privacyIcon':
native[key] = getImageUrl(adJson, deepAccess(adJson, 'Content.Preview.Credit.Logo.Resource'), 25, 25);
break;
case 'privacyLink':
native[key] = deepAccess(adJson, 'Content.Preview.Credit.Url');
break;
}
});
return native;
}
/* Create bid from response */
function createBid(response, bidRequests) {
if (!response || (!response.Ad && !response.Native && !response.Vast)) {
return;
}
const request = bidRequests && bidRequests[response.BidID];
// In case we don't retreive the size from the adserver, use the given one.
if (request) {
if (!response.Width || response.Width === '0') {
response.Width = request.Width;
}
if (!response.Height || response.Height === '0') {
response.Height = request.Height;
}
}
const bid = {
requestId: response.BidID,
ttl: 3600,
creativeId: response.CreativeID,
cpm: response.Price,
netRevenue: true,
currency: CURRENCY,
meta: response.Meta || { advertiserDomains: [] }
};
// retreive video response if present
const vast64 = response.Vast;
if (vast64) {
bid.width = response.Width;
bid.height = response.Height;
bid.vastXml = window.atob(vast64);
bid.mediaType = 'video';
} else if (request.Native) {
// format Native response if Native was requested
bid.native = getNativeAssets(response, request.Native);
bid.mediaType = 'native';
} else {
bid.width = response.Width;
bid.height = response.Height;
bid.ad = response.Ad;
}
return bid;
}
registerBidder(spec);