forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontxtfulRtdProvider.js
376 lines (322 loc) · 9.03 KB
/
contxtfulRtdProvider.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
/**
* Contxtful Technologies Inc.
* This RTD module provides receptivity that can be accessed using the
* getTargetingData and getBidRequestData functions. The receptivity enriches ad units
* and bid requests.
*/
import { submodule } from '../src/hook.js';
import {
logInfo,
logError,
isStr,
mergeDeep,
isEmptyStr,
isEmpty,
buildUrl,
isArray,
} from '../src/utils.js';
import { loadExternalScript } from '../src/adloader.js';
import { getStorageManager } from '../src/storageManager.js';
import { MODULE_TYPE_RTD } from '../src/activities/modules.js';
const MODULE_NAME = 'contxtful';
const MODULE = `${MODULE_NAME}RtdProvider`;
const CONTXTFUL_HOSTNAME_DEFAULT = 'api.receptivity.io';
const CONTXTFUL_DEFER_DEFAULT = 0;
const storageManager = getStorageManager({
moduleType: MODULE_TYPE_RTD,
moduleName: MODULE_NAME,
});
let rxApi = null;
let isFirstBidRequestCall = true;
/**
* Return current receptivity value for the requester.
* @param { String } requester
* @return { { Object } }
*/
function getRxEngineReceptivity(requester) {
return rxApi?.receptivity(requester);
}
function getItemFromSessionStorage(key) {
try {
return storageManager.getDataFromSessionStorage(key);
} catch (error) {
logError(MODULE, error);
}
}
function loadSessionReceptivity(requester) {
let sessionStorageValue = getItemFromSessionStorage(requester);
if (!sessionStorageValue) {
return null;
}
try {
// Check expiration of the cached value
let sessionStorageReceptivity = JSON.parse(sessionStorageValue);
let expiration = parseInt(sessionStorageReceptivity?.exp);
if (expiration < new Date().getTime()) {
return null;
}
let rx = sessionStorageReceptivity?.rx;
return rx;
} catch {
return null;
}
}
/**
* Prepare a receptivity batch
* @param {Array.<String>} requesters
* @param {Function} method
* @returns A batch
*/
function prepareBatch(requesters, method) {
return requesters.reduce((acc, requester) => {
const receptivity = method(requester);
if (!isEmpty(receptivity)) {
return { ...acc, [requester]: receptivity };
} else {
return acc;
}
}, {});
}
/**
* Init function used to start sub module
* @param { { params: { version: String, customer: String, hostname: String } } } config
* @return { Boolean }
*/
function init(config) {
logInfo(MODULE, 'init', config);
rxApi = null;
try {
initCustomer(config);
observeLastCursorPosition();
return true;
} catch (error) {
logError(MODULE, error);
return false;
}
}
/**
* Extract required configuration for the sub module.
* validate that all required configuration are present and are valid.
* Throws an error if any config is missing of invalid.
* @param { { params: { version: String, customer: String, hostname: String } } } config
* @return { { version: String, customer: String, hostname: String } }
* @throws params.{name} should be a non-empty string
*/
export function extractParameters(config) {
const version = config?.params?.version;
if (!isStr(version) || isEmptyStr(version)) {
throw Error(`${MODULE}: params.version should be a non-empty string`);
}
const customer = config?.params?.customer;
if (!isStr(customer) || isEmptyStr(customer)) {
throw Error(`${MODULE}: params.customer should be a non-empty string`);
}
const hostname = config?.params?.hostname || CONTXTFUL_HOSTNAME_DEFAULT;
const defer = config?.params?.defer || CONTXTFUL_DEFER_DEFAULT;
return { version, customer, hostname, defer };
}
/**
* Initialize sub module for a customer.
* This will load the external resources for the sub module.
* @param { String } config
*/
function initCustomer(config) {
const { version, customer, hostname, defer } = extractParameters(config);
const CONNECTOR_URL = buildUrl({
protocol: 'https',
host: hostname,
pathname: `/${version}/prebid/${customer}/connector/rxConnector.js`,
});
addConnectorEventListener(customer, config);
const loadScript = () => loadExternalScript(CONNECTOR_URL, MODULE_TYPE_RTD, MODULE_NAME);
// Optionally defer the loading of the script
if (Number.isFinite(defer) && defer > 0) {
setTimeout(loadScript, defer);
} else {
loadScript();
}
}
/**
* Add event listener to the script tag for the expected events from the external script.
* @param { String } tagId
* @param { String } prebidConfig
*/
function addConnectorEventListener(tagId, prebidConfig) {
window.addEventListener(
'rxConnectorIsReady',
async ({ detail: { [tagId]: rxConnector } }) => {
if (!rxConnector) {
return;
}
// Fetch the customer configuration
const { rxApiBuilder, fetchConfig } = rxConnector;
let config = await fetchConfig(tagId);
if (!config) {
return;
}
config['prebid'] = prebidConfig || {};
rxApi = await rxApiBuilder(config);
// Remove listener now that we can use rxApi.
removeListeners();
}
);
}
/**
* Set targeting data for ad server
* @param { [String] } adUnits
* @param {*} config
* @param {*} _userConsent
* @return {{ code: { ReceptivityState: String } }}
*/
function getTargetingData(adUnits, config, _userConsent) {
try {
if (String(config?.params?.adServerTargeting) === 'false') {
return {};
}
logInfo(MODULE, 'getTargetingData');
const requester = config?.params?.customer;
const rx =
getRxEngineReceptivity(requester) ||
loadSessionReceptivity(requester) ||
{};
if (isEmpty(rx)) {
return {};
}
return adUnits.reduce((targets, code) => {
targets[code] = rx;
return targets;
}, {});
} catch (error) {
logError(MODULE, error);
return {};
}
}
/**
* @param {Object} reqBidsConfigObj Bid request configuration object
* @param {Function} onDone Called on completion
* @param {Object} config Configuration for Contxtful RTD module
* @param {Object} userConsent
*/
function getBidRequestData(reqBidsConfigObj, onDone, config, userConsent) {
function onReturn() {
if (isFirstBidRequestCall) {
isFirstBidRequestCall = false;
}
onDone();
}
logInfo(MODULE, 'getBidRequestData');
const bidders = config?.params?.bidders || [];
if (isEmpty(bidders) || !isArray(bidders)) {
onReturn();
return;
}
let fromApi = rxApi?.receptivityBatched?.(bidders) || {};
let fromStorage = prepareBatch(bidders, (bidder) => loadSessionReceptivity(`${config?.params?.customer}_${bidder}`));
let sources = [fromStorage, fromApi];
if (isFirstBidRequestCall) {
sources.reverse();
}
let rxBatch = Object.assign(...sources);
let singlePointEvents;
if (isEmpty(rxBatch)) {
singlePointEvents = btoa(JSON.stringify({ ui: getUiEvents() }));
}
bidders
.forEach(bidderCode => {
const ortb2 = {
user: {
data: [
{
name: MODULE_NAME,
ext: {
rx: rxBatch[bidderCode],
events: singlePointEvents,
params: {
ev: config.params?.version,
ci: config.params?.customer,
},
},
},
],
},
};
mergeDeep(reqBidsConfigObj.ortb2Fragments?.bidder, {
[bidderCode]: ortb2,
});
});
onReturn();
}
function getUiEvents() {
return {
position: lastCursorPosition,
screen: getScreen(),
};
}
function getScreen() {
function getInnerSize() {
let w = window?.innerWidth;
let h = window?.innerHeight;
if (w && h) {
return [w, h];
}
}
function getDocumentSize() {
let body = window?.document?.body;
let w = body.clientWidth;
let h = body.clientHeight;
if (w && h) {
return [w, h];
}
}
// If we cannot access or cast the window dimensions, we get None.
// If we cannot collect the size from the window we try to use the root document dimensions
let [width, height] = getInnerSize() || getDocumentSize() || [0, 0];
let topLeft = { x: window.scrollX, y: window.scrollY };
return {
topLeft,
width,
height,
timestampMs: performance.now(),
};
}
let lastCursorPosition;
function observeLastCursorPosition() {
function pointerEventToPosition(event) {
lastCursorPosition = {
x: event.clientX,
y: event.clientY,
timestampMs: performance.now()
};
}
function touchEventToPosition(event) {
let touch = event.touches.item(0);
if (!touch) {
return;
}
lastCursorPosition = {
x: touch.clientX,
y: touch.clientY,
timestampMs: performance.now()
};
}
addListener('pointermove', pointerEventToPosition);
addListener('touchmove', touchEventToPosition);
}
let listeners = {};
function addListener(name, listener) {
listeners[name] = listener;
window.addEventListener(name, listener);
}
function removeListeners() {
for (const name in listeners) {
window.removeEventListener(name, listeners[name]);
delete listeners[name];
}
}
export const contxtfulSubmodule = {
name: MODULE_NAME,
init,
getTargetingData,
getBidRequestData,
};
submodule('realTimeData', contxtfulSubmodule);