From 483c218046e80c72bbd81f7621655836b6e3da12 Mon Sep 17 00:00:00 2001 From: htang555 Date: Fri, 14 May 2021 07:26:42 -0400 Subject: [PATCH] Datablocks bid adapter: update adapter to conform to new bid server's format (#6696) * update datablocks bid adapter * remove TODO and fix linting errors * updated readme and changed insights to ortb2 * fixed ortb2 change Co-authored-by: John Mayor --- modules/datablocksAnalyticsAdapter.js | 2 +- modules/datablocksBidAdapter.js | 862 ++++++++++++------ modules/datablocksBidAdapter.md | 30 +- .../spec/modules/datablocksBidAdapter_spec.js | 601 +++++++----- 4 files changed, 988 insertions(+), 507 deletions(-) diff --git a/modules/datablocksAnalyticsAdapter.js b/modules/datablocksAnalyticsAdapter.js index 5e9771552840..3e4e9e95a4f6 100644 --- a/modules/datablocksAnalyticsAdapter.js +++ b/modules/datablocksAnalyticsAdapter.js @@ -16,4 +16,4 @@ adapterManager.registerAnalyticsAdapter({ code: 'datablocks' }); -export default datablocksAdapter; +export default datablocksAdapter; \ No newline at end of file diff --git a/modules/datablocksBidAdapter.js b/modules/datablocksBidAdapter.js index b00a3eae659a..038a521308da 100644 --- a/modules/datablocksBidAdapter.js +++ b/modules/datablocksBidAdapter.js @@ -1,330 +1,634 @@ -import * as utils from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; -import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -const NATIVE_MAP = { - 'body': 2, - 'body2': 10, - 'price': 6, - 'displayUrl': 11, - 'cta': 12 -}; -const NATIVE_IMAGE = [{ - id: 1, - required: 1, +import { config } from '../src/config.js'; +import * as utils from '../src/utils.js'; +import { BANNER, NATIVE } from '../src/mediaTypes.js'; +import { getStorageManager } from '../src/storageManager.js'; +import { ajax } from '../src/ajax.js'; +export const storage = getStorageManager(); + +const NATIVE_ID_MAP = {}; +const NATIVE_PARAMS = { title: { - len: 140 - } -}, { - id: 2, - required: 1, - img: { type: 3 } -}, { - id: 3, - required: 1, - data: { - type: 11 - } -}, { - id: 4, - required: 0, - data: { + id: 1, + name: 'title' + }, + icon: { + id: 2, + type: 1, + name: 'img' + }, + image: { + id: 3, + type: 3, + name: 'img' + }, + body: { + id: 4, + name: 'data', type: 2 + }, + sponsoredBy: { + id: 5, + name: 'data', + type: 1 + }, + cta: { + id: 6, + type: 12, + name: 'data' + }, + body2: { + id: 7, + name: 'data', + type: 10 + }, + rating: { + id: 8, + name: 'data', + type: 3 + }, + likes: { + id: 9, + name: 'data', + type: 4 + }, + downloads: { + id: 10, + name: 'data', + type: 5 + }, + displayUrl: { + id: 11, + name: 'data', + type: 11 + }, + price: { + id: 12, + name: 'data', + type: 6 + }, + salePrice: { + id: 13, + name: 'data', + type: 7 + }, + address: { + id: 14, + name: 'data', + type: 9 + }, + phone: { + id: 15, + name: 'data', + type: 8 } -}, { - id: 5, - required: 0, - img: { type: 1 } -}, { - id: 6, - required: 0, - data: { - type: 12 - } -}]; +}; -const VIDEO_PARAMS = ['mimes', 'minduration', 'maxduration', 'protocols', 'w', 'h', 'startdelay', - 'placement', 'linearity', 'skip', 'skipmin', 'skipafter', 'sequence', 'battr', 'maxextended', - 'minbitrate', 'maxbitrate', 'boxingallowed', 'playbackmethod', 'playbackend', 'delivery', - 'pos', 'companionad', 'api', 'companiontype', 'ext']; +Object.keys(NATIVE_PARAMS).forEach((key) => { + NATIVE_ID_MAP[NATIVE_PARAMS[key].id] = key; +}); +// DEFINE THE PREBID BIDDER SPEC export const spec = { - supportedMediaTypes: [BANNER, NATIVE, VIDEO], + supportedMediaTypes: [BANNER, NATIVE], code: 'datablocks', + + // DATABLOCKS SCOPED OBJECT + db_obj: {metrics_host: 'prebid.datablocks.net', metrics: [], metrics_timer: null, metrics_queue_time: 1000, vis_optout: false, source_id: 0}, + + // STORE THE DATABLOCKS BUYERID IN STORAGE + store_dbid: function(dbid) { + let stored = false; + + // CREATE 1 YEAR EXPIRY DATE + let d = new Date(); + d.setTime(Date.now() + (365 * 24 * 60 * 60 * 1000)); + + // TRY TO STORE IN COOKIE + if (storage.cookiesAreEnabled) { + storage.setCookie('_db_dbid', dbid, d.toUTCString(), 'None', null); + stored = true; + } + + // TRY TO STORE IN LOCAL STORAGE + if (storage.localStorageIsEnabled) { + storage.setDataInLocalStorage('_db_dbid', dbid); + stored = true; + } + + return stored; + }, + + // FETCH DATABLOCKS BUYERID FROM STORAGE + get_dbid: function() { + let dbId = ''; + if (storage.cookiesAreEnabled) { + dbId = storage.getCookie('_db_dbid') || ''; + } + + if (!dbId && storage.localStorageIsEnabled) { + dbId = storage.getDataFromLocalStorage('_db_dbid') || ''; + } + return dbId; + }, + + // STORE SYNCS IN STORAGE + store_syncs: function(syncs) { + if (storage.localStorageIsEnabled) { + let syncObj = {}; + syncs.forEach(sync => { + syncObj[sync.id] = sync.uid; + }); + + // FETCH EXISTING SYNCS AND MERGE NEW INTO STORAGE + let storedSyncs = this.get_syncs(); + storage.setDataInLocalStorage('_db_syncs', JSON.stringify(Object.assign(storedSyncs, syncObj))); + + return true; + } + }, + + // GET SYNCS FROM STORAGE + get_syncs: function() { + if (storage.localStorageIsEnabled) { + let syncData = storage.getDataFromLocalStorage('_db_syncs'); + if (syncData) { + return JSON.parse(syncData); + } else { + return {}; + } + } else { + return {}; + } + }, + + // ADD METRIC DATA TO THE METRICS RESPONSE QUEUE + queue_metric: function(metric) { + if (typeof metric === 'object') { + // PUT METRICS IN THE QUEUE + this.db_obj.metrics.push(metric); + + // RESET PREVIOUS TIMER + if (this.db_obj.metrics_timer) { + clearTimeout(this.db_obj.metrics_timer); + } + + // SETUP THE TIMER TO FIRE BACK THE DATA + let scope = this; + this.db_obj.metrics_timer = setTimeout(function() { + scope.send_metrics(); + }, this.db_obj.metrics_queue_time); + + return true; + } else { + return false; + } + }, + + // POST CONSOLIDATED METRICS BACK TO SERVER + send_metrics: function() { + // POST TO SERVER + ajax(`https://${this.db_obj.metrics_host}/a/pb/`, null, JSON.stringify(this.db_obj.metrics), {method: 'POST', withCredentials: true}); + + // RESET THE QUEUE OF METRIC DATA + this.db_obj.metrics = []; + + return true; + }, + + // GET BASIC CLIENT INFORMATION + get_client_info: function () { + let botTest = new BotClientTests(); + let win = utils.getWindowTop(); + return { + 'wiw': win.innerWidth, + 'wih': win.innerHeight, + 'saw': screen ? screen.availWidth : null, + 'sah': screen ? screen.availHeight : null, + 'scd': screen ? screen.colorDepth : null, + 'sw': screen ? screen.width : null, + 'sh': screen ? screen.height : null, + 'whl': win.history.length, + 'wxo': win.pageXOffset, + 'wyo': win.pageYOffset, + 'wpr': win.devicePixelRatio, + 'is_bot': botTest.doTests(), + 'is_hid': win.document.hidden, + 'vs': win.document.visibilityState + }; + }, + + // LISTEN FOR GPT VIEWABILITY EVENTS + get_viewability: function(bid) { + // ONLY RUN ONCE IF PUBLISHER HAS OPTED IN + if (!this.db_obj.vis_optout && !this.db_obj.vis_run) { + this.db_obj.vis_run = true; + + // ADD GPT EVENT LISTENERS + let scope = this; + if (utils.isGptPubadsDefined()) { + if (typeof window['googletag'].pubads().addEventListener == 'function') { + window['googletag'].pubads().addEventListener('impressionViewable', function(event) { + scope.queue_metric({type: 'slot_view', source_id: scope.db_obj.source_id, auction_id: bid.auctionId, div_id: event.slot.getSlotElementId(), slot_id: event.slot.getSlotId().getAdUnitPath()}); + }); + window['googletag'].pubads().addEventListener('slotRenderEnded', function(event) { + scope.queue_metric({type: 'slot_render', source_id: scope.db_obj.source_id, auction_id: bid.auctionId, div_id: event.slot.getSlotElementId(), slot_id: event.slot.getSlotId().getAdUnitPath()}); + }) + } + } + } + }, + + // VALIDATE THE BID REQUEST isBidRequestValid: function(bid) { - return !!(bid.params.host && bid.params.sourceId && - bid.mediaTypes && (bid.mediaTypes.banner || bid.mediaTypes.native || bid.mediaTypes.video)); + // SET GLOBAL VARS FROM BIDDER CONFIG + this.db_obj.source_id = bid.params.source_id; + if (bid.params.vis_optout) { + this.db_obj.vis_optout = true; + } + + return !!(bid.params.source_id && bid.mediaTypes && (bid.mediaTypes.banner || bid.mediaTypes.native)); }, - buildRequests: function(validBidRequests, bidderRequest) { - if (!validBidRequests.length) { return []; } - let imps = {}; - let site = {}; - let device = {}; - let refurl = utils.parseUrl(bidderRequest.referrer); - let requests = []; + // GENERATE THE RTB REQUEST + buildRequests: function(validRequests, bidderRequest) { + // RETURN EMPTY IF THERE ARE NO VALID REQUESTS + if (!validRequests.length) { + return []; + } - validBidRequests.forEach(bidRequest => { + // CONVERT PREBID NATIVE REQUEST OBJ INTO RTB OBJ + function createNativeRequest(bid) { + const assets = []; + if (bid.nativeParams) { + Object.keys(bid.nativeParams).forEach((key) => { + if (NATIVE_PARAMS[key]) { + const {name, type, id} = NATIVE_PARAMS[key]; + const assetObj = type ? {type} : {}; + let {len, sizes, required, aspect_ratios: aRatios} = bid.nativeParams[key]; + if (len) { + assetObj.len = len; + } + if (aRatios && aRatios[0]) { + aRatios = aRatios[0]; + let wmin = aRatios.min_width || 0; + let hmin = aRatios.ratio_height * wmin / aRatios.ratio_width | 0; + assetObj.wmin = wmin; + assetObj.hmin = hmin; + } + if (sizes && sizes.length) { + sizes = [].concat(...sizes); + assetObj.w = sizes[0]; + assetObj.h = sizes[1]; + } + const asset = {required: required ? 1 : 0, id}; + asset[name] = assetObj; + assets.push(asset); + } + }); + } + return { + ver: '1.2', + request: { + assets: assets, + context: 1, + plcmttype: 1, + ver: '1.2' + } + } + } + let imps = []; + // ITERATE THE VALID REQUESTS AND GENERATE IMP OBJECT + validRequests.forEach(bidRequest => { + // BUILD THE IMP OBJECT let imp = { id: bidRequest.bidId, - tagid: bidRequest.adUnitCode, - secure: window.location.protocol == 'https:' + tagid: bidRequest.params.tagid || bidRequest.adUnitCode, + placement_id: bidRequest.params.placement_id || 0, + secure: window.location.protocol == 'https:', + ortb2: utils.deepAccess(bidRequest, `ortb2Imp`) || {}, + floor: {} } + // CHECK FOR FLOORS + if (typeof bidRequest.getFloor === 'function') { + imp.floor = bidRequest.getFloor({ + currency: 'USD', + mediaType: '*', + size: '*' + }); + } + + // BUILD THE SIZES if (utils.deepAccess(bidRequest, `mediaTypes.banner`)) { - let sizes = bidRequest.mediaTypes.banner.sizes; - if (sizes.length == 1) { + let sizes = utils.getAdUnitSizes(bidRequest); + if (sizes.length) { imp.banner = { w: sizes[0][0], - h: sizes[0][1] - } - } else if (sizes.length > 1) { - imp.banner = { + h: sizes[0][1], format: sizes.map(size => ({ w: size[0], h: size[1] })) }; - } else { - return; - } - } else if (utils.deepAccess(bidRequest, 'mediaTypes.native')) { - let nativeImp = bidRequest.mediaTypes.native; - - if (nativeImp.type) { - let nativeAssets = []; - switch (nativeImp.type) { - case 'image': - nativeAssets = NATIVE_IMAGE; - break; - default: - return; - } - imp.native = JSON.stringify({ assets: nativeAssets }); - } else { - let nativeAssets = []; - let nativeKeys = Object.keys(nativeImp); - nativeKeys.forEach((nativeKey, index) => { - let required = !!nativeImp[nativeKey].required; - let assetId = index + 1; - switch (nativeKey) { - case 'title': - nativeAssets.push({ - id: assetId, - required: required, - title: { - len: nativeImp[nativeKey].len || 140 - } - }); - break; - case 'body': // desc - case 'body2': // desc2 - case 'price': - case 'display_url': - let data = { - id: assetId, - required: required, - data: { - type: NATIVE_MAP[nativeKey] - } - } - if (nativeImp[nativeKey].data && nativeImp[nativeKey].data.len) { data.data.len = nativeImp[nativeKey].data.len; } - - nativeAssets.push(data); - break; - case 'image': - if (nativeImp[nativeKey].sizes && nativeImp[nativeKey].sizes.length) { - nativeAssets.push({ - id: assetId, - required: required, - image: { - type: 3, - w: nativeImp[nativeKey].sizes[0], - h: nativeImp[nativeKey].sizes[1] - } - }) - } - } - }); - imp.native = { - request: JSON.stringify({native: {assets: nativeAssets}}) - }; - } - } else if (utils.deepAccess(bidRequest, 'mediaTypes.video')) { - let video = bidRequest.mediaTypes.video; - let sizes = video.playerSize || bidRequest.sizes || []; - if (sizes.length && Array.isArray(sizes[0])) { - imp.video = { - w: sizes[0][0], - h: sizes[0][1] - }; - } else if (sizes.length == 2 && !Array.isArray(sizes[0])) { - imp.video = { - w: sizes[0], - h: sizes[1] - }; - } else { - return; - } - - if (video.durationRangeSec) { - if (Array.isArray(video.durationRangeSec)) { - if (video.durationRangeSec.length == 1) { - imp.video.maxduration = video.durationRangeSec[0]; - } else if (video.durationRangeSec.length == 2) { - imp.video.minduration = video.durationRangeSec[0]; - imp.video.maxduration = video.durationRangeSec[1]; - } - } else { - imp.video.maxduration = video.durationRangeSec; - } - } - if (bidRequest.params.video) { - Object.keys(bidRequest.params.video).forEach(k => { - if (VIDEO_PARAMS.indexOf(k) > -1) { - imp.video[k] = bidRequest.params.video[k]; - } - }) + // ADD TO THE LIST OF IMP REQUESTS + imps.push(imp); } + } else if (utils.deepAccess(bidRequest, `mediaTypes.native`)) { + // ADD TO THE LIST OF IMP REQUESTS + imp.native = createNativeRequest(bidRequest); + imps.push(imp); } - let host = bidRequest.params.host; - let sourceId = bidRequest.params.sourceId; - imps[host] = imps[host] || {}; - let hostImp = imps[host][sourceId] = imps[host][sourceId] || { imps: [] }; - hostImp.imps.push(imp); - hostImp.subid = hostImp.imps.subid || bidRequest.params.subid || 'blank'; - hostImp.path = 'search'; - hostImp.idParam = 'sid'; - hostImp.protocol = '//'; }); - // Generate Site obj - site.domain = refurl.hostname; - site.page = refurl.protocol + '://' + refurl.hostname + refurl.pathname; + // RETURN EMPTY IF THERE WERE NO PROPER ADUNIT REQUESTS TO BE MADE + if (!imps.length) { + return []; + } + + // GENERATE SITE OBJECT + let site = { + domain: window.location.host, + page: bidderRequest.refererInfo.referer, + schain: validRequests[0].schain || {}, + ext: { + p_domain: config.getConfig('publisherDomain'), + rt: bidderRequest.refererInfo.reachedTop, + frames: bidderRequest.refererInfo.numIframes, + stack: bidderRequest.refererInfo.stack, + timeout: config.getConfig('bidderTimeout') + }, + } + + // ADD REF URL IF FOUND if (self === top && document.referrer) { site.ref = document.referrer; } + + // ADD META KEYWORDS IF FOUND let keywords = document.getElementsByTagName('meta')['keywords']; if (keywords && keywords.content) { site.keywords = keywords.content; } - // Generate Device obj. - device.ip = 'peer'; - device.ua = window.navigator.userAgent; - device.js = 1; - device.language = ((navigator.language || navigator.userLanguage || '').split('-'))[0] || 'en'; - - RtbRequest(device, site, imps).forEach(formatted => { - requests.push({ - method: 'POST', - url: formatted.url, - data: formatted.body, - options: { - withCredentials: false + // GENERATE DEVICE OBJECT + let device = { + ip: 'peer', + ua: window.navigator.userAgent, + js: 1, + language: ((navigator.language || navigator.userLanguage || '').split('-'))[0] || 'en', + buyerid: this.get_dbid() || 0, + ext: { + pb_eids: validRequests[0].userIdAsEids || {}, + syncs: this.get_syncs() || {}, + coppa: config.getConfig('coppa') || 0, + gdpr: bidderRequest.gdprConsent || {}, + usp: bidderRequest.uspConsent || {}, + client_info: this.get_client_info(), + ortb2: config.getConfig('ortb2') || {} + } + }; + + let sourceId = validRequests[0].params.source_id || 0; + let host = validRequests[0].params.host || 'prebid.datablocks.net'; + + // RETURN WITH THE REQUEST AND PAYLOAD + return { + method: 'POST', + url: `https://${sourceId}.${host}/openrtb/?sid=${sourceId}`, + data: { + id: bidderRequest.auctionId, + imp: imps, + site: site, + device: device + }, + options: { + withCredentials: true + } + }; + }, + + // INITIATE USER SYNCING + getUserSyncs: function(options, rtbResponse, gdprConsent) { + const syncs = []; + let bidResponse = rtbResponse[0].body; + let scope = this; + + // LISTEN FOR SYNC DATA FROM IFRAME TYPE SYNC + window.addEventListener('message', function (event) { + if (event.data.sentinel && event.data.sentinel === 'dblks_syncData') { + // STORE FOUND SYNCS + if (event.data.syncs) { + scope.store_syncs(event.data.syncs); } - }) + } }); - return requests; - - function RtbRequest(device, site, imps) { - let collection = []; - Object.keys(imps).forEach(host => { - let sourceIds = imps[host]; - Object.keys(sourceIds).forEach(sourceId => { - let impObj = sourceIds[sourceId]; - collection.push({ - url: `https://${host}/${impObj.path}/?${impObj.idParam}=${sourceId}`, - body: { - id: bidderRequest.auctionId, - imp: impObj.imps, - site: Object.assign({ id: impObj.subid || 'blank' }, site), - device: Object.assign({}, device) - } - }) - }) + + // POPULATE GDPR INFORMATION + let gdprData = { + gdpr: 0, + gdprConsent: '' + } + if (typeof gdprConsent === 'object') { + if (typeof gdprConsent.gdprApplies === 'boolean') { + gdprData.gdpr = Number(gdprConsent.gdprApplies); + gdprData.gdprConsent = gdprConsent.consentString; + } else { + gdprData.gdprConsent = gdprConsent.consentString; + } + } + + // EXTRACT BUYERID COOKIE VALUE FROM BID RESPONSE AND PUT INTO STORAGE + let dbBuyerId = this.get_dbid() || ''; + if (bidResponse.ext && bidResponse.ext.buyerid) { + dbBuyerId = bidResponse.ext.buyerid; + this.store_dbid(dbBuyerId); + } + + // EXTRACT USERSYNCS FROM BID RESPONSE + if (bidResponse.ext && bidResponse.ext.syncs) { + bidResponse.ext.syncs.forEach(sync => { + if (checkValid(sync)) { + syncs.push(addParams(sync)); + } }) + } + + // APPEND PARAMS TO SYNC URL + function addParams(sync) { + // PARSE THE URL + let url = new URL(sync.url); + let urlParams = Object.assign({}, Object.fromEntries(url.searchParams)); + + // APPLY EXTRA VARS + urlParams.gdpr = gdprData.gdpr; + urlParams.gdprConsent = gdprData.gdprConsent; + urlParams.bidid = bidResponse.bidid; + urlParams.id = bidResponse.id; + urlParams.uid = dbBuyerId; + + // REBUILD URL + sync.url = `${url.origin}${url.pathname}?${Object.keys(urlParams).map(key => key + '=' + encodeURIComponent(urlParams[key])).join('&')}`; - return collection; + // RETURN THE REBUILT URL + return sync; } + + // ENSURE THAT THE SYNC TYPE IS VALID AND HAS PERMISSION + function checkValid(sync) { + if (!sync.type || !sync.url) { + return false; + } + switch (sync.type) { + case 'iframe': + return options.iframeEnabled; + case 'image': + return options.pixelEnabled; + default: + return false; + } + } + return syncs; }, - interpretResponse: function(serverResponse, bidRequest) { - if (!serverResponse || !serverResponse.body || !serverResponse.body.seatbid) { - return []; + + // DATABLOCKS WON THE AUCTION - REPORT SUCCESS + onBidWon: function(bid) { + this.queue_metric({type: 'bid_won', source_id: bid.params[0].source_id, req_id: bid.requestId, slot_id: bid.adUnitCode, auction_id: bid.auctionId, size: bid.size, cpm: bid.cpm, pb: bid.adserverTargeting.hb_pb, rt: bid.timeToRespond, ttl: bid.ttl}); + }, + + // TARGETING HAS BEEN SET + onSetTargeting: function(bid) { + // LISTEN FOR VIEWABILITY EVENTS + this.get_viewability(bid); + }, + + // PARSE THE RTB RESPONSE AND RETURN FINAL RESULTS + interpretResponse: function(rtbResponse, bidRequest) { + // CONVERT NATIVE RTB RESPONSE INTO PREBID RESPONSE + function parseNative(native) { + const {assets, link, imptrackers, jstracker} = native; + const result = { + clickUrl: link.url, + clickTrackers: link.clicktrackers || [], + impressionTrackers: imptrackers || [], + javascriptTrackers: jstracker ? [jstracker] : [] + }; + + (assets || []).forEach((asset) => { + const {id, img, data, title} = asset; + const key = NATIVE_ID_MAP[id]; + if (key) { + if (!utils.isEmpty(title)) { + result.title = title.text + } else if (!utils.isEmpty(img)) { + result[key] = { + url: img.url, + height: img.h, + width: img.w + } + } else if (!utils.isEmpty(data)) { + result[key] = data.value; + } + } + }); + + return result; } - let body = serverResponse.body; - - let bids = body.seatbid - .map(seatbid => seatbid.bid) - .reduce((memo, bid) => memo.concat(bid), []); - let req = bidRequest.data; - let reqImps = req.imp; - - return bids.map(rtbBid => { - let imp; - for (let i in reqImps) { - let testImp = reqImps[i] - if (testImp.id == rtbBid.impid) { - imp = testImp; + + let bids = []; + let resBids = utils.deepAccess(rtbResponse, 'body.seatbid') || []; + resBids.forEach(bid => { + let resultItem = {requestId: bid.id, cpm: bid.price, creativeId: bid.crid, currency: bid.currency || 'USD', netRevenue: true, ttl: bid.ttl || 360}; + + let mediaType = utils.deepAccess(bid, 'ext.mtype') || ''; + switch (mediaType) { + case 'banner': + bids.push(Object.assign({}, resultItem, {mediaType: BANNER, width: bid.w, height: bid.h, ad: bid.adm})); + break; + + case 'native': + let nativeResult = JSON.parse(bid.adm); + bids.push(Object.assign({}, resultItem, {mediaType: NATIVE, native: parseNative(nativeResult.native)})); + break; + + default: break; - } } - let br = { - requestId: rtbBid.impid, - cpm: rtbBid.price, - creativeId: rtbBid.crid, - currency: rtbBid.currency || 'USD', - netRevenue: true, - ttl: 360 - }; - if (!imp) { - return br; - } else if (imp.banner) { - br.mediaType = BANNER; - br.width = rtbBid.w; - br.height = rtbBid.h; - br.ad = rtbBid.adm; - } else if (imp.native) { - br.mediaType = NATIVE; - - let reverseNativeMap = {}; - let nativeKeys = Object.keys(NATIVE_MAP); - nativeKeys.forEach(k => { - reverseNativeMap[NATIVE_MAP[k]] = k; - }); + }) - let idMap = {}; - let nativeReq = JSON.parse(imp.native.request); - if (nativeReq.native && nativeReq.native.assets) { - nativeReq.native.assets.forEach(asset => { - if (asset.data) { idMap[asset.id] = reverseNativeMap[asset.data.type]; } - }) + return bids; + } +}; + +// DETECT BOTS +export class BotClientTests { + constructor() { + this.tests = { + headless_chrome: function() { + if (self.navigator) { + if (self.navigator.webdriver) { + return true; + } } - const nativeResponse = JSON.parse(rtbBid.adm); - const { assets, link, imptrackers, jstrackers } = nativeResponse.native; - const result = { - clickUrl: link.url, - clickTrackers: link.clicktrackers || undefined, - impressionTrackers: imptrackers || undefined, - javascriptTrackers: jstrackers ? [jstrackers] : undefined - }; - assets.forEach(asset => { - if (asset.title) { - result.title = asset.title.text; - } else if (asset.img) { - result.image = asset.img.url; - } else if (idMap[asset.id]) { - result[idMap[asset.id]] = asset.data.value; + return false; + }, + user_agent: function() { + try { + var re = new RegExp('(googlebot\/|bot|Googlebot-Mobile|Googlebot-Image|Google favicon|Mediapartners-Google|bingbot|slurp|java|wget|curl|Commons-HttpClient|Python-urllib|libwww|httpunit|nutch|phpcrawl|msnbot|jyxobot|FAST-WebCrawler|FAST Enterprise Crawler|biglotron|teoma|convera|seekbot|gigablast|exabot|ngbot|ia_archiver|GingerCrawler|webmon |httrack|webcrawler|grub.org|UsineNouvelleCrawler|antibot|netresearchserver|speedy|fluffy|bibnum.bnf|findlink|msrbot|panscient|yacybot|AISearchBot|IOI|ips-agent|tagoobot|MJ12bot|dotbot|woriobot|yanga|buzzbot|mlbot|yandexbot|purebot|Linguee Bot|Voyager|CyberPatrol|voilabot|baiduspider|citeseerxbot|spbot|twengabot|postrank|turnitinbot|scribdbot|page2rss|sitebot|linkdex|Adidxbot|blekkobot|ezooms|dotbot|Mail.RU_Bot|discobot|heritrix|findthatfile|europarchive.org|NerdByNature.Bot|sistrix crawler|ahrefsbot|Aboundex|domaincrawler|wbsearchbot|summify|ccbot|edisterbot|seznambot|ec2linkfinder|gslfbot|aihitbot|intelium_bot|facebookexternalhit|yeti|RetrevoPageAnalyzer|lb-spider|sogou|lssbot|careerbot|wotbox|wocbot|ichiro|DuckDuckBot|lssrocketcrawler|drupact|webcompanycrawler|acoonbot|openindexspider|gnam gnam spider|web-archive-net.com.bot|backlinkcrawler|coccoc|integromedb|content crawler spider|toplistbot|seokicks-robot|it2media-domain-crawler|ip-web-crawler.com|siteexplorer.info|elisabot|proximic|changedetection|blexbot|arabot|WeSEE:Search|niki-bot|CrystalSemanticsBot|rogerbot|360Spider|psbot|InterfaxScanBot|Lipperhey SEO Service|CC Metadata Scaper|g00g1e.net|GrapeshotCrawler|urlappendbot|brainobot|fr-crawler|binlar|SimpleCrawler|Livelapbot|Twitterbot|cXensebot|smtbot|bnf.fr_bot|A6-Indexer|ADmantX|Facebot|Twitterbot|OrangeBot|memorybot|AdvBot|MegaIndex|SemanticScholarBot|ltx71|nerdybot|xovibot|BUbiNG|Qwantify|archive.org_bot|Applebot|TweetmemeBot|crawler4j|findxbot|SemrushBot|yoozBot|lipperhey|y!j-asr|Domain Re-Animator Bot|AddThis)', 'i'); + if (re.test(navigator.userAgent)) { + return true; } - }) - br.native = result; - } else if (imp.video) { - br.mediaType = VIDEO; - br.width = rtbBid.w; - br.height = rtbBid.h; - if (rtbBid.adm) { br.vastXml = rtbBid.adm; } else if (rtbBid.nurl) { br.vastUrl = rtbBid.nurl; } + return false; + } catch (e) { + return false; + } + }, + + selenium: function () { + let response = false; + + if (window && document) { + let results = [ + 'webdriver' in window, + '_Selenium_IDE_Recorder' in window, + 'callSelenium' in window, + '_selenium' in window, + '__webdriver_script_fn' in document, + '__driver_evaluate' in document, + '__webdriver_evaluate' in document, + '__selenium_evaluate' in document, + '__fxdriver_evaluate' in document, + '__driver_unwrapped' in document, + '__webdriver_unwrapped' in document, + '__selenium_unwrapped' in document, + '__fxdriver_unwrapped' in document, + '__webdriver_script_func' in document, + document.documentElement.getAttribute('selenium') !== null, + document.documentElement.getAttribute('webdriver') !== null, + document.documentElement.getAttribute('driver') !== null + ]; + + results.forEach(result => { + if (result === true) { + response = true; + } + }) + } + + return response; + }, + } + } + + doTests() { + let response = false; + for (const [, t] of Object.entries(this.tests)) { + if (t() === true) { + response = true; } - return br; - }); + } + return response; } +} -}; +// INIT OUR BIDDER WITH PREBID registerBidder(spec); diff --git a/modules/datablocksBidAdapter.md b/modules/datablocksBidAdapter.md index e30cd361974e..2730443d72d2 100644 --- a/modules/datablocksBidAdapter.md +++ b/modules/datablocksBidAdapter.md @@ -8,8 +8,8 @@ Maintainer: support@datablocks.net # Description -Connects to Datablocks Version 5 Platform -Banner Native and Video +Connects to Datablocks Exchange +Banner and Native # Test Parameters @@ -27,12 +27,13 @@ Banner Native and Video { bidder: 'datablocks', params: { - sourceId: 12345, + source_id: 12345, host: 'prebid.datablocks.net' } } ] - }, { + }, + { code: 'native-div', mediaTypes : { native: { @@ -44,28 +45,9 @@ Banner Native and Video { bidder: 'datablocks', params: { - sourceId: 12345, + source_id: 12345, host: 'prebid.datablocks.net' } - }, { - code: 'video-div', - mediaTypes : { - video: { - playerSize:[500,400], - durationRangeSec:[15,30], - context: "linear" - } - }, - bids: [ - { - bidder: 'datablocks', - params: { - sourceId: 12345, - host: 'prebid.datablocks.net', - video: { - mimes:["video/flv"] - } - } } ] } diff --git a/test/spec/modules/datablocksBidAdapter_spec.js b/test/spec/modules/datablocksBidAdapter_spec.js index 18b8aac7371d..147000f2363e 100644 --- a/test/spec/modules/datablocksBidAdapter_spec.js +++ b/test/spec/modules/datablocksBidAdapter_spec.js @@ -1,12 +1,15 @@ import { expect } from 'chai'; import { spec } from '../../../modules/datablocksBidAdapter.js'; +import { BotClientTests } from '../../../modules/datablocksBidAdapter.js'; +import { getStorageManager } from '../../../src/storageManager.js'; +export let storage = getStorageManager(); -let bid = { +const bid = { bidId: '2dd581a2b6281d', bidder: 'datablocks', bidderRequestId: '145e1d6a7837c9', params: { - sourceId: 7560, + source_id: 7560, host: 'v5demo.datablocks.net' }, adUnitCode: '/19968336/header-bid-tag-0', @@ -24,12 +27,12 @@ let bid = { transactionId: '1ccbee15-f6f6-46ce-8998-58fe5542e8e1' }; -let bid2 = { +const bid2 = { bidId: '2dd581a2b624324g', bidder: 'datablocks', bidderRequestId: '145e1d6a7837543', params: { - sourceId: 7560, + source_id: 7560, host: 'v5demo.datablocks.net' }, adUnitCode: '/19968336/header-bid-tag-0', @@ -43,7 +46,7 @@ let bid2 = { transactionId: '1ccbee15-f6f6-46ce-8998-58fe55425432' }; -let nativeBid = { +const nativeBid = { adUnitCode: '/19968336/header-bid-tag-0', auctionId: '160c78a4-f808-410f-b682-d8728f3a79ee', bidId: '332045ee374a99', @@ -78,41 +81,18 @@ let nativeBid = { } }, params: { - sourceId: 7560, + source_id: 7560, host: 'v5demo.datablocks.net' }, transactionId: '0a4e9788-4def-4b94-bc25-564d7cac99f6' } -let videoBid = { - adUnitCode: '/19968336/header-bid-tag-0', - auctionId: '160c78a4-f808-410f-b682-d8728f3a79e1', - bidId: '332045ee374b99', - bidder: 'datablocks', - bidderRequestId: '15d9012765e36d', - mediaTypes: { - video: { - context: 'instream', - playerSize: [501, 400], - durationRangeSec: [15, 60] - } - }, - params: { - sourceId: 7560, - host: 'v5demo.datablocks.net', - video: { - minduration: 14 - } - }, - transactionId: '0a4e9788-4def-4b94-bc25-564d7cac99f7' -} - const bidderRequest = { auctionId: '8bfef1be-d3ac-4d18-8859-754c7b4cf017', auctionStart: Date.now(), biddeCode: 'datablocks', bidderRequestId: '10c47a5fc3c41', - bids: [bid, bid2, nativeBid, videoBid], + bids: [bid, bid2, nativeBid], refererInfo: { numIframes: 0, reachedTop: true, @@ -123,208 +103,423 @@ const bidderRequest = { timeout: 10000 }; -let resObject = { +const res_object = { body: { - id: '10c47a5fc3c41', - bidid: '166895245-28-11347-1', - seatbid: [{ - seat: '7560', - bid: [{ - id: '1090738570', - impid: '2966b257c81d27', - price: 24.000000, - adm: 'RON', - cid: '55', - adid: '177654', - crid: '177656', - cat: [], - api: [], - w: 300, - h: 250 - }, { - id: '1090738571', - impid: '2966b257c81d28', - price: 24.000000, - adm: 'RON', - cid: '55', - adid: '177654', - crid: '177656', - cat: [], - api: [], - w: 728, - h: 90 - }, { - id: '1090738570', - impid: '15d9012765e36c', - price: 24.000000, - adm: '{"native":{"ver":"1.2","assets":[{"id":1,"required":1,"title":{"text":"Example Title"}},{"id":2,"required":1,"data":{"value":"Example Body"}},{"id":3,"required":1,"img":{"url":"https://example.image.com/"}}],"link":{"url":"https://click.example.com/c/264597/?fcid=29699699045816"},"imptrackers":["https://impression.example.com/i/264597/?fcid=29699699045816"]}}', - cid: '132145', - adid: '154321', - crid: '177432', - cat: [], - api: [] - }, { - id: '1090738575', - impid: '15d9012765e36f', - price: 25.000000, - cid: '12345', - adid: '12345', - crid: '123456', - nurl: 'https://click.v5demo.datablocks.net/m//?fcid=435235435432', - cat: [], - api: [], - w: 500, - h: 400 - }] - }], - cur: 'USD', - ext: {} + 'id': '10c47a5fc3c41', + 'bidid': '217868445-30021-19053-0', + 'seatbid': [ + { + 'id': '22621593137287', + 'impid': '1', + 'adm': 'John is great', + 'adomain': ['medianet.com'], + 'price': 0.430000, + 'cid': '2524568', + 'adid': '0', + 'crid': '0', + 'cat': [], + 'w': 300, + 'h': 250, + 'ext': { + 'type': 'CPM', + 'mtype': 'banner' + } + }, + { + 'id': '22645215457415', + 'impid': '2', + 'adm': 'john is the best', + 'adomain': ['td.com'], + 'price': 0.580000, + 'cid': '2524574', + 'adid': '0', + 'crid': '0', + 'cat': [], + 'w': 728, + 'h': 90, + 'ext': { + 'type': 'CPM', + 'mtype': 'banner' + } + }, + + { + 'id': '22645215457416', + 'impid': '3', + 'adm': '{"native":{"ver":"1.2","assets":[{"id":1,"required":1,"title":{"text":"John is amazing"}},{"id":5,"required":1,"data":{"value":"Sponsored by John"}},{"id":3,"required":1,"img":{"url":"https://example.image.com/", "h":"360", "w":"360"}}],"link":{"url":"https://click.example.com/c/264597/?fcid=29699699045816"},"imptrackers":["https://impression.example.com/i/264597/?fcid=29699699045816"]}}', + 'adomain': ['td.com'], + 'price': 10.00, + 'cid': '2524574', + 'adid': '0', + 'crid': '0', + 'cat': [], + 'ext': { + 'type': 'CPM', + 'mtype': 'native' + } + } + ], + 'cur': 'USD', + 'ext': { + 'version': '1.2.93', + 'buyerid': '1234567', + 'syncs': [ + { + 'type': 'iframe', + 'url': 'https://s.0cf.io' + }, + { + 'type': 'image', + 'url': 'https://us.dblks.net/set_uid/' + } + ] + } } -}; -let bidRequest = { +} + +let bid_request = { method: 'POST', - url: 'https://v5demo.datablocks.net/search/?sid=7560', + url: 'https://prebid.datablocks.net/openrtb/?sid=2523014', options: { - withCredentials: false + withCredentials: true }, data: { - device: { - ip: 'peer', - ua: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) Ap…ML, like Gecko) Chrome/73.0.3683.86 Safari/537.36', - js: 1, - language: 'en' - }, - id: '10c47a5fc3c41', - imp: [{ - banner: { w: 300, h: 250 }, - id: '2966b257c81d27', - secure: false, - tagid: '/19968336/header-bid-tag-0' - }, { - banner: { w: 728, h: 90 }, - id: '2966b257c81d28', - secure: false, - tagid: '/19968336/header-bid-tag-0' - }, { - id: '15d9012765e36c', - native: {request: '{"native":{"assets":[{"id":"1","required":true,"title":{"len":140}},{"id":"2","required":true,"data":{"type":2}},{"id":"3","img":{"w":728,"h":90,"type":3}}]}}'}, - secure: false, - tagid: '/19968336/header-bid-tag-0' - }, { - id: '15d9012765e36f', - video: {w: 500, h: 400, minduration: 15, maxduration: 60}, - secure: false, - tagid: '/19968336/header-bid-tag-0' - }], - site: { - domain: '', - id: 'blank', - page: 'https://v5demo.datablocks.net/test' - } + 'id': 'c09c6e47-8bdb-4884-a46d-93165322b368', + 'imp': [{ + 'id': '1', + 'tagid': '/19968336/header-bid-tag-0', + 'placement_id': 0, + 'secure': true, + 'banner': { + 'w': 300, + 'h': 250, + 'format': [{ + 'w': 300, + 'h': 250 + }, { + 'w': 300, + 'h': 600 + }] + } + }, { + 'id': '2', + 'tagid': '/19968336/header-bid-tag-1', + 'placement_id': 12345, + 'secure': true, + 'banner': { + 'w': 729, + 'h': 90, + 'format': [{ + 'w': 729, + 'h': 90 + }, { + 'w': 970, + 'h': 250 + }] + } + }, { + 'id': '3', + 'tagid': '/19968336/prebid_multiformat_test', + 'placement_id': 0, + 'secure': true, + 'native': { + 'ver': '1.2', + 'request': { + 'assets': [{ + 'required': 1, + 'id': 1, + 'title': {} + }, { + 'required': 1, + 'id': 3, + 'img': { + 'type': 3 + } + }, { + 'required': 1, + 'id': 5, + 'data': { + 'type': 1 + } + }], + 'context': 1, + 'plcmttype': 1, + 'ver': '1.2' + } + } + }], + 'site': { + 'domain': 'test.datablocks.net', + 'page': 'https://test.datablocks.net/index.html', + 'schain': {}, + 'ext': { + 'p_domain': 'https://test.datablocks.net', + 'rt': true, + 'frames': 0, + 'stack': ['https://test.datablocks.net/index.html'], + 'timeout': 3000 + }, + 'keywords': 'HTML, CSS, JavaScript' + }, + 'device': { + 'ip': 'peer', + 'ua': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36', + 'js': 1, + 'language': 'en', + 'buyerid': '1234567', + 'ext': { + 'pb_eids': [{ + 'source': 'criteo.com', + 'uids': [{ + 'id': 'test', + 'atype': 1 + }] + }], + 'syncs': { + '1000': 'db_4044853', + '1001': true + }, + 'coppa': 0, + 'gdpr': {}, + 'usp': {}, + 'client_info': { + 'wiw': 2560, + 'wih': 1281, + 'saw': 2560, + 'sah': 1417, + 'scd': 24, + 'sw': 2560, + 'sh': 1440, + 'whl': 4, + 'wxo': 0, + 'wyo': 0, + 'wpr': 2, + 'is_bot': false, + 'is_hid': false, + 'vs': 'hidden' + }, + 'fpd': {} + } + } } } describe('DatablocksAdapter', function() { + describe('All needed functions are available', function() { + it(`isBidRequestValid is present and type function`, function () { + expect(spec.isBidRequestValid).to.exist.and.to.be.a('function') + }); + + it(`buildRequests is present and type function`, function () { + expect(spec.buildRequests).to.exist.and.to.be.a('function') + }); + + it(`getUserSyncs is present and type function`, function () { + expect(spec.getUserSyncs).to.exist.and.to.be.a('function') + }); + + it(`onBidWon is present and type function`, function () { + expect(spec.onBidWon).to.exist.and.to.be.a('function') + }); + + it(`onSetTargeting is present and type function`, function () { + expect(spec.onSetTargeting).to.exist.and.to.be.a('function') + }); + + it(`interpretResponse is present and type function`, function () { + expect(spec.interpretResponse).to.exist.and.to.be.a('function') + }); + + it(`store_dbid is present and type function`, function () { + expect(spec.store_dbid).to.exist.and.to.be.a('function') + }); + + it(`get_dbid is present and type function`, function () { + expect(spec.get_dbid).to.exist.and.to.be.a('function') + }); + + it(`store_syncs is present and type function`, function () { + expect(spec.store_syncs).to.exist.and.to.be.a('function') + }); + + it(`get_syncs is present and type function`, function () { + expect(spec.get_syncs).to.exist.and.to.be.a('function') + }); + + it(`queue_metric is present and type function`, function () { + expect(spec.queue_metric).to.exist.and.to.be.a('function') + }); + + it(`send_metrics is present and type function`, function () { + expect(spec.send_metrics).to.exist.and.to.be.a('function') + }); + + it(`get_client_info is present and type function`, function () { + expect(spec.get_client_info).to.exist.and.to.be.a('function') + }); + + it(`get_viewability is present and type function`, function () { + expect(spec.get_viewability).to.exist.and.to.be.a('function') + }); + }); + + describe('get / store dbid', function() { + it('Should return true / undefined', function() { + expect(spec.store_dbid('12345')).to.be.true; + expect(spec.get_dbid()).to.be.a('string'); + }); + }) + + describe('get / store syncs', function() { + it('Should return true / array', function() { + expect(spec.store_syncs([{id: 1, uid: 'test'}])).to.be.true; + expect(spec.get_syncs()).to.be.a('object'); + }); + }) + + describe('queue / send metrics', function() { + it('Should return true', function() { + expect(spec.queue_metric({type: 'test'})).to.be.true; + expect(spec.queue_metric('string')).to.be.false; + expect(spec.send_metrics()).to.be.true; + }); + }) + + describe('get_viewability', function() { + it('Should return undefined', function() { + expect(spec.get_viewability()).to.equal(undefined); + }); + }) + + describe('get client info', function() { + it('Should return object', function() { + let client_info = spec.get_client_info() + expect(client_info).to.be.a('object'); + expect(client_info).to.have.all.keys('wiw', 'wih', 'saw', 'sah', 'scd', 'sw', 'sh', 'whl', 'wxo', 'wyo', 'wpr', 'is_bot', 'is_hid', 'vs'); + }); + + it('bot test should return boolean', function() { + let bot_test = new BotClientTests(); + expect(bot_test.doTests()).to.be.a('boolean'); + }); + }) + describe('isBidRequestValid', function() { - it('Should return true when sourceId and Host are set', function() { + it('Should return true when source_id and Host are set', function() { expect(spec.isBidRequestValid(bid)).to.be.true; }); - it('Should return false when host/sourceId is not set', function() { + it('Should return false when host/source_id is not set', function() { let moddedBid = Object.assign({}, bid); - delete moddedBid.params.sourceId; - delete moddedBid.params.host; - expect(spec.isBidRequestValid(bid)).to.be.false; + delete moddedBid.params.source_id; + expect(spec.isBidRequestValid(moddedBid)).to.be.false; + }); + + it('Should return true when viewability reporting is opted out', function() { + let moddedBid = Object.assign({}, bid); + moddedBid.params.vis_optout = true; + spec.isBidRequestValid(moddedBid); + expect(spec.db_obj.vis_optout).to.be.true; + }); + }) + + describe('getUserSyncs', function() { + it('Should return array of syncs', function() { + expect(spec.getUserSyncs({iframeEnabled: true, pixelEnabled: true}, [res_object], {gdprApplies: true, gdpr: 1, gdpr_consent: 'consent_string'}, {})).to.an('array'); + }); + }); + + describe('onSetTargeting', function() { + it('Should return undefined', function() { + expect(spec.onSetTargeting()).to.equal(undefined); + }); + }); + + describe('onBidWon', function() { + it('Should return undefined', function() { + let won_bid = {params: [{source_id: 1}], requestId: 1, adUnitCode: 'unit', auctionId: 1, size: '300x250', cpm: 10, adserverTargeting: {hb_pb: 10}, timeToRespond: 10, ttl: 10}; + expect(spec.onBidWon(won_bid)).to.equal(undefined); }); }); describe('buildRequests', function() { - let requests = spec.buildRequests([bid, bid2, nativeBid, videoBid], bidderRequest); + let request = spec.buildRequests([bid, bid2, nativeBid], bidderRequest); + + expect(request).to.exist; + it('Returns POST method', function() { + expect(request.method).to.exist; + expect(request.method).to.equal('POST'); + }); + + it('Returns valid URL', function() { + expect(request.url).to.exist; + expect(request.url).to.equal('https://7560.v5demo.datablocks.net/openrtb/?sid=7560'); + }); + it('Creates an array of request objects', function() { - expect(requests).to.be.an('array').that.is.not.empty; + expect(request.data.imp).to.be.an('array').that.is.not.empty; }); - requests.forEach(request => { - expect(request).to.exist; - it('Returns POST method', function() { - expect(request.method).to.exist; - expect(request.method).to.equal('POST'); - }); - it('Returns valid URL', function() { - expect(request.url).to.exist; - expect(request.url).to.equal('https://v5demo.datablocks.net/search/?sid=7560'); - }); + it('Should be a valid openRTB request', function() { + let data = request.data; - it('Should be a valid openRTB request', function() { - let data = request.data; - expect(data).to.be.an('object'); - expect(data).to.have.all.keys('device', 'imp', 'site', 'id'); - expect(data.id).to.be.a('string'); - - let imps = data['imp']; - imps.forEach((imp, index) => { - let curBid = bidderRequest.bids[index]; - if (imp.banner) { - expect(imp).to.have.all.keys('banner', 'id', 'secure', 'tagid'); - expect(imp.banner).to.be.a('object'); - } else if (imp.native) { - expect(imp).to.have.all.keys('native', 'id', 'secure', 'tagid'); - expect(imp.native).to.have.all.keys('request'); - expect(imp.native.request).to.be.a('string'); - let native = JSON.parse(imp.native.request); - expect(native).to.be.a('object'); - } else if (imp.video) { - expect(imp).to.have.all.keys('video', 'id', 'secure', 'tagid'); - expect(imp.video).to.have.all.keys('w', 'h', 'minduration', 'maxduration') - } else { - expect(true).to.equal(false); - } - - expect(imp.id).to.be.a('string'); - expect(imp.id).to.equal(curBid.bidId); - expect(imp.tagid).to.be.a('string'); - expect(imp.tagid).to.equal(curBid.adUnitCode); - expect(imp.secure).to.equal(false); - }) - - expect(data.device.ip).to.equal('peer'); - }); - }) + expect(data).to.be.an('object'); + expect(data).to.have.all.keys('device', 'imp', 'site', 'id'); + expect(data.id).to.be.a('string'); + expect(data.imp).to.be.a('array'); + expect(data.device.ip).to.equal('peer'); + + let imps = data['imp']; + imps.forEach((imp, index) => { + let curBid = bidderRequest.bids[index]; + if (imp.banner) { + expect(imp.banner).to.be.a('object'); + expect(imp).to.have.all.keys('banner', 'id', 'secure', 'tagid', 'placement_id', 'ortb2', 'floor'); + } else if (imp.native) { + expect(imp).to.have.all.keys('native', 'id', 'secure', 'tagid', 'placement_id', 'ortb2', 'floor'); + expect(imp.native).to.have.all.keys('request', 'ver'); + expect(imp.native.request).to.be.a('object'); + } else { + expect(true).to.equal(false); + } + + expect(imp.id).to.be.a('string'); + expect(imp.id).to.equal(curBid.bidId); + expect(imp.tagid).to.be.a('string'); + expect(imp.tagid).to.equal(curBid.adUnitCode); + expect(imp.secure).to.equal(false); + }) + }); it('Returns empty data if no valid requests are passed', function() { - let request = spec.buildRequests([]); - expect(request).to.be.an('array').that.is.empty; + let test_request = spec.buildRequests([]); + expect(test_request).to.be.an('array').that.is.empty; }); }); + describe('interpretResponse', function() { - let serverResponses = spec.interpretResponse(resObject, bidRequest); + let response = spec.interpretResponse(res_object, bid_request); + it('Returns an array of valid server responses if response object is valid', function() { - expect(serverResponses).to.be.an('array').that.is.not.empty; - for (let i = 0; i < serverResponses.length; i++) { - let dataItem = serverResponses[i]; - expect(Object.keys(dataItem)).to.include('cpm', 'ttl', 'creativeId', - 'netRevenue', 'currency', 'mediaType', 'requestId'); - expect(dataItem.requestId).to.be.a('string'); - expect(dataItem.cpm).to.be.a('number'); - expect(dataItem.ttl).to.be.a('number'); - expect(dataItem.creativeId).to.be.a('string'); - expect(dataItem.netRevenue).to.be.a('boolean'); - expect(dataItem.currency).to.be.a('string'); - expect(dataItem.mediaType).to.be.a('string'); - - if (dataItem.mediaType == 'banner') { - expect(dataItem.ad).to.be.a('string'); - expect(dataItem.width).to.be.a('number'); - expect(dataItem.height).to.be.a('number'); - } else if (dataItem.mediaType == 'native') { - expect(dataItem.native.title).to.be.a('string'); - expect(dataItem.native.body).to.be.a('string'); - expect(dataItem.native.clickUrl).to.be.a('string'); - } else if (dataItem.mediaType == 'video') { - expect(dataItem.vastUrl).to.be.a('string'); - expect(dataItem.width).to.be.a('number'); - expect(dataItem.height).to.be.a('number'); + expect(response).to.be.an('array').that.is.not.empty; + + response.forEach(bid => { + expect(parseInt(bid.requestId)).to.be.a('number').greaterThan(0); + expect(bid.cpm).to.be.a('number'); + expect(bid.creativeId).to.be.a('string'); + expect(bid.currency).to.be.a('string'); + expect(bid.netRevenue).to.be.a('boolean'); + expect(bid.ttl).to.be.a('number'); + expect(bid.mediaType).to.be.a('string'); + + if (bid.mediaType == 'banner') { + expect(bid.width).to.be.a('number'); + expect(bid.height).to.be.a('number'); + expect(bid.ad).to.be.a('string'); + } else if (bid.mediaType == 'native') { + expect(bid.native).to.be.a('object'); } - } + }) + it('Returns an empty array if invalid response is passed', function() { serverResponses = spec.interpretResponse('invalid_response'); expect(serverResponses).to.be.an('array').that.is.empty;