Explorar el Código

逻辑初步完成

jiantaoli hace 4 años
padre
commit
6bf4e30d77

+ 13 - 0
.idea/dictionaries/jiantaoli.xml

@@ -2,10 +2,23 @@
2 2
   <dictionary name="jiantaoli">
3 3
     <words>
4 4
       <w>admd</w>
5
+      <w>andrioid</w>
5 6
       <w>androidid</w>
7
+      <w>arsi</w>
8
+      <w>dalvik</w>
9
+      <w>gelf</w>
10
+      <w>idfa</w>
6 11
       <w>immd</w>
7 12
       <w>ipdd</w>
8 13
       <w>kuxin</w>
14
+      <w>miao</w>
15
+      <w>miui</w>
16
+      <w>moyuntv</w>
17
+      <w>rstrip</w>
18
+      <w>sismember</w>
19
+      <w>videofinish</w>
20
+      <w>videoopen</w>
21
+      <w>videotimer</w>
9 22
       <w>zhiku</w>
10 23
       <w>ziyou</w>
11 24
     </words>

+ 29 - 42
ads_handler.go

@@ -4,7 +4,6 @@ import (
4 4
 	"encoding/json"
5 5
 	"fmt"
6 6
 	"github.com/gin-gonic/gin"
7
-	"hash"
8 7
 	"math/rand"
9 8
 	"miads/adslib"
10 9
 	"miads/adslib/addata"
@@ -22,8 +21,6 @@ import (
22 21
 	"time"
23 22
 )
24 23
 
25
-var SECERET_KEY = "%videoopen%!@#$%"
26
-
27 24
 type Response struct {
28 25
 	Result    int    `json:"result"`
29 26
 	Msg       string `json:"msg"`
@@ -34,7 +31,7 @@ type Response struct {
34 31
 func adsHandler(c *gin.Context) {
35 32
 	c.Header("Content-Type", "application/json")
36 33
 
37
-	request := Request{}
34
+	request := adslib.Request{}
38 35
 	request.Parse(c)
39 36
 	//uaClientOrigin := utils.GetArgument(c, "ua","")
40 37
 	//originMac := utils.GetArgument(c, "mac","")
@@ -141,9 +138,9 @@ func adsHandler(c *gin.Context) {
141 138
 		}
142 139
 
143 140
 		hour, _ := strconv.Atoi(time.Now().Format("01"))
144
-		tmpCrontrolInterval, ok := freqControlConf.GetControlTime(hour)
141
+		tmpControlInterval, ok := freqControlConf.GetControlTime(hour)
145 142
 		if ok {
146
-			freqControlInterval = tmpCrontrolInterval
143
+			freqControlInterval = tmpControlInterval
147 144
 		}
148 145
 	}
149 146
 
@@ -311,7 +308,7 @@ func adsHandler(c *gin.Context) {
311 308
 	dspInfo.Init()
312 309
 	dspInfo.DspCityCode = cityCode
313 310
 	dspInfo.Imei = imei
314
-	dspInfo.OriginImei = request.Imei
311
+	dspInfo.OriginImei = originImei
315 312
 	dspInfo.OsVersion = request.OsVersion
316 313
 	dspInfo.Mac = strings.ToUpper(request.Mac)
317 314
 	dspInfo.OriginMac = request.Mac
@@ -353,22 +350,20 @@ func adsHandler(c *gin.Context) {
353 350
 	}
354 351
 
355 352
 	var adData *addata.AdData
356
-	var xiaomiResponse []addata.XiaomiAdData
357
-	xiaomiRspAction := make(map[string]int, 100)
358
-	var adDataNum int
359 353
 
360 354
 	// 非频率控制,设备黑名单,ip黑名单,白名单渠道,并且替换了小米设备的
361
-	if canRequest && !isBlackImei && reqChannelFlag.ChannelFlag == 1 && flowFlag == 1 && !isIpBlack && advertiser == "xiaomi" && request.ReqSource != "" && !isBlackImei && !needControl && (replaceFlag == 1 || request.IsMiDevice()) {
362
-		adData, xiaomiResponse, xiaomiRspAction, adDataNum, err = addata.GetAdsInfos(&dspInfo, advertiser)
355
+	if canRequest && !isBlackImei && reqChannelFlag.ChannelFlag == 1 && flowFlag == 1 && !isIpBlack && advertiser == "xiaomi" && request.ReqSource != "" && !needControl && (replaceFlag == 1 || request.IsMiDevice()) {
356
+		adData, err = addata.GetAdsInfos(&dspInfo, advertiser)
363 357
 	}
364 358
 
365 359
 	canMixFlag := 0
366 360
 	xiaomiResponseFlag := 0
367 361
 	response := Response{}
368 362
 	if adData != nil && len(adData.TargetAddition) > 1 {
363
+		xiaomiResponseFlag = 1
369 364
 		realTarget := ""
370 365
 		if adData.Target != "" {
371
-			md5Skip := utils.Md5(addata.Target)
366
+			md5Skip := utils.Md5(adData.Target)
372 367
 			conf := adslib.GetConf()
373 368
 			realTarget = conf.Host + fmt.Sprintf("?action=LOADING&req_source=%s&advertiser=video&skip=%s&brand=%s&request_id=%s&skip_other=%s",
374 369
 				dspInfo.ReqSource, "", dspInfo.Brand, dspInfo.RequestId, md5Skip)
@@ -381,7 +376,7 @@ func adsHandler(c *gin.Context) {
381 376
 		adData.UserAgent = uaClient
382 377
 
383 378
 		if dspInfo.ReqSource == "kuxin" && adData.Target != "" {
384
-			adData.DpReport = fmt.Sprintf("%s?action=DP_CLICK&advertiser=video&req_source=%s", common.get_request_host(None), dspInfo.ReqSource)
379
+			adData.DpReport = fmt.Sprintf("%s?action=DP_CLICK&advertiser=video&req_source=%s", adslib.GetConf().HostIos, dspInfo.ReqSource)
385 380
 			adData.Dp = adslib.GetConf().DpTest
386 381
 		}
387 382
 		if dspInfo.SendPhoneType == 0 {
@@ -427,7 +422,8 @@ func adsHandler(c *gin.Context) {
427 422
 		if len(adData.TargetAddition) == 2 && serverActionResponse["server_video_finish"] == 1 && (dspInfo.ReqSource == "kuxin" || dspInfo.ReqSource == "zhiku") {
428 423
 			adData, err = addata.CombineOrderBy(adData, advertiser, &dspInfo)
429 424
 			if err != nil {
430
-				return err
425
+				c.String(404, err.Error())
426
+				return
431 427
 			}
432 428
 		}
433 429
 
@@ -445,19 +441,12 @@ func adsHandler(c *gin.Context) {
445 441
 		} else {
446 442
 			jsonBytes, err := json.Marshal(*adData)
447 443
 			if err != nil {
448
-				return err
444
+				c.String(404, err.Error())
445
+				return
449 446
 			}
450
-			encryptData, _ := encrypt.Encrypt(jsonBytes, []byte(SECERET_KEY))
447
+			encryptData, _ := encrypt.Encrypt(jsonBytes, []byte(adslib.GetConf().SecretKey))
451 448
 			response.AdsResult = encryptData
452 449
 		}
453
-
454
-		hour, _ := strconv.Atoi(time.Now().Format("01"))
455
-		if 0 <= hour && hour <= 23 && replaceFlag == 1 {
456
-			randomNum := utils.Hash(imei) % 10000
457
-			if randomNum < 3000 {
458
-				//add_beanstalk_response.BeanstalkHandle().add_ads_response_info(md5_imei,ads_ip,web.utf8(province),web.utf8(city),ads_item_new,dsp_city_code,req_source,real_imei,xiaomi_response,xiaomi_action,server_action_response,dsp_info.request_id,xiaomi_ads_data_num)
459
-			}
460
-		}
461 450
 	}
462 451
 	if canMixFlag == 1 {
463 452
 		response.Result = 2
@@ -467,18 +456,25 @@ func adsHandler(c *gin.Context) {
467 456
 			response.Msg = "ok"
468 457
 		}
469 458
 		// 增加打底广告
470
-		if (dspInfo.ReqSource == "kuxin" || dspInfo.ReqSource == "zhiku") && !needCotrol == 1 && !isBlackImei {
459
+		if (dspInfo.ReqSource == "kuxin" || dspInfo.ReqSource == "zhiku") && !needControl && !isBlackImei {
471 460
 			shortMessage := "kong"
472
-			// 先跑定投
461
+			if err != nil {
462
+				c.String(404, err.Error())
463
+				return
464
+			}
465
+
473 466
 			customAdData, err := addata.GetCustomAdsInfos(&dspInfo, advertiser, 0, 0, xiaomiResponseFlag)
474 467
 			if err != nil {
475
-				return err
468
+				c.String(404, err.Error())
469
+				return
476 470
 			}
471
+
477 472
 			// 定投没有就跑其他的
478 473
 			if customAdData == nil {
479 474
 				customAdData, err = addata.GetCustomAdsInfos(&dspInfo, advertiser, 0, 1, xiaomiResponseFlag)
480 475
 				if err != nil {
481
-					return err
476
+					c.String(404, err.Error())
477
+					return
482 478
 				}
483 479
 			}
484 480
 			device.SetAdsTagLog(advertiser, dspInfo.ReqSource, "ADS_ZIYOU_GET", cityCode) // 广告获取成功
@@ -487,15 +483,6 @@ func adsHandler(c *gin.Context) {
487 483
 			}
488 484
 
489 485
 			if customAdData != nil && (shortMessage == "ads_vast_response" || shortMessage == "ads_tt_thirds") {
490
-				//response_data_report = {}
491
-				//response_data_report['ip'] = ads_ip
492
-				//response_data_report['short_message'] =  short_message
493
-				//response_data_report['req_source'] = req_source
494
-				//response_data_report['response_vast'] = json.dumps(extra_item)
495
-				//response_data_report['order_name']=order_name
496
-				//response_data_report['advertiser']=advertiser
497
-				//log.send_to_graylog_tornado(gelf_data=response_data_report)
498
-
499 486
 				adDataBytes, err := json.Marshal(*adData)
500 487
 				if err != nil {
501 488
 					fmt.Sprintf("marshal addata failed: %s\n", err)
@@ -575,9 +562,9 @@ func adsHandler(c *gin.Context) {
575 562
 						c.String(404, err.Error())
576 563
 						return
577 564
 					}
578
-					encryptData, _ := encrypt.Encrypt(jsonBytes, []byte(SECERET_KEY))
565
+					encryptData, _ := encrypt.Encrypt(jsonBytes, []byte(adslib.GetConf().SecretKey))
579 566
 					response.AdsResult = encryptData
580
-					//self.report_graylog(json.dumps(extra_item))
567
+					graylog.ReportGrayLog(request, dspInfo, 0, 0)
581 568
 					rspBytes, err := json.Marshal(response)
582 569
 					if err != nil {
583 570
 						c.String(404, err.Error())
@@ -588,7 +575,7 @@ func adsHandler(c *gin.Context) {
588 575
 				} else {
589 576
 					customAdData.Result = 0
590 577
 					customAdData.Msg = "ok"
591
-					//self.report_graylog(json_response)
578
+					graylog.ReportGrayLog(request, dspInfo, 0, 0)
592 579
 					rspBytes, err := json.Marshal(customAdData)
593 580
 					if err != nil {
594 581
 						c.String(404, err.Error())
@@ -608,7 +595,7 @@ func adsHandler(c *gin.Context) {
608 595
 	}
609 596
 
610 597
 	if request.NewAdsFlag == 0 {
611
-		//self.report_graylog(json_response)
598
+		graylog.ReportGrayLog(request, dspInfo, 0, 0)
612 599
 	}
613 600
 	device.SetAdsTagLog(advertiser, dspInfo.ReqSource, "DS_REQ", cityCode) // 所有请求
614 601
 	c.String(200, string(rspBytes))

+ 2 - 2
adslib/addata/custom.go

@@ -41,7 +41,7 @@ func CombineOrderBy(adData *AdData, advertiser string, dsp *utils.DspParam) (*Ad
41 41
 
42 42
 	if hasClickTarget {
43 43
 		adData.Target = customAdData.Target
44
-		adData.JsOrderId = customAdData.JsOrderID
44
+		adData.JsOrderId = customAdData.JsOrderId
45 45
 	}
46 46
 	return adData, nil
47 47
 }
@@ -205,7 +205,7 @@ func GetCustomAdsInfos(dsp *utils.DspParam, advertiser string, orderType int, fi
205 205
 	if curMinuteFinishedDispatchCnt < curMinuteNeedDispatchCnt {
206 206
 		data := AdData{
207 207
 			Duration:  5,
208
-			JsOrderID: order.JsOrderID,
208
+			JsOrderId: order.JsOrderID,
209 209
 			OrderName: order.Title,
210 210
 			UserAgent: dsp.UaOrigin,
211 211
 		}

+ 16 - 16
adslib/addata/xiaomi.go

@@ -101,7 +101,7 @@ func getAdsReqUrl(dsp *utils.DspParam) string {
101 101
 }
102 102
 
103 103
 // 获取广告信息
104
-func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdData, map[string]int, int, error) {
104
+func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, error) {
105 105
 	reqUrl := getAdsReqUrl(dsp)
106 106
 
107 107
 	if dsp.SendPhoneType == 0 {
@@ -114,7 +114,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
114 114
 	fmt.Printf("req url: %s\n", reqUrl)
115 115
 	req, err := http.NewRequest("GET", reqUrl, nil)
116 116
 	if err != nil {
117
-		return nil, nil, nil, 0, err
117
+		return nil,  err
118 118
 	}
119 119
 
120 120
 	req.Header.Set(",authority", "m.video.xiaomi.com")
@@ -131,18 +131,18 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
131 131
 
132 132
 	resp, err := client.Do(req)
133 133
 	if err != nil {
134
-		return nil, nil, nil, 0, err
134
+		return nil, err
135 135
 	}
136 136
 	defer resp.Body.Close()
137 137
 	body, err := ioutil.ReadAll(resp.Body)
138 138
 	fmt.Printf("rsp body: %s\n", body)
139 139
 	if err != nil {
140
-		return nil, nil, nil, 0, err
140
+		return nil,  err
141 141
 	}
142 142
 	rsp := XiaoMiAdInfoRsp{}
143 143
 	err = json.Unmarshal(body, &rsp)
144 144
 	if err != nil {
145
-		return nil, nil, nil, 0, err
145
+		return nil, err
146 146
 	}
147 147
 
148 148
 	adsDataNum := len(rsp.Data)
@@ -151,7 +151,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
151 151
 	}
152 152
 
153 153
 	if rsp.Result != 1 {
154
-		return nil, nil, xiaomiResponseAction, adsDataNum, nil
154
+		return nil, nil
155 155
 	}
156 156
 
157 157
 	// bom渠道不处理
@@ -171,7 +171,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
171 171
 	}
172 172
 
173 173
 	if len(rsp.Data) == 0 {
174
-		return nil, nil, xiaomiResponseAction, 0, nil
174
+		return nil, nil
175 175
 	}
176 176
 	///last_infos = xiaomi_mix.xiaomi_fuse(data, dsp.req_source)
177 177
 
@@ -193,10 +193,10 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
193 193
 			continue
194 194
 		}
195 195
 
196
-		targetParms := targetParseUrl.Query()
196
+		targetParams := targetParseUrl.Query()
197 197
 
198
-		targetUrl := targetParms.Get("url")
199
-		event := targetParms.Get("event")
198
+		targetUrl := targetParams.Get("url")
199
+		event := targetParams.Get("event")
200 200
 
201 201
 		if targetUrl != "" {
202 202
 			switch event {
@@ -218,7 +218,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
218 218
 		}
219 219
 
220 220
 		if event == "VIDEO_TIMER" {
221
-			timeStr := targetParms.Get("time")
221
+			timeStr := targetParams.Get("time")
222 222
 			if timeStr != "" {
223 223
 				videoTimeDuration, _ := strconv.Atoi(timeStr)
224 224
 				dsp.VideoTimeDuration = videoTimeDuration
@@ -260,7 +260,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
260 260
 
261 261
 	fmt.Printf("%+v, addata_num: %d\n", xiaomiResponseAction, adsDataNum)
262 262
 	if len(gotoUrls) == 0 {
263
-		return nil, rsp.Data, xiaomiResponseAction, adsDataNum, nil
263
+		return nil, nil
264 264
 	}
265 265
 
266 266
 	fmt.Printf("goto urls: %+v\nshow urls: %+v\nclick_urls: %+v\nclose urls: %+v\nvideo finish urls: %+v\nimagurls: %+v\nvideo urls:%+v\n",
@@ -268,7 +268,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
268 268
 
269 269
 	adsData, err := CombineLastAdsInfos(dsp, advertiser, gotoUrls, showUrls, clickUrls, closeUrls, videoFinishUrls, videoTimerUrls, imageUrls, videoUrls)
270 270
 	if err != nil {
271
-		return nil, nil, nil, 0, err
271
+		return nil, err
272 272
 	}
273 273
 
274 274
 	fmt.Printf("addata: %+v\n", adsData)
@@ -278,7 +278,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
278 278
 	} else if dsp.SendPhoneType == 1 {
279 279
 		redis_data.SetAdsRequestNum(advertiser, 1)
280 280
 	}
281
-	return adsData, rsp.Data, xiaomiResponseAction, adsDataNum, nil
281
+	return adsData, nil
282 282
 }
283 283
 
284 284
 func getActionsConf(advertiser string) []string {
@@ -303,11 +303,11 @@ func getDurationConf(advertiser string) int {
303 303
 
304 304
 func getCombinationActionsConf(advertiser string) []adslib.CombinationActionsConf {
305 305
 	svrConf := adslib.GetConf()
306
-	combi_actions, ok := svrConf.CombinationActions[advertiser]
306
+	combinationActions, ok := svrConf.CombinationActions[advertiser]
307 307
 	if !ok {
308 308
 		return []adslib.CombinationActionsConf{}
309 309
 	}
310
-	return combi_actions
310
+	return combinationActions
311 311
 }
312 312
 
313 313
 // 组装最后的广告信息

+ 0 - 204
adslib/addata/xiaomi_extra.go

@@ -1,204 +0,0 @@
1
-package addata
2
-
3
-import (
4
-	"encoding/json"
5
-	"fmt"
6
-	"io/ioutil"
7
-	"miads/adslib/graylog"
8
-	"miads/adslib/utils"
9
-	"net/http"
10
-	"net/url"
11
-	"strconv"
12
-)
13
-
14
-// 获取请求的信息
15
-func getRequestInfo(dsp utils.DspParam) (string,error) {
16
-	ipdd := combineIpdd(dsp)
17
-	url := fmt.Sprintf("http://delivery.maihehd.com/d/vast/3.0?pos=147&ip=%s&ipdd=%s", dsp.Ip, ipdd)
18
-
19
-	client := &http.Client{}
20
-	fmt.Printf("req url: %s\n", url)
21
-	req, err := http.NewRequest("GET",  url, nil)
22
-	if err != nil {
23
-		return "", err
24
-	}
25
-
26
-	resp, err := client.Do(req)
27
-	if err != nil {
28
-		return "", err
29
-	}
30
-	defer resp.Body.Close()
31
-	body, err := ioutil.ReadAll(resp.Body)
32
-	fmt.Printf("rsp body: %s\n", body)
33
-	if err != nil {
34
-		return "", err
35
-	}
36
-
37
-	graylog.LogApi("ads_mi_extra_res", string(body), "", "")
38
-	return string(body), nil
39
-}
40
-
41
-// 组装ipdd
42
-func combineIpdd(dsp utils.DspParam) string {
43
-	admd5 := utils.Md5(dsp.Androidid)
44
-	ipdd := url.Values{}
45
-	ipdd.Set("device_type", strconv.Itoa(0))
46
-	ipdd.Set("os_version", dsp.OsVersion)
47
-	ipdd.Set("os", strconv.Itoa(1))
48
-	ipdd.Set("imei", dsp.OriginImei)
49
-	ipdd.Set("immd5", dsp.RealMd5Imei)
50
-	ipdd.Set("androidid", dsp.Androidid)
51
-	ipdd.Set("admd5", admd5)
52
-	ipdd.Set("mac", dsp.Mac)
53
-	ipdd.Set("device_name", dsp.Model)
54
-	ipdd.Set("sr", dsp.ScreenSize)
55
-
56
-	return ipdd.Encode()
57
-}
58
-
59
-// 将xml转为array
60
-func GetXiaomiExtraAdsInfo(dsp utils.DspParam) {
61
-	advertiser := "vast"
62
-	xmlResult = getRequestInfo(dsp)
63
-try:
64
-	soup = BeautifulSoup(xml_result, 'xml')
65
-except:
66
-	raise gen.Return(({},[]))
67
-	// 获取视频总时长duration
68
-try:
69
-	duration_arr = str(soup.Duration.text).split(":")
70
-except:
71
-	raise gen.Return(({},[]))
72
-	video_all_time = int(duration_arr[0])*3600+int(duration_arr[1])*60+int(duration_arr[2])
73
-	### 获取点击率
74
-	click_rate = common.my_int(soup.ClickRate.text)
75
-	ads_ua = dsp_info.ua
76
-	### 获取md5_imei
77
-	if dsp_info.replace_flag==0:
78
-	md5_imei = hashlib.md5(dsp_info.imei).hexdigest()
79
-	else:
80
-	md5_imei = dsp_info.imei
81
-	track_arr = soup.find_all("Tracking")
82
-	action_infos = []
83
-	percent_duration = int(video_all_time/4.0)
84
-	click_rand_duration = random.randint(5,10)
85
-	first_flag = 0
86
-	second_flag = 0
87
-	third_flag = 0
88
-	start_urls = []
89
-	complete_urls = []
90
-	firstQuartile_urls = []
91
-	midpoint_urls = []
92
-	thirdQuartile_urls = []
93
-	for track_info in track_arr:
94
-	url = track_info.text
95
-	url = url.replace('__IMEI__',md5_imei)
96
-	event_name = track_info['event']
97
-	if event_name == "start":
98
-	start_urls.append(url)
99
-	if event_name == "complete":
100
-	complete_urls.append(url)
101
-	if event_name == "firstQuartile":
102
-	first_flag = 1
103
-	firstQuartile_urls.append(url)
104
-	if event_name == "midpoint":
105
-	second_flag = 1
106
-	midpoint_urls.append(url)
107
-	if event_name == "thirdQuartile":
108
-	third_flag = 1
109
-	thirdQuartile_urls.append(url)
110
-	### 排序
111
-	if len(start_urls):
112
-	action_event_dict={}
113
-	action_event_dict['type']="start"
114
-	action_event_dict['duration']=percent_duration
115
-	action_event_dict['urls']=start_urls
116
-	action_event_dict['weight']=100
117
-	action_infos.append(action_event_dict)
118
-	if len(firstQuartile_urls):
119
-	action_event_dict={}
120
-	action_event_dict['type']="firstQuartile"
121
-	action_event_dict['duration']=percent_duration
122
-	action_event_dict['urls']=firstQuartile_urls
123
-	action_event_dict['weight']=90
124
-	action_event_dict['timer_flag']=1
125
-	action_infos.append(action_event_dict)
126
-	if len(midpoint_urls):
127
-	action_event_dict={}
128
-	action_event_dict['type']="midpoint"
129
-	action_event_dict['duration']=percent_duration
130
-	action_event_dict['urls']=midpoint_urls
131
-	action_event_dict['weight']=80
132
-	action_event_dict['timer_flag']=2
133
-	action_infos.append(action_event_dict)
134
-	if len(thirdQuartile_urls):
135
-	action_event_dict={}
136
-	action_event_dict['type']="thirdQuartile"
137
-	action_event_dict['duration']=percent_duration
138
-	action_event_dict['urls']=thirdQuartile_urls
139
-	action_event_dict['weight']=70
140
-	action_event_dict['timer_flag']=3
141
-	action_infos.append(action_event_dict)
142
-	if len(complete_urls):
143
-	action_event_dict={}
144
-	action_event_dict['type']="complete"
145
-	action_event_dict['duration']=percent_duration
146
-	action_event_dict['urls']=complete_urls
147
-	action_event_dict['weight']=60
148
-	action_infos.append(action_event_dict)
149
-	action_infos = sorted(action_infos, key=itemgetter('weight'), reverse=True)
150
-	### 修正每个action的duration
151
-	for action_info in action_infos:
152
-	### 控制view的时间
153
-	if action_info['type']=="start" and first_flag==1:
154
-	action_info['duration']=percent_duration
155
-	elif action_info['type']=="start" and first_flag==0:
156
-	action_info['duration']=video_all_time
157
-	### 控制第一个timer时间
158
-	if action_info['type']=="firstQuartile" and action_info['timer_flag']==1 and second_flag==1:
159
-	action_info['duration']=percent_duration
160
-	elif action_info['type']=="firstQuartile" and action_info['timer_flag']==1 and second_flag==0:
161
-	action_info['duration']=video_all_time-percent_duration
162
-	### 控制第二个timer时间
163
-	if action_info['type']=='midpoint' and action_info['timer_flag']==2 and third_flag==1:
164
-	action_info['duration']=percent_duration
165
-	elif action_info['type']=='midpoint' and action_info['timer_flag']==2 and third_flag==0:
166
-	action_info['duration']=video_all_time-percent_duration*2
167
-	click_url = soup.find('ClickThrough').text
168
-	click_arr = soup.find_all('ClickTracking')
169
-	click_urls = []
170
-	for click_info in click_arr:
171
-	url = click_info.text
172
-	click = url.replace('__IMEI__',md5_imei)
173
-	click_urls.append(click)
174
-	click_event_dict = {}
175
-	has_click = 0
176
-	if click:
177
-	click_event_dict['type'] = "CLICK"
178
-	click_event_dict['duration']=click_rand_duration
179
-	click_event_dict['urls'] = click_urls
180
-	### 先组装click是否可以下发
181
-	click_info_dict = combine_ads_action_infos(click_urls,advertiser,dsp_info,"CLICK",1,click_rate,click_rand_duration)
182
-	if len(click_info_dict['urls']):
183
-	has_click=1
184
-	last_action_infos = []
185
-	sum_duration = 0
186
-	for action_info in action_infos:
187
-	action_info_dict = combine_ads_action_infos(action_info['urls'],advertiser,dsp_info,action_info['type'],0,click_rate,action_info['duration'])
188
-	sum_duration+=action_info['duration']
189
-	last_action_infos.append(action_info_dict)
190
-	if has_click and sum_duration>=click_rand_duration:
191
-	last_action_infos.append(click_info_dict)
192
-	redis_tools.set_ads_distribute_action_num(advertiser,'CLICK')
193
-	break
194
-	if len(last_action_infos):
195
-	redis_tools.set_ads_request_num(advertiser)
196
-	ads_item = {}
197
-	ads_item['target_addition'] = last_action_infos
198
-	ads_item['target'] = click_url
199
-	ads_item['image_url'] = ""
200
-	ads_item['duration'] = video_all_time
201
-	ads_item['video_url'] = ""
202
-	ads_item['user_agent'] = ads_ua
203
-	raise gen.Return((ads_item,[]))
204
-}

+ 3 - 2
adslib/config.go

@@ -7,7 +7,7 @@ import (
7 7
 
8 8
 type SvrConf struct {
9 9
 	HostIos            string                                `toml:"Host_Ios"`
10
-	HostAndoird        string                                `toml:"Host_Andoird"`
10
+	HostAndroid        string                                `toml:"Host_Android"`
11 11
 	Host               string                                `toml:"Host"`
12 12
 	HostScript         string                                `toml:"Host_script"`
13 13
 	HostMiao           string                                `toml:"Host_miao"`
@@ -21,6 +21,7 @@ type SvrConf struct {
21 21
 	AdsDuration        map[string]int                        `toml:"Ads_Duration"`
22 22
 	ActionWeight       ActionWeight                          `toml:"action_weight"`
23 23
 	CombinationActions map[string][]CombinationActionsConf   `toml:"combination_actions"`
24
+	SecretKey          string                                `toml:"secret_key"`
24 25
 }
25 26
 type FlogControlItem struct {
26 27
 	Percent  int `toml:"percent"`
@@ -46,7 +47,7 @@ var once sync.Once
46 47
 
47 48
 func GetConf() *SvrConf {
48 49
 	once.Do(func () {
49
-		_, err := toml.DecodeFile("../../conf/config.toml", &svrConf)
50
+		_, err := toml.DecodeFile("./conf/config.toml", &svrConf)
50 51
 		if err != nil {
51 52
 			panic(err)
52 53
 		}

+ 39 - 51
adslib/graylog/graylog.go

@@ -1,8 +1,13 @@
1 1
 package graylog
2
+
2 3
 import (
3 4
 	"encoding/json"
4
-	"github.com/gin-gonic/gin"
5
+	"fmt"
5 6
 	"github.com/robertkowalski/graylog-golang"
7
+	"miads/adslib"
8
+	"miads/adslib/utils"
9
+	"net/url"
10
+	"time"
6 11
 )
7 12
 var grayLog  *gelf.Gelf
8 13
 
@@ -18,6 +23,7 @@ func init() {
18 23
 
19 24
 func Log(log interface{}) {
20 25
 	logStr, _ := json.Marshal(log)
26
+	fmt.Printf("graylog: %s\n", logStr)
21 27
 	grayLog.Log(string(logStr))
22 28
 }
23 29
 
@@ -37,54 +43,36 @@ func LogApi(shortMsg string, desc string, extraDesc string, reqSource string) {
37 43
 }
38 44
 
39 45
 // 发送返回日志
40
-func ReportGrayLog(c *gin.Context, uid int, response string, jsonFlag int) {
41
-	path := c.Request.URL.Path
42
-	reqTs := c.Request.Time()
43
-	ip = req.headers.get('X-Forwarded-For',"")
44
-	req_source_ip = req_data.get('ip',[])
45
-	if len(req_source_ip):
46
-	check_req_source_flag = redis_ip.check_req_source(req_data.get('req_source',[])[0])
47
-	if check_req_source_flag:
48
-	ip = req_source_ip[0]
49
-	if ip=="":
50
-	ip = self.request.headers.get("X-Real-IP","")
51
-	if ip=="":
52
-	ip = req.remote_ip
53
-	if ip.find(",") > 0:
54
-	ip = ip.split(",")[0]
55
-	device_id = req_data.get('device_id,', '')
56
-	request = urllib.unquote(urllib.urlencode(req_data, 'utf-8'))
57
-	province,city,city_code = ip_location_helper.get_region_by_ip(ip)
58
-	gelf_data = {}
59
-	gelf_data['short_message'] = 'ads_api_log'
60
-	gelf_data['_user_id'] = user_id
61
-	gelf_data['_device_id'] = device_id
62
-	gelf_data['_ip'] = ip
63
-	gelf_data['_uri'] = path
64
-	gelf_data['_province']=province
65
-	gelf_data['_city']=city
66
-	gelf_data['_city_code']=city_code
67
-	for key,value in req_data.items():
68
-	if str(key) in ['ip']:
69
-	continue
70
-	gelf_data['_{0}'.format(key)] = common.my_str(value[0])
71
-	req_len = 102400
72
-	gelf_data['_request'] = request[0:req_len]
73
-	#json_response = json.dumps(response)
74
-	### 结果不上报了
75
-	json_response = ""
76
-	if len(json_response) < req_len and len(json_response) > 60:
77
-try:
78
-	json_response = json.dumps(
79
-		response, indent=4, sort_keys=True,
80
-		ensure_ascii=False).encode("utf-8")
81
-except:
82
-	send_try_except()
83
-try:
84
-	json_response = json_response.decode("utf-8")
85
-except:
86
-	pass
87
-	gelf_data['_response'] = json_response[0:req_len]
88
-	gelf_data['_response_time'] = round(req_ts * 1000.0, 2)
89
-	send_to_graylog_tornado(gelf_data, req=req, req_data=cur_req_data)
46
+func ReportGrayLog(req adslib.Request, dsp utils.DspParam, uid int, jsonFlag int) {
47
+	gelfData := make(map[string]interface{}, 100)
48
+	gelfData["short_message"] = "ads_api_log"
49
+	gelfData["_user_id"] = uid
50
+	gelfData["_device_id"] = req.DeviceId
51
+	gelfData["_ip"] = dsp.Ip
52
+	gelfData["_uri"] = req.QueryString
53
+	gelfData["_province"]=dsp.Province
54
+	gelfData["_city"]=dsp.City
55
+	gelfData["_city_code"]=dsp.DspCityCode
56
+
57
+	var reqData url.Values
58
+	if jsonFlag == 0 {
59
+		reqData, _ = url.ParseQuery(req.QueryString)
60
+	} else {
61
+		err := json.Unmarshal([]byte(req.Body), &reqData)
62
+		if err != nil {
63
+			fmt.Print("parse error")
64
+		}
65
+	}
66
+	for k, v := range reqData {
67
+		if k == "ip" {
68
+			continue
69
+		}
70
+		gelfData["_" + k] = v
71
+	}
72
+
73
+	gelfData["_request"] = reqData.Encode()
74
+	gelfData["_response"] = ""
75
+	gelfData["_response_time"] = time.Now().UnixNano() / 1000
76
+
77
+	Log(gelfData)
90 78
 }

+ 19 - 2
request.go

@@ -1,13 +1,16 @@
1
-package main
1
+package adslib
2 2
 
3 3
 import (
4
+	"bytes"
4 5
 	"encoding/json"
5 6
 	"fmt"
6 7
 	"github.com/gin-gonic/gin"
8
+	"io/ioutil"
7 9
 	"miads/adslib/encrypt"
8 10
 	"miads/adslib/utils"
9 11
 	"net/url"
10 12
 	"strings"
13
+	"time"
11 14
 )
12 15
 
13 16
 type Request struct {
@@ -24,12 +27,25 @@ type Request struct {
24 27
 	ReqSource   string `json:"req_source"`
25 28
 	Mac         string `json:"mac"`
26 29
 	ReqSourceIp string `json:"ip"`
30
+	DeviceId	string `json:"device_id"`
27 31
 
28 32
 	NewAdsFlag int64
29 33
 	content    string
34
+
35
+	RequestTime int64 `json:"-"`
36
+	QueryString string `json:"-"`
37
+	Body string `json:"-"`
30 38
 }
31 39
 
32 40
 func (self *Request) Parse(c *gin.Context) {
41
+	self.RequestTime = time.Now().Unix()
42
+	self.QueryString = c.Request.URL.RawQuery
43
+
44
+	body, _ := c.GetRawData()
45
+	self.Body = string(body)
46
+	// 取了body要塞回去
47
+	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
48
+
33 49
 	self.Imei = utils.GetArgument(c, "imei", "")
34 50
 	self.Idfa = utils.GetArgument(c, "idfa", "")
35 51
 	self.Model = utils.GetArgument(c, "model", "")
@@ -43,6 +59,7 @@ func (self *Request) Parse(c *gin.Context) {
43 59
 	self.ReqSource = utils.GetArgument(c, "req_source", "")
44 60
 	self.Mac = utils.GetArgument(c, "mac", "")
45 61
 	self.ReqSourceIp = utils.GetArgument(c, "ip", "")
62
+	self.DeviceId = utils.GetArgument(c, "device_id", "")
46 63
 
47 64
 	self.NewAdsFlag = utils.GetIntArgument(c, "new_ads_flag", 0)
48 65
 	self.content = utils.GetArgument(c, "ads_content", "")
@@ -50,7 +67,7 @@ func (self *Request) Parse(c *gin.Context) {
50 67
 
51 68
 	// 进行解密
52 69
 	if self.NewAdsFlag == 1 && self.content != "" {
53
-		contentDecode, err := encrypt.Decrypt(self.content, []byte(SECERET_KEY))
70
+		contentDecode, err := encrypt.Decrypt(self.content, []byte(GetConf().SecretKey))
54 71
 		if err != nil {
55 72
 			fmt.Printf("error: %s", err)
56 73
 			c.String(404, "decode failed")

+ 1 - 1
adslib/utils/string.go

@@ -14,7 +14,7 @@ func Rstrip(str string) string {
14 14
 	return reg.ReplaceAllString(str, "")
15 15
 }
16 16
 
17
-func Hash(string) int {
17
+func Hash(s string) int {
18 18
 	v := int(crc32.ChecksumIEEE([]byte(s)))
19 19
 	if v >= 0 {
20 20
 		return v

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 3 - 1
conf/config.toml


+ 1 - 0
go.mod

@@ -4,6 +4,7 @@ go 1.12
4 4
 
5 5
 require (
6 6
 	github.com/BurntSushi/toml v0.3.1
7
+	github.com/beanstalkd/go-beanstalk v0.0.0-20200526060843-1cc502ecaf3c
7 8
 	github.com/gin-gonic/gin v1.6.3
8 9
 	github.com/gomodule/redigo v2.0.0+incompatible
9 10
 	github.com/jarcoal/httpmock v1.0.5

+ 2 - 0
go.sum

@@ -1,5 +1,7 @@
1 1
 github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
2 2
 github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
3
+github.com/beanstalkd/go-beanstalk v0.0.0-20200526060843-1cc502ecaf3c h1:D8zSant5V63LdrIHuEoJ82Yiyo1SRXEg+REzRuZnsbk=
4
+github.com/beanstalkd/go-beanstalk v0.0.0-20200526060843-1cc502ecaf3c/go.mod h1:Q3f6RCbUHp8RHSfBiPUZBojK76rir8Rl+KINuz2/sYs=
3 5
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 6
 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
5 7
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=