-
Notifications
You must be signed in to change notification settings - Fork 2
/
adhese.js
204 lines (176 loc) · 6.6 KB
/
adhese.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
async function getAdheseAds(context, config) {
if (!config || !config.account || (!config.slot && !config.slots)) {
console.error("ADHESE: Config misses obligatory attributes, at least account and (slot or slots) are required.");
return {};
}
let headers = {
'content-type': 'application/json'
};
if (context && context.req.headers['user-agent']) {
headers['User-Agent'] = context.req.headers['user-agent']
}
if (config.debug) {
headers['Cookie'] = 'debugKey=npm_module';
}
let referrer = "";
let xf = "";
if (context && context.req.headers.referer) {
xf = base64urlEncode(context.req.headers.referer);
referrer = context.req.headers.referer;
}
const dt = config.deviceType ? config.deviceType : "unknown";
const tl = config.binaryConsent ? config.binaryConsent : "none";
const xt = config.consentString ? config.consentString : "";
const googleAdManagerTag = config.googleAdManagerTag ? config.googleAdManagerTag : "";
const vi = config.videoId ? config.videoId : "unknown";
const ui = config.userId ? config.userId : "unknown";
const maxCpm = config.maxCpm ? config.maxCpm : 50;
// checken of slots uniek zijn, anders return error
let slots = [];
if (config.slots) {
slots = config.slots.map(slot => ({ slotname: slot }));
}
if (config.slot) {
slots.push({ slotname: config.slot });
}
if (slots.length == 0) return {};
const requestOptions = {
method: 'POST',
credentials: 'include',
cache: 'no-cache',
headers: headers,
referrer: referrer,
body: JSON.stringify({
"slots": slots,
vastContentAsUrl: true,
"parameters": {
"dt": [dt],
"tl": [tl],
"xt": [xt],
"xf": [xf],
"vi": [vi],
"ui": [ui]
}
})
};
let adheseProps = {};
var userSync = getUserSyncMarkup(config);
adheseProps = Object.assign(adheseProps, { ['user_sync_iframe']: userSync });
const res = await fetch('https://ads-' + config.account + '.adhese.com/json/', requestOptions)
const data = await res.json()
const vastPathRegex = /:\/\/(?:www\.)?.[^/]+\/(.*)/;
adheseProps = Object.assign(adheseProps, { ['adh']: (data.length != 0 ? "bid" : "no-bid") });
if (data.length == 0) {
if (config.debug) {
console.debug("ADHESE: no ads");
}
adheseProps = Object.assign(adheseProps, { ['ads']: [] });
adheseProps = Object.assign(adheseProps, { ['google_ad_manager_tag']: '' });
adheseProps = Object.assign(adheseProps, { ['freewheel_config']: {} });
return adheseProps;
}
let returnedAds = [];
data.filter(isValidBid).forEach(function (ad, index) {
if (config.debug) {
console.debug("ADHESE: ad received from ", ad.origin + (ad.originInstance ? "-" + ad.originInstance : ""));
}
let vastUrl = "";
let vastPath = "";
let durationInSec = 30;
if (ad.cachedBodyUrl && ad.cachedBodyUrl != "") {
vastUrl = ad.cachedBodyUrl;
const matches = ad.cachedBodyUrl.match(vastPathRegex);
vastPath = matches[1];
}
let adheseSlot = {};
adheseSlot = Object.assign(adheseSlot, { ['adh_vast_url']: vastUrl });
adheseSlot = Object.assign(adheseSlot, { ['adh_vast_path']: vastPath });
adheseSlot = Object.assign(adheseSlot, { ['adh_origin']: ad.origin + (ad.originInstance ? "-" + ad.originInstance : "") });
if (ad.origin == "JERLICIA") {
adheseSlot = Object.assign(adheseSlot, { ['adh_campaign']: ad.orderName });
} else if (ad.origin == "DALE") {
adheseSlot = Object.assign(adheseSlot, { ['adh_campaign']: ad.originData.seatbid[0].bid[0].ext.adhese.orderId });
} else {
adheseSlot = Object.assign(adheseSlot, { ['adh_campaign']: "unknown" });
}
let cpm = 0;
let currency = '';
if (ad.extension.prebid != undefined) {
cpm = ad.extension.prebid.cpm.amount;
currency = ad.extension.prebid.cpm.currency;
}
adheseSlot = Object.assign(adheseSlot, { ['adh_cpm']: cpm });
adheseSlot = Object.assign(adheseSlot, { ['adh_cpm_currency']: currency });
adheseSlot = Object.assign(adheseSlot, { ['adh_duration']: durationInSec });
adheseSlot = Object.assign(adheseSlot, { ['adh_as_li_target']: Math.round(cpm > maxCpm ? maxCpm : cpm) + '.00_' + durationInSec + 's' });
adheseSlot = Object.assign(adheseSlot, { ['adh_slot']: ad.slotName });
returnedAds.push(adheseSlot);
});
adheseProps = Object.assign(adheseProps, { ['ads']: returnedAds });
let gamUrl = addCustomParamsToGAMURL(googleAdManagerTag, returnedAds);
adheseProps = Object.assign(adheseProps, { ['google_ad_manager_tag']: gamUrl });
let freewheelProps = getFreeWheelProps(returnedAds);
adheseProps = Object.assign(adheseProps, { ['freewheel_config']: freewheelProps });
if (config.debug) {
console.log(adheseProps);
}
return adheseProps;
}
function isValidBid(ad) {
return (ad.cachedBodyUrl && ad.cachedBodyUrl!="") || (ad.body && ad.body != "") || (ad.tag && ad.tag != "")
}
function getDurationFromVastXml(markup, ad) {
if (markup.indexOf('<Wrapper>') == -1) {
const regexDuration = /<Duration>(\d\d):(\d\d):(\d\d)<\/Duration>/;
if (regexDuration.test(markup)) {
let match = markup.match(regexDuration);
let hour = parseInt(match[1]);
let min = parseInt(match[2]);
let sec = parseInt(match[3]);
return (hour * 3600) + (min * 60) + sec;
}
}
return 30;
}
function getUserSyncMarkup(config) {
return "https://user-sync.adhese.com/iframe/user_sync.html?account=" + config.account + "&gdpr=1&consentString=" + config.consentString;
}
function addCustomParamsToGAMURL(gamUrl, ads) {
let str = gamUrl.split("cust_params=");
if (str.length==1) {
// add cust_params
return str[0] + "&cust_params=" + createEscapedKeyValueString(ads);
} else {
// append cust_params
return str[0] + "cust_params=" + createEscapedKeyValueString(ads) + "%26" + str[1];
}
}
function createEscapedKeyValueString(ads) {
var out = "";
ads.forEach((ad, index) => {
out += (index>0?"%26":"") + ad["adh_slot"] + "%3D" + ad["adh_as_li_target"]
});
return out;
}
function getFreeWheelProps(ads) {
var out = {};
ads.forEach((ad) => {
out[ad["adh_slot"]] = ad["adh_as_li_target"];
out[ad["adh_slot"]+"_url"] = ad["adh_vast_path"];
out[ad["adh_slot"]+"_origin"] = ad["adh_origin"];
});
return out;
}
function base64urlEncode(s) {
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function btoa(str) {
var buffer;
if (str instanceof Buffer) {
buffer = str;
} else {
buffer = Buffer.from(str.toString(), 'binary');
}
return buffer.toString('base64');
}
exports.getAdheseAds = getAdheseAds;