Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Adapter: Intertech #3718

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
326 changes: 326 additions & 0 deletions adapters/intertech/intertech.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,326 @@
package intertech

import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"text/template"

"github.com/prebid/openrtb/v20/openrtb2"
"github.com/prebid/prebid-server/v3/adapters"
"github.com/prebid/prebid-server/v3/config"
"github.com/prebid/prebid-server/v3/errortypes"
"github.com/prebid/prebid-server/v3/macros"
"github.com/prebid/prebid-server/v3/openrtb_ext"
)

const (
refererQueryKey = "target-ref"
currencyQueryKey = "ssp-cur"
impIdQueryKey = "imp-id"
)

// intertechPlacementID is the composite id of an ad placement
type intertechPlacementID struct {
PageID string
ImpID string
}

type adapter struct {
endpoint *template.Template
}

func Builder(bidderName openrtb_ext.BidderName, config config.Adapter, server config.Server) (adapters.Bidder, error) {
template, err := template.New("endpointTemplate").Parse(config.Endpoint)
if err != nil {
return nil, fmt.Errorf("unable to parse endpoint url template: %v", err)
}

bidder := &adapter{
endpoint: template,
}

return bidder, nil
}

func (a *adapter) MakeRequests(requestData *openrtb2.BidRequest, requestInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) {
var (
requests []*adapters.RequestData
errors []error
)

referer := getReferer(requestData)
currency := getCurrency(requestData)

for i := range requestData.Imp {
imp := requestData.Imp[i]

placementId, err := getPlacementID(imp)
if err != nil {
errors = append(errors, err)
continue
}
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved

if err := modifyImp(&imp); err != nil {
errors = append(errors, err)
continue
}

resolvedUrl, err := a.resolveUrl(*placementId, referer, currency)
if err != nil {
errors = append(errors, err)
continue
}

splittedRequestData := splitRequestDataByImp(requestData, imp)

requestBody, err := json.Marshal(splittedRequestData)
SyntaxNode marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
errors = append(errors, err)
continue
}

requests = append(requests, &adapters.RequestData{
Method: "POST",
Uri: resolvedUrl,
Body: requestBody,
Headers: getHeaders(&splittedRequestData),
ImpIDs: openrtb_ext.GetImpIDs(splittedRequestData.Imp),
})
}

return requests, errors
}

func getHeaders(request *openrtb2.BidRequest) http.Header {
headers := http.Header{}

if request.Device != nil && request.Site != nil {
addNonEmptyHeader(&headers, "Referer", request.Site.Page)
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
addNonEmptyHeader(&headers, "Accept-Language", request.Device.Language)
addNonEmptyHeader(&headers, "User-Agent", request.Device.UA)
addNonEmptyHeader(&headers, "X-Forwarded-For", request.Device.IP)
addNonEmptyHeader(&headers, "X-Real-Ip", request.Device.IP)
addNonEmptyHeader(&headers, "X-Forwarded-For-IPv6", request.Device.IPv6)
headers.Add("Content-Type", "application/json;charset=utf-8")
headers.Add("Accept", "application/json")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since these don't involve request.Device, I suggest moving these outside of the conditional so that they are always set.

}

return headers
}

func addNonEmptyHeader(headers *http.Header, key, value string) {
if len(value) > 0 {
headers.Add(key, value)
}
}

// splitRequestDataByImp makes a shallow copy of the request for further modification (imp is already a shallow copy)
func splitRequestDataByImp(request *openrtb2.BidRequest, imp openrtb2.Imp) openrtb2.BidRequest {
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
requestCopy := *request
requestCopy.Imp = []openrtb2.Imp{imp}

return requestCopy
}
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved

func getPlacementID(imp openrtb2.Imp) (*intertechPlacementID, error) {
var ext adapters.ExtImpBidder
if err := json.Unmarshal(imp.Ext, &ext); err != nil {
SyntaxNode marked this conversation as resolved.
Show resolved Hide resolved
return nil, &errortypes.BadInput{
Message: fmt.Sprintf("imp %s: unable to unmarshal ext", imp.ID),
}
}

var intertechExt openrtb_ext.ExtImpIntertech
if err := json.Unmarshal(ext.Bidder, &intertechExt); err != nil {
SyntaxNode marked this conversation as resolved.
Show resolved Hide resolved
return nil, &errortypes.BadInput{
Message: fmt.Sprintf("imp %s: unable to unmarshal ext.bidder: %v", imp.ID, err),
}
}

placementID := mapExtToPlacementID(intertechExt)
return placementID, nil
}

func mapExtToPlacementID(intertechExt openrtb_ext.ExtImpIntertech) *intertechPlacementID {
var placementID intertechPlacementID

if len(intertechExt.PlacementID) == 0 {
placementID.ImpID = strconv.Itoa(int(intertechExt.ImpID))
placementID.PageID = strconv.Itoa(int(intertechExt.PageID))
return &placementID
}

idParts := strings.Split(intertechExt.PlacementID, "-")
placementID.PageID = idParts[0]
placementID.ImpID = idParts[1]

return &placementID
}

func modifyImp(imp *openrtb2.Imp) error {
if imp.Banner != nil {
banner, err := modifyBanner(*imp.Banner)
if banner != nil {
imp.Banner = banner
}
return err
}

if imp.Native != nil {
return nil
}

return &errortypes.BadInput{
Message: fmt.Sprintf("Unsupported format. Intertech only supports banner and native types. Ignoring imp id #%s", imp.ID),
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
}
}

