forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathampliffyBidAdapter.js
414 lines (382 loc) · 13.2 KB
/
ampliffyBidAdapter.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
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {logError, logInfo, triggerPixel} from '../src/utils.js';
const BIDDER_CODE = 'ampliffy';
const GVLID = 1258;
const DEFAULT_ENDPOINT = 'bidder.ampliffy.com';
const TTL = 600; // Time-to-Live - how long (in seconds) Prebid can use this bid.
const LOG_PREFIX = 'AmpliffyBidder: ';
function isBidRequestValid(bid) {
logInfo(LOG_PREFIX + 'isBidRequestValid: Code: ' + bid.adUnitCode + ': Param' + JSON.stringify(bid.params), bid.adUnitCode);
if (bid.params) {
if (!bid.params.placementId || !bid.params.format) return false;
if (bid.params.format.toLowerCase() !== 'video' && bid.params.format.toLowerCase() !== 'display' && bid.params.format.toLowerCase() !== 'all') return false;
if (bid.params.format.toLowerCase() === 'video' && !bid.mediaTypes['video']) return false;
if (bid.params.format.toLowerCase() === 'display' && !bid.mediaTypes['banner']) return false;
if (!bid.params.server || bid.params.server === '') {
const server = bid.params.type + bid.params.region + bid.params.adnetwork;
if (server && server !== '') bid.params.server = server;
else bid.params.server = DEFAULT_ENDPOINT;
}
return true;
}
return false;
}
function manageConsentArguments(bidderRequest) {
let consent = null;
if (bidderRequest?.gdprConsent) {
consent = {
gdpr: bidderRequest.gdprConsent.gdprApplies ? '1' : '0',
};
if (bidderRequest.gdprConsent.consentString) {
consent.consent_string = bidderRequest.gdprConsent.consentString;
}
if (bidderRequest.gdprConsent.addtlConsent && bidderRequest.gdprConsent.addtlConsent.indexOf('~') !== -1) {
consent.addtl_consent = bidderRequest.gdprConsent.addtlConsent;
}
}
return consent;
}
function buildRequests(validBidRequests, bidderRequest) {
const bidRequests = [];
for (const bidRequest of validBidRequests) {
for (const sizes of bidRequest.sizes) {
let extraParams = mergeParams(getDefaultParams(), bidRequest.params.extraParams);
// Apply GDPR parameters to request.
extraParams = mergeParams(extraParams, manageConsentArguments(bidderRequest));
const serverURL = getServerURL(bidRequest.params.server, sizes, bidRequest.params.placementId, extraParams);
logInfo(LOG_PREFIX + serverURL, 'requests');
extraParams.bidId = bidRequest.bidId;
bidRequests.push({
method: 'GET',
url: serverURL,
data: extraParams,
bidRequest,
});
}
logInfo(LOG_PREFIX + 'Building request from: ' + bidderRequest.url + ': ' + JSON.stringify(bidRequests), bidRequest.adUnitCode);
}
return bidRequests;
}
export function getDefaultParams() {
return {
ciu_szs: '1x1',
gdfp_req: '1',
env: 'vp',
output: 'xml_vast4',
unviewed_position_start: '1'
};
}
export function mergeParams(params, extraParams) {
if (extraParams) {
for (const k in extraParams) {
params[k] = extraParams[k];
}
}
return params;
}
export function paramsToQueryString(params) {
return Object.entries(params).filter(e => typeof e[1] !== 'undefined').map(e => {
if (e[1]) return encodeURIComponent(e[0]) + '=' + encodeURIComponent(e[1]);
else return encodeURIComponent(e[0]);
}).join('&');
}
const getCacheBuster = () => Math.floor(Math.random() * (9999999999 - 1000000000));
// For testing purposes
let currentUrl = null;
export function getCurrentURL() {
if (!currentUrl) currentUrl = top.location.href;
return currentUrl;
}
export function setCurrentURL(url) {
currentUrl = url;
}
const getCurrentURLEncoded = () => encodeURIComponent(getCurrentURL());
function getServerURL(server, sizes, iu, queryParams) {
const random = getCacheBuster();
const size = sizes[0] + 'x' + sizes[1];
let serverURL = '//' + server + '/gampad/ads';
queryParams.sz = size;
queryParams.iu = iu;
queryParams.url = getCurrentURL();
queryParams.description_url = getCurrentURL();
queryParams.correlator = random;
return serverURL;
}
function interpretResponse(serverResponse, bidRequest) {
const bidResponses = [];
const bidResponse = {};
let mediaType = 'video';
if (
bidRequest.bidRequest?.mediaTypes &&
!bidRequest.bidRequest.mediaTypes['video']
) {
mediaType = 'banner';
}
bidResponse.requestId = bidRequest.bidRequest.bidId;
bidResponse.width = bidRequest.bidRequest?.sizes[0][0];
bidResponse.height = bidRequest.bidRequest?.sizes[0][1];
bidResponse.ttl = TTL;
bidResponse.creativeId = 'ampCreativeID134';
bidResponse.netRevenue = true;
bidResponse.mediaType = mediaType;
bidResponse.meta = {
advertiserDomains: [],
};
let xmlStr = serverResponse.body;
const xml = new window.DOMParser().parseFromString(xmlStr, 'text/xml');
const xmlData = parseXML(xml, bidResponse);
logInfo(LOG_PREFIX + 'Response from: ' + bidRequest.url + ': ' + JSON.stringify(xmlData), bidRequest.bidRequest.adUnitCode);
if (xmlData.cpm < 0 || !xmlData.creativeURL || !xmlData.bidUp) {
return [];
}
bidResponse.cpm = xmlData.cpm;
bidResponse.currency = xmlData.currency;
if (mediaType === 'video') {
logInfo(LOG_PREFIX + xmlData.creativeURL, 'requests');
bidResponse.vastUrl = xmlData.creativeURL;
} else {
bidResponse.adUrl = xmlData.creativeURL;
}
if (xmlData.trackingUrl) {
bidResponse.vastImpUrl = xmlData.trackingUrl;
bidResponse.trackingUrl = xmlData.trackingUrl;
}
bidResponses.push(bidResponse);
return bidResponses;
}
const replaceMacros = (txt, cpm, bid) => {
const size = bid.width + 'x' + bid.height;
txt = txt.replaceAll('%%CACHEBUSTER%%', getCacheBuster());
txt = txt.replaceAll('@@CACHEBUSTER@@', getCacheBuster());
txt = txt.replaceAll('%%REFERER%%', getCurrentURLEncoded());
txt = txt.replaceAll('@@REFERER@@', getCurrentURLEncoded());
txt = txt.replaceAll('%%REFERRER_URL_UNESC%%', getCurrentURLEncoded());
txt = txt.replaceAll('@@REFERRER_URL_UNESC@@', getCurrentURLEncoded());
txt = txt.replaceAll('%%PRICE_ESC%%', encodePrice(cpm));
txt = txt.replaceAll('@@PRICE_ESC@@', encodePrice(cpm));
txt = txt.replaceAll('%%SIZES%%', size);
txt = txt.replaceAll('@@SIZES@@', size);
return txt;
}
const encodePrice = (price) => {
price = parseFloat(price);
const s = 116.54;
const c = 1;
const a = 1;
let encodedPrice = s * Math.log10(price + a) + c;
encodedPrice = Math.min(200, encodedPrice);
encodedPrice = Math.round(Math.max(1, encodedPrice));
// Format the encoded price with leading zeros if necessary
const formattedEncodedPrice = encodedPrice.toString().padStart(3, '0');
// Build the encoding key
const encodingKey = `H--${formattedEncodedPrice}`;
return encodeURIComponent(`vch=${encodingKey}`);
};
function extractCT(xml) {
let ct = null;
try {
try {
const vastAdTagURI = xml.getElementsByTagName('VASTAdTagURI')[0]
if (vastAdTagURI) {
let url = null;
for (const childNode of vastAdTagURI.childNodes) {
if (childNode.nodeValue.trim().includes('http')) {
url = decodeURIComponent(childNode.nodeValue);
}
}
const urlParams = new URLSearchParams(url);
ct = urlParams.get('ct')
}
} catch (e) {
}
if (!ct) {
const geoExtensions = xml.querySelectorAll('Extension[type="geo"]');
geoExtensions.forEach((geoExtension) => {
const countryElement = geoExtension.querySelector('Country');
if (countryElement) {
ct = countryElement.textContent;
}
});
}
} catch (e) {}
return ct;
}
function extractCPM(htmlContent, ct, cpm) {
const cpmMapDiv = htmlContent.querySelectorAll('[cpmMap]')[0];
if (cpmMapDiv) {
let cpmMapJSON = JSON.parse(cpmMapDiv.getAttribute('cpmMap'));
if ((cpmMapJSON)) {
if (cpmMapJSON[ct]) {
cpm = cpmMapJSON[ct];
} else if (cpmMapJSON['default']) {
cpm = cpmMapJSON['default'];
}
}
}
return cpm;
}
function extractCurrency(htmlContent, currency) {
const currencyDiv = htmlContent.querySelectorAll('[cpmCurrency]')[0];
if (currencyDiv) {
const currencyValue = currencyDiv.getAttribute('cpmCurrency');
if (currencyValue && currencyValue !== '') {
currency = currencyValue;
}
}
return currency;
}
function extractCreativeURL(htmlContent, ct, cpm, bid) {
let creativeURL = null;
const creativeMap = htmlContent.querySelectorAll('[creativeMap]')[0];
if (creativeMap) {
const creativeMapString = creativeMap.getAttribute('creativeMap');
const creativeMapJSON = JSON.parse(creativeMapString);
let defaultURL = null;
for (const url of Object.keys(creativeMapJSON)) {
const geo = creativeMapJSON[url];
if (geo.includes(ct)) {
creativeURL = replaceMacros(url, cpm, bid);
} else if (geo.includes('default')) {
defaultURL = url;
}
}
if (!creativeURL && defaultURL) creativeURL = replaceMacros(defaultURL, cpm, bid);
}
return creativeURL;
}
function extractSyncs(htmlContent) {
let userSyncsJSON = null;
const userSyncs = htmlContent.querySelectorAll('[userSyncs]')[0];
if (userSyncs) {
const userSyncsString = userSyncs.getAttribute('userSyncs');
userSyncsJSON = JSON.parse(userSyncsString);
}
return userSyncsJSON;
}
function extractTrackingURL(htmlContent, ret) {
const trackingUrlDiv = htmlContent.querySelectorAll('[bidder-tracking-url]')[0];
if (trackingUrlDiv) {
const trackingUrl = trackingUrlDiv.getAttribute('bidder-tracking-url');
logInfo(LOG_PREFIX + 'parseXML: trackingUrl: ', trackingUrl)
ret.trackingUrl = trackingUrl;
}
}
export function parseXML(xml, bid) {
const ret = { cpm: 0.001, currency: 'EUR', creativeURL: null, bidUp: false };
const ct = extractCT(xml);
if (!ct) return ret;
try {
if (ct) {
const companion = xml.getElementsByTagName('Companion')[0];
const htmlResource = companion.getElementsByTagName('HTMLResource')[0];
const htmlContent = document.createElement('html');
htmlContent.innerHTML = htmlResource.textContent;
ret.cpm = extractCPM(htmlContent, ct, ret.cpm);
ret.currency = extractCurrency(htmlContent, ret.currency);
ret.creativeURL = extractCreativeURL(htmlContent, ct, ret.cpm, bid);
extractTrackingURL(htmlContent, ret);
ret.bidUp = isAllowedToBidUp(htmlContent, getCurrentURL());
ret.userSyncs = extractSyncs(htmlContent);
}
} catch (e) {
logError(LOG_PREFIX + 'Error parsing XML', e);
}
logInfo(LOG_PREFIX + 'parseXML RET:', ret);
return ret;
}
export function isAllowedToBidUp(html, currentURL) {
currentURL = currentURL.split('?')[0]; // Remove parameters
let allowedToPush = false;
try {
const domainsMap = html.querySelectorAll('[domainMap]')[0];
if (domainsMap) {
let domains = JSON.parse(domainsMap.getAttribute('domainMap'));
if (domains.domainMap) {
domains = domains.domainMap;
}
domains.forEach((d) => {
if (currentURL.includes(d) || d === 'all' || d === '*') allowedToPush = true;
})
} else {
allowedToPush = true;
}
if (allowedToPush) {
const excludedURL = html.querySelectorAll('[excludedURLs]')[0];
if (excludedURL) {
const excludedURLsString = domainsMap.getAttribute('excludedURLs');
if (excludedURLsString !== '') {
let excluded = JSON.parse(excludedURLsString);
excluded.forEach((d) => {
if (currentURL.includes(d)) allowedToPush = false;
})
}
}
}
} catch (e) {
logError(LOG_PREFIX + 'isAllowedToBidUp', e);
}
return allowedToPush;
}
function getSyncData(options, syncs) {
const ret = [];
if (syncs?.length) {
for (const sync of syncs) {
if (sync.type === 'syncImage' && options.pixelEnabled) {
ret.push({url: sync.url, type: 'image'});
} else if (sync.type === 'syncIframe' && options.iframeEnabled) {
ret.push({url: sync.url, type: 'iframe'});
}
}
}
return ret;
}
function getUserSyncs(syncOptions, serverResponses) {
const userSyncs = [];
for (const serverResponse of serverResponses) {
if (serverResponse.body) {
try {
const xmlStr = serverResponse.body;
const xml = new window.DOMParser().parseFromString(xmlStr, 'text/xml');
const xmlData = parseXML(xml, {});
if (xmlData.userSyncs) {
userSyncs.push(...getSyncData(syncOptions, xmlData.userSyncs));
}
} catch (e) {}
}
}
return userSyncs;
}
function onBidWon(bid) {
logInfo(`${LOG_PREFIX} WON AMPLIFFY`);
if (bid.trackingUrl) {
let url = bid.trackingUrl;
// Replace macros with URL-encoded bid parameters
Object.keys(bid).forEach(key => {
const macroKey = `%%${key.toUpperCase()}%%`;
const value = encodeURIComponent(JSON.stringify(bid[key]));
url = url.split(macroKey).join(value);
});
triggerPixel(url, () => {
logInfo(`${LOG_PREFIX} send data success`);
},
(e) => {
logError(`${LOG_PREFIX} send data error`, e);
});
}
}
function onTimeOut() {
logInfo(LOG_PREFIX + 'TIMEOUT');
}
export const spec = {
code: BIDDER_CODE,
gvlid: GVLID,
aliases: ['ampliffy', 'amp', 'videoffy', 'publiffy'],
supportedMediaTypes: ['video', 'banner'],
isBidRequestValid,
buildRequests,
interpretResponse,
getUserSyncs,
onTimeOut,
onBidWon,
};
registerBidder(spec);