-
Notifications
You must be signed in to change notification settings - Fork 719
/
huaweiads.go
1641 lines (1493 loc) · 54.3 KB
/
huaweiads.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 huaweiads
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/prebid/openrtb/v20/native1"
nativeRequests "github.com/prebid/openrtb/v20/native1/request"
nativeResponse "github.com/prebid/openrtb/v20/native1/response"
"github.com/prebid/openrtb/v20/openrtb2"
"github.com/prebid/prebid-server/v2/adapters"
"github.com/prebid/prebid-server/v2/config"
"github.com/prebid/prebid-server/v2/errortypes"
"github.com/prebid/prebid-server/v2/openrtb_ext"
"github.com/prebid/prebid-server/v2/util/ptrutil"
)
const huaweiAdxApiVersion = "3.4"
const defaultCountryName = "ZA"
const defaultUnknownNetworkType = 0
const timeFormat = "2006-01-02 15:04:05.000"
const defaultTimeZone = "+0200"
const defaultModelName = "HUAWEI"
const chineseSiteEndPoint = "https://acd.op.hicloud.com/ppsadx/getResult"
const europeanSiteEndPoint = "https://adx-dre.op.hicloud.com/ppsadx/getResult"
const asianSiteEndPoint = "https://adx-dra.op.hicloud.com/ppsadx/getResult"
const russianSiteEndPoint = "https://adx-drru.op.hicloud.com/ppsadx/getResult"
// creative type
const (
text int32 = 1
bigPicture int32 = 2
bigPicture2 int32 = 3
gif int32 = 4
videoText int32 = 6
smallPicture int32 = 7
threeSmallPicturesText int32 = 8
video int32 = 9
iconText int32 = 10
videoWithPicturesText int32 = 11
)
// interaction type
const (
appPromotion int32 = 3
)
// ads type
const (
banner int32 = 8
native int32 = 3
roll int32 = 60
interstitial int32 = 12
rewarded int32 = 7
splash int32 = 1
magazinelock int32 = 2
audio int32 = 17
)
type huaweiAdsRequest struct {
Version string `json:"version"`
Multislot []adslot30 `json:"multislot"`
App app `json:"app"`
Device device `json:"device"`
Network network `json:"network,omitempty"`
Regs regs `json:"regs,omitempty"`
Geo geo `json:"geo,omitempty"`
Consent string `json:"consent,omitempty"`
ClientAdRequestId string `json:"clientAdRequestId,omitempty"`
}
type adslot30 struct {
Slotid string `json:"slotid"`
Adtype int32 `json:"adtype"`
Test int32 `json:"test"`
TotalDuration int32 `json:"totalDuration,omitempty"`
Orientation int32 `json:"orientation,omitempty"`
W int64 `json:"w,omitempty"`
H int64 `json:"h,omitempty"`
Format []format `json:"format,omitempty"`
DetailedCreativeTypeList []string `json:"detailedCreativeTypeList,omitempty"`
}
type format struct {
W int64 `json:"w,omitempty"`
H int64 `json:"h,omitempty"`
}
type app struct {
Version string `json:"version,omitempty"`
Name string `json:"name,omitempty"`
Pkgname string `json:"pkgname"`
Lang string `json:"lang,omitempty"`
Country string `json:"country,omitempty"`
}
type device struct {
Type int32 `json:"type,omitempty"`
Useragent string `json:"useragent,omitempty"`
Os string `json:"os,omitempty"`
Version string `json:"version,omitempty"`
Maker string `json:"maker,omitempty"`
Model string `json:"model,omitempty"`
Width int32 `json:"width,omitempty"`
Height int32 `json:"height,omitempty"`
Language string `json:"language,omitempty"`
BuildVersion string `json:"buildVersion,omitempty"`
Dpi int32 `json:"dpi,omitempty"`
Pxratio float32 `json:"pxratio,omitempty"`
Imei string `json:"imei,omitempty"`
Oaid string `json:"oaid,omitempty"`
IsTrackingEnabled string `json:"isTrackingEnabled,omitempty"`
EmuiVer string `json:"emuiVer,omitempty"`
LocaleCountry string `json:"localeCountry"`
BelongCountry string `json:"belongCountry"`
GaidTrackingEnabled string `json:"gaidTrackingEnabled,omitempty"`
Gaid string `json:"gaid,omitempty"`
ClientTime string `json:"clientTime"`
Ip string `json:"ip,omitempty"`
}
type network struct {
Type int32 `json:"type"`
Carrier int32 `json:"carrier,omitempty"`
CellInfo []cellInfo `json:"cellInfo,omitempty"`
}
type regs struct {
Coppa int32 `json:"coppa,omitempty"`
}
type geo struct {
Lon float32 `json:"lon,omitempty"`
Lat float32 `json:"lat,omitempty"`
Accuracy int32 `json:"accuracy,omitempty"`
Lastfix int32 `json:"lastfix,omitempty"`
}
type cellInfo struct {
Mcc string `json:"mcc,omitempty"`
Mnc string `json:"mnc,omitempty"`
}
type huaweiAdsResponse struct {
Retcode int32 `json:"retcode"`
Reason string `json:"reason"`
Multiad []ad30 `json:"multiad"`
}
type ad30 struct {
AdType int32 `json:"adtype"`
Slotid string `json:"slotid"`
Retcode30 int32 `json:"retcode30"`
Content []content `json:"content"`
}
type content struct {
Contentid string `json:"contentid"`
Interactiontype int32 `json:"interactiontype"`
Creativetype int32 `json:"creativetype"`
MetaData metaData `json:"metaData"`
Monitor []monitor `json:"monitor"`
Cur string `json:"cur"`
Price float64 `json:"price"`
}
type metaData struct {
Title string `json:"title"`
Description string `json:"description"`
ImageInfo []imageInfo `json:"imageInfo"`
Icon []icon `json:"icon"`
ClickUrl string `json:"clickUrl"`
Intent string `json:"intent"`
VideoInfo videoInfo `json:"videoInfo"`
ApkInfo apkInfo `json:"apkInfo"`
Duration int64 `json:"duration"`
MediaFile mediaFile `json:"mediaFile"`
Cta string `json:"cta"`
}
type imageInfo struct {
Url string `json:"url"`
Height int64 `json:"height"`
FileSize int64 `json:"fileSize"`
Sha256 string `json:"sha256"`
ImageType string `json:"imageType"`
Width int64 `json:"width"`
}
type icon struct {
Url string `json:"url"`
Height int64 `json:"height"`
FileSize int64 `json:"fileSize"`
Sha256 string `json:"sha256"`
ImageType string `json:"imageType"`
Width int64 `json:"width"`
}
type videoInfo struct {
VideoDownloadUrl string `json:"videoDownloadUrl"`
VideoDuration int32 `json:"videoDuration"`
VideoFileSize int32 `json:"videoFileSize"`
Sha256 string `json:"sha256"`
VideoRatio float32 `json:"videoRatio"`
Width int32 `json:"width"`
Height int32 `json:"height"`
}
type apkInfo struct {
Url string `json:"url"`
FileSize int64 `json:"fileSize"`
Sha256 string `json:"sha256"`
PackageName string `json:"packageName"`
SecondUrl string `json:"secondUrl"`
AppName string `json:"appName"`
VersionName string `json:"versionName"`
AppDesc string `json:"appDesc"`
AppIcon string `json:"appIcon"`
}
type mediaFile struct {
Mime string `json:"mime"`
Width int64 `json:"width"`
Height int64 `json:"height"`
FileSize int64 `json:"fileSize"`
Url string `json:"url"`
Sha256 string `json:"sha256"`
}
type monitor struct {
EventType string `json:"eventType"`
Url []string `json:"url"`
}
type adapter struct {
endpoint string
extraInfo ExtraInfo
}
type ExtraInfo struct {
PkgNameConvert []pkgNameConvert `json:"pkgNameConvert,omitempty"`
CloseSiteSelectionByCountry string `json:"closeSiteSelectionByCountry,omitempty"`
}
type pkgNameConvert struct {
ConvertedPkgName string `json:"convertedPkgName,omitempty"`
UnconvertedPkgNames []string `json:"unconvertedPkgNames,omitempty"`
UnconvertedPkgNameKeyWords []string `json:"unconvertedPkgNameKeyWords,omitempty"`
UnconvertedPkgNamePrefixs []string `json:"unconvertedPkgNamePrefixs,omitempty"`
ExceptionPkgNames []string `json:"exceptionPkgNames,omitempty"`
}
type empty struct {
}
func (a *adapter) MakeRequests(openRTBRequest *openrtb2.BidRequest,
reqInfo *adapters.ExtraRequestInfo) (requestsToBidder []*adapters.RequestData, errs []error) {
// the upstream code already confirms that there is a non-zero number of impressions
numRequests := len(openRTBRequest.Imp)
var request huaweiAdsRequest
var header http.Header
var multislot = make([]adslot30, 0, numRequests)
var huaweiAdsImpExt *openrtb_ext.ExtImpHuaweiAds
for index := 0; index < numRequests; index++ {
var err1 error
huaweiAdsImpExt, err1 = unmarshalExtImpHuaweiAds(&openRTBRequest.Imp[index])
if err1 != nil {
return nil, []error{err1}
}
if huaweiAdsImpExt == nil {
return nil, []error{errors.New("Unmarshal ExtImpHuaweiAds failed: huaweiAdsImpExt is nil.")}
}
adslot30, err := getReqAdslot30(huaweiAdsImpExt, &openRTBRequest.Imp[index])
if err != nil {
return nil, []error{err}
}
multislot = append(multislot, adslot30)
}
request.Multislot = multislot
request.ClientAdRequestId = openRTBRequest.ID
countryCode, err := getReqJson(&request, openRTBRequest, a.extraInfo)
if err != nil {
return nil, []error{err}
}
reqJSON, err := json.Marshal(request)
if err != nil {
return nil, []error{err}
}
// our request header's Authorization is changing by time, cannot verify by a certain string,
// use isTestAuthorization = true only when run testcase
var isTestAuthorization = false
if huaweiAdsImpExt != nil && huaweiAdsImpExt.IsTestAuthorization == "true" {
isTestAuthorization = true
}
header = getHeaders(huaweiAdsImpExt, openRTBRequest, isTestAuthorization)
bidRequest := &adapters.RequestData{
Method: http.MethodPost,
Uri: getFinalEndPoint(countryCode, a.endpoint, a.extraInfo),
Body: reqJSON,
Headers: header,
ImpIDs: openrtb_ext.GetImpIDs(openRTBRequest.Imp),
}
return []*adapters.RequestData{bidRequest}, nil
}
// countryCode is alpha2, choose the corresponding site end point
func getFinalEndPoint(countryCode string, defaultEndpoint string, extraInfo ExtraInfo) string {
// closeSiteSelectionByCountry == 1, close site selection, use the defaultEndpoint
if "1" == extraInfo.CloseSiteSelectionByCountry {
return defaultEndpoint
}
if countryCode == "" || len(countryCode) > 2 {
return defaultEndpoint
}
var europeanSiteCountryCodeGroup = map[string]empty{"AX": {}, "AL": {}, "AD": {}, "AU": {}, "AT": {}, "BE": {},
"BA": {}, "BG": {}, "CA": {}, "HR": {}, "CY": {}, "CZ": {}, "DK": {}, "EE": {}, "FO": {}, "FI": {},
"FR": {}, "DE": {}, "GI": {}, "GR": {}, "GL": {}, "GG": {}, "VA": {}, "HU": {}, "IS": {}, "IE": {},
"IM": {}, "IL": {}, "IT": {}, "JE": {}, "YK": {}, "LV": {}, "LI": {}, "LT": {}, "LU": {}, "MT": {},
"MD": {}, "MC": {}, "ME": {}, "NL": {}, "AN": {}, "NZ": {}, "NO": {}, "PL": {}, "PT": {}, "RO": {},
"MF": {}, "VC": {}, "SM": {}, "RS": {}, "SX": {}, "SK": {}, "SI": {}, "ES": {}, "SE": {}, "CH": {},
"TR": {}, "UA": {}, "GB": {}, "US": {}, "MK": {}, "SJ": {}, "BQ": {}, "PM": {}, "CW": {}}
var russianSiteCountryCodeGroup = map[string]empty{"RU": {}}
var chineseSiteCountryCodeGroup = map[string]empty{"CN": {}}
// choose site
if _, exists := chineseSiteCountryCodeGroup[countryCode]; exists {
return chineseSiteEndPoint
} else if _, exists := russianSiteCountryCodeGroup[countryCode]; exists {
return russianSiteEndPoint
} else if _, exists := europeanSiteCountryCodeGroup[countryCode]; exists {
return europeanSiteEndPoint
} else {
return asianSiteEndPoint
}
}
func (a *adapter) MakeBids(openRTBRequest *openrtb2.BidRequest, requestToBidder *adapters.RequestData,
bidderRawResponse *adapters.ResponseData) (bidderResponse *adapters.BidderResponse, errs []error) {
httpStatusError := checkRespStatusCode(bidderRawResponse)
if httpStatusError != nil {
return nil, []error{httpStatusError}
}
var huaweiAdsResponse huaweiAdsResponse
if err := json.Unmarshal(bidderRawResponse.Body, &huaweiAdsResponse); err != nil {
return nil, []error{&errortypes.BadServerResponse{
Message: "Unable to parse server response",
}}
}
if err := checkHuaweiAdsResponseRetcode(huaweiAdsResponse); err != nil {
return nil, []error{err}
}
bidderResponse, err := a.convertHuaweiAdsRespToBidderResp(&huaweiAdsResponse, openRTBRequest)
if err != nil {
return nil, []error{err}
}
return bidderResponse, nil
}
// Builder builds a new instance of the HuaweiAds adapter for the given bidder with the given config.
func Builder(bidderName openrtb_ext.BidderName, config config.Adapter, server config.Server) (adapters.Bidder, error) {
extraInfo, err := getExtraInfo(config.ExtraAdapterInfo)
if err != nil {
return nil, err
}
bidder := &adapter{
endpoint: config.Endpoint,
extraInfo: extraInfo,
}
return bidder, nil
}
func getExtraInfo(v string) (ExtraInfo, error) {
var extraInfo ExtraInfo
if len(v) == 0 {
return extraInfo, nil
}
if err := json.Unmarshal([]byte(v), &extraInfo); err != nil {
return extraInfo, fmt.Errorf("invalid extra info: %v , pls check", err)
}
for _, convert := range extraInfo.PkgNameConvert {
if convert.ConvertedPkgName == "" {
return extraInfo, fmt.Errorf("invalid extra info: ConvertedPkgName is empty, pls check")
}
if convert.UnconvertedPkgNameKeyWords != nil {
for _, keyword := range convert.UnconvertedPkgNameKeyWords {
if keyword == "" {
return extraInfo, fmt.Errorf("invalid extra info: UnconvertedPkgNameKeyWords has a empty keyword, pls check")
}
}
}
if convert.UnconvertedPkgNamePrefixs != nil {
for _, prefix := range convert.UnconvertedPkgNamePrefixs {
if prefix == "" {
return extraInfo, fmt.Errorf("invalid extra info: UnconvertedPkgNamePrefixs has a empty value, pls check")
}
}
}
}
return extraInfo, nil
}
// getHeaders: get request header, Authorization -> digest
func getHeaders(huaweiAdsImpExt *openrtb_ext.ExtImpHuaweiAds, request *openrtb2.BidRequest, isTestAuthorization bool) http.Header {
headers := http.Header{}
headers.Add("Content-Type", "application/json;charset=utf-8")
headers.Add("Accept", "application/json")
if huaweiAdsImpExt == nil {
return headers
}
headers.Add("Authorization", getDigestAuthorization(huaweiAdsImpExt, isTestAuthorization))
if request.Device != nil && len(request.Device.UA) > 0 {
headers.Add("User-Agent", request.Device.UA)
}
return headers
}
// getReqJson: get body json for HuaweiAds request
func getReqJson(request *huaweiAdsRequest, openRTBRequest *openrtb2.BidRequest, extraInfo ExtraInfo) (countryCode string, err error) {
request.Version = huaweiAdxApiVersion
if countryCode, err = getReqAppInfo(request, openRTBRequest, extraInfo); err != nil {
return "", err
}
if err = getReqDeviceInfo(request, openRTBRequest); err != nil {
return "", err
}
getReqNetWorkInfo(request, openRTBRequest)
getReqRegsInfo(request, openRTBRequest)
getReqGeoInfo(request, openRTBRequest)
getReqConsentInfo(request, openRTBRequest)
return countryCode, nil
}
func getReqAdslot30(huaweiAdsImpExt *openrtb_ext.ExtImpHuaweiAds,
openRTBImp *openrtb2.Imp) (adslot30, error) {
adtype := convertAdtypeStringToInteger(strings.ToLower(huaweiAdsImpExt.Adtype))
testStatus := 0
if huaweiAdsImpExt.IsTestAuthorization == "true" {
testStatus = 1
}
var adslot30 = adslot30{
Slotid: huaweiAdsImpExt.SlotId,
Adtype: adtype,
Test: int32(testStatus),
}
if err := checkAndExtractOpenrtbFormat(&adslot30, adtype, huaweiAdsImpExt.Adtype, openRTBImp); err != nil {
return adslot30, err
}
return adslot30, nil
}
// opentrb : huawei adtype
// banner <-> banner, interstitial
// native <-> native
// video <-> banner, roll, interstitial, rewarded
func checkAndExtractOpenrtbFormat(adslot30 *adslot30, adtype int32, yourAdtype string, openRTBImp *openrtb2.Imp) error {
if openRTBImp.Banner != nil {
if adtype != banner && adtype != interstitial {
return errors.New("check openrtb format: request has banner, doesn't correspond to huawei adtype " + yourAdtype)
}
getBannerFormat(adslot30, openRTBImp)
} else if openRTBImp.Native != nil {
if adtype != native {
return errors.New("check openrtb format: request has native, doesn't correspond to huawei adtype " + yourAdtype)
}
if err := getNativeFormat(adslot30, openRTBImp); err != nil {
return err
}
} else if openRTBImp.Video != nil {
if adtype != banner && adtype != interstitial && adtype != rewarded && adtype != roll {
return errors.New("check openrtb format: request has video, doesn't correspond to huawei adtype " + yourAdtype)
}
if err := getVideoFormat(adslot30, adtype, openRTBImp); err != nil {
return err
}
} else if openRTBImp.Audio != nil {
return errors.New("check openrtb format: request has audio, not currently supported")
} else {
return errors.New("check openrtb format: please choose one of our supported type banner, native, or video")
}
return nil
}
func getBannerFormat(adslot30 *adslot30, openRTBImp *openrtb2.Imp) {
if openRTBImp.Banner.W != nil && openRTBImp.Banner.H != nil {
adslot30.W = *openRTBImp.Banner.W
adslot30.H = *openRTBImp.Banner.H
}
if len(openRTBImp.Banner.Format) != 0 {
var formats = make([]format, 0, len(openRTBImp.Banner.Format))
for _, f := range openRTBImp.Banner.Format {
if f.H != 0 && f.W != 0 {
formats = append(formats, format{f.W, f.H})
}
}
adslot30.Format = formats
}
}
func getNativeFormat(adslot30 *adslot30, openRTBImp *openrtb2.Imp) error {
if openRTBImp.Native.Request == "" {
return errors.New("extract openrtb native failed: imp.Native.Request is empty")
}
var nativePayload nativeRequests.Request
if err := json.Unmarshal(json.RawMessage(openRTBImp.Native.Request), &nativePayload); err != nil {
return err
}
//popular size for native ads
popularSizes := []format{{W: 225, H: 150}, {W: 1080, H: 607}, {W: 300, H: 250}, {W: 1080, H: 1620}, {W: 1280, H: 720}, {W: 640, H: 360}, {W: 1080, H: 1920}, {W: 720, H: 1280}}
// only compute the main image number, type = native1.ImageAssetTypeMain
var numMainImage = 0
var numVideo = 0
var formats = make([]format, 0)
var numFormat = 0
var detailedCreativeTypeList = make([]string, 0, 2)
//number of the requested image size
for _, asset := range nativePayload.Assets {
if numFormat > 1 {
break
}
if asset.Img != nil {
if asset.Img.Type == native1.ImageAssetTypeMain {
numFormat++
}
}
}
sizeMap := make(map[format]struct{})
for _, size := range popularSizes {
sizeMap[size] = struct{}{}
}
for _, asset := range nativePayload.Assets {
// Only one of the {title,img,video,data} objects should be present in each object.
if asset.Video != nil {
numVideo++
formats = popularSizes
w := ptrutil.ValueOrDefault(asset.Video.W)
h := ptrutil.ValueOrDefault(asset.Video.H)
_, ok := sizeMap[format{W: w, H: h}]
if (w != 0 && h != 0) && !ok {
formats = append(formats, format{w, h})
}
}
// every image has the same W, H.
if asset.Img != nil {
if asset.Img.Type == native1.ImageAssetTypeMain {
numMainImage++
if numFormat > 1 && asset.Img.H != 0 && asset.Img.W != 0 && asset.Img.WMin != 0 && asset.Img.HMin != 0 {
formats = append(formats, format{asset.Img.W, asset.Img.H})
}
if numFormat == 1 && asset.Img.H != 0 && asset.Img.W != 0 && asset.Img.WMin != 0 && asset.Img.HMin != 0 {
result := filterPopularSizes(popularSizes, asset.Img.W, asset.Img.H, "ratio")
formats = append(formats, result...)
}
if numFormat == 1 && asset.Img.H == 0 && asset.Img.W == 0 && asset.Img.WMin != 0 && asset.Img.HMin != 0 {
result := filterPopularSizes(popularSizes, asset.Img.WMin, asset.Img.HMin, "range")
formats = append(formats, result...)
}
}
}
adslot30.Format = formats
}
if numVideo >= 1 {
detailedCreativeTypeList = append(detailedCreativeTypeList, "903")
}
if numMainImage >= 1 {
detailedCreativeTypeList = append(detailedCreativeTypeList, "901", "904", "905")
}
adslot30.DetailedCreativeTypeList = detailedCreativeTypeList
return nil
}
// filter popular size by range or ratio to append format array
func filterPopularSizes(sizes []format, width int64, height int64, byWhat string) []format {
filtered := []format{}
for _, size := range sizes {
w := size.W
h := size.H
if byWhat == "ratio" {
ratio := float64(width) / float64(height)
diff := math.Abs(float64(w)/float64(h) - ratio)
if diff <= 0.5 {
filtered = append(filtered, size)
}
}
if byWhat == "range" && w > width && h > height {
filtered = append(filtered, size)
}
}
return filtered
}
// roll ad need TotalDuration
func getVideoFormat(adslot30 *adslot30, adtype int32, openRTBImp *openrtb2.Imp) error {
adslot30.W = ptrutil.ValueOrDefault(openRTBImp.Video.W)
adslot30.H = ptrutil.ValueOrDefault(openRTBImp.Video.H)
if adtype == roll {
if openRTBImp.Video.MaxDuration == 0 {
return errors.New("extract openrtb video failed: MaxDuration is empty when huaweiads adtype is roll.")
}
adslot30.TotalDuration = int32(openRTBImp.Video.MaxDuration)
}
return nil
}
func convertAdtypeStringToInteger(adtypeLower string) int32 {
switch adtypeLower {
case "banner":
return banner
case "native":
return native
case "rewarded":
return rewarded
case "interstitial":
return interstitial
case "roll":
return roll
case "splash":
return splash
case "magazinelock":
return magazinelock
case "audio":
return audio
default:
return banner
}
}
// getReqAppInfo: get app information for HuaweiAds request
func getReqAppInfo(request *huaweiAdsRequest, openRTBRequest *openrtb2.BidRequest, extraInfo ExtraInfo) (countryCode string, err error) {
var app app
if openRTBRequest.App != nil {
if openRTBRequest.App.Ver != "" {
app.Version = openRTBRequest.App.Ver
}
if openRTBRequest.App.Name != "" {
app.Name = openRTBRequest.App.Name
}
// bundle cannot be empty, we need package name.
if openRTBRequest.App.Bundle != "" {
app.Pkgname = getFinalPkgName(openRTBRequest.App.Bundle, extraInfo)
} else {
return "", errors.New("generate HuaweiAds AppInfo failed: openrtb BidRequest.App.Bundle is empty.")
}
if openRTBRequest.App.Content != nil && openRTBRequest.App.Content.Language != "" {
app.Lang = openRTBRequest.App.Content.Language
} else {
app.Lang = "en"
}
}
countryCode = getCountryCode(openRTBRequest)
app.Country = countryCode
request.App = app
return countryCode, nil
}
// when it has pkgNameConvert (include different rules)
// 1. when bundleName in ExceptionPkgNames, finalPkgname = bundleName
// 2. when bundleName conform UnconvertedPkgNames, finalPkgname = ConvertedPkgName
// 3. when bundleName conform keyword, finalPkgname = ConvertedPkgName
// 4. when bundleName conform prefix, finalPkgname = ConvertedPkgName
func getFinalPkgName(bundleName string, extraInfo ExtraInfo) string {
for _, convert := range extraInfo.PkgNameConvert {
if convert.ConvertedPkgName == "" {
continue
}
for _, name := range convert.ExceptionPkgNames {
if name == bundleName {
return bundleName
}
}
for _, name := range convert.UnconvertedPkgNames {
if name == bundleName || name == "*" {
return convert.ConvertedPkgName
}
}
for _, keyword := range convert.UnconvertedPkgNameKeyWords {
if strings.Index(bundleName, keyword) > 0 {
return convert.ConvertedPkgName
}
}
for _, prefix := range convert.UnconvertedPkgNamePrefixs {
if strings.HasPrefix(bundleName, prefix) {
return convert.ConvertedPkgName
}
}
}
return bundleName
}
// getClientTime: get field clientTime, format: 2006-01-02 15:04:05.000+0200
// If this parameter is not passed, the server time is used
func getClientTime(clientTime string) (newClientTime string) {
var zone = defaultTimeZone
t := time.Now().Local().Format(time.RFC822Z)
index := strings.IndexAny(t, "-+")
if index > 0 && len(t)-index == 5 {
zone = t[index:]
}
if clientTime == "" {
return time.Now().Format(timeFormat) + zone
}
if isMatched, _ := regexp.MatchString("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{3}[+-]{1}\\d{4}$", clientTime); isMatched {
return clientTime
}
if isMatched, _ := regexp.MatchString("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{3}$", clientTime); isMatched {
return clientTime + zone
}
return time.Now().Format(timeFormat) + zone
}
// getReqDeviceInfo: get device information for HuaweiAds request
func getReqDeviceInfo(request *huaweiAdsRequest, openRTBRequest *openrtb2.BidRequest) (err error) {
var device device
if openRTBRequest.Device != nil {
device.Type = int32(openRTBRequest.Device.DeviceType)
device.Useragent = openRTBRequest.Device.UA
device.Os = openRTBRequest.Device.OS
device.Version = openRTBRequest.Device.OSV
device.Maker = openRTBRequest.Device.Make
device.Model = openRTBRequest.Device.Model
if device.Model == "" {
device.Model = defaultModelName
}
device.Height = int32(openRTBRequest.Device.H)
device.Width = int32(openRTBRequest.Device.W)
device.Language = openRTBRequest.Device.Language
device.Pxratio = float32(openRTBRequest.Device.PxRatio)
var country = getCountryCode(openRTBRequest)
device.BelongCountry = country
device.LocaleCountry = country
device.Ip = openRTBRequest.Device.IP
device.Gaid = openRTBRequest.Device.IFA
device.ClientTime = getClientTime("")
}
// get oaid gaid imei in openRTBRequest.User.Ext.Data
if err = getDeviceIDFromUserExt(&device, openRTBRequest); err != nil {
return err
}
// IsTrackingEnabled = 1 - DNT
if openRTBRequest.Device != nil && openRTBRequest.Device.DNT != nil {
if device.Oaid != "" {
device.IsTrackingEnabled = strconv.Itoa(1 - int(*openRTBRequest.Device.DNT))
}
if device.Gaid != "" {
device.GaidTrackingEnabled = strconv.Itoa(1 - int(*openRTBRequest.Device.DNT))
}
}
request.Device = device
return nil
}
func getCountryCode(openRTBRequest *openrtb2.BidRequest) string {
if openRTBRequest.Device != nil && openRTBRequest.Device.Geo != nil && openRTBRequest.Device.Geo.Country != "" {
return convertCountryCode(openRTBRequest.Device.Geo.Country)
} else if openRTBRequest.User != nil && openRTBRequest.User.Geo != nil && openRTBRequest.User.Geo.Country != "" {
return convertCountryCode(openRTBRequest.User.Geo.Country)
} else if openRTBRequest.Device != nil && openRTBRequest.Device.MCCMNC != "" {
return getCountryCodeFromMCC(openRTBRequest.Device.MCCMNC)
} else {
return defaultCountryName
}
}
// convertCountryCode: ISO 3166-1 Alpha3 -> Alpha2, Some countries may use
func convertCountryCode(country string) (out string) {
if country == "" {
return defaultCountryName
}
var mapCountryCodeAlpha3ToAlpha2 = map[string]string{"AND": "AD", "AGO": "AO", "AUT": "AT", "BGD": "BD",
"BLR": "BY", "CAF": "CF", "TCD": "TD", "CHL": "CL", "CHN": "CN", "COG": "CG", "COD": "CD", "DNK": "DK",
"GNQ": "GQ", "EST": "EE", "GIN": "GN", "GNB": "GW", "GUY": "GY", "IRQ": "IQ", "IRL": "IE", "ISR": "IL",
"KAZ": "KZ", "LBY": "LY", "MDG": "MG", "MDV": "MV", "MEX": "MX", "MNE": "ME", "MOZ": "MZ", "PAK": "PK",
"PNG": "PG", "PRY": "PY", "POL": "PL", "PRT": "PT", "SRB": "RS", "SVK": "SK", "SVN": "SI", "SWE": "SE",
"TUN": "TN", "TUR": "TR", "TKM": "TM", "UKR": "UA", "ARE": "AE", "URY": "UY"}
if mappedCountry, exists := mapCountryCodeAlpha3ToAlpha2[country]; exists {
return mappedCountry
}
if len(country) >= 2 {
return country[0:2]
}
return defaultCountryName
}
func getCountryCodeFromMCC(MCC string) (out string) {
var countryMCC = strings.Split(MCC, "-")[0]
intVar, err := strconv.Atoi(countryMCC)
if err != nil {
return defaultCountryName
} else {
if result, found := MccList[intVar]; found {
return strings.ToUpper(result)
} else {
return defaultCountryName
}
}
}
// getDeviceID include oaid gaid imei. In prebid mobile, use TargetingParams.addUserData("imei", "imei-test");
// When ifa: gaid exists, other device id can be passed by TargetingParams.addUserData("oaid", "oaid-test");
func getDeviceIDFromUserExt(device *device, openRTBRequest *openrtb2.BidRequest) (err error) {
var userObjExist = true
if openRTBRequest.User == nil || openRTBRequest.User.Ext == nil {
userObjExist = false
}
if userObjExist {
var extUserDataHuaweiAds openrtb_ext.ExtUserDataHuaweiAds
if err := json.Unmarshal(openRTBRequest.User.Ext, &extUserDataHuaweiAds); err != nil {
return errors.New("get gaid from openrtb Device.IFA failed, and get device id failed: Unmarshal openRTBRequest.User.Ext -> extUserDataHuaweiAds. Error: " + err.Error())
}
var deviceId = extUserDataHuaweiAds.Data
isValidDeviceId := false
if len(deviceId.Oaid) > 0 {
device.Oaid = deviceId.Oaid[0]
isValidDeviceId = true
}
if len(deviceId.Gaid) > 0 {
device.Gaid = deviceId.Gaid[0]
isValidDeviceId = true
}
if len(device.Gaid) > 0 {
isValidDeviceId = true
}
if len(deviceId.Imei) > 0 {
device.Imei = deviceId.Imei[0]
isValidDeviceId = true
}
if !isValidDeviceId {
return errors.New("getDeviceID: Imei ,Oaid, Gaid are all empty.")
}
if len(deviceId.ClientTime) > 0 {
device.ClientTime = getClientTime(deviceId.ClientTime[0])
}
} else {
if len(device.Gaid) == 0 {
return errors.New("getDeviceID: openRTBRequest.User.Ext is nil and device.Gaid is not specified.")
}
}
return nil
}
// getReqNetWorkInfo: for HuaweiAds request, include Carrier, Mcc, Mnc
func getReqNetWorkInfo(request *huaweiAdsRequest, openRTBRequest *openrtb2.BidRequest) {
if openRTBRequest.Device != nil {
var network network
if openRTBRequest.Device.ConnectionType != nil {
network.Type = int32(*openRTBRequest.Device.ConnectionType)
} else {
network.Type = defaultUnknownNetworkType
}
var cellInfos []cellInfo
if openRTBRequest.Device.MCCMNC != "" {
var arr = strings.Split(openRTBRequest.Device.MCCMNC, "-")
network.Carrier = 0
if len(arr) >= 2 {
cellInfos = append(cellInfos, cellInfo{
Mcc: arr[0],
Mnc: arr[1],
})
var str = arr[0] + arr[1]
if str == "46000" || str == "46002" || str == "46007" {
network.Carrier = 2
} else if str == "46001" || str == "46006" {
network.Carrier = 1
} else if str == "46003" || str == "46005" || str == "46011" {
network.Carrier = 3
} else {
network.Carrier = 99
}
}
}
network.CellInfo = cellInfos
request.Network = network
}
}
// getReqRegsInfo: get regs information for HuaweiAds request, include Coppa
func getReqRegsInfo(request *huaweiAdsRequest, openRTBRequest *openrtb2.BidRequest) {
if openRTBRequest.Regs != nil && openRTBRequest.Regs.COPPA >= 0 {
var regs regs
regs.Coppa = int32(openRTBRequest.Regs.COPPA)
request.Regs = regs
}
}
// getReqGeoInfo: get geo information for HuaweiAds request, include Lon, Lat, Accuracy, Lastfix
func getReqGeoInfo(request *huaweiAdsRequest, openRTBRequest *openrtb2.BidRequest) {
if openRTBRequest.Device != nil && openRTBRequest.Device.Geo != nil {
request.Geo = geo{
Lon: float32(ptrutil.ValueOrDefault(openRTBRequest.Device.Geo.Lon)),
Lat: float32(ptrutil.ValueOrDefault(openRTBRequest.Device.Geo.Lat)),
Accuracy: int32(openRTBRequest.Device.Geo.Accuracy),
Lastfix: int32(openRTBRequest.Device.Geo.LastFix),
}
}
}
// getReqGeoInfo: get GDPR consent
func getReqConsentInfo(request *huaweiAdsRequest, openRTBRequest *openrtb2.BidRequest) {
if openRTBRequest.User != nil && openRTBRequest.User.Ext != nil {
var extUser openrtb_ext.ExtUser
if err := json.Unmarshal(openRTBRequest.User.Ext, &extUser); err != nil {
return
}
request.Consent = extUser.Consent
}
}
func unmarshalExtImpHuaweiAds(openRTBImp *openrtb2.Imp) (*openrtb_ext.ExtImpHuaweiAds, error) {
var bidderExt adapters.ExtImpBidder
var huaweiAdsImpExt openrtb_ext.ExtImpHuaweiAds
if err := json.Unmarshal(openRTBImp.Ext, &bidderExt); err != nil {
return nil, errors.New("Unmarshal: openRTBImp.Ext -> bidderExt failed")
}
if err := json.Unmarshal(bidderExt.Bidder, &huaweiAdsImpExt); err != nil {
return nil, errors.New("Unmarshal: bidderExt.Bidder -> huaweiAdsImpExt failed")
}
if huaweiAdsImpExt.SlotId == "" {
return nil, errors.New("ExtImpHuaweiAds: slotid is empty.")
}
if huaweiAdsImpExt.Adtype == "" {
return nil, errors.New("ExtImpHuaweiAds: adtype is empty.")
}
if huaweiAdsImpExt.PublisherId == "" {
return nil, errors.New("ExtHuaweiAds: publisherid is empty.")
}
if huaweiAdsImpExt.SignKey == "" {
return nil, errors.New("ExtHuaweiAds: signkey is empty.")
}
if huaweiAdsImpExt.KeyId == "" {
return nil, errors.New("ExtImpHuaweiAds: keyid is empty.")
}
return &huaweiAdsImpExt, nil
}
func checkRespStatusCode(response *adapters.ResponseData) error {
if response.StatusCode == http.StatusNoContent {
return nil
}
if response.StatusCode == http.StatusServiceUnavailable {
return &errortypes.BadInput{
Message: fmt.Sprintf("Something went wrong, please contact your Account Manager. Status Code: [ %d ] ", response.StatusCode),
}
}