func modifyBanner(banner openrtb2.Banner) (*openrtb2.Banner, error) {
format := banner.Format

hasRootSize := banner.W != nil && banner.H != nil && *banner.W > 0 && *banner.H > 0
if !hasRootSize && len(format) == 0 {
w := 0
h := 0
if banner.W != nil {
w = int(*banner.W)
}
if banner.H != nil {
h = int(*banner.H)
}
return nil, &errortypes.BadInput{
Message: fmt.Sprintf("Invalid sizes provided for Banner %dx%d", w, h),
}
}

if !hasRootSize {
firstFormat := format[0]
banner.H = &firstFormat.H
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
banner.W = &firstFormat.W
}

return &banner, nil
}

// resolveUrl "un-templates" the endpoint by replacing macroses and adding the required query parameters
func (a *adapter) resolveUrl(placementID intertechPlacementID, referer string, currency string) (string, error) {
params := macros.EndpointTemplateParams{PageID: placementID.PageID, ImpID: placementID.ImpID}

endpointStr, err := macros.ResolveMacros(a.endpoint, params)
if err != nil {
return "", err
}

parsedUrl, err := url.Parse(endpointStr)
if err != nil {
return "", err
}

addNonEmptyQueryParams(parsedUrl, map[string]string{
refererQueryKey: referer,
currencyQueryKey: currency,
impIdQueryKey: placementID.ImpID,
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
})
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved

return parsedUrl.String(), nil
SyntaxNode marked this conversation as resolved.
Show resolved Hide resolved
}

func addNonEmptyQueryParams(url *url.URL, queryMap map[string]string) {
query := url.Query()
for key, value := range queryMap {
if len(value) > 0 {
query.Add(key, value)
}
}

url.RawQuery = query.Encode()
}

func getReferer(request *openrtb2.BidRequest) string {
if request.Site == nil {
return ""
}

return request.Site.Domain
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
}
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved

func getCurrency(request *openrtb2.BidRequest) string {
if len(request.Cur) == 0 {
return ""
}

return request.Cur[0]
}

func (a *adapter) MakeBids(request *openrtb2.BidRequest, _ *adapters.RequestData, responseData *adapters.ResponseData) (*adapters.BidderResponse, []error) {
if adapters.IsResponseStatusCodeNoContent(responseData) {
return nil, nil
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
}

if err := adapters.CheckResponseStatusCodeForErrors(responseData); err != nil {
return nil, []error{err}
}

var bidResponse openrtb2.BidResponse
if err := json.Unmarshal(responseData.Body, &bidResponse); err != nil {
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
return nil, []error{&errortypes.BadServerResponse{
Message: fmt.Sprintf("Bad server response: %d", err),
}}
}

bidResponseWithCapacity := adapters.NewBidderResponseWithBidsCapacity(len(request.Imp))

var errors []error

impMap := map[string]*openrtb2.Imp{}
for i := range request.Imp {
imp := request.Imp[i]

impMap[imp.ID] = &imp
}

for _, seatBid := range bidResponse.SeatBid {
for i := range seatBid.Bid {
bid := seatBid.Bid[i]

imp, exists := impMap[bid.ImpID]
if !exists {
errors = append(errors, &errortypes.BadInput{
Message: fmt.Sprintf("Invalid bid imp ID #%s does not match any imp IDs from the original bid request", bid.ImpID),
})
continue
}

bidType, err := getBidType(*imp)
if err != nil {
errors = append(errors, err)
continue
}

bidResponseWithCapacity.Bids = append(bidResponseWithCapacity.Bids, &adapters.TypedBid{
Bid: &bid,
BidType: bidType,
})
}
}

return bidResponseWithCapacity, errors
}

func getBidType(imp openrtb2.Imp) (openrtb_ext.BidType, error) {
if imp.Native != nil {
SyntaxNode marked this conversation as resolved.
Show resolved Hide resolved
return openrtb_ext.BidTypeNative, nil
}

if imp.Banner != nil {
SyntaxNode marked this conversation as resolved.
Show resolved Hide resolved
return openrtb_ext.BidTypeBanner, nil
}

return "", &errortypes.BadInput{
Message: fmt.Sprintf("Processing an invalid impression; cannot resolve impression type for imp #%s", imp.ID),
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that this adapter only supports banner and native, the bid type is derived from the impression and PBS core will only call the adapter if an impression is one of the supported formats, this error case should not be possible. This function could be simplified as follows:

if imp.Native != nil {
    return openrtb_ext.BidTypeNative, nil
}
return openrtb_ext.BidTypeBanner, nil

}
29 changes: 29 additions & 0 deletions adapters/intertech/intertech_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package intertech

import (
"testing"

"github.com/prebid/prebid-server/v3/adapters/adapterstest"
"github.com/prebid/prebid-server/v3/config"
"github.com/prebid/prebid-server/v3/openrtb_ext"
"github.com/stretchr/testify/assert"
)

func TestJsonSamples(t *testing.T) {
bidder, buildErr := Builder(openrtb_ext.BidderIntertech,
config.Adapter{Endpoint: "https://prebid.intertechsrvcs.com/prebid/{{.PageID}}?ssp-id=10500"},
przemkaczmarek marked this conversation as resolved.
Show resolved Hide resolved
config.Server{ExternalUrl: "http://hosturl.com", GvlID: 1, DataCenter: "2"})

if buildErr != nil {
t.Fatalf("Builder returned unexpected error %v", buildErr)
}

adapterstest.RunJSONBidderTest(t, "intertechtest", bidder)
}

func TestEndpointTemplateMalformed(t *testing.T) {
_, buildErr := Builder(openrtb_ext.BidderIntertech, config.Adapter{
Endpoint: "{{Malformed}}"}, config.Server{ExternalUrl: "http://hosturl.com", GvlID: 1, DataCenter: "2"})

assert.Error(t, buildErr)
}
Loading
Loading