/
adnuntius.go
312 lines (263 loc) · 8.13 KB
/
adnuntius.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package adnuntius
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/mxmCherry/openrtb/v15/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-server/openrtb_ext"
"github.com/prebid/prebid-server/util/timeutil"
)
type QueryString map[string]string
type adapter struct {
time timeutil.Time
endpoint string
}
type adnAdunit struct {
AuId string `json:"auId"`
TargetId string `json:"targetId"`
}
type AdnResponse struct {
AdUnits []struct {
AuId string
TargetId string
Html string
ResponseId string
Ads []struct {
Bid struct {
Amount float64
Currency string
}
AdId string
CreativeWidth string
CreativeHeight string
CreativeId string
LineItemId string
Html string
DestinationUrls map[string]string
}
}
}
type adnMetaData struct {
Usi string `json:"usi,omitempty"`
}
type adnRequest struct {
AdUnits []adnAdunit `json:"adUnits"`
MetaData adnMetaData `json:"metaData,omitempty"`
Context string `json:"context,omitempty"`
}
const defaultNetwork = "default"
const defaultSite = "unknown"
const minutesInHour = 60
// Builder builds a new instance of the Adnuntius adapter for the given bidder with the given config.
func Builder(bidderName openrtb_ext.BidderName, config config.Adapter) (adapters.Bidder, error) {
bidder := &adapter{
time: &timeutil.RealTime{},
endpoint: config.Endpoint,
}
return bidder, nil
}
func (a *adapter) MakeRequests(request *openrtb2.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) {
return a.generateRequests(*request)
}
func setHeaders(ortbRequest openrtb2.BidRequest) http.Header {
headers := http.Header{}
headers.Add("Content-Type", "application/json;charset=utf-8")
headers.Add("Accept", "application/json")
if ortbRequest.Device != nil {
if ortbRequest.Device.IP != "" {
headers.Add("X-Forwarded-For", ortbRequest.Device.IP)
}
if ortbRequest.Device.UA != "" {
headers.Add("user-agent", ortbRequest.Device.UA)
}
}
return headers
}
func makeEndpointUrl(ortbRequest openrtb2.BidRequest, a *adapter) (string, []error) {
uri, err := url.Parse(a.endpoint)
if err != nil {
return "", []error{fmt.Errorf("failed to parse Adnuntius endpoint: %v", err)}
}
gdpr, consent, err := getGDPR(&ortbRequest)
if err != nil {
return "", []error{fmt.Errorf("failed to parse Adnuntius endpoint: %v", err)}
}
_, offset := a.time.Now().Zone()
tzo := -offset / minutesInHour
q := uri.Query()
if gdpr != "" && consent != "" {
q.Set("gdpr", gdpr)
q.Set("consentString", consent)
}
q.Set("tzo", fmt.Sprint(tzo))
q.Set("format", "json")
url := a.endpoint + "?" + q.Encode()
return url, nil
}
/*
Generate the requests to Adnuntius to reduce the amount of requests going out.
*/
func (a *adapter) generateRequests(ortbRequest openrtb2.BidRequest) ([]*adapters.RequestData, []error) {
var requestData []*adapters.RequestData
networkAdunitMap := make(map[string][]adnAdunit)
headers := setHeaders(ortbRequest)
endpoint, err := makeEndpointUrl(ortbRequest, a)
if err != nil {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("failed to parse URL: %s", err),
}}
}
for _, imp := range ortbRequest.Imp {
if imp.Banner == nil {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("ignoring imp id=%s, Adnuntius supports only Banner", imp.ID),
}}
}
var bidderExt adapters.ExtImpBidder
if err := json.Unmarshal(imp.Ext, &bidderExt); err != nil {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("Error unmarshalling ExtImpBidder: %s", err.Error()),
}}
}
var adnuntiusExt openrtb_ext.ImpExtAdnunitus
if err := json.Unmarshal(bidderExt.Bidder, &adnuntiusExt); err != nil {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("Error unmarshalling ExtImpBmtm: %s", err.Error()),
}}
}
network := defaultNetwork
if adnuntiusExt.Network != "" {
network = adnuntiusExt.Network
}
networkAdunitMap[network] = append(
networkAdunitMap[network],
adnAdunit{
AuId: adnuntiusExt.Auid,
TargetId: fmt.Sprintf("%s-%s", adnuntiusExt.Auid, imp.ID),
})
}
site := defaultSite
if ortbRequest.Site != nil && ortbRequest.Site.Page != "" {
site = ortbRequest.Site.Page
}
for _, networkAdunits := range networkAdunitMap {
adnuntiusRequest := adnRequest{
AdUnits: networkAdunits,
Context: site,
}
ortbUser := ortbRequest.User
if ortbUser != nil {
ortbUserId := ortbRequest.User.ID
if ortbUserId != "" {
adnuntiusRequest.MetaData.Usi = ortbRequest.User.ID
}
}
adnJson, err := json.Marshal(adnuntiusRequest)
if err != nil {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("Error unmarshalling adnuntius request: %s", err.Error()),
}}
}
requestData = append(requestData, &adapters.RequestData{
Method: http.MethodPost,
Uri: endpoint,
Body: adnJson,
Headers: headers,
})
}
return requestData, nil
}
func (a *adapter) MakeBids(request *openrtb2.BidRequest, externalRequest *adapters.RequestData, response *adapters.ResponseData) (*adapters.BidderResponse, []error) {
if response.StatusCode == http.StatusBadRequest {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("Status code: %d, Request malformed", response.StatusCode),
}}
}
if response.StatusCode != http.StatusOK {
return nil, []error{&errortypes.BadServerResponse{
Message: fmt.Sprintf("Status code: %d, Something went wrong with your request", response.StatusCode),
}}
}
var adnResponse AdnResponse
if err := json.Unmarshal(response.Body, &adnResponse); err != nil {
return nil, []error{err}
}
bidResponse, bidErr := generateBidResponse(&adnResponse, request)
if bidErr != nil {
return nil, bidErr
}
return bidResponse, nil
}
func getGDPR(request *openrtb2.BidRequest) (string, string, error) {
gdpr := ""
var extRegs openrtb_ext.ExtRegs
if request.Regs != nil {
if err := json.Unmarshal(request.Regs.Ext, &extRegs); err != nil {
return "", "", fmt.Errorf("failed to parse ExtRegs in Adnuntius GDPR check: %v", err)
}
if extRegs.GDPR != nil && (*extRegs.GDPR == 0 || *extRegs.GDPR == 1) {
gdpr = strconv.Itoa(int(*extRegs.GDPR))
}
}
consent := ""
if request.User != nil && request.User.Ext != nil {
var extUser openrtb_ext.ExtUser
if err := json.Unmarshal(request.User.Ext, &extUser); err != nil {
return "", "", fmt.Errorf("failed to parse ExtUser in Adnuntius GDPR check: %v", err)
}
consent = extUser.Consent
}
return gdpr, consent, nil
}
func generateBidResponse(adnResponse *AdnResponse, request *openrtb2.BidRequest) (*adapters.BidderResponse, []error) {
bidResponse := adapters.NewBidderResponseWithBidsCapacity(len(adnResponse.AdUnits))
var currency string
for i, adunit := range adnResponse.AdUnits {
if len(adunit.Ads) > 0 {
ad := adunit.Ads[0]
currency = ad.Bid.Currency
creativeWidth, widthErr := strconv.ParseInt(ad.CreativeWidth, 10, 64)
if widthErr != nil {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("Value of width: %s is not a string", ad.CreativeWidth),
}}
}
creativeHeight, heightErr := strconv.ParseInt(ad.CreativeHeight, 10, 64)
if heightErr != nil {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("Value of height: %s is not a string", ad.CreativeHeight),
}}
}
adDomain := []string{}
for _, url := range ad.DestinationUrls {
domainArray := strings.Split(url, "/")
domain := strings.Replace(domainArray[2], "www.", "", -1)
adDomain = append(adDomain, domain)
}
bid := openrtb2.Bid{
ID: ad.AdId,
ImpID: request.Imp[i].ID,
W: creativeWidth,
H: creativeHeight,
AdID: ad.AdId,
CID: ad.LineItemId,
CrID: ad.CreativeId,
Price: ad.Bid.Amount * 1000,
AdM: adunit.Html,
ADomain: adDomain,
}
bidResponse.Bids = append(bidResponse.Bids, &adapters.TypedBid{
Bid: &bid,
BidType: "banner",
})
}
}
bidResponse.Currency = currency
return bidResponse, nil
}