forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowsiRtdProvider.js
399 lines (371 loc) · 10.6 KB
/
browsiRtdProvider.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
/**
* This module adds browsi provider to the eal time data module
* The {@link module:modules/realTimeData} module is required
* The module will fetch predictions from browsi server
* The module will place browsi bootstrap script on page
* @module modules/browsiProvider
* @requires module:modules/realTimeData
*/
/**
* @typedef {Object} ModuleParams
* @property {string} siteKey
* @property {string} pubKey
* @property {string} url
* @property {?string} keyName
* @property {?string} splitKey
*/
import {deepClone, deepSetValue, isFn, isGptPubadsDefined, isNumber, logError, logInfo, generateUUID} from '../src/utils.js';
import {submodule} from '../src/hook.js';
import {ajaxBuilder} from '../src/ajax.js';
import {loadExternalScript} from '../src/adloader.js';
import {getStorageManager} from '../src/storageManager.js';
import {find, includes} from '../src/polyfill.js';
import {getGlobal} from '../src/prebidGlobal.js';
import * as events from '../src/events.js';
import {EVENTS} from '../src/constants.js';
import {MODULE_TYPE_RTD} from '../src/activities/modules.js';
import {setKeyValue as setGptKeyValue} from '../libraries/gptUtils/gptUtils.js';
/**
* @typedef {import('../modules/rtdModule/index.js').RtdSubmodule} RtdSubmodule
*/
const MODULE_NAME = 'browsi';
const storage = getStorageManager({moduleType: MODULE_TYPE_RTD, moduleName: MODULE_NAME});
const RANDOM = Math.floor(Math.random() * 10) + 1;
/** @type {ModuleParams} */
let _moduleParams = {};
/** @type {null|Object} */
let _browsiData = null;
/** @type {string} */
const DEF_KEYNAME = 'browsiViewability';
/** @type {null | function} */
let _dataReadyCallback = null;
/** @type {null|Object} */
let _ic = {};
/**
* add browsi script to page
* @param {Object} data
*/
export function addBrowsiTag(data) {
let script = loadExternalScript(data.u, MODULE_TYPE_RTD, 'browsi');
script.async = true;
script.setAttribute('data-sitekey', _moduleParams.siteKey);
script.setAttribute('data-pubkey', _moduleParams.pubKey);
script.setAttribute('prebidbpt', 'true');
script.setAttribute('id', 'browsi-tag');
script.setAttribute('src', data.u);
script.prebidData = deepClone(typeof data === 'string' ? Object(data) : data)
script.brwRandom = RANDOM;
if (_moduleParams.keyName) {
script.prebidData.kn = _moduleParams.keyName;
}
return script;
}
export const setKeyValue = (key) => setGptKeyValue(key, RANDOM.toString());
export function sendPageviewEvent(eventType) {
if (eventType === 'PAGEVIEW') {
window.addEventListener('browsi_pageview', () => {
events.emit(EVENTS.BILLABLE_EVENT, {
vendor: 'browsi',
type: 'pageview',
billingId: generateUUID()
})
})
}
}
/**
* collect required data from page
* send data to browsi server to get predictions
*/
export function collectData() {
const win = window.top;
const doc = win.document;
let browsiData = null;
try {
browsiData = storage.getDataFromLocalStorage('__brtd');
} catch (e) {
logError('unable to parse __brtd');
}
let predictorData = {
...{
sk: _moduleParams.siteKey,
pk: _moduleParams.pubKey,
sw: (win.screen && win.screen.width) || -1,
sh: (win.screen && win.screen.height) || -1,
url: `${doc.location.protocol}//${doc.location.host}${doc.location.pathname}`,
},
...(browsiData ? {us: browsiData} : {us: '{}'}),
...(document.referrer ? {r: document.referrer} : {}),
...(document.title ? {at: document.title} : {})
};
getPredictionsFromServer(`//${_moduleParams.url}/prebid?${toUrlParams(predictorData)}`);
}
/**
* wait for data from server
* call callback when data is ready
* @param {function} callback
*/
function waitForData(callback) {
if (_browsiData) {
_dataReadyCallback = null;
callback();
} else {
_dataReadyCallback = callback;
}
}
export function setData(data) {
_browsiData = data;
if (isFn(_dataReadyCallback)) {
_dataReadyCallback();
_dataReadyCallback = null;
}
}
function getRTD(auc) {
logInfo(`Browsi RTD provider is fetching data for ${auc}`);
try {
const _bp = (_browsiData && _browsiData.p) || {};
return auc.reduce((rp, uc) => {
_ic[uc] = _ic[uc] || 0;
const _c = _ic[uc];
if (!uc) {
return rp
}
const adSlot = getSlotByCode(uc);
const identifier = adSlot ? getMacroId(_browsiData['pmd'], adSlot) : uc;
const _pd = _bp[identifier];
if (!_pd) {
return rp
}
if (_pd.ps) {
if (!isIdMatchingAdUnit(adSlot, _pd.w)) {
return rp;
}
rp[uc] = getKVObject(getCurrentData(_pd.ps, _c));
}
return rp;
}, {});
} catch (e) {
return {};
}
}
/**
* get prediction
* return -1 if prediction not found
* @param {object} predictionObject
* @param {number} _c
* @return {number}
*/
export function getCurrentData(predictionObject, _c) {
if (!predictionObject || !isNumber(_c)) {
return -1;
}
if (isNumber(predictionObject[_c])) {
return predictionObject[_c];
}
if (Object.keys(predictionObject).length > 1) {
while (_c > 0) {
_c--;
if (isNumber(predictionObject[_c])) {
return predictionObject[_c];
}
}
}
return -1;
}
/**
* get all slots on page
* @return {Object[]} slot GoogleTag slots
*/
function getAllSlots() {
return isGptPubadsDefined() && window.googletag.pubads().getSlots();
}
/**
* get prediction and return valid object for key value set
* @param {number} p
* @return {Object} key:value
*/
function getKVObject(p) {
const prValue = p < 0 ? 'NA' : (Math.floor(p * 10) / 10).toFixed(2);
let prObject = {};
prObject[getKey()] = prValue.toString();
return prObject;
}
function getKey() {
return ((_moduleParams['keyName'] || (_browsiData && _browsiData['kn']) || DEF_KEYNAME).toString())
}
/**
* check if placement id matches one of given ad units
* @param {Object} slot google slot
* @param {string[]} whitelist ad units
* @return {boolean}
*/
export function isIdMatchingAdUnit(slot, whitelist) {
if (!whitelist || !whitelist.length || !slot) {
return true;
}
const slotAdUnits = slot.getAdUnitPath();
return whitelist.indexOf(slotAdUnits) !== -1;
}
/**
* get GPT slot by placement id
* @param {string} code placement id
* @return {?Object}
*/
function getSlotByCode(code) {
const slots = getAllSlots();
if (!slots || !slots.length) {
return null;
}
return find(slots, s => s.getSlotElementId() === code || s.getAdUnitPath() === code) || null;
}
/**
* generate id according to macro script
* @param {Object} macro replacement macro
* @param {Object} slot google slot
* @return {?Object}
*/
export function getMacroId(macro, slot) {
if (macro) {
try {
const macroResult = evaluate(macro, slot.getSlotElementId(), slot.getAdUnitPath(), (match, p1) => {
return (p1 && slot.getTargeting(p1).join('_')) || 'NA';
});
return macroResult;
} catch (e) {
logError(`failed to evaluate: ${macro}`);
}
}
return slot.getSlotElementId();
}
function evaluate(macro, divId, adUnit, replacer) {
let macroResult = macro.p
.replace(/['"]+/g, '')
.replace(/<DIV_ID>/g, divId);
if (adUnit) {
macroResult = macroResult.replace(/<AD_UNIT>/g, adUnit);
}
if (replacer) {
macroResult = macroResult.replace(/<KEY_(\w+)>/g, replacer);
}
if (macro.s) {
macroResult = macroResult.substring(macro.s.s, macro.s.e);
}
return macroResult;
}
/**
* XMLHttpRequest to get data form browsi server
* @param {string} url server url with query params
*/
function getPredictionsFromServer(url) {
let ajax = ajaxBuilder();
ajax(url,
{
success: function (response, req) {
if (req.status === 200) {
try {
const data = JSON.parse(response);
if (data) {
setData({p: data.p, kn: data.kn, pmd: data.pmd, bet: data.bet});
} else {
setData({});
}
sendPageviewEvent(data.bet);
addBrowsiTag(data);
} catch (err) {
logError('unable to parse data');
setData({})
}
} else if (req.status === 204) {
// unrecognized site key
setData({});
}
},
error: function () {
setData({});
logError('unable to get prediction data');
}
}
);
}
/**
* serialize object and return query params string
* @param {Object} data
* @return {string}
*/
function toUrlParams(data) {
return Object.keys(data)
.map(key => key + '=' + encodeURIComponent(data[key]))
.join('&');
}
function setBidRequestsData(bidObj, callback) {
let adUnitCodes = bidObj.adUnitCodes;
let adUnits = bidObj.adUnits || getGlobal().adUnits || [];
if (adUnitCodes) {
adUnits = adUnits.filter(au => includes(adUnitCodes, au.code));
} else {
adUnitCodes = adUnits.map(au => au.code);
}
waitForData(() => {
const data = getRTD(adUnitCodes);
if (data) {
adUnits.forEach(adUnit => {
const adUnitCode = adUnit.code;
if (data[adUnitCode]) {
deepSetValue(adUnit, 'ortb2Imp.ext.data.browsi', {[getKey()]: data[adUnitCode][getKey()]});
}
});
}
callback();
})
}
/** @type {RtdSubmodule} */
export const browsiSubmodule = {
/**
* used to link submodule with realTimeData
* @type {string}
*/
name: MODULE_NAME,
/**
* get data and send back to realTimeData module
* @function
* @param {string[]} adUnitsCodes
*/
getTargetingData: getTargetingData,
init: init,
getBidRequestData: setBidRequestsData
};
function getTargetingData(uc, c, us, a) {
const targetingData = getRTD(uc);
const auctionId = a.auctionId;
const sendAdRequestEvent = (_browsiData && _browsiData['bet'] === 'AD_REQUEST');
uc.forEach(auc => {
if (isNumber(_ic[auc])) {
_ic[auc] = _ic[auc] + 1;
}
if (sendAdRequestEvent) {
const transactionId = a.adUnits.find(adUnit => adUnit.code === auc).transactionId;
events.emit(EVENTS.BILLABLE_EVENT, {
vendor: 'browsi',
type: 'adRequest',
billingId: generateUUID(),
transactionId: transactionId,
auctionId: auctionId
})
}
});
logInfo('Browsi RTD provider returned targeting data', targetingData, 'for', uc)
return targetingData;
}
function init(moduleConfig) {
_moduleParams = moduleConfig.params;
if (_moduleParams && _moduleParams.siteKey && _moduleParams.pubKey && _moduleParams.url) {
collectData();
setKeyValue(_moduleParams.splitKey);
} else {
logError('missing params for Browsi provider');
}
return true;
}
function registerSubModule() {
submodule('realTimeData', browsiSubmodule);
}
registerSubModule();