-
Notifications
You must be signed in to change notification settings - Fork 691
/
rubicon.go
1159 lines (1006 loc) · 28.8 KB
/
rubicon.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rubicon
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"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/buger/jsonparser"
"github.com/mxmCherry/openrtb/v15/openrtb2"
)
const badvLimitSize = 50
type RubiconAdapter struct {
URI string
XAPIUsername string
XAPIPassword string
}
type rubiconContext struct {
Data json.RawMessage `json:"data"`
}
type rubiconData struct {
AdServer rubiconAdServer `json:"adserver"`
PbAdSlot string `json:"pbadslot"`
}
type rubiconAdServer struct {
Name string `json:"name"`
AdSlot string `json:"adslot"`
}
type rubiconExtImpBidder struct {
Prebid *openrtb_ext.ExtImpPrebid `json:"prebid"`
Bidder json.RawMessage `json:"bidder"`
Gpid string `json:"gpid"`
Data json.RawMessage `json:"data"`
Context rubiconContext `json:"context"`
}
type bidRequestExt struct {
Prebid bidRequestExtPrebid `json:"prebid"`
}
type bidRequestExtPrebid struct {
Bidders bidRequestExtPrebidBidders `json:"bidders"`
}
type bidRequestExtPrebidBidders struct {
Rubicon prebidBiddersRubicon `json:"rubicon,omitempty"`
}
type prebidBiddersRubicon struct {
Debug prebidBiddersRubiconDebug `json:"debug,omitempty"`
}
type prebidBiddersRubiconDebug struct {
CpmOverride float64 `json:"cpmoverride,omitempty"`
}
type rubiconImpExtRPTrack struct {
Mint string `json:"mint"`
MintVersion string `json:"mint_version"`
}
type rubiconImpExt struct {
RP rubiconImpExtRP `json:"rp,omitempty"`
GPID string `json:"gpid,omitempty"`
}
type rubiconImpExtRP struct {
ZoneID int `json:"zone_id"`
Target json.RawMessage `json:"target,omitempty"`
Track rubiconImpExtRPTrack `json:"track"`
}
type rubiconUserExtRP struct {
Target json.RawMessage `json:"target,omitempty"`
}
type rubiconExtUserTpID struct {
Source string `json:"source"`
UID string `json:"uid"`
}
type rubiconDataExt struct {
SegTax int `json:"segtax"`
}
type rubiconUserExt struct {
Consent string `json:"consent,omitempty"`
Eids []openrtb_ext.ExtUserEid `json:"eids,omitempty"`
TpID []rubiconExtUserTpID `json:"tpid,omitempty"`
RP rubiconUserExtRP `json:"rp"`
LiverampIdl string `json:"liveramp_idl,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
}
type rubiconSiteExtRP struct {
SiteID int `json:"site_id"`
Target json.RawMessage `json:"target,omitempty"`
}
type rubiconSiteExt struct {
RP rubiconSiteExtRP `json:"rp"`
}
type rubiconPubExtRP struct {
AccountID int `json:"account_id"`
}
type rubiconPubExt struct {
RP rubiconPubExtRP `json:"rp"`
}
type rubiconBannerExtRP struct {
SizeID int `json:"size_id,omitempty"`
AltSizeIDs []int `json:"alt_size_ids,omitempty"`
MIME string `json:"mime"`
}
type rubiconBannerExt struct {
RP rubiconBannerExtRP `json:"rp"`
}
// ***** Video Extension *****
type rubiconVideoExt struct {
Skip int `json:"skip,omitempty"`
SkipDelay int `json:"skipdelay,omitempty"`
VideoType string `json:"videotype,omitempty"`
RP rubiconVideoExtRP `json:"rp"`
}
type rubiconVideoExtRP struct {
SizeID int `json:"size_id,omitempty"`
}
type rubiconDeviceExtRP struct {
PixelRatio float64 `json:"pixelratio"`
}
type rubiconDeviceExt struct {
RP rubiconDeviceExtRP `json:"rp"`
}
type rubiconBidResponse struct {
openrtb2.BidResponse
SeatBid []rubiconSeatBid `json:"seatbid,omitempty"`
}
type rubiconSeatBid struct {
openrtb2.SeatBid
Buyer string `json:"buyer,omitempty"`
}
type extPrebid struct {
Prebid *openrtb_ext.ExtBidPrebid `json:"prebid,omitempty"`
Bidder json.RawMessage `json:"bidder,omitempty"`
}
type rubiSize struct {
w uint16
h uint16
}
var rubiSizeMap = map[rubiSize]int{
{w: 468, h: 60}: 1,
{w: 728, h: 90}: 2,
{w: 728, h: 91}: 2,
{w: 120, h: 90}: 5,
{w: 125, h: 125}: 7,
{w: 120, h: 600}: 8,
{w: 160, h: 600}: 9,
{w: 300, h: 600}: 10,
{w: 200, h: 200}: 13,
{w: 250, h: 250}: 14,
{w: 300, h: 250}: 15,
{w: 300, h: 251}: 15,
{w: 336, h: 280}: 16,
{w: 240, h: 400}: 17,
{w: 300, h: 100}: 19,
{w: 980, h: 120}: 31,
{w: 250, h: 360}: 32,
{w: 180, h: 500}: 33,
{w: 980, h: 150}: 35,
{w: 468, h: 400}: 37,
{w: 930, h: 180}: 38,
{w: 750, h: 100}: 39,
{w: 750, h: 200}: 40,
{w: 750, h: 300}: 41,
{w: 320, h: 50}: 43,
{w: 300, h: 50}: 44,
{w: 300, h: 300}: 48,
{w: 1024, h: 768}: 53,
{w: 300, h: 1050}: 54,
{w: 970, h: 90}: 55,
{w: 970, h: 250}: 57,
{w: 1000, h: 90}: 58,
{w: 320, h: 80}: 59,
{w: 320, h: 150}: 60,
{w: 1000, h: 1000}: 61,
{w: 580, h: 500}: 64,
{w: 640, h: 480}: 65,
{w: 930, h: 600}: 66,
{w: 320, h: 480}: 67,
{w: 1800, h: 1000}: 68,
{w: 320, h: 320}: 72,
{w: 320, h: 160}: 73,
{w: 980, h: 240}: 78,
{w: 980, h: 300}: 79,
{w: 980, h: 400}: 80,
{w: 480, h: 300}: 83,
{w: 300, h: 120}: 85,
{w: 548, h: 150}: 90,
{w: 970, h: 310}: 94,
{w: 970, h: 100}: 95,
{w: 970, h: 210}: 96,
{w: 480, h: 320}: 101,
{w: 768, h: 1024}: 102,
{w: 480, h: 280}: 103,
{w: 250, h: 800}: 105,
{w: 320, h: 240}: 108,
{w: 1000, h: 300}: 113,
{w: 320, h: 100}: 117,
{w: 800, h: 250}: 125,
{w: 200, h: 600}: 126,
{w: 980, h: 600}: 144,
{w: 980, h: 150}: 145,
{w: 1000, h: 250}: 152,
{w: 640, h: 320}: 156,
{w: 320, h: 250}: 159,
{w: 250, h: 600}: 179,
{w: 600, h: 300}: 195,
{w: 640, h: 360}: 198,
{w: 640, h: 200}: 199,
{w: 1030, h: 590}: 213,
{w: 980, h: 360}: 214,
{w: 320, h: 180}: 229,
{w: 2000, h: 1400}: 230,
{w: 580, h: 400}: 232,
{w: 480, h: 820}: 256,
{w: 400, h: 600}: 257,
{w: 500, h: 200}: 258,
{w: 998, h: 200}: 259,
{w: 970, h: 1000}: 264,
{w: 1920, h: 1080}: 265,
{w: 1800, h: 200}: 274,
{w: 320, h: 500}: 278,
{w: 320, h: 400}: 282,
{w: 640, h: 380}: 288,
{w: 500, h: 1000}: 548,
}
// defines the contract for bidrequest.user.ext.eids[i].ext
type rubiconUserExtEidExt struct {
Segments []string `json:"segments,omitempty"`
}
// defines the contract for bidrequest.user.ext.eids[i].uids[j].ext
type rubiconUserExtEidUidExt struct {
RtiPartner string `json:"rtiPartner,omitempty"`
Stype string `json:"stype"`
}
type mappedRubiconUidsParam struct {
tpIds []rubiconExtUserTpID
segments []string
liverampIdl string
}
// MAS algorithm
func findPrimary(alt []int) (int, []int) {
min, pos, primary := 0, 0, 0
for i, size := range alt {
if size == 15 {
primary = 15
pos = i
break
} else if size == 2 {
primary = 2
pos = i
} else if size == 9 && primary != 2 {
primary = 9
pos = i
} else if size < alt[min] {
min = i
}
}
if primary == 0 {
primary = alt[min]
pos = min
}
alt = append(alt[:pos], alt[pos+1:]...)
return primary, alt
}
func parseRubiconSizes(sizes []openrtb2.Format) (primary int, alt []int, err error) {
// Fixes #317
if len(sizes) < 1 {
err = &errortypes.BadInput{
Message: "rubicon imps must have at least one imp.format element",
}
return
}
for _, size := range sizes {
if rs, ok := rubiSizeMap[rubiSize{w: uint16(size.W), h: uint16(size.H)}]; ok {
alt = append(alt, rs)
}
}
if len(alt) > 0 {
primary, alt = findPrimary(alt)
} else {
err = &errortypes.BadInput{
Message: "No primary size found",
}
}
return
}
func resolveVideoSizeId(placement openrtb2.VideoPlacementType, instl int8, impId string) (sizeID int, err error) {
if placement != 0 {
if placement == 1 {
return 201, nil
}
if placement == 3 {
return 203, nil
}
}
if instl == 1 {
return 202, nil
}
return 0, &errortypes.BadInput{
Message: fmt.Sprintf("video.size_id can not be resolved in impression with id : %s", impId),
}
}
func appendTrackerToUrl(uri string, tracker string) (res string) {
// Append integration method. Adapter init happens once
urlObject, err := url.Parse(uri)
// No other exception throwing mechanism in this stack, so ignoring parse errors.
if err == nil {
values := urlObject.Query()
values.Add("tk_xint", tracker)
urlObject.RawQuery = values.Encode()
res = urlObject.String()
} else {
res = uri
}
return
}
// Builder builds a new instance of the Rubicon adapter for the given bidder with the given config.
func Builder(bidderName openrtb_ext.BidderName, config config.Adapter) (adapters.Bidder, error) {
uri := appendTrackerToUrl(config.Endpoint, config.XAPI.Tracker)
bidder := &RubiconAdapter{
URI: uri,
XAPIUsername: config.XAPI.Username,
XAPIPassword: config.XAPI.Password,
}
return bidder, nil
}
func (a *RubiconAdapter) MakeRequests(request *openrtb2.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) {
numRequests := len(request.Imp)
errs := make([]error, 0, len(request.Imp))
var err error
requestData := make([]*adapters.RequestData, 0, numRequests)
headers := http.Header{}
headers.Add("Content-Type", "application/json;charset=utf-8")
headers.Add("Accept", "application/json")
headers.Add("User-Agent", "prebid-server/1.0")
requestImpCopy := request.Imp
rubiconRequest := *request
for _, imp := range requestImpCopy {
var bidderExt rubiconExtImpBidder
if err = json.Unmarshal(imp.Ext, &bidderExt); err != nil {
errs = append(errs, &errortypes.BadInput{
Message: err.Error(),
})
continue
}
var rubiconExt openrtb_ext.ExtImpRubicon
if err = json.Unmarshal(bidderExt.Bidder, &rubiconExt); err != nil {
errs = append(errs, &errortypes.BadInput{
Message: err.Error(),
})
continue
}
target, err := updateImpRpTargetWithFpdAttributes(bidderExt, rubiconExt, imp, request.Site, request.App)
if err != nil {
errs = append(errs, err)
continue
}
siteId, err := rubiconExt.SiteId.Int64()
if err != nil {
errs = append(errs, err)
continue
}
zoneId, err := rubiconExt.ZoneId.Int64()
if err != nil {
errs = append(errs, err)
continue
}
impExt := rubiconImpExt{
RP: rubiconImpExtRP{
ZoneID: int(zoneId),
Target: target,
Track: rubiconImpExtRPTrack{Mint: "", MintVersion: ""},
},
GPID: bidderExt.Gpid,
}
imp.Ext, err = json.Marshal(&impExt)
if err != nil {
errs = append(errs, err)
continue
}
resolvedBidFloor, err := resolveBidFloor(imp.BidFloor, imp.BidFloorCur, reqInfo)
if err != nil {
errs = append(errs, &errortypes.BadInput{
Message: fmt.Sprintf("Unable to convert provided bid floor currency from %s to USD",
imp.BidFloorCur),
})
continue
}
if resolvedBidFloor > 0 {
imp.BidFloorCur = "USD"
imp.BidFloor = resolvedBidFloor
}
if request.User != nil {
userCopy := *request.User
target, err := updateUserRpTargetWithFpdAttributes(rubiconExt.Visitor, userCopy)
if err != nil {
errs = append(errs, err)
continue
}
userExtRP := rubiconUserExt{RP: rubiconUserExtRP{Target: target}}
userBuyerUID := userCopy.BuyerUID
if request.User.Ext != nil {
var userExt *openrtb_ext.ExtUser
if err = json.Unmarshal(userCopy.Ext, &userExt); err != nil {
errs = append(errs, &errortypes.BadInput{
Message: err.Error(),
})
continue
}
userExtRP.Consent = userExt.Consent
userExtRP.Eids = userExt.Eids
// set user.ext.tpid
if len(userExt.Eids) > 0 {
if userBuyerUID == "" {
userBuyerUID = extractUserBuyerUID(userExt.Eids)
}
mappedRubiconUidsParam, errors := getTpIdsAndSegments(userExt.Eids)
if len(errors) > 0 {
errs = append(errs, errors...)
continue
}
if err := updateUserExtWithTpIdsAndSegments(&userExtRP, mappedRubiconUidsParam); err != nil {
errs = append(errs, err)
continue
}
userExtRP.LiverampIdl = mappedRubiconUidsParam.liverampIdl
}
}
userCopy.Ext, err = json.Marshal(&userExtRP)
if err != nil {
errs = append(errs, err)
continue
}
userCopy.Geo = nil
userCopy.Yob = 0
userCopy.Gender = ""
userCopy.BuyerUID = userBuyerUID
rubiconRequest.User = &userCopy
}
if request.Device != nil {
deviceCopy := *request.Device
deviceExt := rubiconDeviceExt{RP: rubiconDeviceExtRP{PixelRatio: request.Device.PxRatio}}
deviceCopy.Ext, err = json.Marshal(&deviceExt)
rubiconRequest.Device = &deviceCopy
}
isVideo := isVideo(imp)
if isVideo {
videoCopy := *imp.Video
videoSizeId := rubiconExt.Video.VideoSizeID
if videoSizeId == 0 {
resolvedSizeId, err := resolveVideoSizeId(imp.Video.Placement, imp.Instl, imp.ID)
if err != nil {
errs = append(errs, err)
continue
}
videoSizeId = resolvedSizeId
}
// if imp.ext.is_rewarded_inventory = 1, set imp.video.ext.videotype = "rewarded"
var videoType = ""
if bidderExt.Prebid != nil && bidderExt.Prebid.IsRewardedInventory == 1 {
videoType = "rewarded"
}
videoExt := rubiconVideoExt{Skip: rubiconExt.Video.Skip, SkipDelay: rubiconExt.Video.SkipDelay, VideoType: videoType, RP: rubiconVideoExtRP{SizeID: videoSizeId}}
videoCopy.Ext, err = json.Marshal(&videoExt)
imp.Video = &videoCopy
imp.Banner = nil
} else {
primarySizeID, altSizeIDs, err := parseRubiconSizes(imp.Banner.Format)
if err != nil {
errs = append(errs, err)
continue
}
bannerExt := rubiconBannerExt{RP: rubiconBannerExtRP{SizeID: primarySizeID, AltSizeIDs: altSizeIDs, MIME: "text/html"}}
bannerCopy := *imp.Banner
bannerCopy.Ext, err = json.Marshal(&bannerExt)
if err != nil {
errs = append(errs, err)
continue
}
imp.Banner = &bannerCopy
imp.Video = nil
}
accountId, err := rubiconExt.AccountId.Int64()
if err != nil {
errs = append(errs, err)
continue
}
pubExt := rubiconPubExt{RP: rubiconPubExtRP{AccountID: int(accountId)}}
if request.Site != nil {
siteCopy := *request.Site
siteExtRP := rubiconSiteExt{RP: rubiconSiteExtRP{SiteID: int(siteId)}}
if siteCopy.Content != nil {
siteTarget := make(map[string]interface{})
updateExtWithIabAttribute(siteTarget, siteCopy.Content.Data, []int{1, 2, 5, 6})
if len(siteTarget) > 0 {
updatedSiteTarget, err := json.Marshal(siteTarget)
if err != nil {
errs = append(errs, err)
continue
}
siteExtRP.RP.Target = updatedSiteTarget
}
}
siteCopy.Ext, err = json.Marshal(&siteExtRP)
if err != nil {
errs = append(errs, err)
continue
}
siteCopy.Publisher = &openrtb2.Publisher{}
siteCopy.Publisher.Ext, err = json.Marshal(&pubExt)
rubiconRequest.Site = &siteCopy
} else {
appCopy := *request.App
appCopy.Ext, err = json.Marshal(rubiconSiteExt{RP: rubiconSiteExtRP{SiteID: int(siteId)}})
appCopy.Publisher = &openrtb2.Publisher{}
appCopy.Publisher.Ext, err = json.Marshal(&pubExt)
rubiconRequest.App = &appCopy
}
reqBadv := request.BAdv
if reqBadv != nil {
if len(reqBadv) > badvLimitSize {
rubiconRequest.BAdv = reqBadv[:badvLimitSize]
}
}
rubiconRequest.Imp = []openrtb2.Imp{imp}
rubiconRequest.Cur = nil
rubiconRequest.Ext = nil
reqJSON, err := json.Marshal(rubiconRequest)
if err != nil {
errs = append(errs, err)
continue
}
reqData := &adapters.RequestData{
Method: "POST",
Uri: a.URI,
Body: reqJSON,
Headers: headers,
}
reqData.SetBasicAuth(a.XAPIUsername, a.XAPIPassword)
requestData = append(requestData, reqData)
}
return requestData, errs
}
func resolveBidFloor(bidFloor float64, bidFloorCur string, reqInfo *adapters.ExtraRequestInfo) (float64, error) {
if bidFloor > 0 && bidFloorCur != "" && strings.ToUpper(bidFloorCur) != "USD" {
return reqInfo.ConvertCurrency(bidFloor, bidFloorCur, "USD")
}
return bidFloor, nil
}
func updateImpRpTargetWithFpdAttributes(extImp rubiconExtImpBidder, extImpRubicon openrtb_ext.ExtImpRubicon,
imp openrtb2.Imp, site *openrtb2.Site, app *openrtb2.App) (json.RawMessage, error) {
existingTarget, _, _, err := jsonparser.Get(imp.Ext, "rp", "target")
if isNotKeyPathError(err) {
return nil, err
}
target, err := rawJSONToMap(existingTarget)
if err != nil {
return nil, err
}
err = populateFirstPartyDataAttributes(extImpRubicon.Inventory, target)
if err != nil {
return nil, err
}
if site != nil {
siteExtData, _, _, err := jsonparser.Get(site.Ext, "data")
if isNotKeyPathError(err) {
return nil, err
}
err = populateFirstPartyDataAttributes(siteExtData, target)
if err != nil {
return nil, err
}
if len(site.SectionCat) > 0 {
addStringArrayAttribute(site.SectionCat, target, "sectioncat")
}
if len(site.PageCat) > 0 {
addStringArrayAttribute(site.PageCat, target, "pagecat")
}
if site.Page != "" {
addStringAttribute(site.Page, target, "page")
}
if site.Ref != "" {
addStringAttribute(site.Ref, target, "ref")
}
if site.Search != "" {
addStringAttribute(site.Search, target, "search")
}
} else {
appExtData, _, _, err := jsonparser.Get(app.Ext, "data")
if isNotKeyPathError(err) {
return nil, err
}
err = populateFirstPartyDataAttributes(appExtData, target)
if err != nil {
return nil, err
}
if len(app.SectionCat) > 0 {
addStringArrayAttribute(app.SectionCat, target, "sectioncat")
}
if len(app.PageCat) > 0 {
addStringArrayAttribute(app.PageCat, target, "pagecat")
}
}
if len(extImp.Context.Data) > 0 {
err = populateFirstPartyDataAttributes(extImp.Context.Data, target)
} else if len(extImp.Data) > 0 {
err = populateFirstPartyDataAttributes(extImp.Data, target)
}
if isNotKeyPathError(err) {
return nil, err
}
var data rubiconData
if len(extImp.Data) > 0 {
err := json.Unmarshal(extImp.Data, &data)
if err != nil {
return nil, err
}
}
var contextData rubiconData
if len(extImp.Context.Data) > 0 {
err := json.Unmarshal(extImp.Context.Data, &contextData)
if err != nil {
return nil, err
}
}
if data.PbAdSlot != "" {
target["pbadslot"] = data.PbAdSlot
} else {
dfpAdUnitCode := extractDfpAdUnitCode(data, contextData)
if dfpAdUnitCode != "" {
target["dfp_ad_unit_code"] = dfpAdUnitCode
}
}
if len(extImpRubicon.Keywords) > 0 {
addStringArrayAttribute(extImpRubicon.Keywords, target, "keywords")
}
updatedTarget, err := json.Marshal(target)
if err != nil {
return nil, err
}
return updatedTarget, nil
}
func extractDfpAdUnitCode(data rubiconData, contextData rubiconData) string {
if contextData.AdServer.Name == "gam" && contextData.AdServer.AdSlot != "" {
return contextData.AdServer.AdSlot
} else if data.AdServer.Name == "gam" && data.AdServer.AdSlot != "" {
return data.AdServer.AdSlot
}
return ""
}
func isNotKeyPathError(err error) bool {
return err != nil && err != jsonparser.KeyPathNotFoundError
}
func addStringAttribute(attribute string, target map[string]interface{}, attributeName string) {
target[attributeName] = [1]string{attribute}
}
func addStringArrayAttribute(attribute []string, target map[string]interface{}, attributeName string) {
target[attributeName] = attribute
}
func updateUserRpTargetWithFpdAttributes(visitor json.RawMessage, user openrtb2.User) (json.RawMessage, error) {
existingTarget, _, _, err := jsonparser.Get(user.Ext, "rp", "target")
if isNotKeyPathError(err) {
return nil, err
}
target, err := rawJSONToMap(existingTarget)
if err != nil {
return nil, err
}
err = populateFirstPartyDataAttributes(visitor, target)
if err != nil {
return nil, err
}
userExtData, _, _, err := jsonparser.Get(user.Ext, "data")
if isNotKeyPathError(err) {
return nil, err
}
err = populateFirstPartyDataAttributes(userExtData, target)
if err != nil {
return nil, err
}
updateExtWithIabAttribute(target, user.Data, []int{4})
updatedTarget, err := json.Marshal(target)
if err != nil {
return nil, err
}
return updatedTarget, nil
}
func updateExtWithIabAttribute(target map[string]interface{}, data []openrtb2.Data, segTaxes []int) {
var segmentIdsToCopy = getSegmentIdsToCopy(data, segTaxes)
if len(segmentIdsToCopy) == 0 {
return
}
target["iab"] = segmentIdsToCopy
}
func populateFirstPartyDataAttributes(source json.RawMessage, target map[string]interface{}) error {
sourceAsMap, err := rawJSONToMap(source)
if err != nil {
return err
}
for key, val := range sourceAsMap {
switch typedValue := val.(type) {
case string:
target[key] = [1]string{typedValue}
case float64:
if typedValue == float64(int(typedValue)) {
target[key] = [1]string{strconv.Itoa(int(typedValue))}
}
case bool:
target[key] = [1]string{strconv.FormatBool(typedValue)}
case []interface{}:
if isStringArray(typedValue) {
target[key] = typedValue
}
if isBoolArray(typedValue) {
target[key] = convertToStringArray(typedValue)
}
}
}
return nil
}
func isStringArray(array []interface{}) bool {
for _, val := range array {
if _, ok := val.(string); !ok {
return false
}
}
return true
}
func isBoolArray(array []interface{}) bool {
for _, val := range array {
if _, ok := val.(bool); !ok {
return false
}
}
return true
}
func convertToStringArray(arr []interface{}) []string {
var stringArray []string
for _, val := range arr {
if boolVal, ok := val.(bool); ok {
stringArray = append(stringArray, strconv.FormatBool(boolVal))
}
}
return stringArray
}
func rawJSONToMap(message json.RawMessage) (map[string]interface{}, error) {
if message == nil {
return make(map[string]interface{}), nil
}
return mapFromRawJSON(message)
}
func mapFromRawJSON(message json.RawMessage) (map[string]interface{}, error) {
targetAsMap := make(map[string]interface{})
err := json.Unmarshal(message, &targetAsMap)
if err != nil {
return nil, err
}
return targetAsMap, nil
}
func getSegmentIdsToCopy(data []openrtb2.Data, segTaxValues []int) []string {
var segmentIdsToCopy = make([]string, 0, len(data))
for _, dataRecord := range data {
if dataRecord.Ext != nil {
var dataExtObject rubiconDataExt
err := json.Unmarshal(dataRecord.Ext, &dataExtObject)
if err != nil {
continue
}
if contains(segTaxValues, dataExtObject.SegTax) {
for _, segment := range dataRecord.Segment {
segmentIdsToCopy = append(segmentIdsToCopy, segment.ID)
}
}
}
}
return segmentIdsToCopy
}
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func extractUserBuyerUID(eids []openrtb_ext.ExtUserEid) string {
for _, eid := range eids {
if eid.Source != "rubiconproject.com" {
continue
}
for _, uid := range eid.Uids {
var uidExt rubiconUserExtEidUidExt
err := json.Unmarshal(uid.Ext, &uidExt)
if err != nil {
continue
}
if uidExt.Stype == "ppuid" || uidExt.Stype == "other" {
return uid.ID
}
}
}
return ""
}
func getTpIdsAndSegments(eids []openrtb_ext.ExtUserEid) (mappedRubiconUidsParam, []error) {
rubiconUidsParam := mappedRubiconUidsParam{
tpIds: make([]rubiconExtUserTpID, 0),
segments: make([]string, 0),
}
errs := make([]error, 0)
for _, eid := range eids {
switch eid.Source {
case "adserver.org":
uids := eid.Uids
if len(uids) > 0 {
uid := uids[0]
if uid.Ext != nil {
var eidUidExt rubiconUserExtEidUidExt
if err := json.Unmarshal(uid.Ext, &eidUidExt); err != nil {
errs = append(errs, &errortypes.BadInput{
Message: err.Error(),
})
continue
}
if eidUidExt.RtiPartner == "TDID" {
rubiconUidsParam.tpIds = append(rubiconUidsParam.tpIds, rubiconExtUserTpID{Source: "tdid", UID: uid.ID})
}
}
}
case "liveintent.com":
uids := eid.Uids
if len(uids) > 0 {
uidId := uids[0].ID
if uidId != "" {
rubiconUidsParam.tpIds = append(rubiconUidsParam.tpIds, rubiconExtUserTpID{Source: "liveintent.com", UID: uidId})
}
if eid.Ext != nil {
var eidExt rubiconUserExtEidExt
if err := json.Unmarshal(eid.Ext, &eidExt); err != nil {
errs = append(errs, &errortypes.BadInput{
Message: err.Error(),
})
continue
}
rubiconUidsParam.segments = eidExt.Segments
}
}
case "liveramp.com":
uids := eid.Uids
if len(uids) > 0 {
uidId := uids[0].ID
if uidId != "" && rubiconUidsParam.liverampIdl == "" {
rubiconUidsParam.liverampIdl = uidId
}
}
}
}
return rubiconUidsParam, errs
}
func updateUserExtWithTpIdsAndSegments(userExtRP *rubiconUserExt, rubiconUidsParam mappedRubiconUidsParam) error {
if len(rubiconUidsParam.tpIds) > 0 {
userExtRP.TpID = rubiconUidsParam.tpIds
if rubiconUidsParam.segments != nil {
userExtRPTarget := make(map[string]interface{})
if userExtRP.RP.Target != nil {
if err := json.Unmarshal(userExtRP.RP.Target, &userExtRPTarget); err != nil {
return &errortypes.BadInput{Message: err.Error()}
}
}
userExtRPTarget["LIseg"] = rubiconUidsParam.segments
if target, err := json.Marshal(&userExtRPTarget); err != nil {
return &errortypes.BadInput{Message: err.Error()}