Browse Source

继续更新

jiantaoli 4 years ago
parent
commit
31e7c825f4

+ 7 - 0
.idea/dictionaries/zhanlangpc.xml

@@ -0,0 +1,7 @@
1
+<component name="ProjectDictionaryState">
2
+  <dictionary name="zhanlangpc">
3
+    <words>
4
+      <w>smembers</w>
5
+    </words>
6
+  </dictionary>
7
+</component>

+ 4 - 0
.idea/encodings.xml

@@ -0,0 +1,4 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project version="4">
3
+  <component name="Encoding" addBOMForNewFiles="with NO BOM" />
4
+</project>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project version="4">
3
+  <component name="VcsDirectoryMappings">
4
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+  </component>
6
+</project>

+ 21 - 21
ads_handler.go

@@ -79,7 +79,7 @@ func adsHandler(c *gin.Context) {
79 79
 			Ip string
80 80
 			Imei string
81 81
 			Model string
82
-			NetworkType string `json:"network_type"`
82
+			NetworkType int `json:"network_type"`
83 83
 			Provice string
84 84
 			City string
85 85
 			ScreeSize string `json:"screen_size"`
@@ -396,29 +396,29 @@ func adsHandler(c *gin.Context) {
396 396
 			//extra_infos = []
397 397
 		}
398 398
 
399
-		adDataNew, err := xiaomi_mix.combine_mix_infos_v2(ads_item,extra_infos)
400
-
401 399
 		// 组装返回去的action
402
-		//target_addition_infos = ads_item.get('target_addition')
403
-		//server_action_response = {"server_view":0,"server_click":0,"server_close":0,"server_video_finish":0,"server_video_timer":0}
404
-		//for target_info in target_addition_infos:
405
-		//if target_info['type']=="VIEW":
406
-		//server_action_response['server_view']=1
407
-		//redis_device.set_req_source_view('xiaomi',req_source,'xiafa')
408
-		//if target_info['type']=="CLICK":
409
-		//server_action_response['server_click']=1
410
-		//if target_info['type']=="CLOSE":
411
-		//server_action_response['server_close']=1
412
-		//if target_info['type']=="VIDEO_FINISH":
413
-		//server_action_response['server_video_finish']=1
414
-		//if target_info['type']=="VIDEO_TIMER":
415
-		//server_action_response['server_video_timer']=1
400
+		serverActionResponse := map[string]int{"server_view":0,"server_click":0,"server_close":0,"server_video_finish":0,"server_video_timer":0}
401
+		for _, targetInfo := range adData.TargetAddition {
402
+			if targetInfo.Type == "VIEW" {
403
+				serverActionResponse["server_view"]=1
404
+				redis_data.SetReqSourceView(advertiser, dspInfo.ReqSource,"xiafa")
405
+			} else if targetInfo.Type == "CLICK" {
406
+				serverActionResponse["server_click"]=1
407
+			} else if targetInfo.Type=="CLOSE" {
408
+				serverActionResponse["server_close"]=1
409
+			} else if targetInfo.Type=="VIDEO_FINISH" {
410
+				serverActionResponse["server_video_finish"]=1
411
+			} else if targetInfo.Type =="VIDEO_TIMER" {
412
+				serverActionResponse["server_video_timer"]=1
413
+			}
414
+		}
416 415
 		//response_report_flag = 1
417 416
 
418
-		//#增加跟随订单
419
-		//if len(target_addition_infos) == 2  and server_action_response['server_video_finish'] == 1 and req_source in ['kuxin','zhiku']:
420
-		//from thirds import tt_thirds
421
-		//ads_item_new =yield tt_thirds.combine_order_by(ads_item_new,dsp_info)
417
+		// 增加跟随订单
418
+		if len(adData.TargetAddition) == 2  && server_action_response["server_video_finish"] == 1 && (dspInfo.ReqSource == "kuxin" or dspInfo.ReqSource == "zhiku") {
419
+			//from thirds import tt_thirds
420
+			//ads_item_new =yield tt_thirds.combine_order_by(ads_item_new,dsp_info)
421
+		}
422 422
 		//# 检查最后是否有click
423 423
 		//last_target_addition_infos = ads_item_new.get('target_addition',[])
424 424
 		//for last_target_addition_info in last_target_addition_infos:

+ 233 - 0
adslib/addata/custom.go

@@ -0,0 +1,233 @@
1
+package addata
2
+
3
+import (
4
+	"math/rand"
5
+	"miads/adslib/redis_data"
6
+	"miads/adslib/utils"
7
+)
8
+
9
+func CombineOrderBy(adData *AdData, dsp *utils.DspParam) {
10
+	ads_item, extra_item = yield get_ads_infos(dsp, order_type = 1)
11
+	if extra_item == None:
12
+	raise
13
+	gen.Return(infos)
14
+	last_target_addition = infos.get('target_addition', [])
15
+	extra_item_addition = extra_item.get('target_addition', [])
16
+	if len(extra_item_addition) == 0:
17
+	raise
18
+	gen.Return(infos)
19
+	if len(extra_item_addition) == 1:
20
+	last_target_addition[0]['urls'].extend(extra_item_addition[0]['urls'])
21
+	raise
22
+	gen.Return(infos)
23
+	else:
24
+	last_target_addition[0]['urls'].extend(extra_item_addition[0]['urls'])
25
+	last_target_addition[1]['urls'].extend(extra_item_addition[1]['urls'])
26
+	infos['target'] = extra_item['target']
27
+	infos['js_order_id'] = extra_item['js_order_id']
28
+	last_target_addition[1]['type'] = 'CLICK'
29
+	raise
30
+	gen.Return(infos)
31
+}
32
+
33
+
34
+// 获取一个广告
35
+func GetOneAds(dsp *utils.DspParam, orderType int, fixFlag int) (*redis_data.AdOrderInfo, error){
36
+	// 取出广告
37
+	orders, err := redis_data.GetOrderInfos(dsp, fixFlag)
38
+	if err != nil {
39
+		return nil, err
40
+	}
41
+	if len(orders) == 0 {
42
+		return nil, nil
43
+	}
44
+
45
+	gotOrders := make([]redis_data.AdOrderInfo, 0, 1000)
46
+	allKpi := int64(0)
47
+	for _, order := range orders {
48
+		if order.OrderType == int64(orderType) {
49
+			gotOrders = append(gotOrders, order)
50
+			allKpi += order.ShowKpi
51
+		}
52
+	}
53
+
54
+	orderRange := make([]int, 0, 1000)
55
+
56
+	curRateIdx := 0
57
+
58
+	// orderRange中记录的是当前同索引位置的gotOrders里的order的比例上限, 比如如果有两个order [ShowKpi:40, ShowKpi: 60]
59
+	// 那么orderRange就是 [rate:400, rate: 1000], 所以要按比例取order, 只需要获得在比例上限里随机取一个数, 然后判断落在那个orderRange里,
60
+	// 对应去gotOrders取同索引里的order即可, 因为算法里有对小于1的比例做补偿, 所以rate上限可能超出1000, rate乘1000而不是100主要是为了
61
+	// 如果showKpi差异过大, 对大量小于1的订单做补偿, 会影响整体流量分布, 这里放到1000倍, 降低补偿1的影响, 算法复杂度是O(n), 只有三个非嵌套循环
62
+	for _, order := range gotOrders {
63
+		rate := int(float32(order.ShowKpi) / float32(allKpi) * 1000)
64
+
65
+		// 防止比例过小, 取int后变为0
66
+		if rate < 1 {
67
+			rate = 1
68
+		}
69
+
70
+		curRateIdx = curRateIdx + rate
71
+		orderRange = append(orderRange, curRateIdx)
72
+	}
73
+
74
+	randNum := rand.Intn(curRateIdx)
75
+	for i, rateRange := range orderRange {
76
+		if randNum <= rateRange {
77
+			return &gotOrders[i], nil
78
+		}
79
+	}
80
+	return nil, nil
81
+}
82
+
83
+func GetAdsInfos(dsp *utils.DspParam, advertiser string, orderType int, fixFlag int, xiaomiHasFlag int) {
84
+	ua = dsp.ua_client
85
+	req_source = dsp.req_source
86
+
87
+	ads_item = getOneAds(dsp, order_type, fix_flag)
88
+	if ads_item is
89
+None:
90
+	raise
91
+	gen.Return((None, None))
92
+	r = random.randint(0, 100)
93
+	if xiaomi_has_flag == 1:
94
+	if ads_item['title'].find("_ios") > 0:
95
+	raise
96
+	gen.Return((None, None)) else:
97
+	r = random.randint(50, 100)
98
+
99
+	a = datetime.now()
100
+
101
+	#获取剩余时间内的值
102
+	all_count = get_sub_time_value(ads_item, a)
103
+	all_count = all_count * 1.0
104
+
105
+	#已经投放的key
106
+	show_key = "order_kpi_%s_%d%d%d_show_kpi" % (ads_item['order_id'], a.year, a.month, a.day)
107
+	click_key = "order_kpi_%s_%d%d%d_click_kpi" % (ads_item['order_id'], a.year, a.month, a.day)
108
+	over_kpi = redis_tools.get_key_int_value(show_key)
109
+	show_kpi = ads_item['show_kpi']
110
+	click_kpi = ads_item['click_kpi']
111
+	if all_count < 1:
112
+	raise
113
+	gen.Return((None, None))
114
+	plan_key = "plan_all_kpi_%s_%d%d%d_show_kpi" % (ads_item['order_id'], a.year, a.month, a.day)
115
+	redis_common.redis_ads().set(plan_key, all_count, 60*24*60)
116
+
117
+	w_value, rate = get_now_min_value(ads_item, all_count, show_kpi, a)
118
+	if w_value < 1:
119
+	w_value = 1
120
+
121
+	plan_key = "plan_kpi_%s_%d%d%d_%d_show_kpi" % (ads_item['order_id'], a.year, a.month, a.day, a.hour*60 + a.minute)
122
+	redis_common.redis_ads().set(plan_key, w_value, 60*24*60)
123
+
124
+	over_key = "order_kpi_%s_%d%d%d_%d_show_kpi" % (ads_item['order_id'], a.year, a.month, a.day, a.hour*60 + a.minute)
125
+	o_value = int(redis_tools.get_key_int_value(over_key))
126
+
127
+	js_order_id = int(ads_item['js_order_id'])
128
+	if o_value < w_value:
129
+	order_name = ads_item['title']
130
+	data =
131
+	{
132
+		"js_order_id":js_order_id,
133
+		"target":"",
134
+		"video_url":"",
135
+		"duration":5,
136
+		"target_addition":[],
137
+		"image_url":"",
138
+		"result":0,
139
+		"msg":0,
140
+		"user_agent":ua,
141
+		"order_name":order_name
142
+	}
143
+
144
+	#放量
145
+	redis_tools.incr_key_value(over_key)
146
+	redis_tools.incr_key_value(show_key)
147
+	show_url = ads_item['show_url']
148
+	click_url = ads_item['click_url']
149
+
150
+	target = ads_item['target_url']
151
+
152
+	if order_name.find("_ios") > 0:
153
+	ios_imei, ios_ua = get_ios_ua_imei(dsp)
154
+	if ios_ua:
155
+	data['user_agent'] = ios_ua
156
+	if ads_item.get('imei_replace_flag', 0) == 1 and
157
+ios_imei:
158
+	show_url = show_url.replace('__IDFA__', ios_imei)
159
+	click_url = click_url.replace('__IDFA__', ios_imei)
160
+	target = target.replace('__IDFA__', ios_imei)
161
+	if order_name.find("__OS__") > 0:
162
+	show_url = show_url.replace('__OS__', '1')
163
+	click_url = click_url.replace('__OS__', '1')
164
+	target = target.replace('__OS__', '1')
165
+
166
+	elif
167
+	order_name.find("_android") > 0 :
168
+	### 判断是否需要替换imei
169
+	if ads_item.get('imei_replace_flag', 0) == 1:
170
+	show_url = show_url.replace('__IMEI__', dsp.real_md5_imei)
171
+	click_url = click_url.replace('__IMEI__', dsp.real_md5_imei)
172
+	target = target.replace('__IMEI__', dsp.real_md5_imei)
173
+
174
+	if order_name.find("__OS__") > 0:
175
+	show_url = show_url.replace('__OS__', '0')
176
+	click_url = click_url.replace('__OS__', '0')
177
+	target = target.replace('__OS__', '0')
178
+
179
+	else:
180
+	if r < 40:
181
+	ios_imei, ios_ua = get_ios_ua_imei(dsp)
182
+	if ios_ua:
183
+	data['user_agent'] = ios_ua
184
+	if ads_item.get('imei_replace_flag', 0) == 1 and
185
+ios_imei:
186
+	show_url = show_url.replace('__IDFA__', ios_imei)
187
+	click_url = click_url.replace('__IDFA__', ios_imei)
188
+	target = target.replace('__IDFA__', ios_imei)
189
+	if order_name.find("__OS__") > 0:
190
+	show_url = show_url.replace('__OS__', '1')
191
+	click_url = click_url.replace('__OS__', '1')
192
+	target = target.replace('__OS__', '1')
193
+	else:
194
+	if ads_item.get('imei_replace_flag', 0) == 1:
195
+	show_url = show_url.replace('__IMEI__', dsp.real_md5_imei)
196
+	click_url = click_url.replace('__IMEI__', dsp.real_md5_imei)
197
+	target = target.replace('__IMEI__', dsp.real_md5_imei)
198
+	if order_name.find("__OS__") > 0:
199
+	show_url = show_url.replace('__OS__', '0')
200
+	click_url = click_url.replace('__OS__', '0')
201
+	target = target.replace('__OS__', '0')
202
+
203
+	if order_name.find("__IP__") > 0:
204
+	show_url = show_url.replace('__IP__', dsp.ip)
205
+	click_url = click_url.replace('__IP__', dsp.ip)
206
+	target = target.replace('__IP__', dsp.ip)
207
+	if order_type == 0:
208
+	addi = get_monitor_url('VIEW', 5, order_name, req_source, show_url)
209
+	else:
210
+	addi = get_monitor_url('VIEW', 5, order_name, 'follow', show_url)
211
+
212
+	#addi['urls'].append(show_url)
213
+	data['target_addition'].append(addi)
214
+
215
+	r = random.randint(0, 1000)
216
+	c_rate = click_kpi * 1.0 / (ads_item['show_kpi']) * 1000
217
+	if r < c_rate:
218
+	#下发点击
219
+	addi = get_monitor_url('CLICK', 1, order_name, req_source, click_url)
220
+	#addi['urls'].append(click_url)
221
+	data['target_addition'].append(addi)
222
+	md5_skip = hashlib.md5(target).hexdigest()
223
+	redis_tools.incr_key_value(click_key)
224
+	real_target = ads_config.Host + "?action=LOADING&req_source={0}&advertiser={2}&skip={1}&skip_other={3}".format(
225
+		req_source, '', order_name, md5_skip)
226
+	### 塞入缓存中
227
+	redis_tools.set_skip_info(md5_skip, target)
228
+	data['target'] = real_target
229
+	raise
230
+	gen.Return((None, data))
231
+	#获取当前已经放出去的次数
232
+	raise gen.Return((None, None))
233
+}~

+ 84 - 84
adslib/addata/xiaomi.go

@@ -17,60 +17,60 @@ import (
17 17
 )
18 18
 
19 19
 type XiaomiAdData struct {
20
-DetailURL   string `json:"detail_url"`
21
-DisplayType struct {
22
-Delay    int64  `json:"delay"`
23
-Name     string `json:"name"`
24
-RowCount int64  `json:"row_count"`
25
-} `json:"display_type"`
26
-Duration   int64  `json:"duration"`
27
-EmcType    string `json:"emc_type"`
28
-ID         string `json:"id"`
29
-ImageURL   string `json:"image_url"`
30
-Proportion string `json:"proportion"`
31
-Settings   struct {
32
-ClickType   string `json:"click_type"`
33
-HideCloseAt int64  `json:"hide_close_at"`
34
-LogTime     string `json:"log_time"`
35
-ShowCloseAt int64  `json:"show_close_at"`
36
-} `json:"settings"`
37
-SkipTime        int64    `json:"skip_time"`
38
-TagID           string   `json:"tag_id"`
39
-Target          string   `json:"target"`
40
-TargetAddition  []string `json:"target_addition"`
41
-TargetAddition1 string   `json:"target_addition1"`
42
-Title           string   `json:"title"`
43
-VideoURL        string   `json:"video_url"`
20
+	DetailURL   string `json:"detail_url"`
21
+	DisplayType struct {
22
+		Delay    int64  `json:"delay"`
23
+		Name     string `json:"name"`
24
+		RowCount int64  `json:"row_count"`
25
+	} `json:"display_type"`
26
+	Duration   int64  `json:"duration"`
27
+	EmcType    string `json:"emc_type"`
28
+	ID         string `json:"id"`
29
+	ImageURL   string `json:"image_url"`
30
+	Proportion string `json:"proportion"`
31
+	Settings   struct {
32
+		ClickType   string `json:"click_type"`
33
+		HideCloseAt int64  `json:"hide_close_at"`
34
+		LogTime     string `json:"log_time"`
35
+		ShowCloseAt int64  `json:"show_close_at"`
36
+	} `json:"settings"`
37
+	SkipTime        int64    `json:"skip_time"`
38
+	TagID           string   `json:"tag_id"`
39
+	Target          string   `json:"target"`
40
+	TargetAddition  []string `json:"target_addition"`
41
+	TargetAddition1 string   `json:"target_addition1"`
42
+	Title           string   `json:"title"`
43
+	VideoURL        string   `json:"video_url"`
44 44
 }
45 45
 
46 46
 type XiaoMiAdInfoRsp struct {
47
-	Data []XiaomiAdData  `json:"data"`
48
-	Msg    string `json:"msg"`
49
-	Result int64  `json:"result"`
47
+	Data   []XiaomiAdData `json:"data"`
48
+	Msg    string         `json:"msg"`
49
+	Result int64          `json:"result"`
50 50
 }
51 51
 
52 52
 type AdAction struct {
53
-	Type string `json:"type"`
54
-	Duration int `json:"duration"`
55
-	Urls []string `json:"urls"`
53
+	Type     string   `json:"type"`
54
+	Duration int      `json:"duration"`
55
+	Urls     []string `json:"urls"`
56 56
 }
57 57
 
58 58
 type AdInfo struct {
59
-	AdActions []AdAction `json:"ads_infos"`
60
-	PercentBegin int`json:"percent_begin"`
61
-	PercentEnd int`json:"percent_end"`
59
+	AdActions    []AdAction `json:"ads_infos"`
60
+	PercentBegin int        `json:"percent_begin"`
61
+	PercentEnd   int        `json:"percent_end"`
62 62
 }
63 63
 
64 64
 type AdData struct {
65 65
 	TargetAddition []AdAction `json:"target_addition"`
66
-	Target string
67
-	ImageUrl string`json:"image_url"`
68
-	Duration int64
69
-	VideoUrl string`json:"video_url"`
70
-	JsOrderId string `json:"js_order_id"`
71
-	UserAgent string `json:"user_agent"`
72
-	DpReport string `json:"dp_report"`
73
-	Dp string `json:"dp"`
66
+	Target         string
67
+	ImageUrl       string `json:"image_url"`
68
+	Duration       int64
69
+	VideoUrl       string `json:"video_url"`
70
+	JsOrderId      string `json:"js_order_id"`
71
+	UserAgent      string `json:"user_agent"`
72
+	DpReport       string `json:"dp_report"`
73
+	Dp             string `json:"dp"`
74 74
 }
75 75
 
76 76
 func getAdsReqUrl(dsp *utils.DspParam) string {
@@ -80,7 +80,7 @@ func getAdsReqUrl(dsp *utils.DspParam) string {
80 80
 	// 组装 emcp
81 81
 	reqUrl = reqUrl + "_emcp=pre_play"
82 82
 	// 组装 devid
83
-	reqUrl = reqUrl + "&_devid="+ dsp.RealMd5Imei
83
+	reqUrl = reqUrl + "&_devid=" + dsp.RealMd5Imei
84 84
 	//  组装 ref
85 85
 	reqUrl = reqUrl + "&ref=" + ref
86 86
 	// 组装 sn
@@ -96,34 +96,35 @@ func getAdsReqUrl(dsp *utils.DspParam) string {
96 96
 	reqUrl = reqUrl + fmt.Sprintf("&_phonetype=%d", dsp.SendPhoneType)
97 97
 	return reqUrl
98 98
 }
99
+
99 100
 // 获取广告信息
100 101
 func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdData, map[string]int, int, error) {
101 102
 	reqUrl := getAdsReqUrl(dsp)
102 103
 
103 104
 	if dsp.SendPhoneType == 0 {
104 105
 		device.SetAdsTagLog("xiaomi", dsp.ReqSource, "ADS_XIAOMI", dsp.DspCityCode)
105
-	} else if dsp.SendPhoneType == 1{
106
+	} else if dsp.SendPhoneType == 1 {
106 107
 		device.SetAdsTagLog("xiaomi", dsp.ReqSource, "ADS_XIAOMI_1", dsp.DspCityCode)
107 108
 	}
108 109
 
109 110
 	client := &http.Client{}
110 111
 	fmt.Printf("req url: %s\n", reqUrl)
111
-	req, err := http.NewRequest("GET", reqUrl,  nil)
112
+	req, err := http.NewRequest("GET", reqUrl, nil)
112 113
 	if err != nil {
113 114
 		return nil, nil, nil, 0, err
114 115
 	}
115 116
 
116
-	req.Header.Set(",authority","m.video.xiaomi.com")
117
-	req.Header.Set(",method","GET")
117
+	req.Header.Set(",authority", "m.video.xiaomi.com")
118
+	req.Header.Set(",method", "GET")
118 119
 	req.Header.Set(",path", reqUrl[26:])
119
-	req.Header.Set(",scheme","https")
120
-	req.Header.Set("content-type","application/json")
121
-	req.Header.Set("accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
122
-	req.Header.Set("accept-encoding","gzip, deflate, br")
123
-	req.Header.Set("accept-language","zh-CN,zh;q=0.9")
124
-	req.Header.Set("cache-control","max-age=0")
125
-	req.Header.Set("upgrade-insecure-requests","1")
126
-	req.Header.Set("user-agent",dsp.Ua)
120
+	req.Header.Set(",scheme", "https")
121
+	req.Header.Set("content-type", "application/json")
122
+	req.Header.Set("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
123
+	req.Header.Set("accept-encoding", "gzip, deflate, br")
124
+	req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
125
+	req.Header.Set("cache-control", "max-age=0")
126
+	req.Header.Set("upgrade-insecure-requests", "1")
127
+	req.Header.Set("user-agent", dsp.Ua)
127 128
 
128 129
 	resp, err := client.Do(req)
129 130
 	if err != nil {
@@ -142,8 +143,8 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
142 143
 	}
143 144
 
144 145
 	adsDataNum := len(rsp.Data)
145
-	xiaomiResponseAction := map[string]int {
146
-		"xiaomi_view":0, "xiaomi_click":0, "xiaomi_close":0, "xiaomi_video_finish":0, "xiaomi_video_timer":0,
146
+	xiaomiResponseAction := map[string]int{
147
+		"xiaomi_view": 0, "xiaomi_click": 0, "xiaomi_close": 0, "xiaomi_video_finish": 0, "xiaomi_video_timer": 0,
147 148
 	}
148 149
 
149 150
 	if rsp.Result != 1 {
@@ -196,20 +197,20 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
196 197
 
197 198
 		if targetUrl != "" {
198 199
 			switch event {
199
-				case "VIEW":
200
-					showUrls = append(showUrls, targetUrl)
201
-					xiaomiResponseAction["xiaomi_view"] = 1
200
+			case "VIEW":
201
+				showUrls = append(showUrls, targetUrl)
202
+				xiaomiResponseAction["xiaomi_view"] = 1
202 203
 			case "CLICK":
203
-					clickUrls = append(clickUrls, targetUrl)
204
-					xiaomiResponseAction["xiaomi_click"] = 1
204
+				clickUrls = append(clickUrls, targetUrl)
205
+				xiaomiResponseAction["xiaomi_click"] = 1
205 206
 			case "CLOSE":
206
-					closeUrls = append(closeUrls, targetUrl)
207
-					xiaomiResponseAction["xiaomi_close"] = 1
207
+				closeUrls = append(closeUrls, targetUrl)
208
+				xiaomiResponseAction["xiaomi_close"] = 1
208 209
 			case "VIDEO_FINISH":
209
-					videoFinishUrls = append(videoFinishUrls, targetUrl)
210
-					xiaomiResponseAction["xiaomi_video_finish"] = 1
210
+				videoFinishUrls = append(videoFinishUrls, targetUrl)
211
+				xiaomiResponseAction["xiaomi_video_finish"] = 1
211 212
 			case "VIDEO_TIMER":
212
-					videoTimerUrls = append(videoTimerUrls, targetUrl)
213
+				videoTimerUrls = append(videoTimerUrls, targetUrl)
213 214
 			}
214 215
 		}
215 216
 
@@ -238,7 +239,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
238 239
 			gotoUrls = append(gotoUrls, targetUrl)
239 240
 		}
240 241
 	}
241
-	if dsp.ReqSource ==  "mh" {
242
+	if dsp.ReqSource == "mh" {
242 243
 		closeUrls = videoFinishUrls
243 244
 	}
244 245
 
@@ -256,7 +257,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
256 257
 
257 258
 	fmt.Printf("%+v, addata_num: %d\n", xiaomiResponseAction, adsDataNum)
258 259
 	if len(gotoUrls) == 0 {
259
-		return nil,  rsp.Data, xiaomiResponseAction, adsDataNum, nil
260
+		return nil, rsp.Data, xiaomiResponseAction, adsDataNum, nil
260 261
 	}
261 262
 
262 263
 	fmt.Printf("goto urls: %+v\nshow urls: %+v\nclick_urls: %+v\nclose urls: %+v\nvideo finish urls: %+v\nimagurls: %+v\nvideo urls:%+v\n",
@@ -271,7 +272,7 @@ func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, []XiaomiAdDat
271 272
 
272 273
 	if dsp.SendPhoneType == 0 {
273 274
 		redis_data.SetAdsRequestNum(advertiser, 0)
274
-	} else if dsp.SendPhoneType == 1{
275
+	} else if dsp.SendPhoneType == 1 {
275 276
 		redis_data.SetAdsRequestNum(advertiser, 1)
276 277
 	}
277 278
 	return adsData, rsp.Data, xiaomiResponseAction, adsDataNum, nil
@@ -309,7 +310,7 @@ func getCombinationActionsConf(advertiser string) []adslib.CombinationActionsCon
309 310
 // 组装最后的广告信息
310 311
 func CombineLastAdsInfos(dsp *utils.DspParam, advertiser string, gotoUrls []string, showUrls []string,
311 312
 	clickUrls []string, closeUrls []string, videoFinishUrls []string,
312
-	videoTimerUrls []string, imageUrls []string, videoUrls []string) (*AdData, error){
313
+	videoTimerUrls []string, imageUrls []string, videoUrls []string) (*AdData, error) {
313 314
 
314 315
 	// 判断是不是关掉所有Action
315 316
 	actions := getActionsConf(advertiser)
@@ -317,7 +318,7 @@ func CombineLastAdsInfos(dsp *utils.DspParam, advertiser string, gotoUrls []stri
317 318
 		return nil, nil
318 319
 	}
319 320
 
320
-	clickChannelFlag, err := redis_data.GetChannelFlag(dsp.ReqSource,"ads_click")
321
+	clickChannelFlag, err := redis_data.GetChannelFlag(dsp.ReqSource, "ads_click")
321 322
 	if err != nil {
322 323
 		return nil, err
323 324
 	}
@@ -333,7 +334,7 @@ func CombineLastAdsInfos(dsp *utils.DspParam, advertiser string, gotoUrls []stri
333 334
 	lastInfos := make([]AdInfo, 0, 50)
334 335
 	combinationActions := getCombinationActionsConf(advertiser)
335 336
 	for _, combAction := range combinationActions {
336
-		adActionDatas := make([]AdAction, 0 ,20)
337
+		adActionDatas := make([]AdAction, 0, 20)
337 338
 		percentBegin := combAction.PercentBegin
338 339
 		percentEnd := combAction.PercentEnd
339 340
 		actionGroup := combAction.GroupValue
@@ -360,18 +361,18 @@ func CombineLastAdsInfos(dsp *utils.DspParam, advertiser string, gotoUrls []stri
360 361
 			}
361 362
 
362 363
 			// click的控制 控制bom
363
-			if action =="CLICK" && dsp.RealReqSource=="bom" && dsp.SupClickFlag==0{
364
+			if action == "CLICK" && dsp.RealReqSource == "bom" && dsp.SupClickFlag == 0 {
364 365
 				continue
365 366
 			}
366 367
 			// show的控制 控制bom
367
-			if action=="VIEW" && dsp.RealReqSource=="bom" && dsp.SupShowFlag==0 {
368
+			if action == "VIEW" && dsp.RealReqSource == "bom" && dsp.SupShowFlag == 0 {
368 369
 				continue
369 370
 			}
370
-			if action=="CLICK" && !needClick {
371
+			if action == "CLICK" && !needClick {
371 372
 				continue
372 373
 			}
373 374
 
374
-			if len(urls)==0 && action=="VIDEO_TIMER" {
375
+			if len(urls) == 0 && action == "VIDEO_TIMER" {
375 376
 				continue
376 377
 			}
377 378
 
@@ -414,7 +415,7 @@ func CombineLastAdsInfos(dsp *utils.DspParam, advertiser string, gotoUrls []stri
414 415
 		videoUrl = videoUrls[0]
415 416
 	}
416 417
 
417
-	randAdData := make([]AdAction,0, 50)
418
+	randAdData := make([]AdAction, 0, 50)
418 419
 	if len(lastInfos) != 0 {
419 420
 		randIdx := rand.Intn(len(lastInfos))
420 421
 		randAdData = lastInfos[randIdx].AdActions
@@ -434,7 +435,7 @@ func CombineLastAdsInfos(dsp *utils.DspParam, advertiser string, gotoUrls []stri
434 435
 
435 436
 	// 重新组装duration
436 437
 	videoTimerUrls = make([]string, 0, 100)
437
-	if len(randAdData)>=3 {
438
+	if len(randAdData) >= 3 {
438 439
 		if randAdData[1].Type == "VIDEO_TIMER" {
439 440
 			videoTimerUrls = randAdData[1].Urls
440 441
 		}
@@ -446,20 +447,19 @@ func CombineLastAdsInfos(dsp *utils.DspParam, advertiser string, gotoUrls []stri
446 447
 			continue
447 448
 		}
448 449
 
449
-
450 450
 		if adData.Type == "VIDEO_TIMER" && len(videoTimerUrls) > 0 {
451 451
 			adData.Duration = int(dsp.AllDuration) - dsp.VideoTimeDuration
452
-		} else if adData.Type == "VIDEO_TIMER" && len(videoTimerUrls) == 0{
452
+		} else if adData.Type == "VIDEO_TIMER" && len(videoTimerUrls) == 0 {
453 453
 			adData.Duration = dsp.VideoTimeDuration
454 454
 		} else if adData.Type == "VIEW" {
455
-			if  len(videoTimerUrls) > 0 {
455
+			if len(videoTimerUrls) > 0 {
456 456
 				adData.Duration = dsp.VideoTimeDuration
457 457
 			} else {
458 458
 				adData.Duration = int(dsp.AllDuration)
459 459
 			}
460 460
 		}
461 461
 
462
-		if adData.Type != "VIEW"{
462
+		if adData.Type != "VIEW" {
463 463
 			redis_data.SetDistributeActionNum(advertiser, adData.Type, dsp.SendPhoneType)
464 464
 		}
465 465
 
@@ -504,7 +504,7 @@ func genAdsAction(urls []string, advertiser string,
504 504
 	}
505 505
 	allShowNum, err := redis_data.GetAdsFeedbackNum(advertiser, action, dsp.SendPhoneType)
506 506
 	if err != nil {
507
-		return nil ,err
507
+		return nil, err
508 508
 	}
509 509
 
510 510
 	flowControlConf := redis_data.GetFlowPercentDuration(advertiser, action)
@@ -517,7 +517,7 @@ func genAdsAction(urls []string, advertiser string,
517 517
 		duration = flowControlConf.Duration
518 518
 	}
519 519
 
520
-	lastUrls := make([]string, 0,20)
520
+	lastUrls := make([]string, 0, 20)
521 521
 	if !needControl || allSendNum == 0 || int(
522 522
 		float32(allShowNum)/float32(allSendNum)*100) < flowPercent {
523 523
 		reportUrl := getReportUrl(action, advertiser, dsp)

+ 0 - 3
adslib/addata/xiaomi_mix.go

@@ -1,3 +0,0 @@
1
-package addata
2
-
3
-combine_mix_infos_v2(ads_item,extra_infos)

+ 1 - 1
adslib/ads_checker/ip.go

@@ -1,7 +1,7 @@
1 1
 package ads_checker
2 2
 
3 3
 import (
4
-	"miads/lib/ads_redis"
4
+	"miads/adslib/ads_redis"
5 5
 
6 6
 	"github.com/gomodule/redigo/redis"
7 7
 )

+ 194 - 0
adslib/redis_data/order.go

@@ -0,0 +1,194 @@
1
+package redis_data
2
+
3
+import (
4
+	"encoding/base64"
5
+	"encoding/json"
6
+	"github.com/gomodule/redigo/redis"
7
+	"miads/adslib/ads_redis"
8
+	"miads/adslib/graylog"
9
+	"miads/adslib/utils"
10
+	"strings"
11
+)
12
+
13
+type AdOrderInfo struct {
14
+	BeginTime       int64  `json:"begin_time"`
15
+	Channel         string `json:"channel"`
16
+	City            string `json:"city"`
17
+	ClickKpi        int64  `json:"click_kpi"`
18
+	ClickURL        string `json:"click_url"`
19
+	EndTime         int64  `json:"end_time"`
20
+	ImeiReplaceFlag int64  `json:"imei_replace_flag"`
21
+	JsOrderID       int64  `json:"js_order_id"`
22
+	Level           int64  `json:"level"`
23
+	LineType        int64  `json:"line_type"`
24
+	NewRegionFlag   string `json:"new_region_flag"`
25
+	NoCity          string `json:"no_city"`
26
+	NoProvince      string `json:"no_province"`
27
+	OrderID         int64  `json:"order_id"`
28
+	OrderType       int64  `json:"order_type"`
29
+	Province        string `json:"province"`
30
+	RegionFlag      int64  `json:"region_flag"`
31
+	RegionInfo      string `json:"region_info"`
32
+	ShowKpi         int64  `json:"show_kpi"`
33
+	ShowURL         string `json:"show_url"`
34
+	TargetURL       string `json:"target_url"`
35
+	Title           string `json:"title"`
36
+}
37
+
38
+func getOrderIds() ([]string, error) {
39
+	conn := ads_redis.RedisConn.Get()
40
+	defer conn.Close()
41
+
42
+	rsp, err := conn.Do("SMEMBERS", "order_key")
43
+	if err != nil {
44
+		return []string{}, err
45
+	}
46
+
47
+	if rsp == nil {
48
+		return []string{}, err
49
+	}
50
+
51
+	orderIds, _ := redis.Strings(rsp, err)
52
+	return orderIds, nil
53
+}
54
+
55
+func getOrderInfo(id string) (*AdOrderInfo, error) {
56
+	conn := ads_redis.RedisConn.Get()
57
+	defer conn.Close()
58
+
59
+	rsp, err := conn.Do("GET", id)
60
+	if err != nil {
61
+		return nil, err
62
+	}
63
+
64
+	if rsp == nil {
65
+		return nil, err
66
+	}
67
+
68
+	orderBase64Str, _ := redis.String(rsp, err)
69
+	orderByte, err := base64.StdEncoding.DecodeString(orderBase64Str)
70
+	if err != nil {
71
+		return nil, err
72
+	}
73
+
74
+	a := AdOrderInfo{}
75
+	err = json.Unmarshal(orderByte, &a)
76
+	if err != nil {
77
+		return nil, err
78
+	}
79
+	return &a, nil
80
+}
81
+
82
+func GetOrderInfos(dsp *utils.DspParam, fixFlag int) ([]AdOrderInfo, error) {
83
+	orderIds, err := getOrderIds()
84
+	if err != nil {
85
+		return []AdOrderInfo{}, err
86
+	}
87
+
88
+	orders := make([]AdOrderInfo, 0, 50)
89
+	for _, id := range orderIds {
90
+		order, err := getOrderInfo(id)
91
+		if err != nil {
92
+			continue
93
+		}
94
+
95
+		if order == nil {
96
+			continue
97
+		}
98
+
99
+		needInsert := true
100
+		areaFlag := 0 // 0 通投 1 定投
101
+
102
+		if dsp != nil {
103
+			// 判断是否要做渠道剔除
104
+			channelStr := order.Channel
105
+			if channelStr != "" {
106
+				channelArr := strings.Split(channelStr, ",")
107
+				isValidChannel := false
108
+				for _, channel := range channelArr {
109
+					if dsp.ReqSource == channel {
110
+						isValidChannel = true
111
+					}
112
+				}
113
+				if !isValidChannel {
114
+					continue
115
+				}
116
+			}
117
+
118
+			newRegionFlagStr := order.NewRegionFlag
119
+			newRegionFlagArr := strings.Split(newRegionFlagStr, ",")
120
+			for _, regionFlag := range newRegionFlagArr {
121
+				if regionFlag == "1" {
122
+					// 对省定投
123
+					if strings.Index(order.Province, dsp.Province) == -1 {
124
+						needInsert = false
125
+						break
126
+					}
127
+				} else if regionFlag == "2" {
128
+					// 对市定投
129
+					if strings.Index(order.City, dsp.City) == -1 {
130
+						needInsert = false
131
+						break
132
+					}
133
+				} else if regionFlag == "3" {
134
+					// 对省禁投
135
+					if order.NoProvince != "" && strings.Index(order.NoProvince, dsp.Province) != -1 {
136
+						needInsert = false
137
+						break
138
+					}
139
+				} else if regionFlag == "4" {
140
+					// 对市禁投
141
+					if order.NoCity != "" && strings.Index(order.NoCity, dsp.City) != -1 {
142
+						needInsert = false
143
+						break
144
+					}
145
+				} else {
146
+					continue
147
+				}
148
+
149
+				areaFlag = 1
150
+			}
151
+		}
152
+
153
+		if !needInsert {
154
+			return []AdOrderInfo{}, nil
155
+		}
156
+
157
+		if dsp != nil {
158
+			grayLogData := struct {
159
+				Ip              string
160
+				ShortMessage    string `json:"short_message"`
161
+				ReqSource       string `json:"req_source"`
162
+				Province        string
163
+				City            string
164
+				OrderId         int64  `json:"order_id"`
165
+				orderProvince   string `json:"order_province"`
166
+				orderCity       string `json:"order_city"`
167
+				orderNoProvince string `json:"order_no_province"`
168
+				orderNoCity     string `json:"order_no_city"`
169
+			}{
170
+				Ip:              dsp.Ip,
171
+				ShortMessage:    "area_result_v2",
172
+				ReqSource:       dsp.ReqSource,
173
+				Province:        dsp.Province,
174
+				City:            dsp.City,
175
+				OrderId:         order.OrderID,
176
+				orderProvince:   order.Province,
177
+				orderCity:       order.City,
178
+				orderNoProvince: order.NoProvince,
179
+				orderNoCity:     order.NoCity,
180
+			}
181
+			graylog.Log(grayLogData)
182
+		}
183
+
184
+		if fixFlag == 0 && areaFlag == 0 {
185
+			orders = append(orders, *order)
186
+		} else if fixFlag == 1 && areaFlag == 1 {
187
+			orders = append(orders, *order)
188
+		} else if fixFlag == -1 {
189
+			orders = append(orders, *order)
190
+		}
191
+	}
192
+
193
+	return orders, nil
194
+}

+ 15 - 4
adslib/redis_data/redis_data.go

@@ -6,6 +6,7 @@ import (
6 6
 	"github.com/gomodule/redigo/redis"
7 7
 	"miads/adslib"
8 8
 	"miads/adslib/ads_redis"
9
+	"strconv"
9 10
 	"time"
10 11
 )
11 12
 
@@ -208,7 +209,7 @@ func SetAdsRequestNum(advertiser string, bannerid int) {
208 209
 	defer conn.Close()
209 210
 
210 211
 	redisKey := fmt.Sprintf("adsv2_%s_%d", advertiser, bannerid)
211
-	if time.Now().Unix() %100==0 {
212
+	if time.Now().Unix()%100 == 0 {
212 213
 		conn.Do("delete", redisKey)
213 214
 	}
214 215
 	conn.Do("incr", redisKey)
@@ -219,12 +220,12 @@ func SetSkipInfo(md5Skip string, skipUrl string) {
219 220
 	conn := ads_redis.RedisConn.Get()
220 221
 	defer conn.Close()
221 222
 
222
-	redisKey:="su_" + md5Skip
223
-	conn.Do("set" , redisKey, skipUrl, 300)
223
+	redisKey := "su_" + md5Skip
224
+	conn.Do("set", redisKey, skipUrl, 300)
224 225
 }
225 226
 
226 227
 // 通过advertiser获取最小的script_order
227
-func GetMinScriptOrderByAdv(advertiser string) (string, error){
228
+func GetMinScriptOrderByAdv(advertiser string) (string, error) {
228 229
 	conn := ads_redis.RedisConn.Get()
229 230
 	defer conn.Close()
230 231
 
@@ -240,3 +241,13 @@ func GetMinScriptOrderByAdv(advertiser string) (string, error){
240 241
 	scriptOrder, _ := redis.String(rsp, err)
241 242
 	return scriptOrder, nil
242 243
 }
244
+
245
+// 设置来源的曝光次数
246
+func SetReqSourceView(adv string, reqSource string, source string) {
247
+	conn := ads_redis.RedisConn.Get()
248
+	defer conn.Close()
249
+
250
+	dateInt, _ := strconv.Atoi(time.Now().Format("20060102"))
251
+	key := fmt.Sprintf("view3_%s_%s_%d_%s", adv, reqSource, dateInt, source)
252
+	conn.Do("incr", key)
253
+}