forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadnuntiusBidAdapter.js
473 lines (429 loc) · 17.6 KB
/
adnuntiusBidAdapter.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
import { registerBidder } from '../src/adapters/bidderFactory.js';
import {BANNER, VIDEO} from '../src/mediaTypes.js';
import {isStr, isEmpty, deepAccess, getUnixTimestampFromNow, convertObjectToArray, getWindowTop} from '../src/utils.js';
import { config } from '../src/config.js';
import { getStorageManager } from '../src/storageManager.js';
const BIDDER_CODE = 'adnuntius';
const BIDDER_CODE_DEAL_ALIAS_BASE = 'adndeal';
const BIDDER_CODE_DEAL_ALIASES = [1, 2, 3, 4, 5].map(num => {
return BIDDER_CODE_DEAL_ALIAS_BASE + num;
});
const ENDPOINT_URL = 'https://ads.adnuntius.delivery/i';
const ENDPOINT_URL_EUROPE = 'https://europe.delivery.adnuntius.com/i';
const GVLID = 855;
const SUPPORTED_MEDIA_TYPES = [BANNER, VIDEO];
const MAXIMUM_DEALS_LIMIT = 5;
const VALID_BID_TYPES = ['netBid', 'grossBid'];
const METADATA_KEY = 'adn.metaData';
const METADATA_KEY_SEPARATOR = '@@@';
export const misc = {
findHighestPrice: function(arr, bidType) {
return arr.reduce((highest, cur) => {
const currentBid = cur[bidType];
const highestBid = highest[bidType]
return currentBid.currency === highestBid.currency && currentBid.amount > highestBid.amount ? cur : highest;
}, arr[0]);
}
};
const storageTool = (function () {
const storage = getStorageManager({ bidderCode: BIDDER_CODE });
let metaInternal;
const getMetaDataFromLocalStorage = function (pNetwork) {
if (!storage.localStorageIsEnabled()) {
return [];
}
let parsedJson;
try {
parsedJson = JSON.parse(storage.getDataFromLocalStorage(METADATA_KEY));
} catch (e) {
return [];
}
let network = pNetwork;
if (Array.isArray(pNetwork)) {
network = (pNetwork.find((p) => p.network) || {}).network;
}
let filteredEntries = parsedJson ? parsedJson.filter((datum) => {
if (datum.key === 'voidAuIds' && Array.isArray(datum.value)) {
return true;
}
return datum.key && datum.value && datum.exp && datum.exp > getUnixTimestampFromNow() && (!network || network === datum.network);
}) : [];
const voidAuIdsEntry = filteredEntries.find(entry => entry.key === 'voidAuIds');
if (voidAuIdsEntry) {
const now = getUnixTimestampFromNow();
voidAuIdsEntry.value = voidAuIdsEntry.value.filter(voidAuId => voidAuId.auId && voidAuId.exp > now);
if (!voidAuIdsEntry.value.length) {
filteredEntries = filteredEntries.filter(entry => entry.key !== 'voidAuIds');
}
}
return filteredEntries;
};
const setMetaInternal = function (apiRespMetadata, network) {
if (!storage.localStorageIsEnabled()) {
return;
}
const updateVoidAuIds = function (currentVoidAuIds, auIdsAsString) {
const newAuIds = isStr(auIdsAsString) ? auIdsAsString.split(';') : [];
const notNewExistingAuIds = currentVoidAuIds.filter(auIdObj => {
return newAuIds.indexOf(auIdObj.value) < -1;
}) || [];
const oneDayFromNow = getUnixTimestampFromNow(1);
const apiIdsArray = newAuIds.map(auId => {
return { exp: oneDayFromNow, auId: auId };
}) || [];
return notNewExistingAuIds.concat(apiIdsArray) || [];
}
// use the metadata key separator to distinguish the same key for different networks.
const metaAsObj = getMetaDataFromLocalStorage().reduce((a, entry) => ({ ...a, [entry.key + METADATA_KEY_SEPARATOR + (entry.network ? entry.network : '')]: { value: entry.value, exp: entry.exp, network: entry.network } }), {});
for (const key in apiRespMetadata) {
if (key !== 'voidAuIds') {
metaAsObj[key + METADATA_KEY_SEPARATOR + network] = {
value: apiRespMetadata[key],
exp: getUnixTimestampFromNow(100),
network: network
}
}
}
const currentAuIds = updateVoidAuIds(metaAsObj.voidAuIds || [], apiRespMetadata.voidAuIds);
if (currentAuIds.length > 0) {
metaAsObj.voidAuIds = { value: currentAuIds };
}
const metaDataForSaving = Object.entries(metaAsObj).map((entrySet) => {
if (entrySet.length !== 2) {
return {};
}
const key = entrySet[0].split(METADATA_KEY_SEPARATOR)[0];
if (key === 'voidAuIds') {
return {
key: key,
value: entrySet[1].value
};
}
return {
key: key,
value: entrySet[1].value,
exp: entrySet[1].exp,
network: entrySet[1].network
}
}).filter(entry => entry.key);
storage.setDataInLocalStorage(METADATA_KEY, JSON.stringify(metaDataForSaving));
};
const getUsi = function (meta, ortb2, bidParams) {
// Fetch user id from parameters.
for (let i = 0; i < bidParams.length; i++) {
const bidParam = bidParams[i];
if (bidParam.userId) {
return bidParam.userId;
}
}
if (ortb2 && ortb2.user && ortb2.user.id) {
return ortb2.user.id
}
return (meta && meta.usi) ? meta.usi : false
}
return {
refreshStorage: function (bidderRequest) {
const ortb2 = bidderRequest.ortb2 || {};
const bidParams = (bidderRequest.bids || []).map((b) => {
return b.params ? b.params : {};
});
metaInternal = getMetaDataFromLocalStorage(bidParams).reduce((a, entry) => ({ ...a, [entry.key]: entry.value }), {});
metaInternal.usi = getUsi(metaInternal, ortb2, bidParams);
if (!metaInternal.usi) {
delete metaInternal.usi;
}
if (metaInternal.voidAuIds) {
metaInternal.voidAuIdsArray = metaInternal.voidAuIds.map((voidAuId) => {
return voidAuId.auId;
});
}
},
saveToStorage: function (serverData, network) {
setMetaInternal(serverData, network);
},
getUrlRelatedData: function () {
// getting the URL information is theoretically not network-specific
const { usi, voidAuIdsArray } = metaInternal;
return { usi, voidAuIdsArray };
},
getPayloadRelatedData: function (network) {
// getting the payload data should be network-specific
const { segments, usi, userId, voidAuIdsArray, voidAuIds, ...payloadRelatedData } = getMetaDataFromLocalStorage(network).reduce((a, entry) => ({ ...a, [entry.key]: entry.value }), {});
return payloadRelatedData;
}
};
})();
const targetingTool = (function() {
const getSegmentsFromOrtb = function(bidderRequest) {
const userData = deepAccess(bidderRequest.ortb2 || {}, 'user.data');
let segments = [];
if (userData) {
userData.forEach(userdat => {
if (userdat.segment) {
segments.push(...userdat.segment.map((segment) => {
if (isStr(segment)) return segment;
if (isStr(segment.id)) return segment.id;
}).filter((seg) => !!seg));
}
});
}
return segments
};
const getKvsFromOrtb = function(bidderRequest) {
return deepAccess(bidderRequest.ortb2 || {}, 'site.ext.data');
};
return {
addSegmentsToUrlData: function (validBids, bidderRequest, existingUrlRelatedData) {
let segments = getSegmentsFromOrtb(bidderRequest || {});
for (let i = 0; i < validBids.length; i++) {
const bid = validBids[i];
const targeting = bid.params.targeting || {};
if (Array.isArray(targeting.segments)) {
segments = segments.concat(targeting.segments);
delete bid.params.targeting.segments;
}
}
existingUrlRelatedData.segments = segments;
},
mergeKvsFromOrtb: function(bidTargeting, bidderRequest) {
const kv = getKvsFromOrtb(bidderRequest || {});
if (isEmpty(kv)) {
return;
}
if (bidTargeting.kv && !Array.isArray(bidTargeting.kv)) {
bidTargeting.kv = convertObjectToArray(bidTargeting.kv);
}
bidTargeting.kv = bidTargeting.kv || [];
bidTargeting.kv = bidTargeting.kv.concat(convertObjectToArray(kv));
}
}
})();
const validateBidType = function (bidTypeOption) {
return VALID_BID_TYPES.indexOf(bidTypeOption || '') > -1 ? bidTypeOption : 'bid';
}
const AU_ID_REGEX = new RegExp('^[0-9A-Fa-f]{1,20}$');
export const spec = {
code: BIDDER_CODE,
aliases: BIDDER_CODE_DEAL_ALIASES,
gvlid: GVLID,
supportedMediaTypes: SUPPORTED_MEDIA_TYPES,
isBidRequestValid: function (bid) {
// The auId MUST be a hexadecimal string
const validAuId = AU_ID_REGEX.test(bid.params.auId);
return !!(validAuId && (bid.bidId || (bid.params.member && bid.params.invCode)));
},
buildRequests: function (validBidRequests, bidderRequest) {
const queryParamsAndValues = [];
queryParamsAndValues.push('tzo=' + new Date().getTimezoneOffset())
queryParamsAndValues.push('format=prebid')
const gdprApplies = deepAccess(bidderRequest, 'gdprConsent.gdprApplies');
const consentString = deepAccess(bidderRequest, 'gdprConsent.consentString');
if (gdprApplies !== undefined) {
const flag = gdprApplies ? '1' : '0'
queryParamsAndValues.push('consentString=' + consentString);
queryParamsAndValues.push('gdpr=' + flag);
}
const win = getWindowTop() || window;
if (win.screen && win.screen.availHeight) {
queryParamsAndValues.push('screen=' + win.screen.availWidth + 'x' + win.screen.availHeight);
}
if (win.innerWidth) {
queryParamsAndValues.push('viewport=' + win.innerWidth + 'x' + win.innerHeight);
}
const searchParams = new URLSearchParams(window.location.search);
if (searchParams.has('script-override')) {
queryParamsAndValues.push('so=' + searchParams.get('script-override'));
}
storageTool.refreshStorage(bidderRequest);
const urlRelatedMetaData = storageTool.getUrlRelatedData();
targetingTool.addSegmentsToUrlData(validBidRequests, bidderRequest, urlRelatedMetaData);
if (urlRelatedMetaData.segments.length > 0) queryParamsAndValues.push('segments=' + urlRelatedMetaData.segments.join(','));
if (urlRelatedMetaData.usi) queryParamsAndValues.push('userId=' + urlRelatedMetaData.usi);
const bidderConfig = config.getConfig();
if (bidderConfig.useCookie === false) queryParamsAndValues.push('noCookies=true');
if (bidderConfig.advertiserTransparency === true) queryParamsAndValues.push('advertiserTransparency=true');
if (bidderConfig.maxDeals > 0) queryParamsAndValues.push('ds=' + Math.min(bidderConfig.maxDeals, MAXIMUM_DEALS_LIMIT));
const bidRequests = {};
const networks = {};
for (let i = 0; i < validBidRequests.length; i++) {
const bid = validBidRequests[i];
if ((urlRelatedMetaData.voidAuIdsArray && (urlRelatedMetaData.voidAuIdsArray.indexOf(bid.params.auId) > -1 || urlRelatedMetaData.voidAuIdsArray.indexOf(bid.params.auId.padStart(16, '0')) > -1))) {
// This auId is void. Do NOT waste time and energy sending a request to the server
continue;
}
let network = bid.params.network || 'network';
bidRequests[network] = bidRequests[network] || [];
bidRequests[network].push(bid);
networks[network] = networks[network] || {};
networks[network].adUnits = networks[network].adUnits || [];
const refererInfo = bidderRequest && bidderRequest.refererInfo ? bidderRequest.refererInfo : {};
if (refererInfo.page) {
networks[network].context = bidderRequest.refererInfo.page;
}
if (refererInfo.canonicalUrl) {
networks[network].canonical = bidderRequest.refererInfo.canonicalUrl;
}
const payloadRelatedData = storageTool.getPayloadRelatedData(bid.params.network);
if (Object.keys(payloadRelatedData).length > 0) {
networks[network].metaData = payloadRelatedData;
}
const bidTargeting = {...bid.params.targeting || {}};
targetingTool.mergeKvsFromOrtb(bidTargeting, bidderRequest);
const mediaTypes = bid.mediaTypes || {};
const validMediaTypes = SUPPORTED_MEDIA_TYPES.filter(mt => {
return mediaTypes[mt];
}) || [];
if (validMediaTypes.length === 0) {
// banner ads by default if nothing specified, dimensions to be derived from the ad unit within adnuntius system
validMediaTypes.push(BANNER);
}
const isSingleFormat = validMediaTypes.length === 1;
validMediaTypes.forEach(mediaType => {
const mediaTypeData = mediaTypes[mediaType];
if (mediaType === VIDEO && mediaTypeData && mediaTypeData.context === 'outstream') {
return;
}
const targetId = (bid.params.targetId || bid.bidId) + (isSingleFormat || mediaType === BANNER ? '' : ('-' + mediaType));
const adUnit = {...bidTargeting, auId: bid.params.auId, targetId: targetId};
if (mediaType === VIDEO) {
adUnit.adType = 'VAST';
}
const maxDeals = Math.max(0, Math.min(bid.params.maxDeals || 0, MAXIMUM_DEALS_LIMIT));
if (maxDeals > 0) {
adUnit.maxDeals = maxDeals;
}
if (mediaType === BANNER && mediaTypeData && mediaTypeData.sizes) {
adUnit.dimensions = mediaTypeData.sizes;
}
networks[network].adUnits.push(adUnit);
});
}
const requests = [];
const networkKeys = Object.keys(networks);
for (let j = 0; j < networkKeys.length; j++) {
const network = networkKeys[j];
const requestURL = gdprApplies ? ENDPOINT_URL_EUROPE : ENDPOINT_URL
requests.push({
method: 'POST',
url: requestURL + '?' + queryParamsAndValues.join('&'),
data: JSON.stringify(networks[network]),
bid: bidRequests[network]
});
}
return requests;
},
interpretResponse: function (serverResponse, bidRequest) {
if (serverResponse.body.metaData) {
storageTool.saveToStorage(serverResponse.body.metaData, serverResponse.body.network);
}
const responseAdUnits = serverResponse.body.adUnits;
let validatedBidType = validateBidType(config.getConfig().bidType);
if (bidRequest.bid) {
bidRequest.bid.forEach(b => {
if (b.params && b.params.bidType) {
validatedBidType = validateBidType(b.params.bidType);
}
});
}
function buildAdResponse(bidderCode, ad, adUnit, dealCount) {
const advertiserDomains = ad.advertiserDomains || [];
if (advertiserDomains.length === 0) {
const destinationUrls = ad.destinationUrls || {};
for (const value of Object.values(destinationUrls)) {
advertiserDomains.push(value.split('/')[2])
}
}
const adResponse = {
bidderCode: bidderCode,
requestId: adUnit.targetId,
cpm: ad[validatedBidType] ? ad[validatedBidType].amount * 1000 : 0,
width: Number(ad.creativeWidth),
height: Number(ad.creativeHeight),
creativeId: ad.creativeId,
currency: (ad.bid) ? ad.bid.currency : 'EUR',
dealId: ad.dealId || '',
dealCount: dealCount,
meta: {
advertiserDomains: advertiserDomains
},
netRevenue: false,
ttl: 360,
};
// Deal bids provide the rendered ad content along with the
// bid; whereas regular bids have it stored on the ad-unit.
const isDeal = dealCount > 0;
const renderSource = isDeal ? ad : adUnit;
if (renderSource.vastXml) {
adResponse.vastXml = renderSource.vastXml
adResponse.mediaType = VIDEO
} else {
adResponse.ad = renderSource.html
}
return adResponse;
}
const highestYieldingAdUnits = [];
if (responseAdUnits.length === 1) {
highestYieldingAdUnits.push(responseAdUnits[0]);
} else if (responseAdUnits.length > 1) {
bidRequest.bid.forEach((resp) => {
const multiFormatAdUnits = [];
SUPPORTED_MEDIA_TYPES.forEach((mediaType) => {
const suffix = mediaType === BANNER ? '' : '-' + mediaType;
const targetId = (resp?.params?.targetId || resp.bidId) + suffix;
const au = responseAdUnits.find((rAu) => {
return rAu.targetId === targetId && rAu.matchedAdCount > 0;
});
if (au) {
multiFormatAdUnits.push(au);
}
});
if (multiFormatAdUnits.length > 0) {
const highestYield = multiFormatAdUnits.length === 1 ? multiFormatAdUnits[0] : multiFormatAdUnits.reduce((highest, cur) => {
const highestBid = misc.findHighestPrice(highest.ads, validatedBidType)[validatedBidType];
const curBid = misc.findHighestPrice(cur.ads, validatedBidType)[validatedBidType];
return curBid.currency === highestBid.currency && curBid.amount > highestBid.amount ? cur : highest;
}, multiFormatAdUnits[0]);
highestYield.targetId = resp.bidId;
highestYieldingAdUnits.push(highestYield);
}
});
}
const bidsById = bidRequest.bid.reduce((response, bid) => {
return {
...response,
[bid.bidId]: bid
};
}, {});
const hasBidAdUnits = highestYieldingAdUnits.filter((au) => {
const bid = bidsById[au.targetId];
if (bid && bid.bidder && BIDDER_CODE_DEAL_ALIASES.indexOf(bid.bidder) < 0) {
return au.matchedAdCount > 0;
} else {
// We do NOT accept bids when using this adaptor via one of the
// "deals" aliases; those requests are for ONLY getting deals from Adnuntius
return false;
}
});
const hasDealsAdUnits = highestYieldingAdUnits.filter((au) => {
return au.deals && au.deals.length > 0;
});
const dealAdResponses = hasDealsAdUnits.reduce((response, au) => {
const bid = bidsById[au.targetId];
if (bid) {
(au.deals || []).forEach((deal, i) => {
response.push(buildAdResponse(bid.bidder, deal, au, i + 1));
});
}
return response;
}, []);
const bidAdResponses = hasBidAdUnits.reduce((response, au) => {
const bid = bidsById[au.targetId];
if (bid) {
response.push(buildAdResponse(bid.bidder, au.ads[0], au, 0));
}
return response;
}, []);
return [...dealAdResponses, ...bidAdResponses];
}
}
registerBidder(spec);