forked from prebid/prebid-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheplanning.go
355 lines (293 loc) · 9.11 KB
/
eplanning.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package eplanning
import (
"encoding/json"
"math/rand"
"net/http"
"net/url"
"strings"
"regexp"
"fmt"
"github.com/prebid/openrtb/v17/adcom1"
"github.com/prebid/openrtb/v17/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"
"strconv"
)
const nullSize = "1x1"
const defaultPageURL = "FILE"
const sec = "ROS"
const dfpClientID = "1"
const requestTargetInventory = "1"
var priorityOrderForMobileSizesAsc = []string{"1x1", "300x50", "320x50", "300x250"}
var priorityOrderForDesktopSizesAsc = []string{"1x1", "970x90", "970x250", "160x600", "300x600", "728x90", "300x250"}
var cleanNameSteps = []cleanNameStep{
{regexp.MustCompile(`_|\.|-|\/`), ""},
{regexp.MustCompile(`\)\(|\(|\)|:`), "_"},
{regexp.MustCompile(`^_+|_+$`), ""},
}
type cleanNameStep struct {
expression *regexp.Regexp
replacementString string
}
type EPlanningAdapter struct {
URI string
testing bool
}
type hbResponse struct {
Spaces []hbResponseSpace `json:"sp"`
}
type hbResponseSpace struct {
Name string `json:"k"`
Ads []hbResponseAd `json:"a"`
}
type hbResponseAd struct {
ImpressionID string `json:"i"`
AdID string `json:"id,omitempty"`
Price string `json:"pr"`
AdM string `json:"adm"`
CrID string `json:"crid"`
Width uint64 `json:"w,omitempty"`
Height uint64 `json:"h,omitempty"`
}
func (adapter *EPlanningAdapter) MakeRequests(request *openrtb2.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) {
errors := make([]error, 0, len(request.Imp))
totalImps := len(request.Imp)
spacesStrings := make([]string, 0, totalImps)
totalRequests := 0
clientID := ""
isMobile := isMobileDevice(request)
for i := 0; i < totalImps; i++ {
imp := request.Imp[i]
extImp, err := verifyImp(&imp, isMobile)
if err != nil {
errors = append(errors, err)
continue
}
if clientID == "" {
clientID = extImp.ClientID
}
totalRequests++
// Save valid imp
name := cleanName(extImp.AdUnitCode)
spacesStrings = append(spacesStrings, name+":"+extImp.SizeString)
}
if totalRequests == 0 {
return nil, errors
}
headers := http.Header{}
headers.Add("Content-Type", "application/json")
headers.Add("Accept", "application/json")
ip := ""
if request.Device != nil {
ip = request.Device.IP
addHeaderIfNonEmpty(headers, "User-Agent", request.Device.UA)
addHeaderIfNonEmpty(headers, "X-Forwarded-For", ip)
addHeaderIfNonEmpty(headers, "Accept-Language", request.Device.Language)
if request.Device.DNT != nil {
addHeaderIfNonEmpty(headers, "DNT", strconv.Itoa(int(*request.Device.DNT)))
}
}
pageURL := defaultPageURL
if request.Site != nil && request.Site.Page != "" {
pageURL = request.Site.Page
}
pageDomain := defaultPageURL
if request.Site != nil {
if request.Site.Domain != "" {
pageDomain = request.Site.Domain
} else if request.Site.Page != "" {
u, err := url.Parse(request.Site.Page)
if err != nil {
errors = append(errors, err)
return nil, errors
}
pageDomain = u.Hostname()
}
}
requestTarget := pageDomain
if request.App != nil && request.App.Bundle != "" {
requestTarget = request.App.Bundle
}
uriObj, err := url.Parse(adapter.URI)
if err != nil {
errors = append(errors, err)
return nil, errors
}
uriObj.Path = uriObj.Path + fmt.Sprintf("/%s/%s/%s/%s", clientID, dfpClientID, requestTarget, sec)
query := url.Values{}
query.Set("ncb", "1")
if request.App == nil {
query.Set("ur", pageURL)
}
query.Set("e", strings.Join(spacesStrings, "+"))
if request.User != nil && request.User.BuyerUID != "" {
query.Set("uid", request.User.BuyerUID)
}
if ip != "" {
query.Set("ip", ip)
}
var body []byte
if adapter.testing {
body = []byte("{}")
} else {
t := strconv.Itoa(rand.Int())
query.Set("rnd", t)
body = nil
}
if request.App != nil {
if request.App.Name != "" {
query.Set("appn", request.App.Name)
}
if request.App.ID != "" {
query.Set("appid", request.App.ID)
}
if request.Device != nil && request.Device.IFA != "" {
query.Set("ifa", request.Device.IFA)
}
query.Set("app", requestTargetInventory)
}
uriObj.RawQuery = query.Encode()
uri := uriObj.String()
requestData := adapters.RequestData{
Method: "GET",
Uri: uri,
Body: body,
Headers: headers,
}
requests := []*adapters.RequestData{&requestData}
return requests, errors
}
func isMobileDevice(request *openrtb2.BidRequest) bool {
return request.Device != nil && (request.Device.DeviceType == adcom1.DeviceMobile || request.Device.DeviceType == adcom1.DevicePhone || request.Device.DeviceType == adcom1.DeviceTablet)
}
func cleanName(name string) string {
for _, step := range cleanNameSteps {
name = step.expression.ReplaceAllString(name, step.replacementString)
}
return name
}
func verifyImp(imp *openrtb2.Imp, isMobile bool) (*openrtb_ext.ExtImpEPlanning, error) {
var bidderExt adapters.ExtImpBidder
if err := json.Unmarshal(imp.Ext, &bidderExt); err != nil {
return nil, &errortypes.BadInput{
Message: fmt.Sprintf("Ignoring imp id=%s, error while decoding extImpBidder, err: %s", imp.ID, err),
}
}
impExt := openrtb_ext.ExtImpEPlanning{}
err := json.Unmarshal(bidderExt.Bidder, &impExt)
if err != nil {
return nil, &errortypes.BadInput{
Message: fmt.Sprintf("Ignoring imp id=%s, error while decoding impExt, err: %s", imp.ID, err),
}
}
if impExt.ClientID == "" {
return nil, &errortypes.BadInput{
Message: fmt.Sprintf("Ignoring imp id=%s, no ClientID present", imp.ID),
}
}
width, height := getSizeFromImp(imp, isMobile)
if width == 0 && height == 0 {
impExt.SizeString = nullSize
} else {
impExt.SizeString = fmt.Sprintf("%dx%d", width, height)
}
if impExt.AdUnitCode == "" {
impExt.AdUnitCode = impExt.SizeString
}
return &impExt, nil
}
func searchSizePriority(hashedFormats map[string]int, format []openrtb2.Format, priorityOrderForSizesAsc []string) (int64, int64) {
for i := len(priorityOrderForSizesAsc) - 1; i >= 0; i-- {
if formatIndex, wasFound := hashedFormats[priorityOrderForSizesAsc[i]]; wasFound {
return format[formatIndex].W, format[formatIndex].H
}
}
return format[0].W, format[0].H
}
func getSizeFromImp(imp *openrtb2.Imp, isMobile bool) (int64, int64) {
if imp.Banner.W != nil && imp.Banner.H != nil {
return *imp.Banner.W, *imp.Banner.H
}
if imp.Banner.Format != nil {
hashedFormats := make(map[string]int, len(imp.Banner.Format))
for i, format := range imp.Banner.Format {
if format.W != 0 && format.H != 0 {
hashedFormats[fmt.Sprintf("%dx%d", format.W, format.H)] = i
}
}
if isMobile {
return searchSizePriority(hashedFormats, imp.Banner.Format, priorityOrderForMobileSizesAsc)
} else {
return searchSizePriority(hashedFormats, imp.Banner.Format, priorityOrderForDesktopSizesAsc)
}
}
return 0, 0
}
func addHeaderIfNonEmpty(headers http.Header, headerName string, headerValue string) {
if len(headerValue) > 0 {
headers.Add(headerName, headerValue)
}
}
func (adapter *EPlanningAdapter) MakeBids(internalRequest *openrtb2.BidRequest, externalRequest *adapters.RequestData, response *adapters.ResponseData) (*adapters.BidderResponse, []error) {
if response.StatusCode == http.StatusNoContent {
return nil, nil
}
if response.StatusCode == http.StatusBadRequest {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
}}
}
if response.StatusCode != http.StatusOK {
return nil, []error{&errortypes.BadServerResponse{
Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
}}
}
var parsedResponse hbResponse
if err := json.Unmarshal(response.Body, &parsedResponse); err != nil {
return nil, []error{&errortypes.BadServerResponse{
Message: fmt.Sprintf("Error unmarshaling HB response: %s", err.Error()),
}}
}
isMobile := isMobileDevice(internalRequest)
bidResponse := adapters.NewBidderResponse()
spaceNameToImpID := make(map[string]string)
for _, imp := range internalRequest.Imp {
extImp, err := verifyImp(&imp, isMobile)
if err != nil {
continue
}
name := cleanName(extImp.AdUnitCode)
spaceNameToImpID[name] = imp.ID
}
for _, space := range parsedResponse.Spaces {
for _, ad := range space.Ads {
if price, err := strconv.ParseFloat(ad.Price, 64); err == nil {
bid := openrtb2.Bid{
ID: ad.ImpressionID,
AdID: ad.AdID,
ImpID: spaceNameToImpID[space.Name],
Price: price,
AdM: ad.AdM,
CrID: ad.CrID,
W: int64(ad.Width),
H: int64(ad.Height),
}
bidResponse.Bids = append(bidResponse.Bids, &adapters.TypedBid{
Bid: &bid,
BidType: openrtb_ext.BidTypeBanner,
})
}
}
}
return bidResponse, nil
}
// Builder builds a new instance of the EPlanning adapter for the given bidder with the given config.
func Builder(bidderName openrtb_ext.BidderName, config config.Adapter, server config.Server) (adapters.Bidder, error) {
bidder := &EPlanningAdapter{
URI: config.Endpoint,
testing: false,
}
return bidder, nil
}