From 24a1349558ba78b5567f8ab83165e5c71aa4b97a Mon Sep 17 00:00:00 2001 From: Dusan Veljovic Date: Mon, 30 Aug 2021 10:23:29 +0200 Subject: [PATCH 1/7] added goldbach adapter --- modules/goldbachXandrBidAdapter.js | 1124 ++++++++++++++ modules/goldbachXandrBidAdapter.md | 151 ++ .../modules/goldbachXandrBidAdapter_spec.js | 1352 +++++++++++++++++ 3 files changed, 2627 insertions(+) create mode 100644 modules/goldbachXandrBidAdapter.js create mode 100644 modules/goldbachXandrBidAdapter.md create mode 100644 test/spec/modules/goldbachXandrBidAdapter_spec.js diff --git a/modules/goldbachXandrBidAdapter.js b/modules/goldbachXandrBidAdapter.js new file mode 100644 index 00000000000..e73e2ce2802 --- /dev/null +++ b/modules/goldbachXandrBidAdapter.js @@ -0,0 +1,1124 @@ +import { Renderer } from '../src/Renderer.js'; +import * as utils from '../src/utils.js'; +import { config } from '../src/config.js'; +import { registerBidder, getIabSubCategory } from '../src/adapters/bidderFactory.js'; +import { BANNER, NATIVE, VIDEO, ADPOD } from '../src/mediaTypes.js'; +import { auctionManager } from '../src/auctionManager.js'; +import find from 'core-js-pure/features/array/find.js'; +import includes from 'core-js-pure/features/array/includes.js'; +import { OUTSTREAM, INSTREAM } from '../src/video.js'; +import { getStorageManager } from '../src/storageManager.js'; + +const BIDDER_CODE = 'gb_xandr'; +const URL = 'https://ib.adnxs.com/ut/v3/prebid'; +const URL_SIMPLE = 'https://ib.adnxs-simple.com/ut/v3/prebid'; +const VIDEO_TARGETING = ['id', 'minduration', 'maxduration', + 'skippable', 'playback_method', 'frameworks', 'context', 'skipoffset']; +const VIDEO_RTB_TARGETING = ['minduration', 'maxduration', 'skip', 'skipafter', 'playbackmethod', 'api']; +const USER_PARAMS = ['age', 'externalUid', 'segments', 'gender', 'dnt', 'language']; +const APP_DEVICE_PARAMS = ['geo', 'device_id']; // appid is collected separately +const DEBUG_PARAMS = ['enabled', 'dongle', 'member_id', 'debug_timeout']; +const VIDEO_MAPPING = { + playback_method: { + 'unknown': 0, + 'auto_play_sound_on': 1, + 'auto_play_sound_off': 2, + 'click_to_play': 3, + 'mouse_over': 4, + 'auto_play_sound_unknown': 5 + }, + context: { + 'unknown': 0, + 'pre_roll': 1, + 'mid_roll': 2, + 'post_roll': 3, + 'outstream': 4, + 'in-banner': 5 + } +}; +const NATIVE_MAPPING = { + body: 'description', + body2: 'desc2', + cta: 'ctatext', + image: { + serverName: 'main_image', + requiredParams: { required: true } + }, + icon: { + serverName: 'icon', + requiredParams: { required: true } + }, + sponsoredBy: 'sponsored_by', + privacyLink: 'privacy_link', + salePrice: 'saleprice', + displayUrl: 'displayurl' +}; +const SOURCE = 'pbjs'; +const MAX_IMPS_PER_REQUEST = 15; +const mappingFileUrl = 'https://acdn.adnxs-simple.com/prebid/appnexus-mapping/mappings.json'; +const SCRIPT_TAG_START = ' includes(USER_PARAMS, param)) + .forEach((param) => { + let uparam = utils.convertCamelToUnderscore(param); + if (param === 'segments' && utils.isArray(userObjBid.params.user[param])) { + let segs = []; + userObjBid.params.user[param].forEach(val => { + if (utils.isNumber(val)) { + segs.push({'id': val}); + } else if (utils.isPlainObject(val)) { + segs.push(val); + } + }); + userObj[uparam] = segs; + } else if (param !== 'segments') { + userObj[uparam] = userObjBid.params.user[param]; + } + }); + } + + const appDeviceObjBid = find(bidRequests, hasAppDeviceInfo); + let appDeviceObj; + if (appDeviceObjBid && appDeviceObjBid.params && appDeviceObjBid.params.app) { + appDeviceObj = {}; + Object.keys(appDeviceObjBid.params.app) + .filter(param => includes(APP_DEVICE_PARAMS, param)) + .forEach(param => appDeviceObj[param] = appDeviceObjBid.params.app[param]); + } + + const appIdObjBid = find(bidRequests, hasAppId); + let appIdObj; + if (appIdObjBid && appIdObjBid.params && appDeviceObjBid.params.app && appDeviceObjBid.params.app.id) { + appIdObj = { + appid: appIdObjBid.params.app.id + }; + } + + let debugObj = {}; + let debugObjParams = {}; + const debugCookieName = 'apn_prebid_debug'; + const debugCookie = storage.getCookie(debugCookieName) || null; + + if (debugCookie) { + try { + debugObj = JSON.parse(debugCookie); + } catch (e) { + utils.logError('AppNexus Debug Auction Cookie Error:\n\n' + e); + } + } else { + const debugBidRequest = find(bidRequests, hasDebug); + if (debugBidRequest && debugBidRequest.debug) { + debugObj = debugBidRequest.debug; + } + } + + if (debugObj && debugObj.enabled) { + Object.keys(debugObj) + .filter(param => includes(DEBUG_PARAMS, param)) + .forEach(param => { + debugObjParams[param] = debugObj[param]; + }); + } + + const memberIdBid = find(bidRequests, hasMemberId); + const member = memberIdBid ? parseInt(memberIdBid.params.member, 10) : 0; + const schain = bidRequests[0].schain; + const omidSupport = find(bidRequests, hasOmidSupport); + + const payload = { + tags: [...tags], + user: userObj, + sdk: { + source: SOURCE, + version: '$prebid.version$' + }, + schain: schain + }; + + if (omidSupport) { + payload['iab_support'] = { + omidpn: 'Appnexus', + omidpv: '$prebid.version$' + } + } + + if (member > 0) { + payload.member_id = member; + } + + if (appDeviceObjBid) { + payload.device = appDeviceObj + } + if (appIdObjBid) { + payload.app = appIdObj; + } + + if (config.getConfig('adpod.brandCategoryExclusion')) { + payload.brand_category_uniqueness = true; + } + + if (debugObjParams.enabled) { + payload.debug = debugObjParams; + utils.logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); + } + + if (bidderRequest && bidderRequest.gdprConsent) { + // note - objects for impbus use underscore instead of camelCase + payload.gdpr_consent = { + consent_string: bidderRequest.gdprConsent.consentString, + consent_required: bidderRequest.gdprConsent.gdprApplies + }; + + if (bidderRequest.gdprConsent.addtlConsent && bidderRequest.gdprConsent.addtlConsent.indexOf('~') !== -1) { + let ac = bidderRequest.gdprConsent.addtlConsent; + // pull only the ids from the string (after the ~) and convert them to an array of ints + let acStr = ac.substring(ac.indexOf('~') + 1); + payload.gdpr_consent.addtl_consent = acStr.split('.').map(id => parseInt(id, 10)); + } + } + + if (bidderRequest && bidderRequest.uspConsent) { + payload.us_privacy = bidderRequest.uspConsent + } + + if (bidderRequest && bidderRequest.refererInfo) { + let refererinfo = { + rd_ref: encodeURIComponent(bidderRequest.refererInfo.referer), + rd_top: bidderRequest.refererInfo.reachedTop, + rd_ifs: bidderRequest.refererInfo.numIframes, + rd_stk: bidderRequest.refererInfo.stack.map((url) => encodeURIComponent(url)).join(',') + } + payload.referrer_detection = refererinfo; + } + + const hasAdPodBid = find(bidRequests, hasAdPod); + if (hasAdPodBid) { + bidRequests.filter(hasAdPod).forEach(adPodBid => { + const adPodTags = createAdPodRequest(tags, adPodBid); + // don't need the original adpod placement because it's in adPodTags + const nonPodTags = payload.tags.filter(tag => tag.uuid !== adPodBid.bidId); + payload.tags = [...nonPodTags, ...adPodTags]; + }); + } + + if (bidRequests[0].userId) { + let eids = []; + + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); + + if (eids.length) { + payload.eids = eids; + } + } + + if (tags[0].publisher_id) { + payload.publisher_id = tags[0].publisher_id; + } + + const request = formatRequest(payload, bidderRequest); + return request; + }, + + /** + * Unpack the response from the server into a list of bids. + * + * @param {*} serverResponse A successful response from the server. + * @return {Bid[]} An array of bids which were nested inside the server. + */ + interpretResponse: function (serverResponse, { bidderRequest }) { + serverResponse = serverResponse.body; + const bids = []; + if (!serverResponse || serverResponse.error) { + let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`; + if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; } + utils.logError(errorMessage); + return bids; + } + + if (serverResponse.tags) { + serverResponse.tags.forEach(serverBid => { + const rtbBid = getRtbBid(serverBid); + if (rtbBid) { + if (rtbBid.cpm !== 0 && includes(this.supportedMediaTypes, rtbBid.ad_type)) { + const bid = newBid(serverBid, rtbBid, bidderRequest); + bid.mediaType = parseMediaType(rtbBid); + bids.push(bid); + } + } + }); + } + + if (serverResponse.debug && serverResponse.debug.debug_info) { + let debugHeader = 'AppNexus Debug Auction for Prebid\n\n' + let debugText = debugHeader + serverResponse.debug.debug_info + debugText = debugText + .replace(/(|)/gm, '\t') // Tables + .replace(/(<\/td>|<\/th>)/gm, '\n') // Tables + .replace(/^
/gm, '') // Remove leading
+ .replace(/(
\n|
)/gm, '\n') //
+ .replace(/

(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1 + .replace(/(.*)<\/h[2-6]>/gm, '\n\n*** $1 ***\n\n') // Headers + .replace(/(<([^>]+)>)/igm, ''); // Remove any other tags + utils.logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction'); + utils.logMessage(debugText); + } + + return bids; + }, + + /** + * @typedef {Object} mappingFileInfo + * @property {string} url mapping file json url + * @property {number} refreshInDays prebid stores mapping data in localstorage so you can return in how many days you want to update value stored in localstorage. + * @property {string} localStorageKey unique key to store your mapping json in localstorage + */ + + /** + * Returns mapping file info. This info will be used by bidderFactory to preload mapping file and store data in local storage + * @returns {mappingFileInfo} + */ + getMappingFileInfo: function () { + return { + url: mappingFileUrl, + refreshInDays: 2 + } + }, + + getUserSyncs: function (syncOptions, responses, gdprConsent) { + if (syncOptions.iframeEnabled && hasPurpose1Consent({gdprConsent})) { + return [{ + type: 'iframe', + url: 'https://acdn.adnxs.com/dmp/async_usersync.html' + }]; + } + }, + + transformBidParams: function (params, isOpenRtb) { + params = utils.convertTypes({ + 'member': 'string', + 'invCode': 'string', + 'placementId': 'number', + 'keywords': utils.transformBidderParamKeywords, + 'publisherId': 'number' + }, params); + + if (isOpenRtb) { + params.use_pmt_rule = (typeof params.usePaymentRule === 'boolean') ? params.usePaymentRule : false; + if (params.usePaymentRule) { delete params.usePaymentRule; } + + if (isPopulatedArray(params.keywords)) { + params.keywords.forEach(deleteValues); + } + + Object.keys(params).forEach(paramKey => { + let convertedKey = utils.convertCamelToUnderscore(paramKey); + if (convertedKey !== paramKey) { + params[convertedKey] = params[paramKey]; + delete params[paramKey]; + } + }); + } + + return params; + }, + + /** + * Add element selector to javascript tracker to improve native viewability + * @param {Bid} bid + */ + onBidWon: function (bid) { + if (bid.native) { + reloadViewabilityScriptWithCorrectParameters(bid); + } + } +} + +function isPopulatedArray(arr) { + return !!(utils.isArray(arr) && arr.length > 0); +} + +function deleteValues(keyPairObj) { + if (isPopulatedArray(keyPairObj.value) && keyPairObj.value[0] === '') { + delete keyPairObj.value; + } +} + +function reloadViewabilityScriptWithCorrectParameters(bid) { + let viewJsPayload = getAppnexusViewabilityScriptFromJsTrackers(bid.native.javascriptTrackers); + + if (viewJsPayload) { + let prebidParams = 'pbjs_adid=' + bid.adId + ';pbjs_auc=' + bid.adUnitCode; + + let jsTrackerSrc = getViewabilityScriptUrlFromPayload(viewJsPayload) + + let newJsTrackerSrc = jsTrackerSrc.replace('dom_id=%native_dom_id%', prebidParams); + + // find iframe containing script tag + let frameArray = document.getElementsByTagName('iframe'); + + // boolean var to modify only one script. That way if there are muliple scripts, + // they won't all point to the same creative. + let modifiedAScript = false; + + // first, loop on all ifames + for (let i = 0; i < frameArray.length && !modifiedAScript; i++) { + let currentFrame = frameArray[i]; + try { + // IE-compatible, see https://stackoverflow.com/a/3999191/2112089 + let nestedDoc = currentFrame.contentDocument || currentFrame.contentWindow.document; + + if (nestedDoc) { + // if the doc is present, we look for our jstracker + let scriptArray = nestedDoc.getElementsByTagName('script'); + for (let j = 0; j < scriptArray.length && !modifiedAScript; j++) { + let currentScript = scriptArray[j]; + if (currentScript.getAttribute('data-src') == jsTrackerSrc) { + currentScript.setAttribute('src', newJsTrackerSrc); + currentScript.setAttribute('data-src', ''); + if (currentScript.removeAttribute) { + currentScript.removeAttribute('data-src'); + } + modifiedAScript = true; + } + } + } + } catch (exception) { + // trying to access a cross-domain iframe raises a SecurityError + // this is expected and ignored + if (!(exception instanceof DOMException && exception.name === 'SecurityError')) { + // all other cases are raised again to be treated by the calling function + throw exception; + } + } + } + } +} + +function strIsAppnexusViewabilityScript(str) { + let regexMatchUrlStart = str.match(VIEWABILITY_URL_START); + let viewUrlStartInStr = regexMatchUrlStart != null && regexMatchUrlStart.length >= 1; + + let regexMatchFileName = str.match(VIEWABILITY_FILE_NAME); + let fileNameInStr = regexMatchFileName != null && regexMatchFileName.length >= 1; + + return str.startsWith(SCRIPT_TAG_START) && fileNameInStr && viewUrlStartInStr; +} + +function getAppnexusViewabilityScriptFromJsTrackers(jsTrackerArray) { + let viewJsPayload; + if (utils.isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { + viewJsPayload = jsTrackerArray; + } else if (utils.isArray(jsTrackerArray)) { + for (let i = 0; i < jsTrackerArray.length; i++) { + let currentJsTracker = jsTrackerArray[i]; + if (strIsAppnexusViewabilityScript(currentJsTracker)) { + viewJsPayload = currentJsTracker; + } + } + } + return viewJsPayload; +} + +function getViewabilityScriptUrlFromPayload(viewJsPayload) { + // extracting the content of the src attribute + // -> substring between src=" and " + let indexOfFirstQuote = viewJsPayload.indexOf('src="') + 5; // offset of 5: the length of 'src=' + 1 + let indexOfSecondQuote = viewJsPayload.indexOf('"', indexOfFirstQuote); + let jsTrackerSrc = viewJsPayload.substring(indexOfFirstQuote, indexOfSecondQuote); + return jsTrackerSrc; +} + +function hasPurpose1Consent(bidderRequest) { + let result = true; + if (bidderRequest && bidderRequest.gdprConsent) { + if (bidderRequest.gdprConsent.gdprApplies && bidderRequest.gdprConsent.apiVersion === 2) { + result = !!(utils.deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); + } + } + return result; +} + +function formatRequest(payload, bidderRequest) { + let request = []; + let options = { + withCredentials: true + }; + + let endpointUrl = URL; + + if (!hasPurpose1Consent(bidderRequest)) { + endpointUrl = URL_SIMPLE; + } + + if (utils.getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { + options.customHeaders = { + 'X-Is-Test': 1 + } + } + + if (payload.tags.length > MAX_IMPS_PER_REQUEST) { + const clonedPayload = utils.deepClone(payload); + + utils.chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { + clonedPayload.tags = tags; + const payloadString = JSON.stringify(clonedPayload); + request.push({ + method: 'POST', + url: endpointUrl, + data: payloadString, + bidderRequest, + options + }); + }); + } else { + const payloadString = JSON.stringify(payload); + request = { + method: 'POST', + url: endpointUrl, + data: payloadString, + bidderRequest, + options + }; + } + + return request; +} + +function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { + const renderer = Renderer.install({ + id: rtbBid.renderer_id, + url: rtbBid.renderer_url, + config: rendererOptions, + loaded: false, + adUnitCode + }); + + try { + renderer.setRender(outstreamRender); + } catch (err) { + utils.logWarn('Prebid Error calling setRender on renderer', err); + } + + renderer.setEventHandlers({ + impression: () => utils.logMessage('AppNexus outstream video impression event'), + loaded: () => utils.logMessage('AppNexus outstream video loaded event'), + ended: () => { + utils.logMessage('AppNexus outstream renderer video event'); + document.querySelector(`#${adUnitCode}`).style.display = 'none'; + } + }); + return renderer; +} + +/** + * Unpack the Server's Bid into a Prebid-compatible one. + * @param serverBid + * @param rtbBid + * @param bidderRequest + * @return Bid + */ +function newBid(serverBid, rtbBid, bidderRequest) { + const bidRequest = utils.getBidRequest(serverBid.uuid, [bidderRequest]); + const bid = { + requestId: serverBid.uuid, + cpm: rtbBid.cpm, + creativeId: rtbBid.creative_id, + dealId: rtbBid.deal_id, + currency: 'USD', + netRevenue: true, + ttl: 300, + adUnitCode: bidRequest.adUnitCode, + appnexus: { + buyerMemberId: rtbBid.buyer_member_id, + dealPriority: rtbBid.deal_priority, + dealCode: rtbBid.deal_code + } + }; + + // WE DON'T FULLY SUPPORT THIS ATM - future spot for adomain code; creating a stub for 5.0 compliance + if (rtbBid.adomain) { + bid.meta = Object.assign({}, bid.meta, { advertiserDomains: [] }); + } + + if (rtbBid.advertiser_id) { + bid.meta = Object.assign({}, bid.meta, { advertiserId: rtbBid.advertiser_id }); + } + + if (rtbBid.rtb.video) { + // shared video properties used for all 3 contexts + Object.assign(bid, { + width: rtbBid.rtb.video.player_width, + height: rtbBid.rtb.video.player_height, + vastImpUrl: rtbBid.notify_url, + ttl: 3600 + }); + + const videoContext = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + switch (videoContext) { + case ADPOD: + const primaryCatId = getIabSubCategory(bidRequest.bidder, rtbBid.brand_category_id); + bid.meta = Object.assign({}, bid.meta, { primaryCatId }); + const dealTier = rtbBid.deal_priority; + bid.video = { + context: ADPOD, + durationSeconds: Math.floor(rtbBid.rtb.video.duration_ms / 1000), + dealTier + }; + bid.vastUrl = rtbBid.rtb.video.asset_url; + break; + case OUTSTREAM: + bid.adResponse = serverBid; + bid.adResponse.ad = bid.adResponse.ads[0]; + bid.adResponse.ad.video = bid.adResponse.ad.rtb.video; + bid.vastXml = rtbBid.rtb.video.content; + + if (rtbBid.renderer_url) { + const videoBid = find(bidderRequest.bids, bid => bid.bidId === serverBid.uuid); + const rendererOptions = utils.deepAccess(videoBid, 'renderer.options'); + bid.renderer = newRenderer(bid.adUnitCode, rtbBid, rendererOptions); + } + break; + case INSTREAM: + bid.vastUrl = rtbBid.notify_url + '&redir=' + encodeURIComponent(rtbBid.rtb.video.asset_url); + break; + } + } else if (rtbBid.rtb[NATIVE]) { + const nativeAd = rtbBid.rtb[NATIVE]; + + // setting up the jsTracker: + // we put it as a data-src attribute so that the tracker isn't called + // until we have the adId (see onBidWon) + let jsTrackerDisarmed = rtbBid.viewability.config.replace('src=', 'data-src='); + + let jsTrackers = nativeAd.javascript_trackers; + + if (jsTrackers == undefined) { + jsTrackers = jsTrackerDisarmed; + } else if (utils.isStr(jsTrackers)) { + jsTrackers = [jsTrackers, jsTrackerDisarmed]; + } else { + jsTrackers.push(jsTrackerDisarmed); + } + + bid[NATIVE] = { + title: nativeAd.title, + body: nativeAd.desc, + body2: nativeAd.desc2, + cta: nativeAd.ctatext, + rating: nativeAd.rating, + sponsoredBy: nativeAd.sponsored, + privacyLink: nativeAd.privacy_link, + address: nativeAd.address, + downloads: nativeAd.downloads, + likes: nativeAd.likes, + phone: nativeAd.phone, + price: nativeAd.price, + salePrice: nativeAd.saleprice, + clickUrl: nativeAd.link.url, + displayUrl: nativeAd.displayurl, + clickTrackers: nativeAd.link.click_trackers, + impressionTrackers: nativeAd.impression_trackers, + javascriptTrackers: jsTrackers + }; + if (nativeAd.main_img) { + bid['native'].image = { + url: nativeAd.main_img.url, + height: nativeAd.main_img.height, + width: nativeAd.main_img.width, + }; + } + if (nativeAd.icon) { + bid['native'].icon = { + url: nativeAd.icon.url, + height: nativeAd.icon.height, + width: nativeAd.icon.width, + }; + } + } else { + Object.assign(bid, { + width: rtbBid.rtb.banner.width, + height: rtbBid.rtb.banner.height, + ad: rtbBid.rtb.banner.content + }); + try { + if (rtbBid.rtb.trackers) { + const url = rtbBid.rtb.trackers[0].impression_urls[0]; + const tracker = utils.createTrackPixelHtml(url); + bid.ad += tracker; + } + } catch (error) { + utils.logError('Error appending tracking pixel', error); + } + } + + return bid; +} + +function bidToTag(bid) { + const tag = {}; + tag.sizes = transformSizes(bid.sizes); + tag.primary_size = tag.sizes[0]; + tag.ad_types = []; + tag.uuid = bid.bidId; + if (bid.params.placementId) { + tag.id = parseInt(bid.params.placementId, 10); + } else { + tag.code = bid.params.invCode; + } + tag.allow_smaller_sizes = bid.params.allowSmallerSizes || false; + tag.use_pmt_rule = bid.params.usePaymentRule || false + tag.prebid = true; + tag.disable_psa = true; + let bidFloor = getBidFloor(bid); + if (bidFloor) { + tag.reserve = bidFloor; + } + if (bid.params.position) { + tag.position = { 'above': 1, 'below': 2 }[bid.params.position] || 0; + } + if (bid.params.trafficSourceCode) { + tag.traffic_source_code = bid.params.trafficSourceCode; + } + if (bid.params.privateSizes) { + tag.private_sizes = transformSizes(bid.params.privateSizes); + } + if (bid.params.supplyType) { + tag.supply_type = bid.params.supplyType; + } + if (bid.params.pubClick) { + tag.pubclick = bid.params.pubClick; + } + if (bid.params.extInvCode) { + tag.ext_inv_code = bid.params.extInvCode; + } + if (bid.params.publisherId) { + tag.publisher_id = parseInt(bid.params.publisherId, 10); + } + if (bid.params.externalImpId) { + tag.external_imp_id = bid.params.externalImpId; + } + if (!utils.isEmpty(bid.params.keywords)) { + let keywords = utils.transformBidderParamKeywords(bid.params.keywords); + + if (keywords.length > 0) { + keywords.forEach(deleteValues); + } + tag.keywords = keywords; + } + + let gpid = utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); + if (gpid) { + tag.gpid = gpid; + } + + if (bid.mediaType === NATIVE || utils.deepAccess(bid, `mediaTypes.${NATIVE}`)) { + tag.ad_types.push(NATIVE); + if (tag.sizes.length === 0) { + tag.sizes = transformSizes([1, 1]); + } + + if (bid.nativeParams) { + const nativeRequest = buildNativeRequest(bid.nativeParams); + tag[NATIVE] = { layouts: [nativeRequest] }; + } + } + + const videoMediaType = utils.deepAccess(bid, `mediaTypes.${VIDEO}`); + const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + + if (videoMediaType && context === 'adpod') { + tag.hb_source = 7; + } else { + tag.hb_source = 1; + } + if (bid.mediaType === VIDEO || videoMediaType) { + tag.ad_types.push(VIDEO); + } + + // instream gets vastUrl, outstream gets vastXml + if (bid.mediaType === VIDEO || (videoMediaType && context !== 'outstream')) { + tag.require_asset_url = true; + } + + if (bid.params.video) { + tag.video = {}; + // place any valid video params on the tag + Object.keys(bid.params.video) + .filter(param => includes(VIDEO_TARGETING, param)) + .forEach(param => { + switch (param) { + case 'context': + case 'playback_method': + let type = bid.params.video[param]; + type = (utils.isArray(type)) ? type[0] : type; + tag.video[param] = VIDEO_MAPPING[param][type]; + break; + // Deprecating tags[].video.frameworks in favor of tags[].video_frameworks + case 'frameworks': + break; + default: + tag.video[param] = bid.params.video[param]; + } + }); + + if (bid.params.video.frameworks && utils.isArray(bid.params.video.frameworks)) { + tag['video_frameworks'] = bid.params.video.frameworks; + } + } + + // use IAB ORTB values if the corresponding values weren't already set by bid.params.video + if (videoMediaType) { + tag.video = tag.video || {}; + Object.keys(videoMediaType) + .filter(param => includes(VIDEO_RTB_TARGETING, param)) + .forEach(param => { + switch (param) { + case 'minduration': + case 'maxduration': + if (typeof tag.video[param] !== 'number') tag.video[param] = videoMediaType[param]; + break; + case 'skip': + if (typeof tag.video['skippable'] !== 'boolean') tag.video['skippable'] = (videoMediaType[param] === 1); + break; + case 'skipafter': + if (typeof tag.video['skipoffset'] !== 'number') tag.video['skippoffset'] = videoMediaType[param]; + break; + case 'playbackmethod': + if (typeof tag.video['playback_method'] !== 'number') { + let type = videoMediaType[param]; + type = (utils.isArray(type)) ? type[0] : type; + + // we only support iab's options 1-4 at this time. + if (type >= 1 && type <= 4) { + tag.video['playback_method'] = type; + } + } + break; + case 'api': + if (!tag['video_frameworks'] && utils.isArray(videoMediaType[param])) { + // need to read thru array; remove 6 (we don't support it), swap 4 <> 5 if found (to match our adserver mapping for these specific values) + let apiTmp = videoMediaType[param].map(val => { + let v = (val === 4) ? 5 : (val === 5) ? 4 : val; + + if (v >= 1 && v <= 5) { + return v; + } + }).filter(v => v); + tag['video_frameworks'] = apiTmp; + } + break; + } + }); + } + + if (bid.renderer) { + tag.video = Object.assign({}, tag.video, { custom_renderer_present: true }); + } + + if (bid.params.frameworks && utils.isArray(bid.params.frameworks)) { + tag['banner_frameworks'] = bid.params.frameworks; + } + + let adUnit = find(auctionManager.getAdUnits(), au => bid.transactionId === au.transactionId); + if (adUnit && adUnit.mediaTypes && adUnit.mediaTypes.banner) { + tag.ad_types.push(BANNER); + } + + if (tag.ad_types.length === 0) { + delete tag.ad_types; + } + + return tag; +} + +/* Turn bid request sizes into ut-compatible format */ +function transformSizes(requestSizes) { + let sizes = []; + let sizeObj = {}; + + if (utils.isArray(requestSizes) && requestSizes.length === 2 && + !utils.isArray(requestSizes[0])) { + sizeObj.width = parseInt(requestSizes[0], 10); + sizeObj.height = parseInt(requestSizes[1], 10); + sizes.push(sizeObj); + } else if (typeof requestSizes === 'object') { + for (let i = 0; i < requestSizes.length; i++) { + let size = requestSizes[i]; + sizeObj = {}; + sizeObj.width = parseInt(size[0], 10); + sizeObj.height = parseInt(size[1], 10); + sizes.push(sizeObj); + } + } + + return sizes; +} + +function hasUserInfo(bid) { + return !!bid.params.user; +} + +function hasMemberId(bid) { + return !!parseInt(bid.params.member, 10); +} + +function hasAppDeviceInfo(bid) { + if (bid.params) { + return !!bid.params.app + } +} + +function hasAppId(bid) { + if (bid.params && bid.params.app) { + return !!bid.params.app.id + } + return !!bid.params.app +} + +function hasDebug(bid) { + return !!bid.debug +} + +function hasAdPod(bid) { + return ( + bid.mediaTypes && + bid.mediaTypes.video && + bid.mediaTypes.video.context === ADPOD + ); +} + +function hasOmidSupport(bid) { + let hasOmid = false; + const bidderParams = bid.params; + const videoParams = bid.params.video; + if (bidderParams.frameworks && utils.isArray(bidderParams.frameworks)) { + hasOmid = includes(bid.params.frameworks, 6); + } + if (!hasOmid && videoParams && videoParams.frameworks && utils.isArray(videoParams.frameworks)) { + hasOmid = includes(bid.params.video.frameworks, 6); + } + return hasOmid; +} + +/** + * Expand an adpod placement into a set of request objects according to the + * total adpod duration and the range of duration seconds. Sets minduration/ + * maxduration video property according to requireExactDuration configuration + */ +function createAdPodRequest(tags, adPodBid) { + const { durationRangeSec, requireExactDuration } = adPodBid.mediaTypes.video; + + const numberOfPlacements = getAdPodPlacementNumber(adPodBid.mediaTypes.video); + const maxDuration = utils.getMaxValueFromArray(durationRangeSec); + + const tagToDuplicate = tags.filter(tag => tag.uuid === adPodBid.bidId); + let request = utils.fill(...tagToDuplicate, numberOfPlacements); + + if (requireExactDuration) { + const divider = Math.ceil(numberOfPlacements / durationRangeSec.length); + const chunked = utils.chunk(request, divider); + + // each configured duration is set as min/maxduration for a subset of requests + durationRangeSec.forEach((duration, index) => { + chunked[index].map(tag => { + setVideoProperty(tag, 'minduration', duration); + setVideoProperty(tag, 'maxduration', duration); + }); + }); + } else { + // all maxdurations should be the same + request.map(tag => setVideoProperty(tag, 'maxduration', maxDuration)); + } + + return request; +} + +function getAdPodPlacementNumber(videoParams) { + const { adPodDurationSec, durationRangeSec, requireExactDuration } = videoParams; + const minAllowedDuration = utils.getMinValueFromArray(durationRangeSec); + const numberOfPlacements = Math.floor(adPodDurationSec / minAllowedDuration); + + return requireExactDuration + ? Math.max(numberOfPlacements, durationRangeSec.length) + : numberOfPlacements; +} + +function setVideoProperty(tag, key, value) { + if (utils.isEmpty(tag.video)) { tag.video = {}; } + tag.video[key] = value; +} + +function getRtbBid(tag) { + return tag && tag.ads && tag.ads.length && find(tag.ads, ad => ad.rtb); +} + +function buildNativeRequest(params) { + const request = {}; + + // map standard prebid native asset identifier to /ut parameters + // e.g., tag specifies `body` but /ut only knows `description`. + // mapping may be in form {tag: ''} or + // {tag: {serverName: '', requiredParams: {...}}} + Object.keys(params).forEach(key => { + // check if one of the forms is used, otherwise + // a mapping wasn't specified so pass the key straight through + const requestKey = + (NATIVE_MAPPING[key] && NATIVE_MAPPING[key].serverName) || + NATIVE_MAPPING[key] || + key; + + // required params are always passed on request + const requiredParams = NATIVE_MAPPING[key] && NATIVE_MAPPING[key].requiredParams; + request[requestKey] = Object.assign({}, requiredParams, params[key]); + + // convert the sizes of image/icon assets to proper format (if needed) + const isImageAsset = !!(requestKey === NATIVE_MAPPING.image.serverName || requestKey === NATIVE_MAPPING.icon.serverName); + if (isImageAsset && request[requestKey].sizes) { + let sizes = request[requestKey].sizes; + if (utils.isArrayOfNums(sizes) || (utils.isArray(sizes) && sizes.length > 0 && sizes.every(sz => utils.isArrayOfNums(sz)))) { + request[requestKey].sizes = transformSizes(request[requestKey].sizes); + } + } + + if (requestKey === NATIVE_MAPPING.privacyLink) { + request.privacy_supported = true; + } + }); + + return request; +} + +/** + * This function hides google div container for outstream bids to remove unwanted space on page. Appnexus renderer creates a new iframe outside of google iframe to render the outstream creative. + * @param {string} elementId element id + */ +function hidedfpContainer(elementId) { + var el = document.getElementById(elementId).querySelectorAll("div[id^='google_ads']"); + if (el[0]) { + el[0].style.setProperty('display', 'none'); + } +} + +function hideSASIframe(elementId) { + try { + // find script tag with id 'sas_script'. This ensures it only works if you're using Smart Ad Server. + const el = document.getElementById(elementId).querySelectorAll("script[id^='sas_script']"); + if (el[0].nextSibling && el[0].nextSibling.localName === 'iframe') { + el[0].nextSibling.style.setProperty('display', 'none'); + } + } catch (e) { + // element not found! + } +} + +function outstreamRender(bid) { + hidedfpContainer(bid.adUnitCode); + hideSASIframe(bid.adUnitCode); + // push to render queue because ANOutstreamVideo may not be loaded yet + bid.renderer.push(() => { + window.ANOutstreamVideo.renderAd({ + tagId: bid.adResponse.tag_id, + sizes: [bid.getSize().split('x')], + targetId: bid.adUnitCode, // target div id to render video + uuid: bid.adResponse.uuid, + adResponse: bid.adResponse, + rendererOptions: bid.renderer.getConfig() + }, handleOutstreamRendererEvents.bind(null, bid)); + }); +} + +function handleOutstreamRendererEvents(bid, id, eventName) { + bid.renderer.handleVideoEvent({ id, eventName }); +} + +function parseMediaType(rtbBid) { + const adType = rtbBid.ad_type; + if (adType === VIDEO) { + return VIDEO; + } else if (adType === NATIVE) { + return NATIVE; + } else { + return BANNER; + } +} + +function addUserId(eids, id, source, rti) { + if (id) { + if (rti) { + eids.push({ source, id, rti_partner: rti }); + } else { + eids.push({ source, id }); + } + } + return eids; +} + +function getBidFloor(bid) { + if (!utils.isFn(bid.getFloor)) { + return (bid.params.reserve) ? bid.params.reserve : null; + } + + let floor = bid.getFloor({ + currency: 'USD', + mediaType: '*', + size: '*' + }); + if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + return floor.floor; + } + return null; +} + +registerBidder(spec); diff --git a/modules/goldbachXandrBidAdapter.md b/modules/goldbachXandrBidAdapter.md new file mode 100644 index 00000000000..57b2b084f6e --- /dev/null +++ b/modules/goldbachXandrBidAdapter.md @@ -0,0 +1,151 @@ +#Overview + +``` +Module Name: Goldbach Xander Bid Adapter +Module Type: Bidder Adapter +Maintainer: dusan.veljovic@goldbach.com +``` + +# Description + +Connects to Xandr exchange for bids. + +Goldbach Xandr bid adapter supports Banner, Video (instream and outstream) and Native. + +# Test Parameters +``` +var adUnits = [ + // Banner adUnit + { + code: 'banner-div', + mediaTypes: { + banner: { + sizes: [[300, 250], [300,600]] + } + }, + bids: [{ + bidder: 'gb_xandr', + params: { + placementId: 13144370 + } + }] + }, + // Native adUnit + { + code: 'native-div', + sizes: [[1, 1]], + mediaTypes: { + native: { + title: { + required: true + }, + body: { + required: true + }, + image: { + required: true + }, + sponsoredBy: { + required: true + }, + icon: { + required: false + } + } + }, + bids: [{ + bidder: 'gb_xandr', + params: { + placementId: 13232354, + allowSmallerSizes: true + } + }] + }, + // Video instream adUnit + { + code: 'video-instream', + sizes: [[640, 480]], + mediaTypes: { + video: { + playerSize: [[640, 480]], + context: 'instream' + }, + }, + bids: [{ + gb_xandr: 'gb_xandr', + params: { + placementId: 13232361, + video: { + skippable: true, + playback_methods: ['auto_play_sound_off'] + } + } + }] + }, + // Video outstream adUnit + { + code: 'video-outstream', + sizes: [[300, 250]], + mediaTypes: { + video: { + playerSize: [[300, 250]], + context: 'outstream', + // Certain ORTB 2.5 video values can be read from the mediatypes object; below are examples of supported params. + // To note - gb_xandr supports additional values for our system that are not part of the ORTB spec. If you want + // to use these values, they will have to be declared in the bids[].params.video object instead using the gb_xandr syntax. + // Between the corresponding values of the mediaTypes.video and params.video objects, the properties in params.video will + // take precedence if declared; eg in the example below, the `skippable: true` setting will be used instead of the `skip: 0`. + minduration: 1, + maxduration: 60, + skip: 0, // 1 - true, 0 - false + skipafter: 5, + playbackmethod: [2], // note - we only support options 1-4 at this time + api: [1,2,3] // note - option 6 is not supported at this time + } + }, + bids: [ + { + bidder: 'gb_xandr', + params: { + placementId: 13232385, + video: { + skippable: true, + playback_method: 'auto_play_sound_off' + } + } + } + ] + }, + // Banner adUnit in a App Webview + // Only use this for situations where prebid.js is in a webview of an App + // See Prebid Mobile for displaying ads via an SDK + { + code: 'banner-div', + mediaTypes: { + banner: { + sizes: [[300, 250], [300,600]] + } + } + bids: [{ + bidder: 'gb_xandr', + params: { + placementId: 13144370, + app: { + id: "B1O2W3M4AN.com.prebid.webview", + geo: { + lat: 40.0964439, + lng: -75.3009142 + }, + device_id: { + idfa: "4D12078D-3246-4DA4-AD5E-7610481E7AE", // Apple advertising identifier + aaid: "38400000-8cf0-11bd-b23e-10b96e40000d", // Android advertising identifier + md5udid: "5756ae9022b2ea1e47d84fead75220c8", // MD5 hash of the ANDROID_ID + sha1udid: "4DFAA92388699AC6539885AEF1719293879985BF", // SHA1 hash of the ANDROID_ID + windowsadid: "750c6be243f1c4b5c9912b95a5742fc5" // Windows advertising identifier + } + } + } + }] + } +]; +``` diff --git a/test/spec/modules/goldbachXandrBidAdapter_spec.js b/test/spec/modules/goldbachXandrBidAdapter_spec.js new file mode 100644 index 00000000000..b5eb71e96d0 --- /dev/null +++ b/test/spec/modules/goldbachXandrBidAdapter_spec.js @@ -0,0 +1,1352 @@ +import { expect } from 'chai'; +import { spec } from 'modules/goldbachXandrBidAdapter.js'; +import { newBidder } from 'src/adapters/bidderFactory.js'; +import * as bidderFactory from 'src/adapters/bidderFactory.js'; +import { auctionManager } from 'src/auctionManager.js'; +import { deepClone } from 'src/utils.js'; +import { config } from 'src/config.js'; + +const ENDPOINT = 'https://ib.adnxs.com/ut/v3/prebid'; + +describe('GoldbachXandrAdapter', function () { + const adapter = newBidder(spec); + + describe('inherited functions', function () { + it('exists and is a function', function () { + expect(adapter.callBids).to.exist.and.to.be.a('function'); + }); + }); + + describe('isBidRequestValid', function () { + let bid = { + 'bidder': 'gb_xandr', + 'params': { + 'placementId': '10433394' + }, + 'adUnitCode': 'adunit-code', + 'sizes': [[300, 250], [300, 600]], + 'bidId': '30b31c1838de1e', + 'bidderRequestId': '22edbae2733bf6', + 'auctionId': '1d1a030790a475', + }; + + it('should return true when required params found', function () { + expect(spec.isBidRequestValid(bid)).to.equal(true); + }); + + it('should return true when required params found', function () { + let bid = Object.assign({}, bid); + delete bid.params; + bid.params = { + 'member': '1234', + 'invCode': 'ABCD' + }; + + expect(spec.isBidRequestValid(bid)).to.equal(true); + }); + + it('should return false when required params are not passed', function () { + let bid = Object.assign({}, bid); + delete bid.params; + bid.params = { + 'placementId': 0 + }; + expect(spec.isBidRequestValid(bid)).to.equal(false); + }); + }); + + describe('buildRequests', function () { + let getAdUnitsStub; + let bidRequests = [ + { + 'bidder': 'gb_xandr', + 'params': { + 'placementId': '10433394' + }, + 'adUnitCode': 'adunit-code', + 'sizes': [[300, 250], [300, 600]], + 'bidId': '30b31c1838de1e', + 'bidderRequestId': '22edbae2733bf6', + 'auctionId': '1d1a030790a475', + 'transactionId': '04f2659e-c005-4eb1-a57c-fa93145e3843' + } + ]; + + beforeEach(function() { + getAdUnitsStub = sinon.stub(auctionManager, 'getAdUnits').callsFake(function() { + return []; + }); + }); + + afterEach(function() { + getAdUnitsStub.restore(); + }); + + it('should parse out private sizes', function () { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { + placementId: '10433394', + privateSizes: [300, 250] + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].private_sizes).to.exist; + expect(payload.tags[0].private_sizes).to.deep.equal([{width: 300, height: 250}]); + }); + + it('should add publisher_id in request', function() { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { + placementId: '10433394', + publisherId: '1231234' + } + }); + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].publisher_id).to.exist; + expect(payload.tags[0].publisher_id).to.deep.equal(1231234); + expect(payload.publisher_id).to.exist; + expect(payload.publisher_id).to.deep.equal(1231234); + }) + + it('should add source and verison to the tag', function () { + const request = spec.buildRequests(bidRequests); + const payload = JSON.parse(request.data); + expect(payload.sdk).to.exist; + expect(payload.sdk).to.deep.equal({ + source: 'pbjs', + version: '$prebid.version$' + }); + }); + + it('should populate the ad_types array on all requests', function () { + let adUnits = [{ + code: 'adunit-code', + mediaTypes: { + banner: { + sizes: [[300, 250], [300, 600]] + } + }, + bids: [{ + bidder: 'gb_xandr', + params: { + placementId: '10433394' + } + }], + transactionId: '04f2659e-c005-4eb1-a57c-fa93145e3843' + }]; + + ['banner', 'video', 'native'].forEach(type => { + getAdUnitsStub.callsFake(function(...args) { + return adUnits; + }); + + const bidRequest = Object.assign({}, bidRequests[0]); + bidRequest.mediaTypes = {}; + bidRequest.mediaTypes[type] = {}; + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].ad_types).to.deep.equal([type]); + + if (type === 'banner') { + delete adUnits[0].mediaTypes; + } + }); + }); + + it('should not populate the ad_types array when adUnit.mediaTypes is undefined', function() { + const bidRequest = Object.assign({}, bidRequests[0]); + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].ad_types).to.not.exist; + }); + + it('should populate the ad_types array on outstream requests', function () { + const bidRequest = Object.assign({}, bidRequests[0]); + bidRequest.mediaTypes = {}; + bidRequest.mediaTypes.video = {context: 'outstream'}; + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].ad_types).to.deep.equal(['video']); + expect(payload.tags[0].hb_source).to.deep.equal(1); + }); + + it('sends bid request to ENDPOINT via POST', function () { + const request = spec.buildRequests(bidRequests); + expect(request.url).to.equal(ENDPOINT); + expect(request.method).to.equal('POST'); + }); + + it('should attach valid video params to the tag', function () { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { + placementId: '10433394', + video: { + id: 123, + minduration: 100, + foobar: 'invalid' + } + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + expect(payload.tags[0].video).to.deep.equal({ + id: 123, + minduration: 100 + }); + expect(payload.tags[0].hb_source).to.deep.equal(1); + }); + + it('should include ORTB video values when video params were not set', function() { + let bidRequest = deepClone(bidRequests[0]); + bidRequest.params = { + placementId: '1234235', + video: { + skippable: true, + playback_method: ['auto_play_sound_off', 'auto_play_sound_unknown'], + context: 'outstream' + } + }; + bidRequest.mediaTypes = { + video: { + playerSize: [640, 480], + context: 'outstream', + mimes: ['video/mp4'], + skip: 0, + minduration: 5, + api: [1, 5, 6], + playbackmethod: [2, 4] + } + }; + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].video).to.deep.equal({ + minduration: 5, + playback_method: 2, + skippable: true, + context: 4 + }); + expect(payload.tags[0].video_frameworks).to.deep.equal([1, 4]) + }); + + it('should add video property when adUnit includes a renderer', function () { + const videoData = { + mediaTypes: { + video: { + context: 'outstream', + mimes: ['video/mp4'] + } + }, + params: { + placementId: '10433394', + video: { + skippable: true, + playback_method: ['auto_play_sound_off'] + } + } + }; + + let bidRequest1 = deepClone(bidRequests[0]); + bidRequest1 = Object.assign({}, bidRequest1, videoData, { + renderer: { + url: 'https://test.renderer.url', + render: function () {} + } + }); + + let bidRequest2 = deepClone(bidRequests[0]); + bidRequest2.adUnitCode = 'adUnit_code_2'; + bidRequest2 = Object.assign({}, bidRequest2, videoData); + + const request = spec.buildRequests([bidRequest1, bidRequest2]); + const payload = JSON.parse(request.data); + expect(payload.tags[0].video).to.deep.equal({ + skippable: true, + playback_method: 2, + custom_renderer_present: true + }); + expect(payload.tags[1].video).to.deep.equal({ + skippable: true, + playback_method: 2 + }); + }); + + it('should attach valid user params to the tag', function () { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { + placementId: '10433394', + user: { + externalUid: '123', + segments: [123, { id: 987, value: 876 }], + foobar: 'invalid' + } + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.user).to.exist; + expect(payload.user).to.deep.equal({ + external_uid: '123', + segments: [{id: 123}, {id: 987, value: 876}] + }); + }); + + it('should attach reserve param when either bid param or getFloor function exists', function () { + let getFloorResponse = { currency: 'USD', floor: 3 }; + let request, payload = null; + let bidRequest = deepClone(bidRequests[0]); + + // 1 -> reserve not defined, getFloor not defined > empty + request = spec.buildRequests([bidRequest]); + payload = JSON.parse(request.data); + + expect(payload.tags[0].reserve).to.not.exist; + + // 2 -> reserve is defined, getFloor not defined > reserve is used + bidRequest.params = { + 'placementId': '10433394', + 'reserve': 0.5 + }; + request = spec.buildRequests([bidRequest]); + payload = JSON.parse(request.data); + + expect(payload.tags[0].reserve).to.exist.and.to.equal(0.5); + + // 3 -> reserve is defined, getFloor is defined > getFloor is used + bidRequest.getFloor = () => getFloorResponse; + + request = spec.buildRequests([bidRequest]); + payload = JSON.parse(request.data); + + expect(payload.tags[0].reserve).to.exist.and.to.equal(3); + }); + + it('should duplicate adpod placements into batches and set correct maxduration', function() { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { placementId: '14542875' } + }, + { + mediaTypes: { + video: { + context: 'adpod', + playerSize: [640, 480], + adPodDurationSec: 300, + durationRangeSec: [15, 30], + } + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload1 = JSON.parse(request[0].data); + const payload2 = JSON.parse(request[1].data); + + // 300 / 15 = 20 total + expect(payload1.tags.length).to.equal(15); + expect(payload2.tags.length).to.equal(5); + + expect(payload1.tags[0]).to.deep.equal(payload1.tags[1]); + expect(payload1.tags[0].video.maxduration).to.equal(30); + + expect(payload2.tags[0]).to.deep.equal(payload1.tags[1]); + expect(payload2.tags[0].video.maxduration).to.equal(30); + }); + + it('should round down adpod placements when numbers are uneven', function() { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { placementId: '14542875' } + }, + { + mediaTypes: { + video: { + context: 'adpod', + playerSize: [640, 480], + adPodDurationSec: 123, + durationRangeSec: [45], + } + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + expect(payload.tags.length).to.equal(2); + }); + + it('should duplicate adpod placements when requireExactDuration is set', function() { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { placementId: '14542875' } + }, + { + mediaTypes: { + video: { + context: 'adpod', + playerSize: [640, 480], + adPodDurationSec: 300, + durationRangeSec: [15, 30], + requireExactDuration: true, + } + } + } + ); + + // 20 total placements with 15 max impressions = 2 requests + const request = spec.buildRequests([bidRequest]); + expect(request.length).to.equal(2); + + // 20 spread over 2 requests = 15 in first request, 5 in second + const payload1 = JSON.parse(request[0].data); + const payload2 = JSON.parse(request[1].data); + expect(payload1.tags.length).to.equal(15); + expect(payload2.tags.length).to.equal(5); + + // 10 placements should have max/min at 15 + // 10 placemenst should have max/min at 30 + const payload1tagsWith15 = payload1.tags.filter(tag => tag.video.maxduration === 15); + const payload1tagsWith30 = payload1.tags.filter(tag => tag.video.maxduration === 30); + expect(payload1tagsWith15.length).to.equal(10); + expect(payload1tagsWith30.length).to.equal(5); + + // 5 placemenst with min/max at 30 were in the first request + // so 5 remaining should be in the second + const payload2tagsWith30 = payload2.tags.filter(tag => tag.video.maxduration === 30); + expect(payload2tagsWith30.length).to.equal(5); + }); + + it('should set durations for placements when requireExactDuration is set and numbers are uneven', function() { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { placementId: '14542875' } + }, + { + mediaTypes: { + video: { + context: 'adpod', + playerSize: [640, 480], + adPodDurationSec: 105, + durationRangeSec: [15, 30, 60], + requireExactDuration: true, + } + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + expect(payload.tags.length).to.equal(7); + + const tagsWith15 = payload.tags.filter(tag => tag.video.maxduration === 15); + const tagsWith30 = payload.tags.filter(tag => tag.video.maxduration === 30); + const tagsWith60 = payload.tags.filter(tag => tag.video.maxduration === 60); + expect(tagsWith15.length).to.equal(3); + expect(tagsWith30.length).to.equal(3); + expect(tagsWith60.length).to.equal(1); + }); + + it('should break adpod request into batches', function() { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { placementId: '14542875' } + }, + { + mediaTypes: { + video: { + context: 'adpod', + playerSize: [640, 480], + adPodDurationSec: 225, + durationRangeSec: [5], + } + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload1 = JSON.parse(request[0].data); + const payload2 = JSON.parse(request[1].data); + const payload3 = JSON.parse(request[2].data); + + expect(payload1.tags.length).to.equal(15); + expect(payload2.tags.length).to.equal(15); + expect(payload3.tags.length).to.equal(15); + }); + + it('should contain hb_source value for adpod', function() { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { placementId: '14542875' } + }, + { + mediaTypes: { + video: { + context: 'adpod', + playerSize: [640, 480], + adPodDurationSec: 300, + durationRangeSec: [15, 30], + } + } + } + ); + const request = spec.buildRequests([bidRequest])[0]; + const payload = JSON.parse(request.data); + expect(payload.tags[0].hb_source).to.deep.equal(7); + }); + + it('should contain hb_source value for other media', function() { + let bidRequest = Object.assign({}, + bidRequests[0], + { + mediaType: 'banner', + params: { + sizes: [[300, 250], [300, 600]], + placementId: 13144370 + } + } + ); + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + expect(payload.tags[0].hb_source).to.deep.equal(1); + }); + + it('adds brand_category_exclusion to request when set', function() { + let bidRequest = Object.assign({}, bidRequests[0]); + sinon + .stub(config, 'getConfig') + .withArgs('adpod.brandCategoryExclusion') + .returns(true); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.brand_category_uniqueness).to.equal(true); + + config.getConfig.restore(); + }); + + it('should attach native params to the request', function () { + let bidRequest = Object.assign({}, + bidRequests[0], + { + mediaType: 'native', + nativeParams: { + title: {required: true}, + body: {required: true}, + body2: {required: true}, + image: {required: true, sizes: [100, 100]}, + icon: {required: true}, + cta: {required: false}, + rating: {required: true}, + sponsoredBy: {required: true}, + privacyLink: {required: true}, + displayUrl: {required: true}, + address: {required: true}, + downloads: {required: true}, + likes: {required: true}, + phone: {required: true}, + price: {required: true}, + salePrice: {required: true} + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].native.layouts[0]).to.deep.equal({ + title: {required: true}, + description: {required: true}, + desc2: {required: true}, + main_image: {required: true, sizes: [{ width: 100, height: 100 }]}, + icon: {required: true}, + ctatext: {required: false}, + rating: {required: true}, + sponsored_by: {required: true}, + privacy_link: {required: true}, + displayurl: {required: true}, + address: {required: true}, + downloads: {required: true}, + likes: {required: true}, + phone: {required: true}, + price: {required: true}, + saleprice: {required: true}, + privacy_supported: true + }); + expect(payload.tags[0].hb_source).to.equal(1); + }); + + it('should always populated tags[].sizes with 1,1 for native if otherwise not defined', function () { + let bidRequest = Object.assign({}, + bidRequests[0], + { + mediaType: 'native', + nativeParams: { + image: { required: true } + } + } + ); + bidRequest.sizes = [[150, 100], [300, 250]]; + + let request = spec.buildRequests([bidRequest]); + let payload = JSON.parse(request.data); + expect(payload.tags[0].sizes).to.deep.equal([{width: 150, height: 100}, {width: 300, height: 250}]); + + delete bidRequest.sizes; + + request = spec.buildRequests([bidRequest]); + payload = JSON.parse(request.data); + + expect(payload.tags[0].sizes).to.deep.equal([{width: 1, height: 1}]); + }); + + it('should convert keyword params to proper form and attaches to request', function () { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { + placementId: '10433394', + keywords: { + single: 'val', + singleArr: ['val'], + singleArrNum: [5], + multiValMixed: ['value1', 2, 'value3'], + singleValNum: 123, + emptyStr: '', + emptyArr: [''], + badValue: {'foo': 'bar'} // should be dropped + } + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].keywords).to.deep.equal([{ + 'key': 'single', + 'value': ['val'] + }, { + 'key': 'singleArr', + 'value': ['val'] + }, { + 'key': 'singleArrNum', + 'value': ['5'] + }, { + 'key': 'multiValMixed', + 'value': ['value1', '2', 'value3'] + }, { + 'key': 'singleValNum', + 'value': ['123'] + }, { + 'key': 'emptyStr' + }, { + 'key': 'emptyArr' + }]); + }); + + it('should add payment rules to the request', function () { + let bidRequest = Object.assign({}, + bidRequests[0], + { + params: { + placementId: '10433394', + usePaymentRule: true + } + } + ); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].use_pmt_rule).to.equal(true); + }); + + it('should add gpid to the request', function () { + let testGpid = '/12345/my-gpt-tag-0'; + let bidRequest = deepClone(bidRequests[0]); + bidRequest.ortb2Imp = { ext: { data: { pbadslot: testGpid } } }; + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.tags[0].gpid).to.exist.and.equal(testGpid) + }); + + it('should add gdpr consent information to the request', function () { + let consentString = 'BOJ8RZsOJ8RZsABAB8AAAAAZ+A=='; + let bidderRequest = { + 'bidderCode': 'gb_xandr', + 'auctionId': '1d1a030790a475', + 'bidderRequestId': '22edbae2733bf6', + 'timeout': 3000, + 'gdprConsent': { + consentString: consentString, + gdprApplies: true, + addtlConsent: '1~7.12.35.62.66.70.89.93.108' + } + }; + bidderRequest.bids = bidRequests; + + const request = spec.buildRequests(bidRequests, bidderRequest); + expect(request.options).to.deep.equal({withCredentials: true}); + const payload = JSON.parse(request.data); + + expect(payload.gdpr_consent).to.exist; + expect(payload.gdpr_consent.consent_string).to.exist.and.to.equal(consentString); + expect(payload.gdpr_consent.consent_required).to.exist.and.to.be.true; + expect(payload.gdpr_consent.addtl_consent).to.exist.and.to.deep.equal([7, 12, 35, 62, 66, 70, 89, 93, 108]); + }); + + it('should add us privacy string to payload', function() { + let consentString = '1YA-'; + let bidderRequest = { + 'bidderCode': 'gb_xandr', + 'auctionId': '1d1a030790a475', + 'bidderRequestId': '22edbae2733bf6', + 'timeout': 3000, + 'uspConsent': consentString + }; + bidderRequest.bids = bidRequests; + + const request = spec.buildRequests(bidRequests, bidderRequest); + const payload = JSON.parse(request.data); + + expect(payload.us_privacy).to.exist; + expect(payload.us_privacy).to.exist.and.to.equal(consentString); + }); + + it('supports sending hybrid mobile app parameters', function () { + let appRequest = Object.assign({}, + bidRequests[0], + { + params: { + placementId: '10433394', + app: { + id: 'B1O2W3M4AN.com.prebid.webview', + geo: { + lat: 40.0964439, + lng: -75.3009142 + }, + device_id: { + idfa: '4D12078D-3246-4DA4-AD5E-7610481E7AE', // Apple advertising identifier + aaid: '38400000-8cf0-11bd-b23e-10b96e40000d', // Android advertising identifier + md5udid: '5756ae9022b2ea1e47d84fead75220c8', // MD5 hash of the ANDROID_ID + sha1udid: '4DFAA92388699AC6539885AEF1719293879985BF', // SHA1 hash of the ANDROID_ID + windowsadid: '750c6be243f1c4b5c9912b95a5742fc5' // Windows advertising identifier + } + } + } + } + ); + const request = spec.buildRequests([appRequest]); + const payload = JSON.parse(request.data); + expect(payload.app).to.exist; + expect(payload.app).to.deep.equal({ + appid: 'B1O2W3M4AN.com.prebid.webview' + }); + expect(payload.device.device_id).to.exist; + expect(payload.device.device_id).to.deep.equal({ + aaid: '38400000-8cf0-11bd-b23e-10b96e40000d', + idfa: '4D12078D-3246-4DA4-AD5E-7610481E7AE', + md5udid: '5756ae9022b2ea1e47d84fead75220c8', + sha1udid: '4DFAA92388699AC6539885AEF1719293879985BF', + windowsadid: '750c6be243f1c4b5c9912b95a5742fc5' + }); + expect(payload.device.geo).to.exist; + expect(payload.device.geo).to.deep.equal({ + lat: 40.0964439, + lng: -75.3009142 + }); + }); + + it('should add referer info to payload', function () { + const bidRequest = Object.assign({}, bidRequests[0]) + const bidderRequest = { + refererInfo: { + referer: 'https://example.com/page.html', + reachedTop: true, + numIframes: 2, + stack: [ + 'https://example.com/page.html', + 'https://example.com/iframe1.html', + 'https://example.com/iframe2.html' + ] + } + } + const request = spec.buildRequests([bidRequest], bidderRequest); + const payload = JSON.parse(request.data); + + expect(payload.referrer_detection).to.exist; + expect(payload.referrer_detection).to.deep.equal({ + rd_ref: 'https%3A%2F%2Fexample.com%2Fpage.html', + rd_top: true, + rd_ifs: 2, + rd_stk: bidderRequest.refererInfo.stack.map((url) => encodeURIComponent(url)).join(',') + }); + }); + + it('should populate schain if available', function () { + const bidRequest = Object.assign({}, bidRequests[0], { + schain: { + ver: '1.0', + complete: 1, + nodes: [ + { + 'asi': 'blob.com', + 'sid': '001', + 'hp': 1 + } + ] + } + }); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + expect(payload.schain).to.deep.equal({ + ver: '1.0', + complete: 1, + nodes: [ + { + 'asi': 'blob.com', + 'sid': '001', + 'hp': 1 + } + ] + }); + }); + + it('should populate coppa if set in config', function () { + let bidRequest = Object.assign({}, bidRequests[0]); + sinon.stub(config, 'getConfig') + .withArgs('coppa') + .returns(true); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + + expect(payload.user.coppa).to.equal(true); + + config.getConfig.restore(); + }); + + it('should set the X-Is-Test customHeader if test flag is enabled', function () { + let bidRequest = Object.assign({}, bidRequests[0]); + sinon.stub(config, 'getConfig') + .withArgs('apn_test') + .returns(true); + + const request = spec.buildRequests([bidRequest]); + expect(request.options.customHeaders).to.deep.equal({'X-Is-Test': 1}); + + config.getConfig.restore(); + }); + + it('should always set withCredentials: true on the request.options', function () { + let bidRequest = Object.assign({}, bidRequests[0]); + const request = spec.buildRequests([bidRequest]); + expect(request.options.withCredentials).to.equal(true); + }); + + it('should set simple domain variant if purpose 1 consent is not given', function () { + let consentString = 'BOJ8RZsOJ8RZsABAB8AAAAAZ+A=='; + let bidderRequest = { + 'bidderCode': 'gb_xandr', + 'auctionId': '1d1a030790a475', + 'bidderRequestId': '22edbae2733bf6', + 'timeout': 3000, + 'gdprConsent': { + consentString: consentString, + gdprApplies: true, + apiVersion: 2, + vendorData: { + purpose: { + consents: { + 1: false + } + } + } + } + }; + bidderRequest.bids = bidRequests; + + const request = spec.buildRequests(bidRequests, bidderRequest); + expect(request.url).to.equal('https://ib.adnxs-simple.com/ut/v3/prebid'); + }); + + it('should populate eids when supported userIds are available', function () { + const bidRequest = Object.assign({}, bidRequests[0], { + userId: { + tdid: 'sample-userid', + uid2: { id: 'sample-uid2-value' }, + criteoId: 'sample-criteo-userid', + netId: 'sample-netId-userid', + idl_env: 'sample-idl-userid', + flocId: { + id: 'sample-flocid-value', + version: 'chrome.1.0' + } + } + }); + + const request = spec.buildRequests([bidRequest]); + const payload = JSON.parse(request.data); + expect(payload.eids).to.deep.include({ + source: 'adserver.org', + id: 'sample-userid', + rti_partner: 'TDID' + }); + + expect(payload.eids).to.deep.include({ + source: 'criteo.com', + id: 'sample-criteo-userid', + }); + + expect(payload.eids).to.deep.include({ + source: 'chrome.com', + id: 'sample-flocid-value' + }); + + expect(payload.eids).to.deep.include({ + source: 'netid.de', + id: 'sample-netId-userid', + }); + + expect(payload.eids).to.deep.include({ + source: 'liveramp.com', + id: 'sample-idl-userid' + }); + + expect(payload.eids).to.deep.include({ + source: 'uidapi.com', + id: 'sample-uid2-value', + rti_partner: 'UID2' + }); + }); + + it('should populate iab_support object at the root level if omid support is detected', function () { + // with bid.params.frameworks + let bidRequest_A = Object.assign({}, bidRequests[0], { + params: { + frameworks: [1, 2, 5, 6], + video: { + frameworks: [1, 2, 5, 6] + } + } + }); + let request = spec.buildRequests([bidRequest_A]); + let payload = JSON.parse(request.data); + expect(payload.iab_support).to.be.an('object'); + expect(payload.iab_support).to.deep.equal({ + omidpn: 'Appnexus', + omidpv: '$prebid.version$' + }); + expect(payload.tags[0].banner_frameworks).to.be.an('array'); + expect(payload.tags[0].banner_frameworks).to.deep.equal([1, 2, 5, 6]); + expect(payload.tags[0].video_frameworks).to.be.an('array'); + expect(payload.tags[0].video_frameworks).to.deep.equal([1, 2, 5, 6]); + expect(payload.tags[0].video.frameworks).to.not.exist; + + // without bid.params.frameworks + const bidRequest_B = Object.assign({}, bidRequests[0]); + request = spec.buildRequests([bidRequest_B]); + payload = JSON.parse(request.data); + expect(payload.iab_support).to.not.exist; + expect(payload.tags[0].banner_frameworks).to.not.exist; + expect(payload.tags[0].video_frameworks).to.not.exist; + + // with video.frameworks but it is not an array + const bidRequest_C = Object.assign({}, bidRequests[0], { + params: { + video: { + frameworks: "'1', '2', '3', '6'" + } + } + }); + request = spec.buildRequests([bidRequest_C]); + payload = JSON.parse(request.data); + expect(payload.iab_support).to.not.exist; + expect(payload.tags[0].banner_frameworks).to.not.exist; + expect(payload.tags[0].video_frameworks).to.not.exist; + }); + }) + + describe('interpretResponse', function () { + let bfStub; + before(function() { + bfStub = sinon.stub(bidderFactory, 'getIabSubCategory'); + }); + + after(function() { + bfStub.restore(); + }); + + let response = { + 'version': '3.0.0', + 'tags': [ + { + 'uuid': '3db3773286ee59', + 'tag_id': 10433394, + 'auction_id': '4534722592064951574', + 'nobid': false, + 'no_ad_url': 'https://lax1-ib.adnxs.com/no-ad', + 'timeout_ms': 10000, + 'ad_profile_id': 27079, + 'ads': [ + { + 'content_source': 'rtb', + 'ad_type': 'banner', + 'buyer_member_id': 958, + 'creative_id': 29681110, + 'media_type_id': 1, + 'media_subtype_id': 1, + 'cpm': 0.5, + 'cpm_publisher_currency': 0.5, + 'publisher_currency_code': '$', + 'client_initiated_ad_counting': true, + 'viewability': { + 'config': '' + }, + 'rtb': { + 'banner': { + 'content': '', + 'width': 300, + 'height': 250 + }, + 'trackers': [ + { + 'impression_urls': [ + 'https://lax1-ib.adnxs.com/impression' + ], + 'video_events': {} + } + ] + } + } + ] + } + ] + }; + + it('should get correct bid response', function () { + let expectedResponse = [ + { + 'requestId': '3db3773286ee59', + 'cpm': 0.5, + 'creativeId': 29681110, + 'dealId': undefined, + 'width': 300, + 'height': 250, + 'ad': '', + 'mediaType': 'banner', + 'currency': 'USD', + 'ttl': 300, + 'netRevenue': true, + 'adUnitCode': 'code', + 'appnexus': { + 'buyerMemberId': 958 + } + } + ]; + let bidderRequest = { + bids: [{ + bidId: '3db3773286ee59', + adUnitCode: 'code' + }] + } + let result = spec.interpretResponse({ body: response }, {bidderRequest}); + expect(Object.keys(result[0])).to.have.members(Object.keys(expectedResponse[0])); + }); + + it('handles nobid responses', function () { + let response = { + 'version': '0.0.1', + 'tags': [{ + 'uuid': '84ab500420319d', + 'tag_id': 5976557, + 'auction_id': '297492697822162468', + 'nobid': true + }] + }; + let bidderRequest; + + let result = spec.interpretResponse({ body: response }, {bidderRequest}); + expect(result.length).to.equal(0); + }); + + it('handles outstream video responses', function () { + let response = { + 'tags': [{ + 'uuid': '84ab500420319d', + 'ads': [{ + 'ad_type': 'video', + 'cpm': 0.500000, + 'notify_url': 'imptracker.com', + 'rtb': { + 'video': { + 'content': '' + } + }, + 'javascriptTrackers': '' + }] + }] + }; + let bidderRequest = { + bids: [{ + bidId: '84ab500420319d', + adUnitCode: 'code', + mediaTypes: { + video: { + context: 'outstream' + } + } + }] + } + + let result = spec.interpretResponse({ body: response }, {bidderRequest}); + expect(result[0]).to.have.property('vastXml'); + expect(result[0]).to.have.property('vastImpUrl'); + expect(result[0]).to.have.property('mediaType', 'video'); + }); + + it('handles instream video responses', function () { + let response = { + 'tags': [{ + 'uuid': '84ab500420319d', + 'ads': [{ + 'ad_type': 'video', + 'cpm': 0.500000, + 'notify_url': 'imptracker.com', + 'rtb': { + 'video': { + 'asset_url': 'https://sample.vastURL.com/here/vid' + } + }, + 'javascriptTrackers': '' + }] + }] + }; + let bidderRequest = { + bids: [{ + bidId: '84ab500420319d', + adUnitCode: 'code', + mediaTypes: { + video: { + context: 'instream' + } + } + }] + } + + let result = spec.interpretResponse({ body: response }, {bidderRequest}); + expect(result[0]).to.have.property('vastUrl'); + expect(result[0]).to.have.property('vastImpUrl'); + expect(result[0]).to.have.property('mediaType', 'video'); + }); + + it('handles adpod responses', function () { + let response = { + 'tags': [{ + 'uuid': '84ab500420319d', + 'ads': [{ + 'ad_type': 'video', + 'brand_category_id': 10, + 'cpm': 0.500000, + 'notify_url': 'imptracker.com', + 'rtb': { + 'video': { + 'asset_url': 'https://sample.vastURL.com/here/adpod', + 'duration_ms': 30000, + } + }, + 'viewability': { + 'config': '' + } + }] + }] + }; + + let bidderRequest = { + bids: [{ + bidId: '84ab500420319d', + adUnitCode: 'code', + mediaTypes: { + video: { + context: 'adpod' + } + } + }] + }; + bfStub.returns('1'); + + let result = spec.interpretResponse({ body: response }, {bidderRequest}); + expect(result[0]).to.have.property('vastUrl'); + expect(result[0].video.context).to.equal('adpod'); + expect(result[0].video.durationSeconds).to.equal(30); + }); + + it('handles native responses', function () { + let response1 = deepClone(response); + response1.tags[0].ads[0].ad_type = 'native'; + response1.tags[0].ads[0].rtb.native = { + 'title': 'Native Creative', + 'desc': 'Cool description great stuff', + 'desc2': 'Additional body text', + 'ctatext': 'Do it', + 'sponsored': 'AppNexus', + 'icon': { + 'width': 0, + 'height': 0, + 'url': 'https://cdn.adnxs.com/icon.png' + }, + 'main_img': { + 'width': 2352, + 'height': 1516, + 'url': 'https://cdn.adnxs.com/img.png' + }, + 'link': { + 'url': 'https://www.appnexus.com', + 'fallback_url': '', + 'click_trackers': ['https://nym1-ib.adnxs.com/click'] + }, + 'impression_trackers': ['https://example.com'], + 'rating': '5', + 'displayurl': 'https://AppNexus.com/?url=display_url', + 'likes': '38908320', + 'downloads': '874983', + 'price': '9.99', + 'saleprice': 'FREE', + 'phone': '1234567890', + 'address': '28 W 23rd St, New York, NY 10010', + 'privacy_link': 'https://appnexus.com/?url=privacy_url', + 'javascriptTrackers': '' + }; + let bidderRequest = { + bids: [{ + bidId: '3db3773286ee59', + adUnitCode: 'code' + }] + } + + let result = spec.interpretResponse({ body: response1 }, {bidderRequest}); + expect(result[0].native.title).to.equal('Native Creative'); + expect(result[0].native.body).to.equal('Cool description great stuff'); + expect(result[0].native.cta).to.equal('Do it'); + expect(result[0].native.image.url).to.equal('https://cdn.adnxs.com/img.png'); + }); + + it('supports configuring outstream renderers', function () { + const outstreamResponse = deepClone(response); + outstreamResponse.tags[0].ads[0].rtb.video = {}; + outstreamResponse.tags[0].ads[0].renderer_url = 'renderer.js'; + + const bidderRequest = { + bids: [{ + bidId: '3db3773286ee59', + renderer: { + options: { + adText: 'configured' + } + }, + mediaTypes: { + video: { + context: 'outstream' + } + } + }] + }; + + const result = spec.interpretResponse({ body: outstreamResponse }, {bidderRequest}); + expect(result[0].renderer.config).to.deep.equal( + bidderRequest.bids[0].renderer.options + ); + }); + + it('should add deal_priority and deal_code', function() { + let responseWithDeal = deepClone(response); + responseWithDeal.tags[0].ads[0].ad_type = 'video'; + responseWithDeal.tags[0].ads[0].deal_priority = 5; + responseWithDeal.tags[0].ads[0].deal_code = '123'; + responseWithDeal.tags[0].ads[0].rtb.video = { + duration_ms: 1500, + player_width: 640, + player_height: 340, + }; + + let bidderRequest = { + bids: [{ + bidId: '3db3773286ee59', + adUnitCode: 'code', + mediaTypes: { + video: { + context: 'adpod' + } + } + }] + } + let result = spec.interpretResponse({ body: responseWithDeal }, {bidderRequest}); + expect(Object.keys(result[0].appnexus)).to.include.members(['buyerMemberId', 'dealPriority', 'dealCode']); + expect(result[0].video.dealTier).to.equal(5); + }); + + it('should add advertiser id', function() { + let responseAdvertiserId = deepClone(response); + responseAdvertiserId.tags[0].ads[0].advertiser_id = '123'; + + let bidderRequest = { + bids: [{ + bidId: '3db3773286ee59', + adUnitCode: 'code' + }] + } + let result = spec.interpretResponse({ body: responseAdvertiserId }, {bidderRequest}); + expect(Object.keys(result[0].meta)).to.include.members(['advertiserId']); + }); + + it('should add advertiserDomains', function() { + let responseAdvertiserId = deepClone(response); + responseAdvertiserId.tags[0].ads[0].adomain = ['123']; + + let bidderRequest = { + bids: [{ + bidId: '3db3773286ee59', + adUnitCode: 'code' + }] + } + let result = spec.interpretResponse({ body: responseAdvertiserId }, {bidderRequest}); + expect(Object.keys(result[0].meta)).to.include.members(['advertiserDomains']); + expect(Object.keys(result[0].meta.advertiserDomains)).to.deep.equal([]); + }); + }); +}); From ba6d86083350d132a1282ef0afe47ca3dd5414e9 Mon Sep 17 00:00:00 2001 From: Dusan Veljovic Date: Tue, 2 Nov 2021 08:24:56 +0100 Subject: [PATCH 2/7] updated logic --- modules/goldbachXandrBidAdapter.js | 65 ++++++++- .../modules/goldbachXandrBidAdapter_spec.js | 129 +++++++++--------- 2 files changed, 130 insertions(+), 64 deletions(-) diff --git a/modules/goldbachXandrBidAdapter.js b/modules/goldbachXandrBidAdapter.js index e73e2ce2802..93cca45395c 100644 --- a/modules/goldbachXandrBidAdapter.js +++ b/modules/goldbachXandrBidAdapter.js @@ -11,6 +11,7 @@ import { getStorageManager } from '../src/storageManager.js'; const BIDDER_CODE = 'gb_xandr'; const URL = 'https://ib.adnxs.com/ut/v3/prebid'; +const PRICING_URL = 'https://templates.da-services.ch/01_universal/burda_prebid/1.0/json/sizeCPMMapping.json'; const URL_SIMPLE = 'https://ib.adnxs-simple.com/ut/v3/prebid'; const VIDEO_TARGETING = ['id', 'minduration', 'maxduration', 'skippable', 'playback_method', 'frameworks', 'context', 'skipoffset']; @@ -18,6 +19,13 @@ const VIDEO_RTB_TARGETING = ['minduration', 'maxduration', 'skip', 'skipafter', const USER_PARAMS = ['age', 'externalUid', 'segments', 'gender', 'dnt', 'language']; const APP_DEVICE_PARAMS = ['geo', 'device_id']; // appid is collected separately const DEBUG_PARAMS = ['enabled', 'dongle', 'member_id', 'debug_timeout']; +const DEFAULT_PRICE_MAPPING = { + '0x0': 2.5, + '300x600': 5, + '800x250': 6, + '350x600': 6 +}; +let PRICE_MAPPING; const VIDEO_MAPPING = { playback_method: { 'unknown': 0, @@ -97,7 +105,19 @@ export const spec = { * @return ServerRequest Info describing the request to the server. */ buildRequests: function (bidRequests, bidderRequest) { - const tags = bidRequests.map(bidToTag); + let localBidRequests = []; + bidRequests.forEach(bid => { + if (Array.isArray(bid.params.placementId)) { + const ids = bid.params.placementId; + for (let i = 0; i < ids.length; i++) { + const newBid = Object.assign({}, bid, {params: {placementId: ids[i]}}); + localBidRequests.push(newBid) + } + } else { + localBidRequests.push(bid); + } + }); + const tags = localBidRequests.map(bidToTag); const userObjBid = find(bidRequests, hasUserInfo); let userObj = {}; if (config.getConfig('coppa') === true) { @@ -268,7 +288,45 @@ export const spec = { } const request = formatRequest(payload, bidderRequest); - return request; + // add pricing endpoint + return [{method: 'GET', url: PRICING_URL, options: {withCredentials: false}}, request]; + }, + + parseAndMapCpm: function(serverResponse) { + const responseBody = serverResponse.body; + if (Array.isArray(responseBody) && responseBody.length) { + let localData = {}; + responseBody.forEach(cpmPerSize => { + Object.keys(cpmPerSize).forEach(size => { + let obj = {}; + obj[size] = cpmPerSize[size]; + localData = Object.assign({}, localData, obj) + }) + }) + PRICE_MAPPING = localData; + return null; + } + + if (responseBody.version) { + const localPriceMapping = PRICE_MAPPING || DEFAULT_PRICE_MAPPING; + if (responseBody.tags && Array.isArray(responseBody.tags) && responseBody.tags.length) { + responseBody.tags.forEach((tag) => { + if (tag.ads && Array.isArray(tag.ads) && tag.ads.length) { + tag.ads.forEach(ad => { + if (ad.ad_type === 'banner') { + const size = `${ad.rtb.banner.width}x${ad.rtb.banner.height}`; + if (localPriceMapping[size]) { + ad.cpm = localPriceMapping[size]; + } else { + ad.cpm = localPriceMapping['0x0']; + } + } + }) + } + }); + } + } + return responseBody; }, /** @@ -278,7 +336,8 @@ export const spec = { * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: function (serverResponse, { bidderRequest }) { - serverResponse = serverResponse.body; + serverResponse = this.parseAndMapCpm(serverResponse); + if (!serverResponse) return []; const bids = []; if (!serverResponse || serverResponse.error) { let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`; diff --git a/test/spec/modules/goldbachXandrBidAdapter_spec.js b/test/spec/modules/goldbachXandrBidAdapter_spec.js index b5eb71e96d0..13c37740cf7 100644 --- a/test/spec/modules/goldbachXandrBidAdapter_spec.js +++ b/test/spec/modules/goldbachXandrBidAdapter_spec.js @@ -7,6 +7,7 @@ import { deepClone } from 'src/utils.js'; import { config } from 'src/config.js'; const ENDPOINT = 'https://ib.adnxs.com/ut/v3/prebid'; +const PRICING_ENDPOINT = 'https://templates.da-services.ch/01_universal/burda_prebid/1.0/json/sizeCPMMapping.json'; describe('GoldbachXandrAdapter', function () { const adapter = newBidder(spec); @@ -93,7 +94,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].private_sizes).to.exist; @@ -109,7 +110,7 @@ describe('GoldbachXandrAdapter', function () { publisherId: '1231234' } }); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].publisher_id).to.exist; @@ -119,7 +120,7 @@ describe('GoldbachXandrAdapter', function () { }) it('should add source and verison to the tag', function () { - const request = spec.buildRequests(bidRequests); + const request = spec.buildRequests(bidRequests)[1]; const payload = JSON.parse(request.data); expect(payload.sdk).to.exist; expect(payload.sdk).to.deep.equal({ @@ -154,7 +155,7 @@ describe('GoldbachXandrAdapter', function () { bidRequest.mediaTypes = {}; bidRequest.mediaTypes[type] = {}; - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].ad_types).to.deep.equal([type]); @@ -167,7 +168,7 @@ describe('GoldbachXandrAdapter', function () { it('should not populate the ad_types array when adUnit.mediaTypes is undefined', function() { const bidRequest = Object.assign({}, bidRequests[0]); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].ad_types).to.not.exist; @@ -178,7 +179,7 @@ describe('GoldbachXandrAdapter', function () { bidRequest.mediaTypes = {}; bidRequest.mediaTypes.video = {context: 'outstream'}; - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].ad_types).to.deep.equal(['video']); @@ -186,11 +187,17 @@ describe('GoldbachXandrAdapter', function () { }); it('sends bid request to ENDPOINT via POST', function () { - const request = spec.buildRequests(bidRequests); + const request = spec.buildRequests(bidRequests)[1]; expect(request.url).to.equal(ENDPOINT); expect(request.method).to.equal('POST'); }); + it('sends bid request to ENDPOINT via GET', function () { + const request = spec.buildRequests(bidRequests)[0]; + expect(request.url).to.equal(PRICING_ENDPOINT); + expect(request.method).to.equal('GET'); + }); + it('should attach valid video params to the tag', function () { let bidRequest = Object.assign({}, bidRequests[0], @@ -206,7 +213,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].video).to.deep.equal({ id: 123, @@ -237,7 +244,7 @@ describe('GoldbachXandrAdapter', function () { } }; - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].video).to.deep.equal({ @@ -278,7 +285,7 @@ describe('GoldbachXandrAdapter', function () { bidRequest2.adUnitCode = 'adUnit_code_2'; bidRequest2 = Object.assign({}, bidRequest2, videoData); - const request = spec.buildRequests([bidRequest1, bidRequest2]); + const request = spec.buildRequests([bidRequest1, bidRequest2])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].video).to.deep.equal({ skippable: true, @@ -306,7 +313,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.user).to.exist; @@ -322,7 +329,7 @@ describe('GoldbachXandrAdapter', function () { let bidRequest = deepClone(bidRequests[0]); // 1 -> reserve not defined, getFloor not defined > empty - request = spec.buildRequests([bidRequest]); + request = spec.buildRequests([bidRequest])[1]; payload = JSON.parse(request.data); expect(payload.tags[0].reserve).to.not.exist; @@ -332,7 +339,7 @@ describe('GoldbachXandrAdapter', function () { 'placementId': '10433394', 'reserve': 0.5 }; - request = spec.buildRequests([bidRequest]); + request = spec.buildRequests([bidRequest])[1]; payload = JSON.parse(request.data); expect(payload.tags[0].reserve).to.exist.and.to.equal(0.5); @@ -340,7 +347,7 @@ describe('GoldbachXandrAdapter', function () { // 3 -> reserve is defined, getFloor is defined > getFloor is used bidRequest.getFloor = () => getFloorResponse; - request = spec.buildRequests([bidRequest]); + request = spec.buildRequests([bidRequest])[1]; payload = JSON.parse(request.data); expect(payload.tags[0].reserve).to.exist.and.to.equal(3); @@ -364,7 +371,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload1 = JSON.parse(request[0].data); const payload2 = JSON.parse(request[1].data); @@ -397,7 +404,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags.length).to.equal(2); }); @@ -422,7 +429,7 @@ describe('GoldbachXandrAdapter', function () { ); // 20 total placements with 15 max impressions = 2 requests - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; expect(request.length).to.equal(2); // 20 spread over 2 requests = 15 in first request, 5 in second @@ -463,7 +470,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags.length).to.equal(7); @@ -493,7 +500,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload1 = JSON.parse(request[0].data); const payload2 = JSON.parse(request[1].data); const payload3 = JSON.parse(request[2].data); @@ -503,27 +510,27 @@ describe('GoldbachXandrAdapter', function () { expect(payload3.tags.length).to.equal(15); }); - it('should contain hb_source value for adpod', function() { - let bidRequest = Object.assign({}, - bidRequests[0], - { - params: { placementId: '14542875' } - }, - { - mediaTypes: { - video: { - context: 'adpod', - playerSize: [640, 480], - adPodDurationSec: 300, - durationRangeSec: [15, 30], - } - } - } - ); - const request = spec.buildRequests([bidRequest])[0]; - const payload = JSON.parse(request.data); - expect(payload.tags[0].hb_source).to.deep.equal(7); - }); + // it('should contain hb_source value for adpod', function() { + // let bidRequest = Object.assign({}, + // bidRequests[0], + // { + // params: { placementId: '14542875' } + // }, + // { + // mediaTypes: { + // video: { + // context: 'adpod', + // playerSize: [640, 480], + // adPodDurationSec: 300, + // durationRangeSec: [15, 30], + // } + // } + // } + // ); + // const request = spec.buildRequests([bidRequest])[1]; + // const payload = JSON.parse(request.data); + // expect(payload.tags[0].hb_source).to.deep.equal(7); + // }); it('should contain hb_source value for other media', function() { let bidRequest = Object.assign({}, @@ -536,7 +543,7 @@ describe('GoldbachXandrAdapter', function () { } } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].hb_source).to.deep.equal(1); }); @@ -548,7 +555,7 @@ describe('GoldbachXandrAdapter', function () { .withArgs('adpod.brandCategoryExclusion') .returns(true); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.brand_category_uniqueness).to.equal(true); @@ -582,7 +589,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].native.layouts[0]).to.deep.equal({ @@ -619,13 +626,13 @@ describe('GoldbachXandrAdapter', function () { ); bidRequest.sizes = [[150, 100], [300, 250]]; - let request = spec.buildRequests([bidRequest]); + let request = spec.buildRequests([bidRequest])[1]; let payload = JSON.parse(request.data); expect(payload.tags[0].sizes).to.deep.equal([{width: 150, height: 100}, {width: 300, height: 250}]); delete bidRequest.sizes; - request = spec.buildRequests([bidRequest]); + request = spec.buildRequests([bidRequest])[1]; payload = JSON.parse(request.data); expect(payload.tags[0].sizes).to.deep.equal([{width: 1, height: 1}]); @@ -651,7 +658,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].keywords).to.deep.equal([{ @@ -687,7 +694,7 @@ describe('GoldbachXandrAdapter', function () { } ); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].use_pmt_rule).to.equal(true); @@ -698,7 +705,7 @@ describe('GoldbachXandrAdapter', function () { let bidRequest = deepClone(bidRequests[0]); bidRequest.ortb2Imp = { ext: { data: { pbadslot: testGpid } } }; - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.tags[0].gpid).to.exist.and.equal(testGpid) @@ -719,7 +726,7 @@ describe('GoldbachXandrAdapter', function () { }; bidderRequest.bids = bidRequests; - const request = spec.buildRequests(bidRequests, bidderRequest); + const request = spec.buildRequests(bidRequests, bidderRequest)[1]; expect(request.options).to.deep.equal({withCredentials: true}); const payload = JSON.parse(request.data); @@ -740,7 +747,7 @@ describe('GoldbachXandrAdapter', function () { }; bidderRequest.bids = bidRequests; - const request = spec.buildRequests(bidRequests, bidderRequest); + const request = spec.buildRequests(bidRequests, bidderRequest)[1]; const payload = JSON.parse(request.data); expect(payload.us_privacy).to.exist; @@ -770,7 +777,7 @@ describe('GoldbachXandrAdapter', function () { } } ); - const request = spec.buildRequests([appRequest]); + const request = spec.buildRequests([appRequest])[1]; const payload = JSON.parse(request.data); expect(payload.app).to.exist; expect(payload.app).to.deep.equal({ @@ -805,7 +812,7 @@ describe('GoldbachXandrAdapter', function () { ] } } - const request = spec.buildRequests([bidRequest], bidderRequest); + const request = spec.buildRequests([bidRequest], bidderRequest)[1]; const payload = JSON.parse(request.data); expect(payload.referrer_detection).to.exist; @@ -832,7 +839,7 @@ describe('GoldbachXandrAdapter', function () { } }); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.schain).to.deep.equal({ ver: '1.0', @@ -853,7 +860,7 @@ describe('GoldbachXandrAdapter', function () { .withArgs('coppa') .returns(true); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.user.coppa).to.equal(true); @@ -867,7 +874,7 @@ describe('GoldbachXandrAdapter', function () { .withArgs('apn_test') .returns(true); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; expect(request.options.customHeaders).to.deep.equal({'X-Is-Test': 1}); config.getConfig.restore(); @@ -875,7 +882,7 @@ describe('GoldbachXandrAdapter', function () { it('should always set withCredentials: true on the request.options', function () { let bidRequest = Object.assign({}, bidRequests[0]); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; expect(request.options.withCredentials).to.equal(true); }); @@ -901,7 +908,7 @@ describe('GoldbachXandrAdapter', function () { }; bidderRequest.bids = bidRequests; - const request = spec.buildRequests(bidRequests, bidderRequest); + const request = spec.buildRequests(bidRequests, bidderRequest)[1]; expect(request.url).to.equal('https://ib.adnxs-simple.com/ut/v3/prebid'); }); @@ -920,7 +927,7 @@ describe('GoldbachXandrAdapter', function () { } }); - const request = spec.buildRequests([bidRequest]); + const request = spec.buildRequests([bidRequest])[1]; const payload = JSON.parse(request.data); expect(payload.eids).to.deep.include({ source: 'adserver.org', @@ -965,7 +972,7 @@ describe('GoldbachXandrAdapter', function () { } } }); - let request = spec.buildRequests([bidRequest_A]); + let request = spec.buildRequests([bidRequest_A])[1]; let payload = JSON.parse(request.data); expect(payload.iab_support).to.be.an('object'); expect(payload.iab_support).to.deep.equal({ @@ -980,7 +987,7 @@ describe('GoldbachXandrAdapter', function () { // without bid.params.frameworks const bidRequest_B = Object.assign({}, bidRequests[0]); - request = spec.buildRequests([bidRequest_B]); + request = spec.buildRequests([bidRequest_B])[1]; payload = JSON.parse(request.data); expect(payload.iab_support).to.not.exist; expect(payload.tags[0].banner_frameworks).to.not.exist; @@ -994,7 +1001,7 @@ describe('GoldbachXandrAdapter', function () { } } }); - request = spec.buildRequests([bidRequest_C]); + request = spec.buildRequests([bidRequest_C])[1]; payload = JSON.parse(request.data); expect(payload.iab_support).to.not.exist; expect(payload.tags[0].banner_frameworks).to.not.exist; From f57e15870475af470596ee966f3db4c583a14c32 Mon Sep 17 00:00:00 2001 From: Dusan Veljovic Date: Mon, 8 Nov 2021 08:41:30 +0100 Subject: [PATCH 3/7] removed serverResponse condition from interpretResponse --- modules/goldbachXandrBidAdapter.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/modules/goldbachXandrBidAdapter.js b/modules/goldbachXandrBidAdapter.js index 93cca45395c..d3708ad990f 100644 --- a/modules/goldbachXandrBidAdapter.js +++ b/modules/goldbachXandrBidAdapter.js @@ -339,9 +339,8 @@ export const spec = { serverResponse = this.parseAndMapCpm(serverResponse); if (!serverResponse) return []; const bids = []; - if (!serverResponse || serverResponse.error) { - let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`; - if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; } + if (serverResponse.error) { + let errorMessage = `in response for ${bidderRequest.bidderCode} adapter : ${serverResponse.error}`; utils.logError(errorMessage); return bids; } From c4f1048295bc6761b47fca1bf1bef3c7e8fdbf6f Mon Sep 17 00:00:00 2001 From: Dusan Veljovic Date: Tue, 9 Nov 2021 11:29:07 +0100 Subject: [PATCH 4/7] removed xandr reference --- ...ndrBidAdapter.js => goldbachBidAdapter.js} | 26 +++++-------------- ...ndrBidAdapter.md => goldbachBidAdapter.md} | 18 ++++++------- ...ter_spec.js => goldbachBidAdapter_spec.js} | 14 +++++----- 3 files changed, 22 insertions(+), 36 deletions(-) rename modules/{goldbachXandrBidAdapter.js => goldbachBidAdapter.js} (97%) rename modules/{goldbachXandrBidAdapter.md => goldbachBidAdapter.md} (90%) rename test/spec/modules/{goldbachXandrBidAdapter_spec.js => goldbachBidAdapter_spec.js} (99%) diff --git a/modules/goldbachXandrBidAdapter.js b/modules/goldbachBidAdapter.js similarity index 97% rename from modules/goldbachXandrBidAdapter.js rename to modules/goldbachBidAdapter.js index d3708ad990f..85152b7f277 100644 --- a/modules/goldbachXandrBidAdapter.js +++ b/modules/goldbachBidAdapter.js @@ -9,7 +9,7 @@ import includes from 'core-js-pure/features/array/includes.js'; import { OUTSTREAM, INSTREAM } from '../src/video.js'; import { getStorageManager } from '../src/storageManager.js'; -const BIDDER_CODE = 'gb_xandr'; +const BIDDER_CODE = 'godlbach'; const URL = 'https://ib.adnxs.com/ut/v3/prebid'; const PRICING_URL = 'https://templates.da-services.ch/01_universal/burda_prebid/1.0/json/sizeCPMMapping.json'; const URL_SIMPLE = 'https://ib.adnxs-simple.com/ut/v3/prebid'; @@ -73,19 +73,6 @@ const storage = getStorageManager(GVLID, BIDDER_CODE); export const spec = { code: BIDDER_CODE, gvlid: GVLID, - aliases: [ - { code: 'appnexusAst', gvlid: 32 }, - { code: 'emxdigital', gvlid: 183 }, - { code: 'pagescience' }, - { code: 'defymedia' }, - { code: 'gourmetads' }, - { code: 'matomy' }, - { code: 'featureforward' }, - { code: 'oftmedia' }, - { code: 'districtm', gvlid: 144 }, - { code: 'adasta' }, - { code: 'beintoo', gvlid: 618 }, - ], supportedMediaTypes: [BANNER, VIDEO, NATIVE], /** @@ -170,7 +157,7 @@ export const spec = { try { debugObj = JSON.parse(debugCookie); } catch (e) { - utils.logError('AppNexus Debug Auction Cookie Error:\n\n' + e); + utils.logError('Debug Auction Cookie Error:\n\n' + e); } } else { const debugBidRequest = find(bidRequests, hasDebug); @@ -226,7 +213,7 @@ export const spec = { if (debugObjParams.enabled) { payload.debug = debugObjParams; - utils.logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); + utils.logInfo('Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); } if (bidderRequest && bidderRequest.gdprConsent) { @@ -369,7 +356,6 @@ export const spec = { .replace(/

(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1 .replace(/(.*)<\/h[2-6]>/gm, '\n\n*** $1 ***\n\n') // Headers .replace(/(<([^>]+)>)/igm, ''); // Remove any other tags - utils.logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction'); utils.logMessage(debugText); } @@ -610,10 +596,10 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { } renderer.setEventHandlers({ - impression: () => utils.logMessage('AppNexus outstream video impression event'), - loaded: () => utils.logMessage('AppNexus outstream video loaded event'), + impression: () => utils.logMessage('Outstream video impression event'), + loaded: () => utils.logMessage('Outstream video loaded event'), ended: () => { - utils.logMessage('AppNexus outstream renderer video event'); + utils.logMessage('Outstream renderer video event'); document.querySelector(`#${adUnitCode}`).style.display = 'none'; } }); diff --git a/modules/goldbachXandrBidAdapter.md b/modules/goldbachBidAdapter.md similarity index 90% rename from modules/goldbachXandrBidAdapter.md rename to modules/goldbachBidAdapter.md index 57b2b084f6e..f7c9479439b 100644 --- a/modules/goldbachXandrBidAdapter.md +++ b/modules/goldbachBidAdapter.md @@ -1,7 +1,7 @@ #Overview ``` -Module Name: Goldbach Xander Bid Adapter +Module Name: Goldbach Bid Adapter Module Type: Bidder Adapter Maintainer: dusan.veljovic@goldbach.com ``` @@ -10,7 +10,7 @@ Maintainer: dusan.veljovic@goldbach.com Connects to Xandr exchange for bids. -Goldbach Xandr bid adapter supports Banner, Video (instream and outstream) and Native. +Goldbach bid adapter supports Banner, Video (instream and outstream) and Native. # Test Parameters ``` @@ -24,7 +24,7 @@ var adUnits = [ } }, bids: [{ - bidder: 'gb_xandr', + bidder: 'goldbach', params: { placementId: 13144370 } @@ -54,7 +54,7 @@ var adUnits = [ } }, bids: [{ - bidder: 'gb_xandr', + bidder: 'goldbach', params: { placementId: 13232354, allowSmallerSizes: true @@ -72,7 +72,7 @@ var adUnits = [ }, }, bids: [{ - gb_xandr: 'gb_xandr', + goldbach: 'goldbach', params: { placementId: 13232361, video: { @@ -91,8 +91,8 @@ var adUnits = [ playerSize: [[300, 250]], context: 'outstream', // Certain ORTB 2.5 video values can be read from the mediatypes object; below are examples of supported params. - // To note - gb_xandr supports additional values for our system that are not part of the ORTB spec. If you want - // to use these values, they will have to be declared in the bids[].params.video object instead using the gb_xandr syntax. + // To note - goldbach supports additional values for our system that are not part of the ORTB spec. If you want + // to use these values, they will have to be declared in the bids[].params.video object instead using the goldbach syntax. // Between the corresponding values of the mediaTypes.video and params.video objects, the properties in params.video will // take precedence if declared; eg in the example below, the `skippable: true` setting will be used instead of the `skip: 0`. minduration: 1, @@ -105,7 +105,7 @@ var adUnits = [ }, bids: [ { - bidder: 'gb_xandr', + bidder: 'goldbach', params: { placementId: 13232385, video: { @@ -127,7 +127,7 @@ var adUnits = [ } } bids: [{ - bidder: 'gb_xandr', + bidder: 'goldbach', params: { placementId: 13144370, app: { diff --git a/test/spec/modules/goldbachXandrBidAdapter_spec.js b/test/spec/modules/goldbachBidAdapter_spec.js similarity index 99% rename from test/spec/modules/goldbachXandrBidAdapter_spec.js rename to test/spec/modules/goldbachBidAdapter_spec.js index 13c37740cf7..91d67fa0461 100644 --- a/test/spec/modules/goldbachXandrBidAdapter_spec.js +++ b/test/spec/modules/goldbachBidAdapter_spec.js @@ -1,5 +1,5 @@ import { expect } from 'chai'; -import { spec } from 'modules/goldbachXandrBidAdapter.js'; +import { spec } from 'modules/goldbachBidAdapter.js'; import { newBidder } from 'src/adapters/bidderFactory.js'; import * as bidderFactory from 'src/adapters/bidderFactory.js'; import { auctionManager } from 'src/auctionManager.js'; @@ -20,7 +20,7 @@ describe('GoldbachXandrAdapter', function () { describe('isBidRequestValid', function () { let bid = { - 'bidder': 'gb_xandr', + 'bidder': 'godlbach', 'params': { 'placementId': '10433394' }, @@ -60,7 +60,7 @@ describe('GoldbachXandrAdapter', function () { let getAdUnitsStub; let bidRequests = [ { - 'bidder': 'gb_xandr', + 'bidder': 'goldbach', 'params': { 'placementId': '10433394' }, @@ -138,7 +138,7 @@ describe('GoldbachXandrAdapter', function () { } }, bids: [{ - bidder: 'gb_xandr', + bidder: 'goldbach', params: { placementId: '10433394' } @@ -714,7 +714,7 @@ describe('GoldbachXandrAdapter', function () { it('should add gdpr consent information to the request', function () { let consentString = 'BOJ8RZsOJ8RZsABAB8AAAAAZ+A=='; let bidderRequest = { - 'bidderCode': 'gb_xandr', + 'bidderCode': 'goldbach', 'auctionId': '1d1a030790a475', 'bidderRequestId': '22edbae2733bf6', 'timeout': 3000, @@ -739,7 +739,7 @@ describe('GoldbachXandrAdapter', function () { it('should add us privacy string to payload', function() { let consentString = '1YA-'; let bidderRequest = { - 'bidderCode': 'gb_xandr', + 'bidderCode': 'goldbach', 'auctionId': '1d1a030790a475', 'bidderRequestId': '22edbae2733bf6', 'timeout': 3000, @@ -889,7 +889,7 @@ describe('GoldbachXandrAdapter', function () { it('should set simple domain variant if purpose 1 consent is not given', function () { let consentString = 'BOJ8RZsOJ8RZsABAB8AAAAAZ+A=='; let bidderRequest = { - 'bidderCode': 'gb_xandr', + 'bidderCode': 'goldbach', 'auctionId': '1d1a030790a475', 'bidderRequestId': '22edbae2733bf6', 'timeout': 3000, From a7ef2c0da2dd511f2975d38384a3f167dd755c5f Mon Sep 17 00:00:00 2001 From: Dusan Veljovic Date: Tue, 16 Nov 2021 16:29:10 +0100 Subject: [PATCH 5/7] fixed typo --- modules/goldbachBidAdapter.js | 2 +- test/spec/modules/goldbachBidAdapter_spec.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/goldbachBidAdapter.js b/modules/goldbachBidAdapter.js index 85152b7f277..69229d108bb 100644 --- a/modules/goldbachBidAdapter.js +++ b/modules/goldbachBidAdapter.js @@ -9,7 +9,7 @@ import includes from 'core-js-pure/features/array/includes.js'; import { OUTSTREAM, INSTREAM } from '../src/video.js'; import { getStorageManager } from '../src/storageManager.js'; -const BIDDER_CODE = 'godlbach'; +const BIDDER_CODE = 'goldbach'; const URL = 'https://ib.adnxs.com/ut/v3/prebid'; const PRICING_URL = 'https://templates.da-services.ch/01_universal/burda_prebid/1.0/json/sizeCPMMapping.json'; const URL_SIMPLE = 'https://ib.adnxs-simple.com/ut/v3/prebid'; diff --git a/test/spec/modules/goldbachBidAdapter_spec.js b/test/spec/modules/goldbachBidAdapter_spec.js index 91d67fa0461..459cda7958f 100644 --- a/test/spec/modules/goldbachBidAdapter_spec.js +++ b/test/spec/modules/goldbachBidAdapter_spec.js @@ -20,7 +20,7 @@ describe('GoldbachXandrAdapter', function () { describe('isBidRequestValid', function () { let bid = { - 'bidder': 'godlbach', + 'bidder': 'goldbach', 'params': { 'placementId': '10433394' }, From 0b61f264c3a7f1d2abc0eadffd914cade84e7a45 Mon Sep 17 00:00:00 2001 From: Dusan Veljovic Date: Tue, 16 Nov 2021 17:20:12 +0100 Subject: [PATCH 6/7] removed gvlid and storage manager --- modules/goldbachBidAdapter.js | 21 +++------------------ 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/modules/goldbachBidAdapter.js b/modules/goldbachBidAdapter.js index 69229d108bb..ffa78be4332 100644 --- a/modules/goldbachBidAdapter.js +++ b/modules/goldbachBidAdapter.js @@ -7,7 +7,6 @@ import { auctionManager } from '../src/auctionManager.js'; import find from 'core-js-pure/features/array/find.js'; import includes from 'core-js-pure/features/array/includes.js'; import { OUTSTREAM, INSTREAM } from '../src/video.js'; -import { getStorageManager } from '../src/storageManager.js'; const BIDDER_CODE = 'goldbach'; const URL = 'https://ib.adnxs.com/ut/v3/prebid'; @@ -67,12 +66,9 @@ const mappingFileUrl = 'https://acdn.adnxs-simple.com/prebid/appnexus-mapping/ma const SCRIPT_TAG_START = ' Date: Wed, 17 Nov 2021 09:44:16 +0100 Subject: [PATCH 7/7] changed utils import to named --- modules/goldbachBidAdapter.js | 137 ++++++++++++++++++++-------------- 1 file changed, 80 insertions(+), 57 deletions(-) diff --git a/modules/goldbachBidAdapter.js b/modules/goldbachBidAdapter.js index ffa78be4332..8057925a62c 100644 --- a/modules/goldbachBidAdapter.js +++ b/modules/goldbachBidAdapter.js @@ -1,5 +1,28 @@ import { Renderer } from '../src/Renderer.js'; -import * as utils from '../src/utils.js'; +import { + isEmpty, + convertCamelToUnderscore, + isFn, + createTrackPixelHtml, + convertTypes, + deepClone, + fill, + getParameterByName, + getMaxValueFromArray, + getMinValueFromArray, + chunk, + isArray, + isArrayOfNums, + isNumber, + isStr, + isPlainObject, + logError, + logInfo, + logMessage, + deepAccess, + getBidRequest, + transformBidderParamKeywords +} from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder, getIabSubCategory } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO, ADPOD } from '../src/mediaTypes.js'; @@ -110,13 +133,13 @@ export const spec = { Object.keys(userObjBid.params.user) .filter(param => includes(USER_PARAMS, param)) .forEach((param) => { - let uparam = utils.convertCamelToUnderscore(param); - if (param === 'segments' && utils.isArray(userObjBid.params.user[param])) { + let uparam = convertCamelToUnderscore(param); + if (param === 'segments' && isArray(userObjBid.params.user[param])) { let segs = []; userObjBid.params.user[param].forEach(val => { - if (utils.isNumber(val)) { + if (isNumber(val)) { segs.push({'id': val}); - } else if (utils.isPlainObject(val)) { + } else if (isPlainObject(val)) { segs.push(val); } }); @@ -198,7 +221,7 @@ export const spec = { if (debugObjParams.enabled) { payload.debug = debugObjParams; - utils.logInfo('Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); + logInfo('Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); } if (bidderRequest && bidderRequest.gdprConsent) { @@ -243,12 +266,12 @@ export const spec = { if (bidRequests[0].userId) { let eids = []; - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); + addUserId(eids, deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); + addUserId(eids, deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); if (eids.length) { payload.eids = eids; @@ -313,7 +336,7 @@ export const spec = { const bids = []; if (serverResponse.error) { let errorMessage = `in response for ${bidderRequest.bidderCode} adapter : ${serverResponse.error}`; - utils.logError(errorMessage); + logError(errorMessage); return bids; } @@ -341,7 +364,7 @@ export const spec = { .replace(/

(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1 .replace(/(.*)<\/h[2-6]>/gm, '\n\n*** $1 ***\n\n') // Headers .replace(/(<([^>]+)>)/igm, ''); // Remove any other tags - utils.logMessage(debugText); + logMessage(debugText); } return bids; @@ -375,11 +398,11 @@ export const spec = { }, transformBidParams: function (params, isOpenRtb) { - params = utils.convertTypes({ + params = convertTypes({ 'member': 'string', 'invCode': 'string', 'placementId': 'number', - 'keywords': utils.transformBidderParamKeywords, + 'keywords': transformBidderParamKeywords, 'publisherId': 'number' }, params); @@ -392,7 +415,7 @@ export const spec = { } Object.keys(params).forEach(paramKey => { - let convertedKey = utils.convertCamelToUnderscore(paramKey); + let convertedKey = convertCamelToUnderscore(paramKey); if (convertedKey !== paramKey) { params[convertedKey] = params[paramKey]; delete params[paramKey]; @@ -415,7 +438,7 @@ export const spec = { } function isPopulatedArray(arr) { - return !!(utils.isArray(arr) && arr.length > 0); + return !!(isArray(arr) && arr.length > 0); } function deleteValues(keyPairObj) { @@ -487,9 +510,9 @@ function strIsAppnexusViewabilityScript(str) { function getAppnexusViewabilityScriptFromJsTrackers(jsTrackerArray) { let viewJsPayload; - if (utils.isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { + if (isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { viewJsPayload = jsTrackerArray; - } else if (utils.isArray(jsTrackerArray)) { + } else if (isArray(jsTrackerArray)) { for (let i = 0; i < jsTrackerArray.length; i++) { let currentJsTracker = jsTrackerArray[i]; if (strIsAppnexusViewabilityScript(currentJsTracker)) { @@ -513,7 +536,7 @@ function hasPurpose1Consent(bidderRequest) { let result = true; if (bidderRequest && bidderRequest.gdprConsent) { if (bidderRequest.gdprConsent.gdprApplies && bidderRequest.gdprConsent.apiVersion === 2) { - result = !!(utils.deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); + result = !!(deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); } } return result; @@ -531,16 +554,16 @@ function formatRequest(payload, bidderRequest) { endpointUrl = URL_SIMPLE; } - if (utils.getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { + if (getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { options.customHeaders = { 'X-Is-Test': 1 } } if (payload.tags.length > MAX_IMPS_PER_REQUEST) { - const clonedPayload = utils.deepClone(payload); + const clonedPayload = deepClone(payload); - utils.chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { + chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { clonedPayload.tags = tags; const payloadString = JSON.stringify(clonedPayload); request.push({ @@ -577,14 +600,14 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logError('Prebid Error calling setRender on renderer', err); } renderer.setEventHandlers({ - impression: () => utils.logMessage('Outstream video impression event'), - loaded: () => utils.logMessage('Outstream video loaded event'), + impression: () => logMessage('Outstream video impression event'), + loaded: () => logMessage('Outstream video loaded event'), ended: () => { - utils.logMessage('Outstream renderer video event'); + logMessage('Outstream renderer video event'); document.querySelector(`#${adUnitCode}`).style.display = 'none'; } }); @@ -599,7 +622,7 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { * @return Bid */ function newBid(serverBid, rtbBid, bidderRequest) { - const bidRequest = utils.getBidRequest(serverBid.uuid, [bidderRequest]); + const bidRequest = getBidRequest(serverBid.uuid, [bidderRequest]); const bid = { requestId: serverBid.uuid, cpm: rtbBid.cpm, @@ -634,7 +657,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { ttl: 3600 }); - const videoContext = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + const videoContext = deepAccess(bidRequest, 'mediaTypes.video.context'); switch (videoContext) { case ADPOD: const primaryCatId = getIabSubCategory(bidRequest.bidder, rtbBid.brand_category_id); @@ -655,7 +678,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (rtbBid.renderer_url) { const videoBid = find(bidderRequest.bids, bid => bid.bidId === serverBid.uuid); - const rendererOptions = utils.deepAccess(videoBid, 'renderer.options'); + const rendererOptions = deepAccess(videoBid, 'renderer.options'); bid.renderer = newRenderer(bid.adUnitCode, rtbBid, rendererOptions); } break; @@ -675,7 +698,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (jsTrackers == undefined) { jsTrackers = jsTrackerDisarmed; - } else if (utils.isStr(jsTrackers)) { + } else if (isStr(jsTrackers)) { jsTrackers = [jsTrackers, jsTrackerDisarmed]; } else { jsTrackers.push(jsTrackerDisarmed); @@ -724,11 +747,11 @@ function newBid(serverBid, rtbBid, bidderRequest) { try { if (rtbBid.rtb.trackers) { const url = rtbBid.rtb.trackers[0].impression_urls[0]; - const tracker = utils.createTrackPixelHtml(url); + const tracker = createTrackPixelHtml(url); bid.ad += tracker; } } catch (error) { - utils.logError('Error appending tracking pixel', error); + logError('Error appending tracking pixel', error); } } @@ -778,8 +801,8 @@ function bidToTag(bid) { if (bid.params.externalImpId) { tag.external_imp_id = bid.params.externalImpId; } - if (!utils.isEmpty(bid.params.keywords)) { - let keywords = utils.transformBidderParamKeywords(bid.params.keywords); + if (!isEmpty(bid.params.keywords)) { + let keywords = transformBidderParamKeywords(bid.params.keywords); if (keywords.length > 0) { keywords.forEach(deleteValues); @@ -787,12 +810,12 @@ function bidToTag(bid) { tag.keywords = keywords; } - let gpid = utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); + let gpid = deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); if (gpid) { tag.gpid = gpid; } - if (bid.mediaType === NATIVE || utils.deepAccess(bid, `mediaTypes.${NATIVE}`)) { + if (bid.mediaType === NATIVE || deepAccess(bid, `mediaTypes.${NATIVE}`)) { tag.ad_types.push(NATIVE); if (tag.sizes.length === 0) { tag.sizes = transformSizes([1, 1]); @@ -804,8 +827,8 @@ function bidToTag(bid) { } } - const videoMediaType = utils.deepAccess(bid, `mediaTypes.${VIDEO}`); - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const videoMediaType = deepAccess(bid, `mediaTypes.${VIDEO}`); + const context = deepAccess(bid, 'mediaTypes.video.context'); if (videoMediaType && context === 'adpod') { tag.hb_source = 7; @@ -831,7 +854,7 @@ function bidToTag(bid) { case 'context': case 'playback_method': let type = bid.params.video[param]; - type = (utils.isArray(type)) ? type[0] : type; + type = (isArray(type)) ? type[0] : type; tag.video[param] = VIDEO_MAPPING[param][type]; break; // Deprecating tags[].video.frameworks in favor of tags[].video_frameworks @@ -842,7 +865,7 @@ function bidToTag(bid) { } }); - if (bid.params.video.frameworks && utils.isArray(bid.params.video.frameworks)) { + if (bid.params.video.frameworks && isArray(bid.params.video.frameworks)) { tag['video_frameworks'] = bid.params.video.frameworks; } } @@ -867,7 +890,7 @@ function bidToTag(bid) { case 'playbackmethod': if (typeof tag.video['playback_method'] !== 'number') { let type = videoMediaType[param]; - type = (utils.isArray(type)) ? type[0] : type; + type = (isArray(type)) ? type[0] : type; // we only support iab's options 1-4 at this time. if (type >= 1 && type <= 4) { @@ -876,7 +899,7 @@ function bidToTag(bid) { } break; case 'api': - if (!tag['video_frameworks'] && utils.isArray(videoMediaType[param])) { + if (!tag['video_frameworks'] && isArray(videoMediaType[param])) { // need to read thru array; remove 6 (we don't support it), swap 4 <> 5 if found (to match our adserver mapping for these specific values) let apiTmp = videoMediaType[param].map(val => { let v = (val === 4) ? 5 : (val === 5) ? 4 : val; @@ -896,7 +919,7 @@ function bidToTag(bid) { tag.video = Object.assign({}, tag.video, { custom_renderer_present: true }); } - if (bid.params.frameworks && utils.isArray(bid.params.frameworks)) { + if (bid.params.frameworks && isArray(bid.params.frameworks)) { tag['banner_frameworks'] = bid.params.frameworks; } @@ -917,8 +940,8 @@ function transformSizes(requestSizes) { let sizes = []; let sizeObj = {}; - if (utils.isArray(requestSizes) && requestSizes.length === 2 && - !utils.isArray(requestSizes[0])) { + if (isArray(requestSizes) && requestSizes.length === 2 && + !isArray(requestSizes[0])) { sizeObj.width = parseInt(requestSizes[0], 10); sizeObj.height = parseInt(requestSizes[1], 10); sizes.push(sizeObj); @@ -972,10 +995,10 @@ function hasOmidSupport(bid) { let hasOmid = false; const bidderParams = bid.params; const videoParams = bid.params.video; - if (bidderParams.frameworks && utils.isArray(bidderParams.frameworks)) { + if (bidderParams.frameworks && isArray(bidderParams.frameworks)) { hasOmid = includes(bid.params.frameworks, 6); } - if (!hasOmid && videoParams && videoParams.frameworks && utils.isArray(videoParams.frameworks)) { + if (!hasOmid && videoParams && videoParams.frameworks && isArray(videoParams.frameworks)) { hasOmid = includes(bid.params.video.frameworks, 6); } return hasOmid; @@ -990,14 +1013,14 @@ function createAdPodRequest(tags, adPodBid) { const { durationRangeSec, requireExactDuration } = adPodBid.mediaTypes.video; const numberOfPlacements = getAdPodPlacementNumber(adPodBid.mediaTypes.video); - const maxDuration = utils.getMaxValueFromArray(durationRangeSec); + const maxDuration = getMaxValueFromArray(durationRangeSec); const tagToDuplicate = tags.filter(tag => tag.uuid === adPodBid.bidId); - let request = utils.fill(...tagToDuplicate, numberOfPlacements); + let request = fill(...tagToDuplicate, numberOfPlacements); if (requireExactDuration) { const divider = Math.ceil(numberOfPlacements / durationRangeSec.length); - const chunked = utils.chunk(request, divider); + const chunked = chunk(request, divider); // each configured duration is set as min/maxduration for a subset of requests durationRangeSec.forEach((duration, index) => { @@ -1016,7 +1039,7 @@ function createAdPodRequest(tags, adPodBid) { function getAdPodPlacementNumber(videoParams) { const { adPodDurationSec, durationRangeSec, requireExactDuration } = videoParams; - const minAllowedDuration = utils.getMinValueFromArray(durationRangeSec); + const minAllowedDuration = getMinValueFromArray(durationRangeSec); const numberOfPlacements = Math.floor(adPodDurationSec / minAllowedDuration); return requireExactDuration @@ -1025,7 +1048,7 @@ function getAdPodPlacementNumber(videoParams) { } function setVideoProperty(tag, key, value) { - if (utils.isEmpty(tag.video)) { tag.video = {}; } + if (isEmpty(tag.video)) { tag.video = {}; } tag.video[key] = value; } @@ -1056,7 +1079,7 @@ function buildNativeRequest(params) { const isImageAsset = !!(requestKey === NATIVE_MAPPING.image.serverName || requestKey === NATIVE_MAPPING.icon.serverName); if (isImageAsset && request[requestKey].sizes) { let sizes = request[requestKey].sizes; - if (utils.isArrayOfNums(sizes) || (utils.isArray(sizes) && sizes.length > 0 && sizes.every(sz => utils.isArrayOfNums(sz)))) { + if (isArrayOfNums(sizes) || (isArray(sizes) && sizes.length > 0 && sizes.every(sz => isArrayOfNums(sz)))) { request[requestKey].sizes = transformSizes(request[requestKey].sizes); } } @@ -1135,7 +1158,7 @@ function addUserId(eids, id, source, rti) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return (bid.params.reserve) ? bid.params.reserve : null; } @@ -1144,7 +1167,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null;